🎥 Make videos programmatically with React
`@remotion/media`: Consider FPS when evicting cache
Jonny Burgerf98de91e97b9
diff --git a/packages/media/src/audio-extraction/audio-iterator.ts b/packages/media/src/audio-extraction/audio-iterator.tsindex c3fdaabe8a..cc9044d6cd 100644--- a/packages/media/src/audio-extraction/audio-iterator.ts+++ b/packages/media/src/audio-extraction/audio-iterator.ts@@ -1,6 +1,5 @@import type {AudioSample, AudioSampleSink} from 'mediabunny';import {Internals, type LogLevel} from 'remotion';-import {SAFE_WINDOW_OF_MONOTONICITY} from '../caches';import type {RememberActualMatroskaTimestamps} from '../video-extraction/remember-actual-matroska-timestamps';import {makeAudioCache} from './audio-cache';@@ -11,6 +10,7 @@ import {makeAudioCache} from './audio-cache';// So let's set a threshold of 1.5 seconds.const extraThreshold = 1.5;+const safetyOutOfOrderThreshold = 0.2;const warned: Record<string, boolean> = {};@@ -93,7 +93,7 @@ export const makeAudioIterator = ({if (fullDuration !== null && timestamp > fullDuration) {// Clear all samples before the timestamp// Do this in the while loop because samples might start from 0- cache.clearBeforeThreshold(fullDuration - SAFE_WINDOW_OF_MONOTONICITY);+ cache.clearBeforeThreshold(fullDuration - safetyOutOfOrderThreshold);return [];}@@ -121,7 +121,7 @@ export const makeAudioIterator = ({const deleteBefore =fullDuration === null ? timestamp : Math.min(timestamp, fullDuration);- cache.clearBeforeThreshold(deleteBefore - SAFE_WINDOW_OF_MONOTONICITY);+ cache.clearBeforeThreshold(deleteBefore - safetyOutOfOrderThreshold);if (sample === null) {break;diff --git a/packages/media/src/caches.ts b/packages/media/src/caches.tsindex ded2666a89..dafd35b01d 100644--- a/packages/media/src/caches.ts+++ b/packages/media/src/caches.ts@@ -4,7 +4,7 @@ import {makeAudioManager} from './audio-extraction/audio-manager';import {makeKeyframeManager} from './video-extraction/keyframe-manager';// Frames can be out of order, but we don't expect them to be more than 0.2 seconds out of order-export const SAFE_WINDOW_OF_MONOTONICITY = 0.2;+export const getSafeWindowOfMonotonicity = (fps: number) => (0.2 * 30) / fps;export const keyframeManager = makeKeyframeManager();export const audioManager = makeAudioManager();diff --git a/packages/media/src/video-extraction/extract-frame.ts b/packages/media/src/video-extraction/extract-frame.tsindex b5876d818e..54ad734a4e 100644--- a/packages/media/src/video-extraction/extract-frame.ts+++ b/packages/media/src/video-extraction/extract-frame.ts@@ -103,6 +103,7 @@ const extractFrameInternal = async ({src,logLevel,maxCacheSize,+ fps,});if (!keyframeBank) {@@ -114,7 +115,7 @@ const extractFrameInternal = async ({};}- const frame = await keyframeBank.getFrameFromTimestamp(timeInSeconds);+ const frame = await keyframeBank.getFrameFromTimestamp(timeInSeconds, fps);const rotation = frame?.rotation ?? 0;return {diff --git a/packages/media/src/video-extraction/keyframe-bank.ts b/packages/media/src/video-extraction/keyframe-bank.tsindex e26f9f4f31..3108cb5900 100644--- a/packages/media/src/video-extraction/keyframe-bank.ts+++ b/packages/media/src/video-extraction/keyframe-bank.ts@@ -1,13 +1,16 @@import type {VideoSample, VideoSampleSink} from 'mediabunny';import {Internals, type LogLevel} from 'remotion';-import {SAFE_WINDOW_OF_MONOTONICITY} from '../caches';+import {getSafeWindowOfMonotonicity} from '../caches';import {roundTo4Digits} from '../helpers/round-to-4-digits';import {renderTimestampRange} from '../render-timestamp-range';import {getAllocationSize} from './get-allocation-size';export type KeyframeBank = {src: string;- getFrameFromTimestamp: (timestamp: number) => Promise<VideoSample | null>;+ getFrameFromTimestamp: (+ timestamp: number,+ fps: number,+ ) => Promise<VideoSample | null>;prepareForDeletion: (logLevel: LogLevel,reason: string,@@ -19,7 +22,7 @@ export type KeyframeBank = {timestampInSeconds: number;logLevel: LogLevel;}) => void;- hasTimestampInSecond: (timestamp: number) => Promise<boolean>;+ hasTimestampInSecond: (timestamp: number, fps: number) => Promise<boolean>;addFrame: (frame: VideoSample, logLevel: LogLevel) => void;getOpenFrameCount: () => {size: number;@@ -83,11 +86,13 @@ export const makeKeyframeBank = async ({}}- if (frameTimestamp < timestampInSeconds) {- if (!frames[frameTimestamp]) {- continue;- }+ if (!frames[frameTimestamp]) {+ continue;+ }++ const {duration} = frames[frameTimestamp];+ if (frameTimestamp + duration < timestampInSeconds) {deleteFrameAtTimestamp(frameTimestamp);deletedTimestamps.push(frameTimestamp);}@@ -139,6 +144,7 @@ export const makeKeyframeBank = async ({const ensureEnoughFramesForTimestamp = async (timestampInSeconds: number,logLevel: LogLevel,+ fps: number,) => {while (!hasDecodedEnoughForTimestamp(timestampInSeconds)) {const sample = await sampleIterator.next();@@ -154,7 +160,8 @@ export const makeKeyframeBank = async ({deleteFramesBeforeTimestamp({logLevel: parentLogLevel,- timestampInSeconds: timestampInSeconds - SAFE_WINDOW_OF_MONOTONICITY,+ timestampInSeconds:+ timestampInSeconds - getSafeWindowOfMonotonicity(fps),});}@@ -163,6 +170,7 @@ export const makeKeyframeBank = async ({const getFrameFromTimestamp = async (timestampInSeconds: number,+ fps: number,): Promise<VideoSample | null> => {lastUsed = Date.now();@@ -183,7 +191,11 @@ export const makeKeyframeBank = async ({adjustedTimestamp = frameTimestamps[frameTimestamps.length - 1];}- await ensureEnoughFramesForTimestamp(adjustedTimestamp, parentLogLevel);+ await ensureEnoughFramesForTimestamp(+ adjustedTimestamp,+ parentLogLevel,+ fps,+ );for (let i = frameTimestamps.length - 1; i >= 0; i--) {const sample = frames[frameTimestamps[i]];@@ -205,8 +217,8 @@ export const makeKeyframeBank = async ({return frames[frameTimestamps[0]] ?? null;};- const hasTimestampInSecond = async (timestamp: number) => {- return (await getFrameFromTimestamp(timestamp)) !== null;+ const hasTimestampInSecond = async (timestamp: number, fps: number) => {+ return (await getFrameFromTimestamp(timestamp, fps)) !== null;};const getOpenFrameCount = () => {@@ -240,9 +252,13 @@ export const makeKeyframeBank = async ({return null;}+ const firstTimestamp = frameTimestamps[0];+ const lastTimestamp = frameTimestamps[frameTimestamps.length - 1]!;+ const lastFrame = frames[lastTimestamp];+return {- firstTimestamp: frameTimestamps[0],- lastTimestamp: frameTimestamps[frameTimestamps.length - 1],+ firstTimestamp,+ lastTimestamp: lastTimestamp + lastFrame!.duration,};};@@ -310,13 +326,13 @@ export const makeKeyframeBank = async ({};const keyframeBank: KeyframeBank = {- getFrameFromTimestamp: (timestamp: number) => {- queue = queue.then(() => getFrameFromTimestamp(timestamp));+ getFrameFromTimestamp: (timestamp: number, fps: number) => {+ queue = queue.then(() => getFrameFromTimestamp(timestamp, fps));return queue as Promise<VideoSample | null>;},prepareForDeletion,- hasTimestampInSecond: (timestamp: number) => {- queue = queue.then(() => hasTimestampInSecond(timestamp));+ hasTimestampInSecond: (timestamp: number, fps: number) => {+ queue = queue.then(() => hasTimestampInSecond(timestamp, fps));return queue as Promise<boolean>;},addFrame,diff --git a/packages/media/src/video-extraction/keyframe-manager.ts b/packages/media/src/video-extraction/keyframe-manager.tsindex f034f5770b..48114b3687 100644--- a/packages/media/src/video-extraction/keyframe-manager.ts+++ b/packages/media/src/video-extraction/keyframe-manager.ts@@ -1,6 +1,6 @@import type {VideoSampleSink} from 'mediabunny';import {Internals, type LogLevel} from 'remotion';-import {getTotalCacheStats, SAFE_WINDOW_OF_MONOTONICITY} from '../caches';+import {getSafeWindowOfMonotonicity, getTotalCacheStats} from '../caches';import {renderTimestampRange} from '../render-timestamp-range';import {type KeyframeBank, makeKeyframeBank} from './keyframe-bank';@@ -153,12 +153,14 @@ export const makeKeyframeManager = () => {timestampInSeconds,src,logLevel,+ fps,}: {timestampInSeconds: number;src: string;logLevel: LogLevel;+ fps: number;}) => {- const threshold = timestampInSeconds - SAFE_WINDOW_OF_MONOTONICITY;+ const threshold = timestampInSeconds - getSafeWindowOfMonotonicity(fps);if (!sources[src]) {return;@@ -172,10 +174,11 @@ export const makeKeyframeManager = () => {continue;}- const {lastTimestamp} = range;-- if (lastTimestamp < threshold) {- bank.prepareForDeletion(logLevel, 'cleared before threshold');+ if (range.lastTimestamp < threshold) {+ bank.prepareForDeletion(+ logLevel,+ 'cleared before threshold ' + threshold,+ );Internals.Log.verbose({logLevel, tag: '@remotion/media'},`[Video] Cleared frames for src ${src} from ${range.firstTimestamp}sec to ${range.lastTimestamp}sec`,@@ -270,12 +273,14 @@ export const makeKeyframeManager = () => {src,logLevel,maxCacheSize,+ fps,}: {timestamp: number;videoSampleSink: VideoSampleSink;src: string;logLevel: LogLevel;maxCacheSize: number;+ fps: number;}) => {ensureToStayUnderMaxCacheSize(logLevel, maxCacheSize);@@ -283,6 +288,7 @@ export const makeKeyframeManager = () => {timestampInSeconds: timestamp,src,logLevel,+ fps,});const keyframeBank = await getKeyframeBankOrRefetch({@@ -319,12 +325,14 @@ export const makeKeyframeManager = () => {src,logLevel,maxCacheSize,+ fps,}: {timestamp: number;videoSampleSink: VideoSampleSink;src: string;logLevel: LogLevel;maxCacheSize: number;+ fps: number;}) => {queue = queue.then(() =>requestKeyframeBank({@@ -333,6 +341,7 @@ export const makeKeyframeManager = () => {src,logLevel,maxCacheSize,+ fps,}),);return queue as Promise<KeyframeBank>;