Skip to content

🎥 Make videos programmatically with React

that works, ship it

Jonny Burgerdd70560f660b
diff --git a/packages/core/package.json b/packages/core/package.json
index 8d9b0615f3..5ae54a4247 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -25,6 +25,8 @@
"react-dom": ">=16.8.0"
},
"devDependencies": {
+ "@testing-library/react": "16.1.0",
+ "@testing-library/dom": "10.4.0",
"@happy-dom/global-registrator": "14.5.1",
"@types/dom-webcodecs": "0.1.11",
"happy-dom": "15.10.2",
diff --git a/packages/core/src/animated-image/AnimatedImage.tsx b/packages/core/src/animated-image/AnimatedImage.tsx
index 9d4e6d178d..2f6bf1058a 100644
--- a/packages/core/src/animated-image/AnimatedImage.tsx
+++ b/packages/core/src/animated-image/AnimatedImage.tsx
@@ -2,11 +2,12 @@ import {
forwardRef,
useEffect,
useImperativeHandle,
+ useLayoutEffect,
useRef,
useState,
} from 'react';
import {cancelRender} from '../cancel-render.js';
-import {delayRender} from '../delay-render.js';
+import {continueRender, delayRender} from '../delay-render.js';
import {useCurrentFrame} from '../use-current-frame.js';
import {useVideoConfig} from '../use-video-config.js';
import type {AnimatedImageCanvasRef} from './canvas';
@@ -34,17 +35,27 @@ export const AnimatedImage = forwardRef<
},
canvasRef,
) => {
+ const mountState = useRef({isMounted: true});
+
+ useEffect(() => {
+ const {current} = mountState;
+ current.isMounted = true;
+ return () => {
+ current.isMounted = false;
+ };
+ }, []);
+
const resolvedSrc = resolveAnimatedImageSource(src);
const [imageDecoder, setImageDecoder] =
useState<RemotionImageDecoder | null>(null);
- const [id] = useState(() =>
+ const [decodeHandle] = useState(() =>
delayRender(`Rendering <AnimatedImage/> with src="${resolvedSrc}"`),
);
const frame = useCurrentFrame();
const {fps} = useVideoConfig();
- const currentTime = frame / fps;
+ const currentTime = frame / playbackRate / fps;
const currentTimeRef = useRef<number>(currentTime);
currentTimeRef.current = currentTime;
@@ -59,39 +70,71 @@ export const AnimatedImage = forwardRef<
return c;
}, []);
+ const [initialLoopBehavior] = useState(() => loopBehavior);
+
useEffect(() => {
const controller = new AbortController();
decodeImage({
resolvedSrc,
signal: controller.signal,
currentTime: currentTimeRef.current,
+ initialLoopBehavior,
})
.then((d) => {
setImageDecoder(d);
+ continueRender(decodeHandle);
})
.catch((err) => {
if ((err as Error).name === 'AbortError') {
+ continueRender(decodeHandle);
+
return;
}
- // TODO: Allow to catch error
- cancelRender(err);
+ if (onError) {
+ onError?.(err as Error);
+ continueRender(decodeHandle);
+ } else {
+ cancelRender(err);
+ }
});
return () => {
controller.abort();
};
- }, [resolvedSrc, id, onLoad, onError]);
+ }, [resolvedSrc, decodeHandle, onLoad, onError, initialLoopBehavior]);
- useEffect(() => {
+ useLayoutEffect(() => {
if (!imageDecoder) {
return;
}
- imageDecoder.getFrame(currentTime).then((videoFrame) => {
- ref.current?.draw(videoFrame.frame!);
- });
- }, [currentTime, imageDecoder]);
+ const delay = delayRender(
+ `Rendering frame at ${currentTime} of <AnimatedImage src="${src}"/>`,
+ );
+
+ imageDecoder
+ .getFrame(currentTime, loopBehavior)
+ .then((videoFrame) => {
+ if (mountState.current.isMounted) {
+ if (videoFrame === null) {
+ ref.current?.clear();
+ } else {
+ ref.current?.draw(videoFrame.frame!);
+ }
+ }
+
+ continueRender(delay);
+ })
+ .catch((err) => {
+ if (onError) {
+ onError(err as Error);
+ continueRender(delay);
+ } else {
+ cancelRender(err);
+ }
+ });
+ }, [currentTime, imageDecoder, loopBehavior, onError, src]);
return (
<Canvas ref={ref} width={width} height={height} fit={fit} {...props} />
diff --git a/packages/core/src/animated-image/canvas.tsx b/packages/core/src/animated-image/canvas.tsx
index 451dc3a194..dea6e88cf8 100644
--- a/packages/core/src/animated-image/canvas.tsx
+++ b/packages/core/src/animated-image/canvas.tsx
@@ -86,6 +86,7 @@ type Props = {
export type AnimatedImageCanvasRef = {
readonly draw: (imageData: VideoFrame) => void;
readonly getCanvas: () => HTMLCanvasElement | null;
+ clear: () => void;
};
const CanvasRefForwardingFunction: React.ForwardRefRenderFunction<
@@ -140,6 +141,19 @@ const CanvasRefForwardingFunction: React.ForwardRefRenderFunction<
return canvasRef.current;
},
+ clear: () => {
+ const ctx = canvasRef.current?.getContext('2d');
+ if (!ctx) {
+ throw new Error('Could not get 2d context');
+ }
+
+ ctx.clearRect(
+ 0,
+ 0,
+ canvasRef.current!.width,
+ canvasRef.current!.height,
+ );
+ },
};
}, [draw]);
diff --git a/packages/core/src/animated-image/decode-image.ts b/packages/core/src/animated-image/decode-image.ts
index abff2eaa26..46def9b411 100644
--- a/packages/core/src/animated-image/decode-image.ts
+++ b/packages/core/src/animated-image/decode-image.ts
@@ -1,3 +1,5 @@
+import type {RemotionAnimatedImageLoopBehavior} from './props';
+
export type AnimatedImageCacheItem = {
timeInSeconds: number;
frameIndex: number;
@@ -5,20 +7,41 @@ export type AnimatedImageCacheItem = {
};
export type RemotionImageDecoder = {
- getFrame: (i: number) => Promise<AnimatedImageCacheItem>;
+ getFrame: (
+ i: number,
+ loopBehavior: RemotionAnimatedImageLoopBehavior,
+ ) => Promise<AnimatedImageCacheItem | null>;
frameCount: number;
};
const CACHE_SIZE = 5;
+const getActualTime = ({
+ loopBehavior,
+ durationFound,
+ timeInSec,
+}: {
+ loopBehavior: RemotionAnimatedImageLoopBehavior;
+ durationFound: number | null;
+ timeInSec: number;
+}) => {
+ return loopBehavior === 'loop'
+ ? durationFound
+ ? timeInSec % durationFound
+ : timeInSec
+ : Math.min(timeInSec, durationFound || Infinity);
+};
+
export const decodeImage = async ({
resolvedSrc,
signal,
currentTime,
+ initialLoopBehavior,
}: {
resolvedSrc: string;
signal: AbortSignal;
currentTime: number;
+ initialLoopBehavior: RemotionAnimatedImageLoopBehavior;
}): Promise<RemotionImageDecoder> => {
if (typeof ImageDecoder === 'undefined') {
throw new Error(
@@ -94,10 +117,18 @@ export const decodeImage = async ({
}
};
- const ensureFrameBeforeAndAfter = async (timeInSec: number) => {
- const actualTimeInSec = durationFound
- ? timeInSec % durationFound
- : timeInSec;
+ const ensureFrameBeforeAndAfter = async ({
+ timeInSec,
+ loopBehavior,
+ }: {
+ timeInSec: number;
+ loopBehavior: RemotionAnimatedImageLoopBehavior;
+ }) => {
+ const actualTimeInSec = getActualTime({
+ durationFound,
+ loopBehavior,
+ timeInSec,
+ });
const framesBefore = cache.filter(
(c) => c.timeInSeconds <= actualTimeInSec,
);
@@ -117,7 +148,7 @@ export const decodeImage = async ({
throw new Error('Frame has no duration');
}
- if (i === selectedTrack.frameCount) {
+ if (i === selectedTrack.frameCount && durationFound === null) {
const duration = (f.frame.timestamp + f.frame.duration) / 1_000_000;
durationFound = duration;
}
@@ -131,14 +162,33 @@ export const decodeImage = async ({
};
// Twice because might be over total duration
- await ensureFrameBeforeAndAfter(currentTime);
- await ensureFrameBeforeAndAfter(currentTime);
+ await ensureFrameBeforeAndAfter({
+ timeInSec: currentTime,
+ loopBehavior: initialLoopBehavior,
+ });
+ await ensureFrameBeforeAndAfter({
+ timeInSec: currentTime,
+ loopBehavior: initialLoopBehavior,
+ });
- const getFrame = async (timeInSec: number) => {
- const actualTimeInSec = durationFound
- ? timeInSec % durationFound
- : timeInSec;
- await ensureFrameBeforeAndAfter(actualTimeInSec);
+ const getFrame = async (
+ timeInSec: number,
+ loopBehavior: RemotionAnimatedImageLoopBehavior,
+ ) => {
+ if (
+ durationFound !== null &&
+ timeInSec > durationFound &&
+ loopBehavior === 'unmount-after-finish'
+ ) {
+ return null;
+ }
+
+ const actualTimeInSec = getActualTime({
+ loopBehavior,
+ durationFound,
+ timeInSec,
+ });
+ await ensureFrameBeforeAndAfter({timeInSec: actualTimeInSec, loopBehavior});
const itemsInCache = cache.filter((c) => c.frame);
const closest = itemsInCache.reduce((a, b) => {
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 1207b04e84..4f3aa0c874 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -476,6 +476,12 @@ importers:
'@remotion/eslint-config-internal':
specifier: workspace:*
version: link:../eslint-config-internal
+ '@testing-library/dom':
+ specifier: 10.4.0
+ version: 10.4.0
+ '@testing-library/react':
+ specifier: 16.1.0
'@types/dom-webcodecs':
specifier: 0.1.11
version: 0.1.11
@@ -15584,7 +15590,7 @@ packages:
dependencies:
'@typescript/vfs': 1.3.5
debug: 4.3.7
- lz-string: 1.4.4
+ lz-string: 1.5.0
transitivePeerDependencies:
- supports-color
dev: false
@@ -22806,7 +22812,6 @@ packages:
resolution: {integrity: sha512-h5bgJWpxJNswbU7qCrV0tIKQCaS3blPDrqKWx+QxzuzL1zGUzij9XCWLrSLsJPu5t+eWA/ycetzYAO5IOMcWAQ==}
hasBin: true
- dev: true
resolution: {integrity: sha512-tRvbDF0Pgqz+9XUa4jjfgAQ8/aPKmQdWXilFu2tMy4GWj4NOsx99HlULO4IeREfbO3a0sA145DZYyvXPkybm0g==}