Skip to content

🎥 Make videos programmatically with React

works better

Jonny Burgerabc6e2291c7f
diff --git a/packages/core/src/animated-image/AnimatedImage.tsx b/packages/core/src/animated-image/AnimatedImage.tsx
index 9275c39903..9d4e6d178d 100644
--- a/packages/core/src/animated-image/AnimatedImage.tsx
+++ b/packages/core/src/animated-image/AnimatedImage.tsx
@@ -8,6 +8,7 @@ import {
import {cancelRender} from '../cancel-render.js';
import {delayRender} from '../delay-render.js';
import {useCurrentFrame} from '../use-current-frame.js';
+import {useVideoConfig} from '../use-video-config.js';
import type {AnimatedImageCanvasRef} from './canvas';
import {Canvas} from './canvas';
import type {RemotionImageDecoder} from './decode-image.js';
@@ -41,6 +42,12 @@ export const AnimatedImage = forwardRef<
delayRender(`Rendering <AnimatedImage/> with src="${resolvedSrc}"`),
);
+ const frame = useCurrentFrame();
+ const {fps} = useVideoConfig();
+ const currentTime = frame / fps;
+ const currentTimeRef = useRef<number>(currentTime);
+ currentTimeRef.current = currentTime;
+
const ref = useRef<AnimatedImageCanvasRef>(null);
useImperativeHandle(canvasRef, () => {
@@ -54,7 +61,11 @@ export const AnimatedImage = forwardRef<
useEffect(() => {
const controller = new AbortController();
- decodeImage(resolvedSrc, controller.signal)
+ decodeImage({
+ resolvedSrc,
+ signal: controller.signal,
+ currentTime: currentTimeRef.current,
+ })
.then((d) => {
setImageDecoder(d);
})
@@ -72,19 +83,15 @@ export const AnimatedImage = forwardRef<
};
}, [resolvedSrc, id, onLoad, onError]);
- const frame = useCurrentFrame();
-
useEffect(() => {
if (!imageDecoder) {
return;
}
- imageDecoder
- .getFrame(frame % imageDecoder.frameCount)
- .then((videoFrame) => {
- ref.current?.draw(videoFrame.image);
- });
- }, [frame, imageDecoder]);
+ imageDecoder.getFrame(currentTime).then((videoFrame) => {
+ ref.current?.draw(videoFrame.frame!);
+ });
+ }, [currentTime, imageDecoder]);
return (
<Canvas ref={ref} width={width} height={height} fit={fit} {...props} />
diff --git a/packages/core/src/animated-image/decode-image.ts b/packages/core/src/animated-image/decode-image.ts
index 7572d528e7..abff2eaa26 100644
--- a/packages/core/src/animated-image/decode-image.ts
+++ b/packages/core/src/animated-image/decode-image.ts
@@ -1,12 +1,25 @@
+export type AnimatedImageCacheItem = {
+ timeInSeconds: number;
+ frameIndex: number;
+ frame: VideoFrame | null;
+};
+
export type RemotionImageDecoder = {
- getFrame: (i: number) => Promise<ImageDecodeResult>;
+ getFrame: (i: number) => Promise<AnimatedImageCacheItem>;
frameCount: number;
};
-export const decodeImage = async (
- resolvedSrc: string,
- signal: AbortSignal,
-): Promise<RemotionImageDecoder> => {
+const CACHE_SIZE = 5;
+
+export const decodeImage = async ({
+ resolvedSrc,
+ signal,
+ currentTime,
+}: {
+ resolvedSrc: string;
+ signal: AbortSignal;
+ currentTime: number;
+}): Promise<RemotionImageDecoder> => {
if (typeof ImageDecoder === 'undefined') {
throw new Error(
'Your browser does not support the WebCodecs ImageDecoder API.',
@@ -30,14 +43,119 @@ export const decodeImage = async (
throw new Error('No selected track');
}
- return {
- getFrame: async (i: number) => {
- const frame = await decoder.decode({
- frameIndex: i,
- completeFramesOnly: true,
+ const cache: AnimatedImageCacheItem[] = [];
+
+ let durationFound: number | null = null;
+
+ const getFrameByIndex = async (
+ frameIndex: number,
+ ): Promise<AnimatedImageCacheItem> => {
+ const foundInCache = cache.find((c) => c.frameIndex === frameIndex);
+ if (foundInCache && foundInCache.frame) {
+ return foundInCache;
+ }
+
+ const frame = await decoder.decode({
+ frameIndex,
+ completeFramesOnly: true,
+ });
+
+ if (foundInCache) {
+ foundInCache.frame = frame.image;
+ } else {
+ cache.push({
+ frame: frame.image,
+ frameIndex,
+ timeInSeconds: frame.image.timestamp / 1_000_000,
});
- return frame;
- },
+ }
+
+ return {
+ frame: frame.image,
+ frameIndex,
+ timeInSeconds: frame.image.timestamp / 1_000_000,
+ };
+ };
+
+ const clearCache = (closeToTimeInSec: number) => {
+ const itemsInCache = cache.filter((c) => c.frame);
+ const sortByClosestToCurrentTime = itemsInCache.sort((a, b) => {
+ const aDiff = Math.abs(a.timeInSeconds - closeToTimeInSec);
+ const bDiff = Math.abs(b.timeInSeconds - closeToTimeInSec);
+ return aDiff - bDiff;
+ });
+ for (let i = 0; i < sortByClosestToCurrentTime.length; i++) {
+ if (i < CACHE_SIZE) {
+ continue;
+ }
+
+ const item = sortByClosestToCurrentTime[i];
+ item.frame = null;
+ }
+ };
+
+ const ensureFrameBeforeAndAfter = async (timeInSec: number) => {
+ const actualTimeInSec = durationFound
+ ? timeInSec % durationFound
+ : timeInSec;
+ const framesBefore = cache.filter(
+ (c) => c.timeInSeconds <= actualTimeInSec,
+ );
+ const biggestIndex = framesBefore
+ .map((c) => c.frameIndex)
+ .reduce((a, b) => Math.max(a, b), 0);
+
+ let i = biggestIndex;
+ while (true) {
+ const f = await getFrameByIndex(i);
+ i++;
+ if (!f.frame) {
+ throw new Error('No frame found');
+ }
+
+ if (!f.frame.duration) {
+ throw new Error('Frame has no duration');
+ }
+
+ if (i === selectedTrack.frameCount) {
+ const duration = (f.frame.timestamp + f.frame.duration) / 1_000_000;
+ durationFound = duration;
+ }
+
+ if (f.timeInSeconds > actualTimeInSec || i === selectedTrack.frameCount) {
+ break;
+ }
+ }
+
+ clearCache(actualTimeInSec);
+ };
+
+ // Twice because might be over total duration
+ await ensureFrameBeforeAndAfter(currentTime);
+ await ensureFrameBeforeAndAfter(currentTime);
+
+ const getFrame = async (timeInSec: number) => {
+ const actualTimeInSec = durationFound
+ ? timeInSec % durationFound
+ : timeInSec;
+ await ensureFrameBeforeAndAfter(actualTimeInSec);
+ const itemsInCache = cache.filter((c) => c.frame);
+
+ const closest = itemsInCache.reduce((a, b) => {
+ const aDiff = Math.abs(a.timeInSeconds - actualTimeInSec);
+ const bDiff = Math.abs(b.timeInSeconds - actualTimeInSec);
+ return aDiff < bDiff ? a : b;
+ });
+
+ if (!closest.frame) {
+ throw new Error('No frame found');
+ }
+
+ return closest;
+ };
+
+ return {
+ getFrame,
frameCount: selectedTrack.frameCount,
};
};