π₯ Make videos programmatically with React
`@remotion/media`: scale source byte caches with `mediaCacheSizeInBytes` (#10209)
Alec Wattsa2d4bc167613
diff --git a/packages/docs/docs/media/cache.mdx b/packages/docs/docs/media/cache.mdxindex b6b8029f27..3d76f8b68a 100644--- a/packages/docs/docs/media/cache.mdx+++ b/packages/docs/docs/media/cache.mdx@@ -5,7 +5,7 @@ sidebar_label: Cachecrumb: 'API - @remotion/media'----[`@remotion/media`](/docs/media) keeps a cache of recently decoded video and audio frames.+[`@remotion/media`](/docs/media) keeps an in-memory cache for video and audio decoding.## Mechanism@@ -14,17 +14,17 @@ In order to decode a delta frame, the last keyframe and all the delta frames sinDue to Remotion's [multithreaded rendering and each frame being independent](/docs/flickering), it is not guaranteed that video frames are needed in their natural order.-The cache is shared across all of the instances of [`<Video>`](/docs/media/video) and [`<Audio>`](/docs/media/audio).-Therefore, the settings for the cache are per-render, not per tag.+Decoded media is cached across all instances of [`<Video>`](/docs/media/video) and [`<Audio>`](/docs/media/audio).+Therefore, the decoded media cache is per-render, not per tag.## Default cache size-By default, the cache may grow to up to 50% of the available system memory.+By default, the decoded media cache may grow to up to 50% of the available system memory.A minimum of 500MB and a maximum of 20GB is enforced.## Customizing the cache size-The rendering APIs allow you to customize this limit on a per-render basis:+The rendering APIs allow you to customize the decoded media cache budget on a per-render basis. The same value determines the read cache size for each source:- [`renderMedia()` β `mediaCacheSizeInBytes`](/docs/renderer/render-media#mediacachesizeinbytes)- [`renderStill()` β `mediaCacheSizeInBytes`](/docs/renderer/render-still#mediacachesizeinbytes)diff --git a/packages/media/src/caches.ts b/packages/media/src/caches.tsindex ff8be93020..36b16055e2 100644--- a/packages/media/src/caches.ts+++ b/packages/media/src/caches.ts@@ -1,7 +1,8 @@import React from 'react';-import {cancelRender, Internals, type LogLevel} from 'remotion';+import {Internals, type LogLevel} from 'remotion';import {makeAudioManager} from './audio-extraction/audio-manager';import {makeSinkManager} from './get-sink';+import {getMaxVideoCacheSize} from './max-cache-size';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@@ -109,77 +110,7 @@ export const useRenderMediaCache = (logLevel: LogLevel): MediaCache => {});};-const getUncachedMaxCacheSize = (logLevel: LogLevel) => {- if (- typeof window !== 'undefined' &&- window.remotion_mediaCacheSizeInBytes !== undefined &&- window.remotion_mediaCacheSizeInBytes !== null- ) {- if (window.remotion_mediaCacheSizeInBytes < 240 * 1024 * 1024) {- cancelRender(- new Error(- `The minimum value for the "mediaCacheSizeInBytes" prop is 240MB (${240 * 1024 * 1024}), got: ${window.remotion_mediaCacheSizeInBytes}`,- ),- );- }-- if (window.remotion_mediaCacheSizeInBytes > 20_000 * 1024 * 1024) {- cancelRender(- new Error(- `The maximum value for the "mediaCacheSizeInBytes" prop is 20GB (${20000 * 1024 * 1024}), got: ${window.remotion_mediaCacheSizeInBytes}`,- ),- );- }-- Internals.Log.verbose(- {logLevel, tag: '@remotion/media'},- `Using cache size set using "mediaCacheSizeInBytes": ${(window.remotion_mediaCacheSizeInBytes / 1024 / 1024).toFixed(1)} MB`,- );- return window.remotion_mediaCacheSizeInBytes;- }-- if (- typeof window !== 'undefined' &&- window.remotion_initialMemoryAvailable !== undefined &&- window.remotion_initialMemoryAvailable !== null- ) {- const value = window.remotion_initialMemoryAvailable / 2;- if (value < 500 * 1024 * 1024) {- Internals.Log.verbose(- {logLevel, tag: '@remotion/media'},- `Using cache size set based on minimum value of 500MB (which is more than half of the available system memory!)`,- );- return 500 * 1024 * 1024;- }-- if (value > 20_000 * 1024 * 1024) {- Internals.Log.verbose(- {logLevel, tag: '@remotion/media'},- `Using cache size set based on maximum value of 20GB (which is less than half of the available system memory)`,- );- return 20_000 * 1024 * 1024;- }-- Internals.Log.verbose(- {logLevel, tag: '@remotion/media'},- `Using cache size set based on available memory (50% of available memory): ${(value / 1024 / 1024).toFixed(1)} MB`,- );- return value;- }-- return 1000 * 1000 * 1000; // 1GB-};--let cachedMaxCacheSize: number | null = null;--export const getMaxVideoCacheSize = (logLevel: LogLevel) => {- if (cachedMaxCacheSize !== null) {- return cachedMaxCacheSize;- }-- cachedMaxCacheSize = getUncachedMaxCacheSize(logLevel);- return cachedMaxCacheSize;-};+export {getMaxVideoCacheSize};export const useMaxMediaCacheSize = (logLevel: LogLevel) => {const context = React.useContext(Internals.MaxMediaCacheSizeContext);diff --git a/packages/media/src/get-shared-input.ts b/packages/media/src/get-shared-input.tsindex f5b8a566de..8c52a83334 100644--- a/packages/media/src/get-shared-input.ts+++ b/packages/media/src/get-shared-input.ts@@ -1,4 +1,6 @@import {ALL_FORMATS, Input, UrlSource} from 'mediabunny';+import type {LogLevel} from 'remotion';+import {getMaxSourceCacheSize} from './max-cache-size';import {getMediaRequestInitFingerprint,normalizeMediaRequestInit,@@ -48,10 +50,12 @@ export const acquireSharedInput = ({src,credentials,requestInit,+ logLevel,}: {src: string;credentials: RequestCredentials | undefined;requestInit: MediaRequestInit | undefined;+ logLevel: LogLevel;}): {input: Input; cacheKey: string} => {const normalizedRequestInit = normalizeMediaRequestInit(requestInit);const cacheKey = getSharedInputCacheKey({@@ -71,10 +75,10 @@ export const acquireSharedInput = ({requestInit: normalizedRequestInit,});const input = new Input({- source: new UrlSource(- src,- resolvedRequestInit ? {requestInit: resolvedRequestInit} : undefined,- ),+ source: new UrlSource(src, {+ maxCacheSize: getMaxSourceCacheSize(logLevel),+ ...(resolvedRequestInit ? {requestInit: resolvedRequestInit} : undefined),+ }),formats: ALL_FORMATS,});diff --git a/packages/media/src/max-cache-size.ts b/packages/media/src/max-cache-size.tsnew file mode 100644index 0000000000..cc1dd20ed8--- /dev/null+++ b/packages/media/src/max-cache-size.ts@@ -0,0 +1,99 @@+import {cancelRender, Internals, type LogLevel} from 'remotion';++const getUncachedMaxCacheSize = (logLevel: LogLevel) => {+ if (+ typeof window !== 'undefined' &&+ window.remotion_mediaCacheSizeInBytes !== undefined &&+ window.remotion_mediaCacheSizeInBytes !== null+ ) {+ if (window.remotion_mediaCacheSizeInBytes < 240 * 1024 * 1024) {+ cancelRender(+ new Error(+ `The minimum value for the "mediaCacheSizeInBytes" prop is 240MB (${240 * 1024 * 1024}), got: ${window.remotion_mediaCacheSizeInBytes}`,+ ),+ );+ }++ if (window.remotion_mediaCacheSizeInBytes > 20_000 * 1024 * 1024) {+ cancelRender(+ new Error(+ `The maximum value for the "mediaCacheSizeInBytes" prop is 20GB (${20000 * 1024 * 1024}), got: ${window.remotion_mediaCacheSizeInBytes}`,+ ),+ );+ }++ Internals.Log.verbose(+ {logLevel, tag: '@remotion/media'},+ `Using cache size set using "mediaCacheSizeInBytes": ${(window.remotion_mediaCacheSizeInBytes / 1024 / 1024).toFixed(1)} MB`,+ );+ return window.remotion_mediaCacheSizeInBytes;+ }++ if (+ typeof window !== 'undefined' &&+ window.remotion_initialMemoryAvailable !== undefined &&+ window.remotion_initialMemoryAvailable !== null+ ) {+ const value = window.remotion_initialMemoryAvailable / 2;+ if (value < 500 * 1024 * 1024) {+ Internals.Log.verbose(+ {logLevel, tag: '@remotion/media'},+ `Using cache size set based on minimum value of 500MB (which is more than half of the available system memory!)`,+ );+ return 500 * 1024 * 1024;+ }++ if (value > 20_000 * 1024 * 1024) {+ Internals.Log.verbose(+ {logLevel, tag: '@remotion/media'},+ `Using cache size set based on maximum value of 20GB (which is less than half of the available system memory)`,+ );+ return 20_000 * 1024 * 1024;+ }++ Internals.Log.verbose(+ {logLevel, tag: '@remotion/media'},+ `Using cache size set based on available memory (50% of available memory): ${(value / 1024 / 1024).toFixed(1)} MB`,+ );+ return value;+ }++ return 1000 * 1000 * 1000; // 1GB+};++let cachedMaxCacheSize: number | null = null;++export const getMaxVideoCacheSize = (logLevel: LogLevel) => {+ if (cachedMaxCacheSize !== null) {+ return cachedMaxCacheSize;+ }++ cachedMaxCacheSize = getUncachedMaxCacheSize(logLevel);+ return cachedMaxCacheSize;+};++const MIN_SOURCE_CACHE_SIZE = 8 * 1024 * 1024;+// mediabunny's own default for `UrlSource`. Never allocate more than this, so+// this is a ceiling on existing behaviour rather than a change to it.+const MAX_SOURCE_CACHE_SIZE = 64 * 1024 * 1024;++// Every distinct `src` gets its own mediabunny source, and every source keeps a+// byte cache that is invisible to `getTotalCacheStats()`. That cache is charged+// against nothing, so a composition with many distinct sources can hold+// (sources x 64 MiB) on top of the decoded-frame budget the user configured+// with `mediaCacheSizeInBytes`.+//+// Scaling it with the configured budget keeps the read caches proportional to+// how much memory the user said they have. At the 1 GB default this lands at+// 62.5 MiB, so the common case is effectively unchanged; the difference shows+// up when someone deliberately renders in a small memory envelope.+export const getMaxSourceCacheSizeFromBudget = (budget: number) => {+ return Math.min(+ MAX_SOURCE_CACHE_SIZE,+ Math.max(MIN_SOURCE_CACHE_SIZE, Math.floor(budget / 16)),+ );+};++export const getMaxSourceCacheSize = (logLevel: LogLevel) => {+ return getMaxSourceCacheSizeFromBudget(getMaxVideoCacheSize(logLevel));+};diff --git a/packages/media/src/media-player.ts b/packages/media/src/media-player.tsindex 6945ee211a..e139316e9c 100644--- a/packages/media/src/media-player.ts+++ b/packages/media/src/media-player.ts@@ -171,6 +171,7 @@ export class MediaPlayer {src: this.src,credentials,requestInit,+ logLevel,});this.input = input;this.inputCacheKey = cacheKey;diff --git a/packages/media/src/test/max-source-cache-size.test.ts b/packages/media/src/test/max-source-cache-size.test.tsnew file mode 100644index 0000000000..774bc7837a--- /dev/null+++ b/packages/media/src/test/max-source-cache-size.test.ts@@ -0,0 +1,28 @@+import {expect, test} from 'vitest';+import {+ getMaxSourceCacheSize,+ getMaxSourceCacheSizeFromBudget,+} from '../max-cache-size';++const MIB = 1024 * 1024;++test('the default budget keeps the source cache near the mediabunny default', () => {+ // Falls back to the 1GB default, /16 = 62.5 MB, just under the 64 MiB+ // mediabunny would have used on its own.+ expect(getMaxSourceCacheSize('info')).toBe(+ Math.floor((1000 * 1000 * 1000) / 16),+ );+ expect(getMaxSourceCacheSize('info')).toBeLessThan(64 * MIB);+});++test('a small configured budget shrinks the source cache', () => {+ expect(getMaxSourceCacheSizeFromBudget(240 * MIB)).toBe(15 * MIB);+});++test('a large configured budget is capped at the mediabunny default', () => {+ expect(getMaxSourceCacheSizeFromBudget(20_000 * MIB)).toBe(64 * MIB);+});++test('budgets below the floor are clamped to 8 MiB', () => {+ expect(getMaxSourceCacheSizeFromBudget(MIB)).toBe(8 * MIB);+});diff --git a/packages/media/src/video-extraction/get-frames-since-keyframe.ts b/packages/media/src/video-extraction/get-frames-since-keyframe.tsindex d8843d058a..59460337c9 100644--- a/packages/media/src/video-extraction/get-frames-since-keyframe.ts+++ b/packages/media/src/video-extraction/get-frames-since-keyframe.ts@@ -15,6 +15,7 @@ import {canBrowserUseWebGl2} from '../browser-can-use-webgl2';import {getDurationOrCompute} from '../get-duration-or-compute';import {resolveAudioTrack} from '../helpers/resolve-audio-track';import {isNetworkError} from '../is-type-of-error';+import {getMaxSourceCacheSize} from '../max-cache-size';import type {MediaRequestInit} from '../request-init';import {resolveRequestInit} from '../request-init';import {rememberActualMatroskaTimestamps} from './remember-actual-matroska-timestamps';@@ -71,6 +72,7 @@ export const makeSinks = (formats: ALL_FORMATS,source: new UrlSource(src, {getRetryDelay,+ maxCacheSize: getMaxSourceCacheSize(logLevel),...(resolvedRequestInit ? {requestInit: resolvedRequestInit} : undefined),}),});diff --git a/packages/renderer/src/options/video-cache-size.tsx b/packages/renderer/src/options/video-cache-size.tsxindex a691f2db31..67abec91bf 100644--- a/packages/renderer/src/options/video-cache-size.tsx+++ b/packages/renderer/src/options/video-cache-size.tsx@@ -13,14 +13,16 @@ export const mediaCacheSizeInBytesOption = {cliFlag,description: () => (<>- Specify the maximum size of the cache that <code><Video></code> and{' '}- <code><Audio></code> from <code>@remotion/media</code> may use- combined, in bytes. <br />+ Specify the memory budget for decoded media cached by{' '}+ <code><Video></code> and <code><Audio></code> from{' '}+ <code>@remotion/media</code>, in bytes. This value also determines the+ maximum read cache size for each distinct media source. It is not a limit+ on total memory usage. <br />The default is half of the available system memory when the render starts.</>),ssrName: 'mediaCacheSizeInBytes' as const,- docLink: 'https://www.remotion.dev/docs/media/video#setting-the-cache-size',+ docLink: 'https://www.remotion.dev/docs/media/cache',type: 0 as number | null,getValue: ({commandLine}) => {if (commandLine[cliFlag] !== undefined) {