🎥 Make videos programmatically with React
`@remotion/studio`: Persist timeline waveforms and thumbnails across reloads
JonnyBurgere3ed7b693412
diff --git a/packages/studio/src/components/Timeline/TimelineVideoInfo.tsx b/packages/studio/src/components/Timeline/TimelineVideoInfo.tsxindex 6c617b84c8..63c00c1e63 100644--- a/packages/studio/src/components/Timeline/TimelineVideoInfo.tsx+++ b/packages/studio/src/components/Timeline/TimelineVideoInfo.tsx@@ -10,10 +10,12 @@ import {getFrameDatabaseKeyPrefix,getLoopDisplaySegments,getTimestampFromFrameDatabaseKey,+ hydrateThumbnailsFromPersistentCache,makeFrameDatabaseKey,resizeVideoFrame,snapCanvasPositionToDevicePixel,WEBCODECS_TIMESCALE,+ writeThumbnailToPersistentCache,} from '@remotion/timeline-utils';import React, {useLayoutEffect, useMemo, useRef, useState} from 'react';import type {LoopDisplay} from 'remotion';@@ -117,6 +119,7 @@ const TimelineVideoInfoSegment: React.FC<{}const controller = new AbortController();+ let mediaDurationInSeconds: number | null = null;const pixelRatio = getStudioPixelRatio();const {horizontalOffset} = alignCanvasToDevicePixels({canvas,@@ -196,57 +199,87 @@ const TimelineVideoInfoSegment: React.FC<{return;}- extractFrames({- repeatLastFrame: extendLastFrame,- timestampsInSeconds: ({- track,- }: {- track: {height: number; width: number};- }) => {- aspectRatio.current = track.width / track.height;- aspectRatioCache.set(src, aspectRatio.current);-- return [times.timestampInSeconds];- },- src: resolvedSrc,- onVideoSample: (sample) => {- let frame: VideoFrame | undefined;- try {- frame = sample.toVideoFrame();- const scale = canvas.height / frame.displayHeight;-- const transformed = resizeVideoFrame({- frame,- scale,- });-- if (transformed !== frame) {- frame.close();- }-- frame = undefined;-- const databaseKey = makeFrameDatabaseKey(- src,- transformed.timestamp,- );-- addFrameToCache(databaseKey, transformed);- drawRepeatedFrame(transformed);- } catch (e) {- if (frame) {- frame.close();- }+ hydrateThumbnailsFromPersistentCache({+ src,+ height: canvas.height,+ getTimestamps: () => [timestamp],+ })+ .then(() => {+ if (controller.signal.aborted) {+ return;+ }- throw e;- } finally {- sample.close();+ const persistedFrame = getCachedFrozenFrame(timestamp);+ if (persistedFrame) {+ drawRepeatedFrame(persistedFrame);+ return;}- },- signal: controller.signal,- }).catch((e: unknown) => {- setError(e as Error);- });++ return extractFrames({+ repeatLastFrame: extendLastFrame,+ timestampsInSeconds: ({+ track,+ durationInSeconds,+ }: {+ track: {height: number; width: number};+ durationInSeconds: number | null;+ }) => {+ aspectRatio.current = track.width / track.height;+ aspectRatioCache.set(src, aspectRatio.current);+ mediaDurationInSeconds = durationInSeconds;++ return [times.timestampInSeconds];+ },+ src: resolvedSrc,+ onVideoSample: (sample) => {+ let frame: VideoFrame | undefined;+ try {+ frame = sample.toVideoFrame();+ const scale = canvas.height / frame.displayHeight;++ const transformed = resizeVideoFrame({+ frame,+ scale,+ });++ if (transformed !== frame) {+ frame.close();+ }++ frame = undefined;++ const databaseKey = makeFrameDatabaseKey(+ src,+ transformed.timestamp,+ );++ addFrameToCache(databaseKey, transformed);+ if (aspectRatio.current !== null) {+ writeThumbnailToPersistentCache({+ src,+ frame: transformed,+ aspectRatio: aspectRatio.current,+ durationInSeconds: mediaDurationInSeconds,+ });+ }++ drawRepeatedFrame(transformed);+ } catch (e) {+ if (frame) {+ frame.close();+ }++ throw e;+ } finally {+ sample.close();+ }+ },+ signal: controller.signal,+ });+ })+ .catch((e: unknown) => {+ setError(e as Error);+ });return () => {controller.abort();@@ -307,7 +340,12 @@ const TimelineVideoInfoSegment: React.FC<{ctx.fillRect(0, 0, canvas.width, canvas.height);};- if (aspectRatio.current !== null) {+ // Returns whether every slot could be filled with a frame from memory.+ const fillWithFramesInMemory = () => {+ if (aspectRatio.current === null) {+ return false;+ }+ensureSlots({filledSlots,naturalWidth: targetWidth,@@ -329,89 +367,164 @@ const TimelineVideoInfoSegment: React.FC<{horizontalOffset: frameDrawOffset,});repeatTarget();- const unfilled = Array.from(filledSlots.keys()).filter(- (timestamp) => filledSlots.get(timestamp) === undefined,++ return Array.from(filledSlots.values()).every(+ (filled) => filled !== undefined,);+ };- // Don't extract frames if all slots are filled- if (unfilled.length === 0) {- return;- }+ // Don't extract frames if all slots are filled+ if (fillWithFramesInMemory()) {+ return;}- extractFrames({- repeatLastFrame: extendLastFrame,- timestampsInSeconds: ({- track,- }: {- track: {height: number; width: number};- }) => {- aspectRatio.current = track.width / track.height;- aspectRatioCache.set(src, aspectRatio.current);+ hydrateThumbnailsFromPersistentCache({+ src,+ height: canvas.height,+ getTimestamps: () => {+ // A persisted source also restores its aspect ratio.+ if (aspectRatio.current === null) {+ aspectRatio.current = getAspectRatioFromCache(src);+ }++ if (aspectRatio.current === null) {+ return [];+ }ensureSlots({filledSlots,+ naturalWidth: targetWidth,fromSeconds,toSeconds,- naturalWidth: targetWidth,aspectRatio: aspectRatio.current,frameHeight: canvas.height,});- fillWithCachedFrames({- ctx: targetCtx,- naturalWidth: targetWidth,- filledSlots,- src,- segmentDuration: toSeconds - fromSeconds,- fromSeconds,- devicePixelRatio: 1,- frameHeight: canvas.height,- horizontalOffset: frameDrawOffset,- });- repeatTarget();-- return Array.from(filledSlots.keys())- .filter((timestamp) => filledSlots.get(timestamp) === undefined)- .map((timestamp) => timestamp / WEBCODECS_TIMESCALE);+ return Array.from(filledSlots.keys());},- src: resolvedSrc,- onVideoSample: (sample) => {- let frame: VideoFrame | undefined;- try {- frame = sample.toVideoFrame();- const scale = canvas.height / frame.displayHeight;-- const transformed = resizeVideoFrame({- frame,- scale,- });-- if (transformed !== frame) {- frame.close();- }-- frame = undefined;+ })+ .then(() => {+ if (controller.signal.aborted) {+ return;+ }- const databaseKey = makeFrameDatabaseKey(src, transformed.timestamp);+ if (fillWithFramesInMemory()) {+ return;+ }- addFrameToCache(databaseKey, transformed);- if (aspectRatio.current === null) {- throw new Error('Aspect ratio is not set');+ return extractFrames({+ repeatLastFrame: extendLastFrame,+ timestampsInSeconds: ({+ track,+ durationInSeconds,+ }: {+ track: {height: number; width: number};+ durationInSeconds: number | null;+ }) => {+ aspectRatio.current = track.width / track.height;+ aspectRatioCache.set(src, aspectRatio.current);+ mediaDurationInSeconds = durationInSeconds;++ ensureSlots({+ filledSlots,+ fromSeconds,+ toSeconds,+ naturalWidth: targetWidth,+ aspectRatio: aspectRatio.current,+ frameHeight: canvas.height,+ });+ fillWithCachedFrames({+ ctx: targetCtx,+ naturalWidth: targetWidth,+ filledSlots,+ src,+ segmentDuration: toSeconds - fromSeconds,+ fromSeconds,+ devicePixelRatio: 1,+ frameHeight: canvas.height,+ horizontalOffset: frameDrawOffset,+ });+ repeatTarget();++ return Array.from(filledSlots.keys())+ .filter((timestamp) => filledSlots.get(timestamp) === undefined)+ .map((timestamp) => timestamp / WEBCODECS_TIMESCALE);+ },+ src: resolvedSrc,+ onVideoSample: (sample) => {+ let frame: VideoFrame | undefined;+ try {+ frame = sample.toVideoFrame();+ const scale = canvas.height / frame.displayHeight;++ const transformed = resizeVideoFrame({+ frame,+ scale,+ });++ if (transformed !== frame) {+ frame.close();+ }++ frame = undefined;++ const databaseKey = makeFrameDatabaseKey(+ src,+ transformed.timestamp,+ );++ addFrameToCache(databaseKey, transformed);+ if (aspectRatio.current === null) {+ throw new Error('Aspect ratio is not set');+ }++ writeThumbnailToPersistentCache({+ src,+ frame: transformed,+ aspectRatio: aspectRatio.current,+ durationInSeconds: mediaDurationInSeconds,+ });++ ensureSlots({+ filledSlots,+ fromSeconds,+ toSeconds,+ naturalWidth: targetWidth,+ aspectRatio: aspectRatio.current,+ frameHeight: canvas.height,+ });+ fillFrameWhereItFits({+ ctx: targetCtx,+ filledSlots,+ visualizationWidth: targetWidth,+ frame: transformed,+ segmentDuration: toSeconds - fromSeconds,+ fromSeconds,+ devicePixelRatio: 1,+ frameHeight: canvas.height,+ horizontalOffset: frameDrawOffset,+ });+ repeatTarget();+ } catch (e) {+ if (frame) {+ frame.close();+ }++ throw e;+ } finally {+ sample.close();+ }+ },+ signal: controller.signal,+ }).then(() => {+ if (controller.signal.aborted) {+ return;}- ensureSlots({- filledSlots,- fromSeconds,- toSeconds,- naturalWidth: targetWidth,- aspectRatio: aspectRatio.current,- frameHeight: canvas.height,- });- fillFrameWhereItFits({+ fillWithCachedFrames({ctx: targetCtx,+ naturalWidth: targetWidth,filledSlots,- visualizationWidth: targetWidth,- frame: transformed,+ src,segmentDuration: toSeconds - fromSeconds,fromSeconds,devicePixelRatio: 1,@@ -419,35 +532,7 @@ const TimelineVideoInfoSegment: React.FC<{horizontalOffset: frameDrawOffset,});repeatTarget();- } catch (e) {- if (frame) {- frame.close();- }-- throw e;- } finally {- sample.close();- }- },- signal: controller.signal,- })- .then(() => {- if (controller.signal.aborted) {- return;- }-- fillWithCachedFrames({- ctx: targetCtx,- naturalWidth: targetWidth,- filledSlots,- src,- segmentDuration: toSeconds - fromSeconds,- fromSeconds,- devicePixelRatio: 1,- frameHeight: canvas.height,- horizontalOffset: frameDrawOffset,});- repeatTarget();}).catch((e: unknown) => {setError(e as Error);diff --git a/packages/studio/src/helpers/use-menu-structure.tsx b/packages/studio/src/helpers/use-menu-structure.tsxindex 192e3e896f..e2ff6a99f9 100644--- a/packages/studio/src/helpers/use-menu-structure.tsx+++ b/packages/studio/src/helpers/use-menu-structure.tsx@@ -1,4 +1,5 @@import type {EditorPickerId} from '@remotion/studio-shared';+import {clearPersistentTimelineCache} from '@remotion/timeline-utils';import {useContext, useEffect, useMemo} from 'react';import type {ResolvedStackLocation, _InternalTypes} from 'remotion';import {Internals} from 'remotion';@@ -937,6 +938,32 @@ const useMenuStructureBase = ({subMenu: null,quickSwitcherLabel: `Install package...`,},+ {+ id: 'clear-timeline-cache',+ value: 'clear-timeline-cache',+ label: 'Clear timeline cache',+ onClick: () => {+ closeMenu();+ clearPersistentTimelineCache()+ .then(() => {+ showNotification(+ 'Cleared cached waveforms and thumbnails',+ 2000,+ );+ })+ .catch((err) => {+ showNotification(+ `Could not clear timeline cache: ${(err as Error).message}`,+ 2000,+ );+ });+ },+ type: 'item' as const,+ keyHint: null,+ leftItem: null,+ subMenu: null,+ quickSwitcherLabel: 'Clear timeline cache',+ },].filter(Internals.truthy),quickSwitcherLabel: null,},diff --git a/packages/timeline-utils/src/audio-waveform/subscribe-to-waveform-peaks.ts b/packages/timeline-utils/src/audio-waveform/subscribe-to-waveform-peaks.tsindex 6d3f1b549c..a87d0149e1 100644--- a/packages/timeline-utils/src/audio-waveform/subscribe-to-waveform-peaks.ts+++ b/packages/timeline-utils/src/audio-waveform/subscribe-to-waveform-peaks.ts@@ -1,4 +1,8 @@import type {InputAudioTrack} from 'mediabunny';+import {+ readWaveformFromPersistentCache,+ writeWaveformToPersistentCache,+} from '../persistent-cache/persistent-cache';import type {AudioWaveformWorkerLoadMessage,AudioWaveformWorkerOutgoingMessage,@@ -72,6 +76,16 @@ const emitError = (load: InFlightLoad, error: Error) => {}};+const persistWaveform = (load: InFlightLoad, result: WaveformResult) => {+ if (typeof load.src === 'string') {+ writeWaveformToPersistentCache({+ src: load.src,+ waveformSampleRate: load.waveformSampleRate,+ result,+ });+ }+};+const startMainThreadLoad = (load: InFlightLoad) => {load.requestId = null;@@ -101,6 +115,7 @@ const startMainThreadLoad = (load: InFlightLoad) => {}).then((result) => {emitPeaks(load, result, true);+ persistWaveform(load, result);}).catch((error) => {emitError(@@ -155,6 +170,9 @@ const getOrCreateWorker = (): Worker | null => {}emitPeaks(load, message, message.final);+ if (message.final) {+ persistWaveform(load, message);+ }},);worker.addEventListener('error', (event) => {@@ -211,18 +229,33 @@ export const subscribeToWaveformPeaks = ({};inFlightByCacheKey.set(cacheKey, load);- const workerInstance = typeof src === 'string' ? getOrCreateWorker() : null;- if (workerInstance && typeof src === 'string') {- const requestId = nextRequestId++;- load.requestId = requestId;- inFlightByRequestId.set(requestId, load);- const message: AudioWaveformWorkerLoadMessage = {- type: 'load',- requestId,- src,- waveformSampleRate,- };- workerInstance.postMessage(message);+ if (typeof src === 'string') {+ // Peaks persisted by a previous page load skip fetching and decoding.+ readWaveformFromPersistentCache({src, waveformSampleRate}).then(+ (persisted) => {+ if (persisted) {+ emitPeaks(load, persisted, true);+ return;+ }++ const workerInstance = getOrCreateWorker();+ if (!workerInstance) {+ startMainThreadLoad(load);+ return;+ }++ const requestId = nextRequestId++;+ load.requestId = requestId;+ inFlightByRequestId.set(requestId, load);+ const message: AudioWaveformWorkerLoadMessage = {+ type: 'load',+ requestId,+ src,+ waveformSampleRate,+ };+ workerInstance.postMessage(message);+ },+ );} else {startMainThreadLoad(load);}diff --git a/packages/timeline-utils/src/index.ts b/packages/timeline-utils/src/index.tsindex e6fb4f6474..4e445f9df5 100644--- a/packages/timeline-utils/src/index.ts+++ b/packages/timeline-utils/src/index.ts@@ -43,6 +43,11 @@ export {shouldTileLoopDisplay,} from './loop-display';export type {LoopDisplaySegment, TimelineLoopDisplay} from './loop-display';+export {+ clearPersistentTimelineCache,+ hydrateThumbnailsFromPersistentCache,+ writeThumbnailToPersistentCache,+} from './persistent-cache/persistent-cache';export {WEBCODECS_TIMESCALE,calculateTimestampSlots,diff --git a/packages/timeline-utils/src/persistent-cache/persistent-cache.ts b/packages/timeline-utils/src/persistent-cache/persistent-cache.tsnew file mode 100644index 0000000000..8074627d06--- /dev/null+++ b/packages/timeline-utils/src/persistent-cache/persistent-cache.ts@@ -0,0 +1,693 @@+import type {WaveformResult} from '../audio-waveform/load-waveform-peaks';+import {getWaveformMaxima} from '../audio-waveform/waveform-maxima';+import {+ addFrameToCache,+ aspectRatioCache,+ frameDatabase,+ makeFrameDatabaseKey,+} from '../frame-database';+import {MAX_TIME_DEVIATION, WEBCODECS_TIMESCALE} from '../render-frame-strip';+import {+ dequantizeWaveformPeaks,+ quantizeWaveformPeaks,+} from './quantize-waveform-peaks';++// Bump when the stored data or the way it is computed changes.+// Opening the database with a newer version wipes all stores.+const SCHEMA_VERSION = 1;+const DATABASE_NAME = 'remotion-timeline-cache';+const MAX_TOTAL_BYTES = 256 * 1024 * 1024;+const EVICT_TO_BYTES = 200 * 1024 * 1024;+const MAX_THUMBNAIL_BYTES_PER_SOURCE = 16 * 1024 * 1024;+const MAX_UNUSED_AGE_MS = 30 * 24 * 60 * 60 * 1000;+// Remote sources without ETag or Last-Modified cannot be revalidated.+const MAX_AGE_WITHOUT_VALIDATOR_MS = 7 * 24 * 60 * 60 * 1000;+const THUMBNAIL_FLUSH_DELAY_MS = 1000;+const EVICTION_DELAY_MS = 5000;++type SourceRecord = {+ readonly src: string;+ readonly fingerprint: string;+ readonly createdAt: number;+ readonly lastAccessedAt: number;+ readonly aspectRatio: number | null;+ readonly durationInSeconds: number | null;+ readonly waveformBytes: number;+ readonly thumbnailBytes: number;+};++type WaveformRecord = {+ readonly src: string;+ readonly waveformSampleRate: number;+ readonly peaks: Uint8Array;+ readonly averageVolume: number | null;+};++type ThumbnailRecord = {+ readonly src: string;+ readonly height: number;+ readonly timestamp: number;+ readonly duration: number | null;+ readonly createdAt: number;+ readonly image: Blob;+};++type Fingerprint = {+ readonly value: string;+ readonly maxAgeMs: number | null;+};++type PendingThumbnail = {+ readonly src: string;+ readonly aspectRatio: number;+ readonly durationInSeconds: number | null;+ readonly height: number;+ readonly timestamp: number;+ readonly duration: number | null;+ readonly image: Promise<Blob>;+};++const ALL_STORES = ['sources', 'waveforms', 'thumbnails'];++let databasePromise: Promise<IDBDatabase | null> | null = null;+const remoteFingerprints = new Map<string, Promise<Fingerprint | null>>();+const preparedSources = new Map<string, Promise<IDBDatabase | null>>();+let pendingThumbnails: PendingThumbnail[] = [];+let thumbnailFlushTimeout: ReturnType<typeof setTimeout> | null = null;+let evictionTimeout: ReturnType<typeof setTimeout> | null = null;++const toPromise = <T>(request: IDBRequest<T>) => {+ return new Promise<T>((resolve, reject) => {+ request.onsuccess = () => resolve(request.result);+ request.onerror = () => reject(request.error);+ });+};++const transactionDone = (transaction: IDBTransaction) => {+ return new Promise<void>((resolve, reject) => {+ transaction.oncomplete = () => resolve();+ transaction.onerror = () => reject(transaction.error);+ transaction.onabort = () => reject(transaction.error);+ });+};++// Sorts after every [src, ...] key, since arrays sort after numbers.+const getSourceKeyRange = (src: string) => IDBKeyRange.bound([src], [src, []]);++const deleteSourceData = (transaction: IDBTransaction, src: string) => {+ transaction.objectStore('sources').delete(src);+ transaction.objectStore('waveforms').delete(getSourceKeyRange(src));+ transaction.objectStore('thumbnails').delete(getSourceKeyRange(src));+};++const openDatabase = (): Promise<IDBDatabase | null> => {+ if (databasePromise) {+ return databasePromise;+ }++ databasePromise = new Promise((resolve) => {+ if (typeof indexedDB === 'undefined') {+ resolve(null);+ return;+ }++ const request = indexedDB.open(DATABASE_NAME, SCHEMA_VERSION);+ request.onupgradeneeded = () => {+ const database = request.result;+ for (const name of Array.from(database.objectStoreNames)) {+ database.deleteObjectStore(name);+ }++ database.createObjectStore('sources', {keyPath: 'src'});+ database.createObjectStore('waveforms', {+ keyPath: ['src', 'waveformSampleRate'],+ });+ database+ .createObjectStore('thumbnails', {+ keyPath: ['src', 'height', 'timestamp'],+ })+ .createIndex('createdAt', ['src', 'createdAt']);+ };++ request.onsuccess = () => {+ const database = request.result;+ // Let a tab with a newer schema version upgrade the database.+ database.onversionchange = () => {+ database.close();+ databasePromise = null;+ preparedSources.clear();+ };++ resolve(database);+ };++ request.onerror = () => resolve(null);+ });++ return databasePromise;+};++const getFingerprint = (src: string): Promise<Fingerprint | null> => {+ if (src.startsWith('blob:') || src.startsWith('data:')) {+ return Promise.resolve(null);+ }++ // The Studio knows size and modification time of public folder files,+ // so they can be validated without a request.+ const staticFile =+ typeof window === 'undefined'+ ? undefined+ : window.remotion_staticFiles?.find((file) => file.src === src);+ if (staticFile) {+ return Promise.resolve({+ value: `static:${staticFile.sizeInBytes}:${staticFile.lastModified}`,+ maxAgeMs: null,+ });+ }++ const existing = remoteFingerprints.get(src);+ if (existing) {+ return existing;+ }++ // A ranged GET instead of HEAD, because presigned URLs are only signed for GET.+ const promise = fetch(src, {headers: {Range: 'bytes=0-0'}, cache: 'no-store'})+ .then((response): Fingerprint | null => {+ response.body?.cancel().catch(() => undefined);+ if (!response.ok) {+ return null;+ }++ const etag = response.headers.get('etag');+ const lastModified = response.headers.get('last-modified');+ if (etag === null && lastModified === null) {+ return {+ value: 'unvalidated',+ maxAgeMs: MAX_AGE_WITHOUT_VALIDATOR_MS,+ };+ }++ return {value: `remote:${etag}:${lastModified}`, maxAgeMs: null};+ })+ .catch(() => null);+ remoteFingerprints.set(src, promise);+ return promise;+};++// 'budget' keeps the cache below its size limit, 'halve' makes room after+// the browser rejected a write because the origin ran out of quota.+const evict = async (mode: 'budget' | 'halve') => {+ const database = await openDatabase();+ if (!database) {+ return;+ }++ const sources: SourceRecord[] = await toPromise(+ database.transaction('sources').objectStore('sources').getAll(),+ );++ // Long videos scrolled at a deep zoom level can produce a lot of+ // thumbnails. Drop the oldest ones of a source first.+ for (const {src, thumbnailBytes} of sources) {+ if (thumbnailBytes <= MAX_THUMBNAIL_BYTES_PER_SOURCE) {+ continue;+ }++ const trimTransaction = database.transaction(+ ['sources', 'thumbnails'],+ 'readwrite',+ );+ const source: SourceRecord | undefined = await toPromise(+ trimTransaction.objectStore('sources').get(src),+ );+ if (!source) {+ continue;+ }++ let bytes = source.thumbnailBytes;+ await new Promise<void>((resolve, reject) => {+ const request = trimTransaction+ .objectStore('thumbnails')+ .index('createdAt')+ .openCursor(getSourceKeyRange(src));+ request.onsuccess = () => {+ const cursor = request.result;+ if (!cursor || bytes <= MAX_THUMBNAIL_BYTES_PER_SOURCE * 0.75) {+ resolve();+ return;+ }++ bytes -= (cursor.value as ThumbnailRecord).image.size;+ cursor.delete();+ cursor.continue();+ };++ request.onerror = () => reject(request.error);+ });+ trimTransaction+ .objectStore('sources')+ .put({...source, thumbnailBytes: bytes} satisfies SourceRecord);+ await transactionDone(trimTransaction);+ }++ const transaction = database.transaction(ALL_STORES, 'readwrite');+ const current: SourceRecord[] = await toPromise(+ transaction.objectStore('sources').getAll(),+ );+ let totalBytes = current.reduce(+ (sum, source) => sum + source.waveformBytes + source.thumbnailBytes,+ 0,+ );+ const targetBytes =+ mode === 'halve'+ ? totalBytes / 2+ : totalBytes > MAX_TOTAL_BYTES+ ? EVICT_TO_BYTES+ : Infinity;+ const now = Date.now();+ const leastRecentlyUsedFirst = current.sort(+ (a, b) => a.lastAccessedAt - b.lastAccessedAt,+ );+ for (const source of leastRecentlyUsedFirst) {+ if (+ totalBytes <= targetBytes &&+ now - source.lastAccessedAt <= MAX_UNUSED_AGE_MS+ ) {+ break;+ }++ totalBytes -= source.waveformBytes + source.thumbnailBytes;+ deleteSourceData(transaction, source.src);+ }++ await transactionDone(transaction);+};++const scheduleEviction = () => {+ if (evictionTimeout !== null) {+ return;+ }++ evictionTimeout = setTimeout(() => {+ evictionTimeout = null;+ const run = () => evict('budget').catch(() => undefined);+ // Tabs share the database, one eviction pass at a time is enough.+ if (typeof navigator !== 'undefined' && navigator.locks) {+ navigator.locks+ .request(+ 'remotion-timeline-cache-eviction',+ {ifAvailable: true},+ (lock) => (lock ? run() : undefined),+ )+ .catch(() => undefined);+ return;+ }++ run();+ }, EVICTION_DELAY_MS);+};++// Resolves to the database if cached data for `src` may be read and written.+// Purges the data of a source that has changed since it was cached.+const getDatabaseForSource = async (+ src: string,+): Promise<IDBDatabase | null> => {+ // Avoid the fingerprint request if there is no database to use it with.+ const database = await openDatabase();+ if (!database) {+ return null;+ }++ const fingerprint = await getFingerprint(src);+ if (!fingerprint) {+ return null;+ }++ const key = `${fingerprint.value}|${src}`;+ const existing = preparedSources.get(key);+ if (existing) {+ return existing;+ }++ const promise = (async () => {+ const transaction = database.transaction(ALL_STORES, 'readwrite');+ const sources = transaction.objectStore('sources');+ const source: SourceRecord | undefined = await toPromise(sources.get(src));+ const now = Date.now();+ const stale =+ source !== undefined &&+ (source.fingerprint !== fingerprint.value ||+ (fingerprint.maxAgeMs !== null &&+ now - source.createdAt > fingerprint.maxAgeMs));+ if (stale) {+ deleteSourceData(transaction, src);+ }++ const record: SourceRecord =+ source && !stale+ ? {...source, lastAccessedAt: now}+ : {+ src,+ fingerprint: fingerprint.value,+ createdAt: now,+ lastAccessedAt: now,+ aspectRatio: null,+ durationInSeconds: null,+ waveformBytes: 0,+ thumbnailBytes: 0,+ };+ sources.put(record);+ await transactionDone(transaction);++ if (record.aspectRatio !== null && !aspectRatioCache.has(src)) {+ aspectRatioCache.set(src, record.aspectRatio);+ }++ scheduleEviction();+ return database;+ })().catch(() => null);+ preparedSources.set(key, promise);+ return promise;+};++const onWriteError = (error: unknown) => {+ if (error instanceof DOMException && error.name === 'QuotaExceededError') {+ evict('halve').catch(() => undefined);+ }+};++export const readWaveformFromPersistentCache = async ({+ src,+ waveformSampleRate,+}: {+ readonly src: string;+ readonly waveformSampleRate: number;+}): Promise<WaveformResult | null> => {+ try {+ const database = await getDatabaseForSource(src);+ if (!database) {+ return null;+ }++ const record: WaveformRecord | undefined = await toPromise(+ database+ .transaction('waveforms')+ .objectStore('waveforms')+ .get([src, waveformSampleRate]),+ );+ if (!record) {+ return null;+ }++ const peaks = dequantizeWaveformPeaks(record.peaks);+ return {+ peaks,+ maxima: getWaveformMaxima(peaks, null),+ averageVolume: record.averageVolume,+ };+ } catch {+ return null;+ }+};++export const writeWaveformToPersistentCache = ({+ src,+ waveformSampleRate,+ result,+}: {+ readonly src: string;+ readonly waveformSampleRate: number;+ readonly result: WaveformResult;+}) => {+ (async () => {+ const database = await getDatabaseForSource(src);+ if (!database) {+ return;+ }++ const peaks = quantizeWaveformPeaks(result.peaks);+ const transaction = database.transaction(+ ['sources', 'waveforms'],+ 'readwrite',+ );+ const sources = transaction.objectStore('sources');+ const waveforms = transaction.objectStore('waveforms');+ const [source, existing] = await Promise.all([+ toPromise<SourceRecord | undefined>(sources.get(src)),+ toPromise<WaveformRecord | undefined>(+ waveforms.get([src, waveformSampleRate]),+ ),+ ]);+ // The source was evicted or the cache was cleared in the meantime.+ if (!source) {+ transaction.abort();+ return;+ }++ waveforms.put({+ src,+ waveformSampleRate,+ peaks,+ averageVolume: result.averageVolume,+ } satisfies WaveformRecord);+ sources.put({+ ...source,+ waveformBytes:+ source.waveformBytes -+ (existing?.peaks.byteLength ?? 0) ++ peaks.byteLength,+ } satisfies SourceRecord);+ await transactionDone(transaction);+ scheduleEviction();+ })().catch(onWriteError);+};++// Loads persisted thumbnails into the in-memory frame database, so the+// filmstrip can be drawn without decoding the video.+// Any frame in memory fills every slot of the filmstrip, so a partial set+// would prevent the missing frames from being decoded. Thumbnails are therefore+// only loaded if they cover all timestamps.+export const hydrateThumbnailsFromPersistentCache = async ({+ src,+ height,+ getTimestamps,+}: {+ readonly src: string;+ readonly height: number;+ // Called once the aspect ratio of a persisted source is restored.+ readonly getTimestamps: () => number[];+}): Promise<void> => {+ try {+ const database = await getDatabaseForSource(src);+ if (!database) {+ return;+ }++ const transaction = database.transaction(['sources', 'thumbnails']);+ const source: SourceRecord | undefined = await toPromise(+ transaction.objectStore('sources').get(src),+ );+ // Like extractFrames(), show the last frame for timestamps after the end.+ const durationInSeconds = source?.durationInSeconds ?? null;+ const lastTimestamp =+ durationInSeconds === null+ ? Infinity+ : durationInSeconds * WEBCODECS_TIMESCALE - 1;+ // Segments without a width produce slots that are not finite.+ const timestamps = getTimestamps()+ .filter((timestamp) => Number.isFinite(timestamp))+ .map((timestamp) => Math.min(timestamp, lastTimestamp));+ if (timestamps.length === 0) {+ return;+ }++ const from = Math.min(...timestamps) - MAX_TIME_DEVIATION;+ const to = Math.max(...timestamps) + MAX_TIME_DEVIATION;+ const store = transaction.objectStore('thumbnails');+ // A frame of a variable frame rate video can be shown long after its+ // timestamp, so the last frame before the range may cover it as well.+ const previousRequest = store.openCursor(+ IDBKeyRange.bound([src, height], [src, height, from], false, true),+ 'prev',+ );+ const recordsRequest = store.getAll(+ IDBKeyRange.bound([src, height, from], [src, height, to]),+ );+ const [previous, records] = await Promise.all([+ toPromise(previousRequest),+ toPromise<ThumbnailRecord[]>(recordsRequest),+ ]);+ const candidates: ThumbnailRecord[] = previous+ ? [previous.value, ...records]+ : records;++ const covering = new Set<ThumbnailRecord>();+ for (const timestamp of timestamps) {+ const record = candidates.find(+ (candidate) =>+ Math.abs(candidate.timestamp - timestamp) <= MAX_TIME_DEVIATION ||+ (candidate.timestamp <= timestamp &&+ timestamp < candidate.timestamp + (candidate.duration ?? 0)),+ );+ if (!record) {+ return;+ }++ covering.add(record);+ }++ await Promise.all(+ Array.from(covering).map(async (record) => {+ const key = makeFrameDatabaseKey(src, record.timestamp);+ if (frameDatabase.has(key)) {+ return;+ }++ const bitmap = await createImageBitmap(record.image);+ try {+ addFrameToCache(+ key,+ new VideoFrame(bitmap, {+ timestamp: record.timestamp,+ duration: record.duration ?? undefined,+ }),+ );+ } finally {+ bitmap.close();+ }+ }),+ );+ } catch {+ // The cache is best-effort, missing frames are decoded instead.+ }+};++const flushThumbnails = async () => {+ thumbnailFlushTimeout = null;+ const batch = pendingThumbnails;+ pendingThumbnails = [];++ // Clips with the same source extract the same frames. Deduplicate them, the+ // byte count would otherwise include every copy.+ const bySrc = new Map<string, Map<string, PendingThumbnail>>();+ for (const thumbnail of batch) {+ const thumbnails = bySrc.get(thumbnail.src) ?? new Map();+ thumbnails.set(`${thumbnail.height}:${thumbnail.timestamp}`, thumbnail);+ bySrc.set(thumbnail.src, thumbnails);+ }++ for (const [src, byKey] of bySrc) {+ const thumbnails = Array.from(byKey.values());+ try {+ const database = await getDatabaseForSource(src);+ if (!database) {+ continue;+ }++ // Encode before opening the transaction, it would commit while waiting.+ const images = await Promise.all(thumbnails.map((t) => t.image));+ const transaction = database.transaction(+ ['sources', 'thumbnails'],+ 'readwrite',+ );+ const sources = transaction.objectStore('sources');+ const store = transaction.objectStore('thumbnails');+ const source: SourceRecord | undefined = await toPromise(+ sources.get(src),+ );+ if (!source) {+ transaction.abort();+ continue;+ }++ const createdAt = Date.now();+ let {thumbnailBytes} = source;+ await Promise.all(+ thumbnails.map(async (thumbnail, i) => {+ const existing: ThumbnailRecord | undefined = await toPromise(+ store.get([src, thumbnail.height, thumbnail.timestamp]),+ );+ thumbnailBytes += images[i].size - (existing?.image.size ?? 0);+ store.put({+ src,+ height: thumbnail.height,+ timestamp: thumbnail.timestamp,+ duration: thumbnail.duration,+ createdAt,+ image: images[i],+ } satisfies ThumbnailRecord);+ }),+ );+ sources.put({+ ...source,+ aspectRatio: thumbnails[thumbnails.length - 1].aspectRatio,+ durationInSeconds: thumbnails[thumbnails.length - 1].durationInSeconds,+ thumbnailBytes,+ } satisfies SourceRecord);+ await transactionDone(transaction);+ } catch (error) {+ onWriteError(error);+ }+ }++ scheduleEviction();+};++// Copies the frame, so the caller may close it right away.+export const writeThumbnailToPersistentCache = ({+ src,+ frame,+ aspectRatio,+ durationInSeconds,+}: {+ readonly src: string;+ readonly frame: VideoFrame;+ readonly aspectRatio: number;+ readonly durationInSeconds: number | null;+}) => {+ if (typeof OffscreenCanvas === 'undefined') {+ return;+ }++ const canvas = new OffscreenCanvas(frame.displayWidth, frame.displayHeight);+ const ctx = canvas.getContext('2d');+ if (!ctx) {+ return;+ }++ ctx.drawImage(frame, 0, 0);+ // WebP keeps transparency and is small. Browsers that can't encode it fall+ // back to PNG, which is larger but still correct.+ const image = canvas.convertToBlob({type: 'image/webp', quality: 0.8});+ image.catch(() => undefined);+ pendingThumbnails.push({+ src,+ aspectRatio,+ durationInSeconds,+ height: frame.displayHeight,+ timestamp: frame.timestamp,+ duration: frame.duration,+ image,+ });++ if (thumbnailFlushTimeout === null) {+ thumbnailFlushTimeout = setTimeout(() => {+ flushThumbnails().catch(() => undefined);+ }, THUMBNAIL_FLUSH_DELAY_MS);+ }+};++export const clearPersistentTimelineCache = async () => {+ const database = await openDatabase();+ if (!database) {+ return;+ }++ const transaction = database.transaction(ALL_STORES, 'readwrite');+ for (const name of ALL_STORES) {+ transaction.objectStore(name).clear();+ }++ await transactionDone(transaction);+ preparedSources.clear();+};diff --git a/packages/timeline-utils/src/persistent-cache/quantize-waveform-peaks.ts b/packages/timeline-utils/src/persistent-cache/quantize-waveform-peaks.tsnew file mode 100644index 0000000000..a2513ffb0c--- /dev/null+++ b/packages/timeline-utils/src/persistent-cache/quantize-waveform-peaks.ts@@ -0,0 +1,49 @@+// Peaks are drawn on a decibel scale and can be boosted by the volume, so a+// linear 8-bit encoding would flatten quiet passages. Encoding in 1/3 dB steps+// keeps 0 dB exactly representable, from -72 dB (1) up to +12.67 dB (255).+// 0 is reserved for silence.+const MIN_DECIBELS = -72;+const STEPS_PER_DECIBEL = 3;+const FULL_SCALE_CODE = -MIN_DECIBELS * STEPS_PER_DECIBEL + 1;++const decodeTable = new Float32Array(256);+for (let code = 1; code < 256; code++) {+ decodeTable[code] =+ 10 ** ((MIN_DECIBELS + (code - 1) / STEPS_PER_DECIBEL) / 20);+}++export const quantizeWaveformPeaks = (peaks: Float32Array): Uint8Array => {+ const quantized = new Uint8Array(peaks.length);+ for (let i = 0; i < peaks.length; i++) {+ const peak = peaks[i];+ if (!(peak > 0)) {+ continue;+ }++ const code =+ Math.round((20 * Math.log10(peak) - MIN_DECIBELS) * STEPS_PER_DECIBEL) ++ 1;+ if (code < 1) {+ continue;+ }++ // Never round a peak across full scale, so clipping is still detected.+ quantized[i] =+ peak > 1+ ? Math.min(255, Math.max(FULL_SCALE_CODE + 1, code))+ : Math.min(FULL_SCALE_CODE, code);+ }++ return quantized;+};++export const dequantizeWaveformPeaks = (+ quantized: Uint8Array,+): Float32Array => {+ const peaks = new Float32Array(quantized.length);+ for (let i = 0; i < quantized.length; i++) {+ peaks[i] = decodeTable[quantized[i]];+ }++ return peaks;+};diff --git a/packages/timeline-utils/src/render-frame-strip.ts b/packages/timeline-utils/src/render-frame-strip.tsindex 4d467d0b6b..fd218c4f28 100644--- a/packages/timeline-utils/src/render-frame-strip.ts+++ b/packages/timeline-utils/src/render-frame-strip.ts@@ -7,7 +7,7 @@ import {} from './frame-database';export const WEBCODECS_TIMESCALE = 1_000_000;-const MAX_TIME_DEVIATION = WEBCODECS_TIMESCALE * 0.05;+export const MAX_TIME_DEVIATION = WEBCODECS_TIMESCALE * 0.05;export const getDurationOfOneFrame = ({visualizationWidth,