🎥 Make videos programmatically with React
scope last frame cache
Jonny Burgerdb62e8b097da
diff --git a/packages/core/src/CompositionManager.tsx b/packages/core/src/CompositionManager.tsxindex 78856e1be7..69286b46bc 100644--- a/packages/core/src/CompositionManager.tsx+++ b/packages/core/src/CompositionManager.tsx@@ -94,6 +94,7 @@ export type DownloadMap = {| undefined;};listeners: {[key: string]: {[downloadDir: string]: (() => void)[]}};+ lastFrameMap: Record<string, {lastAccessed: number; data: Buffer}>;};export type RenderAssetInfo = {diff --git a/packages/renderer/src/assets/download-and-map-assets-to-file.ts b/packages/renderer/src/assets/download-and-map-assets-to-file.tsindex e8c7a14497..fd198e8939 100644--- a/packages/renderer/src/assets/download-and-map-assets-to-file.ts+++ b/packages/renderer/src/assets/download-and-map-assets-to-file.ts@@ -23,6 +23,7 @@ export const makeDownloadMap = (): DownloadMap => {isDownloadingMap: {},hasBeenDownloadedMap: {},listeners: {},+ lastFrameMap: {},};};diff --git a/packages/renderer/src/extract-frame-from-video.ts b/packages/renderer/src/extract-frame-from-video.tsindex b4e13aa686..fea66cd4b7 100644--- a/packages/renderer/src/extract-frame-from-video.ts+++ b/packages/renderer/src/extract-frame-from-video.ts@@ -1,5 +1,5 @@import execa from 'execa';-import type {OffthreadVideoImageFormat} from 'remotion';+import type {DownloadMap, OffthreadVideoImageFormat} from 'remotion';import {getVideoStreamDuration} from './assets/get-video-stream-duration';import {ensurePresentationTimestamps} from './ensure-presentation-timestamp';import type {FfmpegExecutable} from './ffmpeg-executable';@@ -210,6 +210,7 @@ const getLastFrameOfVideoFastUnlimited = async (imageFormat: options.imageFormat,specialVCodecForTransparency: options.specialVCodecForTransparency,needsResize: options.needsResize,+ downloadMap: options.downloadMap,});return unlimited;@@ -236,6 +237,7 @@ type Options = {ffmpegExecutable: FfmpegExecutable;ffprobeExecutable: FfmpegExecutable;imageFormat: OffthreadVideoImageFormat;+ downloadMap: DownloadMap;};const extractFrameFromVideoFn = async ({@@ -243,6 +245,7 @@ const extractFrameFromVideoFn = async ({ffmpegExecutable,ffprobeExecutable,imageFormat,+ downloadMap,...options}: Options): Promise<Buffer> => {// We make a new copy of the video only for video because the conversion may affect@@ -273,6 +276,7 @@ const extractFrameFromVideoFn = async ({imageFormat,specialVCodecForTransparency: specialVcodec,needsResize,+ downloadMap,});return lastFrame;}@@ -340,6 +344,7 @@ const extractFrameFromVideoFn = async ({imageFormat,specialVCodecForTransparency: specialVcodec,needsResize,+ downloadMap,});return last;diff --git a/packages/renderer/src/last-frame-from-video-cache.ts b/packages/renderer/src/last-frame-from-video-cache.tsindex 27806bfe8e..453623fc58 100644--- a/packages/renderer/src/last-frame-from-video-cache.ts+++ b/packages/renderer/src/last-frame-from-video-cache.ts@@ -1,6 +1,6 @@// OffthreadVideo requires sometimes that the last frame of a video gets extracted, however, this can be slow. We allocate a cache for it but that can be garbage collected-import type {OffthreadVideoImageFormat} from 'remotion';+import type {DownloadMap, OffthreadVideoImageFormat} from 'remotion';import type {FfmpegExecutable} from './ffmpeg-executable';import type {SpecialVCodecForTransparency} from './get-video-info';@@ -12,10 +12,9 @@ export type LastFrameOptions = {specialVCodecForTransparency: SpecialVCodecForTransparency;imageFormat: OffthreadVideoImageFormat;needsResize: [number, number] | null;+ downloadMap: DownloadMap;};-let map: Record<string, {lastAccessed: number; data: Buffer}> = {};-const MAX_CACHE_SIZE = 50 * 1024 * 1024; // 50MBlet bufferSize = 0;@@ -26,6 +25,7 @@ const makeLastFrameCacheKey = (options: LastFrameOptions) => {options.offset,options.src,options.imageFormat,+ // TODO: Download dir as well?].join('-');};@@ -34,13 +34,13 @@ export const setLastFrameInCache = (data: Buffer) => {const key = makeLastFrameCacheKey(options);- if (map[key]) {- bufferSize -= map[key].data.byteLength;+ if (options.downloadMap.lastFrameMap[key]) {+ bufferSize -= options.downloadMap.lastFrameMap[key].data.byteLength;}- map[key] = {data, lastAccessed: Date.now()};+ options.downloadMap.lastFrameMap[key] = {data, lastAccessed: Date.now()};bufferSize += data.byteLength;- ensureMaxSize();+ ensureMaxSize(options.downloadMap);};export const getLastFrameFromCache = (@@ -48,35 +48,35 @@ export const getLastFrameFromCache = (): Buffer | null => {const key = makeLastFrameCacheKey(options);- if (!map[key]) {+ if (!options.downloadMap.lastFrameMap[key]) {return null;}- map[key].lastAccessed = Date.now();- return map[key].data ?? null;+ options.downloadMap.lastFrameMap[key].lastAccessed = Date.now();+ return options.downloadMap.lastFrameMap[key].data ?? null;};-const removedLastFrameFromCache = (key: string) => {- if (!map[key]) {+const removedLastFrameFromCache = (key: string, downloadMap: DownloadMap) => {+ if (!downloadMap.lastFrameMap[key]) {return;}- bufferSize -= map[key].data.byteLength;+ bufferSize -= downloadMap.lastFrameMap[key].data.byteLength;- delete map[key];+ delete downloadMap.lastFrameMap[key];};-const ensureMaxSize = () => {+const ensureMaxSize = (downloadMap: DownloadMap) => {// eslint-disable-next-line no-unmodified-loop-conditionwhile (bufferSize > MAX_CACHE_SIZE) {- const earliest = Object.entries(map).sort((a, b) => {+ const earliest = Object.entries(downloadMap.lastFrameMap).sort((a, b) => {return a[1].lastAccessed - b[1].lastAccessed;})[0];- removedLastFrameFromCache(earliest[0]);+ removedLastFrameFromCache(earliest[0], downloadMap);}};-export const clearLastFileCache = () => {- map = {};+export const clearLastFileCache = (downloadMap: DownloadMap) => {+ downloadMap.lastFrameMap = {};};diff --git a/packages/renderer/src/offthread-video-server.ts b/packages/renderer/src/offthread-video-server.tsindex f7c4af0a31..434819d9fe 100644--- a/packages/renderer/src/offthread-video-server.ts+++ b/packages/renderer/src/offthread-video-server.ts@@ -91,6 +91,7 @@ export const startOffthreadVideoServer = ({ffmpegExecutable,ffprobeExecutable,imageFormat,+ downloadMap,}),new Promise((_, rej) => {setTimeout(diff --git a/packages/renderer/src/test/extract-frame-from-video.test.ts b/packages/renderer/src/test/extract-frame-from-video.test.tsindex abe53c1a6f..8da0a80ece 100644--- a/packages/renderer/src/test/extract-frame-from-video.test.ts+++ b/packages/renderer/src/test/extract-frame-from-video.test.ts@@ -1,5 +1,6 @@import path from 'path';import {expect, test} from 'vitest';+import {makeDownloadMap} from '../assets/download-and-map-assets-to-file';import {extractFrameFromVideo} from '../extract-frame-from-video';const src = path.join(@@ -19,6 +20,7 @@ test('Should be able to extract a frame from a video', async () => {src,time: 1,imageFormat: 'jpeg',+ downloadMap: makeDownloadMap(),});expect(str.length).toBeGreaterThan(10000);@@ -31,6 +33,7 @@ test('Should be able to extract a frame from a video as PNG', async () => {src,time: 1,imageFormat: 'png',+ downloadMap: makeDownloadMap(),});expect(str.length).toBeGreaterThan(10000);@@ -43,6 +46,7 @@ test('Should get the last frame if out of range', async () => {src,time: 100,imageFormat: 'jpeg',+ downloadMap: makeDownloadMap(),});expect(str.length).toBeGreaterThan(10000);diff --git a/packages/renderer/src/test/get-last-frame-of-corrupted-video.test.ts b/packages/renderer/src/test/get-last-frame-of-corrupted-video.test.tsindex 92a26e5708..d72be4f151 100644--- a/packages/renderer/src/test/get-last-frame-of-corrupted-video.test.ts+++ b/packages/renderer/src/test/get-last-frame-of-corrupted-video.test.ts@@ -1,5 +1,6 @@import path from 'path';import {test} from 'vitest';+import {makeDownloadMap} from '../assets/download-and-map-assets-to-file';import {getLastFrameOfVideo} from '../extract-frame-from-video';test('Get last frame of corrupted video', async () => {@@ -19,5 +20,6 @@ test('Get last frame of corrupted video', async () => {imageFormat: 'png',specialVCodecForTransparency: 'none',needsResize: null,+ downloadMap: makeDownloadMap(),});}, 90000);diff --git a/packages/renderer/src/test/last-frame-video-cache.test.ts b/packages/renderer/src/test/last-frame-video-cache.test.tsindex 64d16d3537..d91dd62a16 100644--- a/packages/renderer/src/test/last-frame-video-cache.test.ts+++ b/packages/renderer/src/test/last-frame-video-cache.test.ts@@ -1,5 +1,7 @@import crypto from 'crypto';+import type {DownloadMap} from 'remotion';import {expect, test} from 'vitest';+import {makeDownloadMap} from '../assets/download-and-map-assets-to-file';import type {LastFrameOptions} from '../last-frame-from-video-cache';import {clearLastFileCache,@@ -7,7 +9,7 @@ import {setLastFrameInCache,} from '../last-frame-from-video-cache';-const makeKey = (id: string): LastFrameOptions => {+const makeKey = (id: string, downloadMap: DownloadMap): LastFrameOptions => {return {ffmpegExecutable: null,ffprobeExecutable: null,@@ -16,39 +18,43 @@ const makeKey = (id: string): LastFrameOptions => {imageFormat: 'jpeg',specialVCodecForTransparency: 'none',needsResize: null,+ downloadMap,};};test('Last frame video cache', () => {- expect(getLastFrameFromCache(makeKey('1'))).toBe(null);+ const downloadMap = makeDownloadMap();+ expect(getLastFrameFromCache(makeKey('1', downloadMap))).toBe(null);const buf = crypto.randomBytes(10 * 1024 * 1024);- setLastFrameInCache(makeKey('1'), buf);- expect(getLastFrameFromCache(makeKey('1'))?.byteLength).toBe(+ setLastFrameInCache(makeKey('1', downloadMap), buf);+ expect(getLastFrameFromCache(makeKey('1', downloadMap))?.byteLength).toBe(10 * 1024 * 1024);- setLastFrameInCache(makeKey('2'), buf);- setLastFrameInCache(makeKey('3'), buf);- setLastFrameInCache(makeKey('4'), buf);- setLastFrameInCache(makeKey('5'), buf);- setLastFrameInCache(makeKey('6'), buf);+ setLastFrameInCache(makeKey('2', downloadMap), buf);+ setLastFrameInCache(makeKey('3', downloadMap), buf);+ setLastFrameInCache(makeKey('4', downloadMap), buf);+ setLastFrameInCache(makeKey('5', downloadMap), buf);+ setLastFrameInCache(makeKey('6', downloadMap), buf);- expect(getLastFrameFromCache(makeKey('1'))?.byteLength ?? 0).toBe(0);- expect(getLastFrameFromCache(makeKey('2'))?.byteLength).toBe(+ expect(+ getLastFrameFromCache(makeKey('1', downloadMap))?.byteLength ?? 0+ ).toBe(0);+ expect(getLastFrameFromCache(makeKey('2', downloadMap))?.byteLength).toBe(10 * 1024 * 1024);- expect(getLastFrameFromCache(makeKey('3'))?.byteLength).toBe(+ expect(getLastFrameFromCache(makeKey('3', downloadMap))?.byteLength).toBe(10 * 1024 * 1024);- expect(getLastFrameFromCache(makeKey('4'))?.byteLength).toBe(+ expect(getLastFrameFromCache(makeKey('4', downloadMap))?.byteLength).toBe(10 * 1024 * 1024);- expect(getLastFrameFromCache(makeKey('5'))?.byteLength).toBe(+ expect(getLastFrameFromCache(makeKey('5', downloadMap))?.byteLength).toBe(10 * 1024 * 1024);- expect(getLastFrameFromCache(makeKey('6'))?.byteLength).toBe(+ expect(getLastFrameFromCache(makeKey('6', downloadMap))?.byteLength).toBe(10 * 1024 * 1024);- clearLastFileCache();+ clearLastFileCache(downloadMap);});