Skip to content

πŸŽ₯ Make videos programmatically with React

@remotion/studio: Cache timeline asset metadata (#7664)

Jonny Burgeraf9f493ec84f
diff --git a/packages/studio/src/components/CurrentAsset.tsx b/packages/studio/src/components/CurrentAsset.tsx
index c7aaffc2c1..153206104b 100644
--- a/packages/studio/src/components/CurrentAsset.tsx
+++ b/packages/studio/src/components/CurrentAsset.tsx
@@ -72,7 +72,10 @@ export const CurrentAsset: React.FC = () => {
}
if (mediaMetadata) {
- subtitleParts.push(mediaMetadata.format);
+ if (mediaMetadata.format) {
+ subtitleParts.push(mediaMetadata.format);
+ }
+
if (mediaMetadata.width !== null && mediaMetadata.height !== null) {
subtitleParts.push(`${mediaMetadata.width}x${mediaMetadata.height}`);
}
diff --git a/packages/studio/src/components/Timeline/TimelineMediaInfo.tsx b/packages/studio/src/components/Timeline/TimelineMediaInfo.tsx
index 86bff322d0..5af58cd142 100644
--- a/packages/studio/src/components/Timeline/TimelineMediaInfo.tsx
+++ b/packages/studio/src/components/Timeline/TimelineMediaInfo.tsx
@@ -170,7 +170,9 @@ export const TimelineMediaInfo: React.FC<{
}
const parts: string[] = [];
- parts.push(metadata.format);
+ if (metadata.format) {
+ parts.push(metadata.format);
+ }
if (type === 'video' && metadata.videoCodec) {
parts.push(metadata.videoCodec);
diff --git a/packages/studio/src/helpers/use-max-media-duration.ts b/packages/studio/src/helpers/use-max-media-duration.ts
index fa099f622f..65f7aa4888 100644
--- a/packages/studio/src/helpers/use-max-media-duration.ts
+++ b/packages/studio/src/helpers/use-max-media-duration.ts
@@ -1,11 +1,11 @@
-import {getVideoMetadata} from '@remotion/media-utils';
-import {ALL_FORMATS, Input, InputDisposedError, UrlSource} from 'mediabunny';
import {useEffect, useState} from 'react';
import {type TSequence} from 'remotion';
-import {getDurationOrCompute} from './get-duration-or-compute';
+import {getMediaMetadata} from './use-media-metadata';
const cache = new Map<string, number>();
+const getCacheKey = (src: string, fps: number) => JSON.stringify([src, fps]);
+
const getSrc = (s: TSequence) => {
if (s.type === 'video') {
return s.src;
@@ -20,48 +20,48 @@ const getSrc = (s: TSequence) => {
export const useMaxMediaDuration = (s: TSequence, fps: number) => {
const src = getSrc(s);
+ const cacheKey = src ? getCacheKey(src, fps) : null;
const [maxMediaDuration, setMaxMediaDuration] = useState(
- src ? (cache.get(src) ?? null) : Infinity,
+ cacheKey ? (cache.get(cacheKey) ?? null) : Infinity,
);
useEffect(() => {
- if (!src) {
+ if (!src || !cacheKey) {
+ return;
+ }
+
+ const cached = cache.get(cacheKey) ?? null;
+ setMaxMediaDuration(cached);
+
+ if (cached !== null) {
return;
}
- const input = new Input({
- formats: ALL_FORMATS,
- source: new UrlSource(src),
- });
+ let cancelled = false;
+
+ getMediaMetadata(src)
+ .then((metadata) => {
+ if (cancelled || !metadata) {
+ return;
+ }
- getDurationOrCompute(input)
- .then((duration) => {
- cache.set(src, Math.floor(duration * fps));
- setMaxMediaDuration(Math.floor(duration * fps));
+ const duration = Math.floor(metadata.duration * fps);
+ cache.set(cacheKey, duration);
+ setMaxMediaDuration(duration);
})
- .catch((e) => {
- if (e instanceof InputDisposedError) {
+ .catch(() => {
+ if (cancelled) {
return;
}
- // In case of CORS errors, fall back to getVideoMetadata
- return getVideoMetadata(src)
- .then((metadata) => {
- const durationOrInfinity = metadata.durationInSeconds ?? Infinity;
-
- cache.set(src, Math.floor(durationOrInfinity * fps));
- setMaxMediaDuration(Math.floor(durationOrInfinity * fps));
- })
- .catch(() => {
- // Silently handle getVideoMetadata failures to prevent unhandled rejections
- });
+ setMaxMediaDuration(null);
});
return () => {
- input.dispose();
+ cancelled = true;
};
- }, [src, fps]);
+ }, [cacheKey, fps, src]);
if (maxMediaDuration !== null && (s.type === 'audio' || s.type === 'video')) {
return maxMediaDuration;
diff --git a/packages/studio/src/helpers/use-media-metadata.ts b/packages/studio/src/helpers/use-media-metadata.ts
index 15f6844c0e..b01536eec7 100644
--- a/packages/studio/src/helpers/use-media-metadata.ts
+++ b/packages/studio/src/helpers/use-media-metadata.ts
@@ -1,94 +1,164 @@
+import {getVideoMetadata} from '@remotion/media-utils';
import {ALL_FORMATS, Input, UrlSource} from 'mediabunny';
import {useEffect, useState} from 'react';
import {getDurationOrCompute} from './get-duration-or-compute';
export type MediaMetadata = {
duration: number;
- format: string;
+ format: string | null;
width: number | null;
height: number | null;
videoCodec: string | null;
audioCodec: string | null;
};
-export const useMediaMetadata = (src: string | null): MediaMetadata | null => {
- const [mediaMetadata, setMediaMetadata] = useState<MediaMetadata | null>(
- null,
- );
+const cache = new Map<string, MediaMetadata>();
+const pendingRequests = new Map<string, Promise<MediaMetadata | null>>();
- useEffect(() => {
- setMediaMetadata(null);
+const safeCall = async <T>(fn: () => Promise<T>): Promise<T | null> => {
+ try {
+ return await fn();
+ } catch {
+ return null;
+ }
+};
- if (!src) {
- return;
+const getMediabunnyMetadata = async (
+ src: string,
+): Promise<MediaMetadata | null> => {
+ let input: Input;
+
+ try {
+ input = new Input({
+ formats: ALL_FORMATS,
+ source: new UrlSource(src),
+ });
+ } catch {
+ return null;
+ }
+
+ try {
+ const [duration, format, videoTrack, audioTrack] = await Promise.all([
+ safeCall(() => getDurationOrCompute(input)),
+ safeCall(() => input.getFormat()),
+ safeCall(() => input.getPrimaryVideoTrack()),
+ safeCall(() => input.getPrimaryAudioTrack()),
+ ]);
+
+ if (duration === null) {
+ return null;
}
- let cancelled = false;
- let input: Input | null = null;
+ const [width, height, videoCodec, audioCodec] = await Promise.all([
+ videoTrack ? safeCall(() => videoTrack.getDisplayWidth()) : null,
+ videoTrack ? safeCall(() => videoTrack.getDisplayHeight()) : null,
+ videoTrack ? safeCall(() => videoTrack.getCodec()) : null,
+ audioTrack ? safeCall(() => audioTrack.getCodec()) : null,
+ ]);
+ return {
+ duration,
+ format: format?.name ?? null,
+ width,
+ height,
+ videoCodec,
+ audioCodec,
+ };
+ } finally {
try {
- input = new Input({
- formats: ALL_FORMATS,
- source: new UrlSource(src),
- });
+ input.dispose();
} catch {
- return;
+ // ignore
}
+ }
+};
- const safeCall = async <T>(fn: () => Promise<T>): Promise<T | null> => {
- try {
- return await fn();
- } catch {
- return null;
- }
+const getFallbackVideoMetadata = async (
+ src: string,
+): Promise<MediaMetadata | null> => {
+ try {
+ const metadata = await getVideoMetadata(src);
+
+ return {
+ duration: metadata.durationInSeconds,
+ format: null,
+ width: metadata.width,
+ height: metadata.height,
+ videoCodec: null,
+ audioCodec: null,
};
+ } catch {
+ return null;
+ }
+};
- (async () => {
- if (!input) {
- return;
- }
+export const getMediaMetadata = (
+ src: string,
+): Promise<MediaMetadata | null> => {
+ const cached = cache.get(src);
- const [duration, format, videoTrack, audioTrack] = await Promise.all([
- safeCall(() => getDurationOrCompute(input!)),
- safeCall(() => input!.getFormat()),
- safeCall(() => input!.getPrimaryVideoTrack()),
- safeCall(() => input!.getPrimaryAudioTrack()),
- ]);
+ if (cached) {
+ return Promise.resolve(cached);
+ }
- if (cancelled || !format || duration === null) {
- return;
- }
+ const pendingRequest = pendingRequests.get(src);
- const [width, height, videoCodec, audioCodec] = await Promise.all([
- videoTrack ? safeCall(() => videoTrack.getDisplayWidth()) : null,
- videoTrack ? safeCall(() => videoTrack.getDisplayHeight()) : null,
- videoTrack ? safeCall(() => videoTrack.getCodec()) : null,
- audioTrack ? safeCall(() => audioTrack.getCodec()) : null,
- ]);
+ if (pendingRequest) {
+ return pendingRequest;
+ }
- if (cancelled) {
- return;
+ const request = getMediabunnyMetadata(src)
+ .catch(() => null)
+ .then((metadata) => metadata ?? getFallbackVideoMetadata(src))
+ .then((metadata) => {
+ if (metadata) {
+ cache.set(src, metadata);
}
- setMediaMetadata({
- duration,
- format: format.name,
- width,
- height,
- videoCodec,
- audioCodec,
- });
- })().catch(() => {
- // Swallow any unexpected error β€” this is a non-essential UI enhancement.
+ return metadata;
+ })
+ .finally(() => {
+ pendingRequests.delete(src);
});
+ pendingRequests.set(src, request);
+
+ return request;
+};
+
+export const useMediaMetadata = (src: string | null): MediaMetadata | null => {
+ const [mediaMetadata, setMediaMetadata] = useState<MediaMetadata | null>(
+ src ? (cache.get(src) ?? null) : null,
+ );
+
+ useEffect(() => {
+ const cached = src ? (cache.get(src) ?? null) : null;
+ setMediaMetadata(cached);
+
+ if (!src || cached) {
+ return;
+ }
+
+ let cancelled = false;
+
+ getMediaMetadata(src)
+ .then((metadata) => {
+ if (cancelled) {
+ return;
+ }
+
+ setMediaMetadata(metadata);
+ })
+ .catch(() => {
+ if (cancelled) {
+ return;
+ }
+
+ setMediaMetadata(null);
+ });
+
return () => {
cancelled = true;
- try {
- input?.dispose();
- } catch {
- // ignore
- }
};
}, [src]);