Skip to content

🎥 Make videos programmatically with React

add animated image component

Mohit Yadav4b754f1bdc67
diff --git a/packages/cloudrun/src/gcpInstaller/gcpInstaller.tar b/packages/cloudrun/src/gcpInstaller/gcpInstaller.tar
index 3a25b51386..8d3608f084 100644
Binary files a/packages/cloudrun/src/gcpInstaller/gcpInstaller.tar and b/packages/cloudrun/src/gcpInstaller/gcpInstaller.tar differ
diff --git a/packages/compositor-darwin-arm64/remotion b/packages/compositor-darwin-arm64/remotion
index b03a107faa..72cba36586 100755
Binary files a/packages/compositor-darwin-arm64/remotion and b/packages/compositor-darwin-arm64/remotion differ
diff --git a/packages/core/package.json b/packages/core/package.json
index 3a8bdb3851..e52eb032b1 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -25,8 +25,9 @@
"react-dom": ">=16.8.0"
},
"devDependencies": {
- "@testing-library/react": "14.0.0",
"@happy-dom/global-registrator": "14.5.1",
+ "@testing-library/react": "14.0.0",
+ "@types/dom-webcodecs": "0.1.11",
"happy-dom": "14.5.1",
"jsdom": "21.1.0",
"react": "18.3.1",
diff --git a/packages/core/src/animate-image/AnimatedImage.tsx b/packages/core/src/animate-image/AnimatedImage.tsx
deleted file mode 100644
index d4d3636453..0000000000
--- a/packages/core/src/animate-image/AnimatedImage.tsx
+++ /dev/null
@@ -1,3 +0,0 @@
-export const AnimatedImage = ({src}: {readonly src: string}) => {
- return <div>Animated image{src}</div>;
-};
diff --git a/packages/core/src/animated-image/AnimatedImage.tsx b/packages/core/src/animated-image/AnimatedImage.tsx
new file mode 100644
index 0000000000..f2757162ec
--- /dev/null
+++ b/packages/core/src/animated-image/AnimatedImage.tsx
@@ -0,0 +1,149 @@
+// @ts-nocheck
+import {forwardRef, useEffect, useState} from 'react';
+import {delayRender} from '../delay-render.js';
+import {Canvas} from './canvas';
+import type {RemotionAnimatedImageProps} from './props';
+import {resolveAnimatedImageSource} from './resolve-image-source';
+
+export const AnimatedImage = forwardRef<
+ HTMLCanvasElement,
+ RemotionAnimatedImageProps
+>(
+ (
+ {
+ src,
+ width,
+ height,
+ onError,
+ loopBehavior = 'loop',
+ playbackRate = 1,
+ onLoad,
+ fit = 'fill',
+ ...props
+ },
+ ref,
+ ) => {
+ const resolvedSrc = resolveAnimatedImageSource(src);
+ const [imageDecoder, setImageDecoder] = useState<ImageDecoder | null>(null);
+ const [imageIndex, setImageIndex] = useState(0);
+ const [frames, setFrames] = useState<ImageData[]>([]);
+
+ const [id] = useState(() =>
+ delayRender(`Rendering <AnimatedImage/> with src="${resolvedSrc}"`),
+ );
+
+ useEffect(() => {
+ if (typeof ImageDecoder === 'undefined') {
+ throw new Error(
+ 'Your browser does not support the WebCodecs ImageDecoder API.',
+ );
+ }
+
+ let aborted = false;
+
+ fetch(resolvedSrc, {mode: 'no-cors'})
+ .then((res) => res.body)
+ .then((body) => {
+ if (aborted) return;
+
+ return new ImageDecoder({
+ data: body,
+ type: 'image/gif',
+ });
+ })
+ .then((decoder) => {
+ console.log({decoder});
+ if (aborted) return;
+ setImageDecoder(decoder);
+ // onLoad?.();
+ // continueRender(id);
+ })
+ .catch((err) => {
+ if (aborted) return;
+ onError?.(err);
+ });
+
+ return () => {
+ aborted = true;
+ };
+ }, [resolvedSrc, id, onLoad, onError]);
+
+ useEffect(() => {
+ if (!imageDecoder) return;
+
+ let animationFrameId: number;
+ const tempCanvas = document.createElement('canvas');
+ const tempCtx = tempCanvas.getContext('2d');
+
+ const decodeNextFrame = (index: number) => {
+ imageDecoder
+ .decode({frameIndex: index})
+ .then((result) => {
+ if (tempCtx) {
+ tempCanvas.width = result.image.width;
+ tempCanvas.height = result.image.height;
+
+ console.log({result});
+
+ tempCtx.drawImage(result.image, 0, 0);
+ const imageData = tempCtx.getImageData(
+ 0,
+ 0,
+ // result.image.displayWidth,
+ result.image.displayHeight,
+ );
+ setFrames((prev) => [...prev, imageData]);
+ }
+
+ const track = imageDecoder.tracks.selectedTrack;
+
+ if (imageDecoder.complete) {
+ if (track.frameCount === 1) return;
+
+ if (index + 1 >= track.frameCount) {
+ if (loopBehavior === 'loop') {
+ setImageIndex(0);
+ } else {
+ return;
+ }
+ } else {
+ setImageIndex((prev) => prev + 1);
+ }
+ }
+
+ animationFrameId = requestAnimationFrame(() => {
+ decodeNextFrame((index + 1) % track.frameCount);
+ });
+ })
+ .catch((e) => {
+ if (e instanceof RangeError) {
+ setImageIndex(0);
+ decodeNextFrame(0);
+ } else {
+ throw e;
+ }
+ });
+ };
+
+ decodeNextFrame(imageIndex);
+
+ return () => {
+ if (animationFrameId) {
+ cancelAnimationFrame(animationFrameId);
+ }
+ };
+ }, [imageDecoder, imageIndex, loopBehavior, playbackRate]);
+
+ return (
+ <Canvas
+ ref={ref}
+ index={imageIndex}
+ frames={frames}
+ 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
new file mode 100644
index 0000000000..785a2c70c0
--- /dev/null
+++ b/packages/core/src/animated-image/canvas.tsx
@@ -0,0 +1,163 @@
+// @ts-nocheck
+import {
+ forwardRef,
+ useEffect,
+ useImperativeHandle,
+ useRef,
+ useState,
+} from 'react';
+import type {AnimatedImageFillMode} from './props';
+import {useElementSize} from './use-element-size';
+
+const calcArgs = (
+ fit: AnimatedImageFillMode,
+ frameSize: {
+ width: number;
+ height: number;
+ },
+ canvasSize: {
+ width: number;
+ height: number;
+ },
+): [number, number, number, number, number, number, number, number] => {
+ switch (fit) {
+ case 'fill': {
+ return [
+ 0,
+ 0,
+ frameSize.width,
+ frameSize.height,
+ 0,
+ 0,
+ canvasSize.width,
+ canvasSize.height,
+ ];
+ }
+
+ case 'contain': {
+ const ratio = Math.min(
+ canvasSize.width / frameSize.width,
+ canvasSize.height / frameSize.height,
+ );
+
+ const centerX = (canvasSize.width - frameSize.width * ratio) / 2;
+ const centerY = (canvasSize.height - frameSize.height * ratio) / 2;
+
+ return [
+ 0,
+ 0,
+ frameSize.width,
+ frameSize.height,
+ centerX,
+ centerY,
+ frameSize.width * ratio,
+ frameSize.height * ratio,
+ ];
+ }
+
+ case 'cover': {
+ const ratio = Math.max(
+ canvasSize.width / frameSize.width,
+ canvasSize.height / frameSize.height,
+ );
+ const centerX = (canvasSize.width - frameSize.width * ratio) / 2;
+ const centerY = (canvasSize.height - frameSize.height * ratio) / 2;
+
+ return [
+ 0,
+ 0,
+ frameSize.width,
+ frameSize.height,
+ centerX,
+ centerY,
+ frameSize.width * ratio,
+ frameSize.height * ratio,
+ ];
+ }
+
+ default:
+ throw new Error('Unknown fit: ' + fit);
+ }
+};
+
+const makeCanvas = () => {
+ if (typeof document === 'undefined') {
+ return null;
+ }
+
+ const canvas = document.createElement('canvas');
+ const ctx = canvas.getContext('2d');
+
+ canvas.width = 0;
+ canvas.height = 0;
+
+ return ctx;
+};
+
+type Props = {
+ index: number;
+ frames: ImageData[];
+ width?: number;
+ height?: number;
+ fit: AnimatedImageFillMode;
+ className?: string;
+ style?: React.CSSProperties;
+};
+
+export const Canvas = forwardRef(
+ ({index, frames, width, height, fit, className, style}: Props, ref) => {
+ const canvasRef = useRef<HTMLCanvasElement>(null);
+ const [tempCtx] = useState(() => {
+ return makeCanvas();
+ });
+
+ const size = useElementSize(canvasRef);
+
+ useImperativeHandle(
+ ref,
+ () => {
+ return canvasRef.current as HTMLCanvasElement;
+ },
+ [],
+ );
+
+ useEffect(() => {
+ if (!size) {
+ return;
+ }
+
+ const imageData = frames[index];
+ const ctx = canvasRef.current?.getContext('2d');
+ if (imageData && tempCtx && ctx) {
+ if (
+ tempCtx.canvas.width < imageData.width ||
+ tempCtx.canvas.height < imageData.height
+ ) {
+ tempCtx.canvas.width = imageData.width;
+ tempCtx.canvas.height = imageData.height;
+ }
+
+ if (size.width > 0 && size.height > 0) {
+ ctx.clearRect(0, 0, size.width, size.height);
+ tempCtx.clearRect(0, 0, tempCtx.canvas.width, tempCtx.canvas.height);
+ }
+
+ tempCtx.putImageData(imageData, 0, 0);
+ ctx.drawImage(
+ tempCtx.canvas,
+ ...calcArgs(fit, imageData, {width: size.width, height: size.height}),
+ );
+ }
+ }, [index, frames, fit, tempCtx, size]);
+
+ return (
+ <canvas
+ ref={canvasRef}
+ className={className}
+ style={style}
+ width={width ?? size?.width}
+ height={height ?? size?.height}
+ />
+ );
+ },
+);
diff --git a/packages/core/src/animate-image/index.ts b/packages/core/src/animated-image/index.ts
similarity index 100%
rename from packages/core/src/animate-image/index.ts
rename to packages/core/src/animated-image/index.ts
diff --git a/packages/core/src/animated-image/props.ts b/packages/core/src/animated-image/props.ts
new file mode 100644
index 0000000000..9df8a8cf0d
--- /dev/null
+++ b/packages/core/src/animated-image/props.ts
@@ -0,0 +1,24 @@
+export type RemotionAnimatedImageLoopBehavior =
+ | 'loop'
+ | 'pause-after-finish'
+ | 'unmount-after-finish';
+
+export type RemotionAnimatedImageProps = {
+ src: string;
+ width?: number;
+ height?: number;
+ onLoad?: (info: {
+ width: number;
+ height: number;
+ delays: number[];
+ frames: ImageData[];
+ }) => void;
+ onError?: (error: Error) => void;
+ fit?: AnimatedImageFillMode;
+ playbackRate?: number;
+ style?: React.CSSProperties;
+ loopBehavior?: RemotionAnimatedImageLoopBehavior;
+ id?: string;
+};
+
+export type AnimatedImageFillMode = 'contain' | 'cover' | 'fill';
diff --git a/packages/core/src/animated-image/resolve-image-source.tsx b/packages/core/src/animated-image/resolve-image-source.tsx
new file mode 100644
index 0000000000..47437a0732
--- /dev/null
+++ b/packages/core/src/animated-image/resolve-image-source.tsx
@@ -0,0 +1,4 @@
+export const resolveAnimatedImageSource = (src: string): string => {
+ return new URL(src, typeof window === 'undefined' ? undefined : window.origin)
+ .href;
+};
diff --git a/packages/core/src/animated-image/use-element-size.tsx b/packages/core/src/animated-image/use-element-size.tsx
new file mode 100644
index 0000000000..a90e6909af
--- /dev/null
+++ b/packages/core/src/animated-image/use-element-size.tsx
@@ -0,0 +1,94 @@
+import {useCallback, useEffect, useMemo, useState} from 'react';
+
+export type Size = {
+ width: number;
+ height: number;
+};
+
+type ElementSizeForceUpdate = () => void;
+
+let elementSizeHooks: ElementSizeForceUpdate[] = [];
+
+export const updateAllElementsSizes = () => {
+ for (const listener of elementSizeHooks) {
+ listener();
+ }
+};
+
+export const useElementSize = (
+ ref: React.RefObject<HTMLElement>,
+): Size | null => {
+ const [size, setSize] = useState<Size | null>(null);
+ const observer = useMemo(() => {
+ if (typeof ResizeObserver === 'undefined') {
+ return null;
+ }
+
+ return new ResizeObserver((entries) => {
+ // The contentRect returns the width without any `scale()`'s being applied. The height is wrong
+ const {contentRect} = entries[0];
+ // The clientRect returns the size with `scale()` being applied.
+ const newSize = entries[0].target.getClientRects();
+
+ if (!newSize?.[0]) {
+ setSize(null);
+ return;
+ }
+
+ const probableCssParentScale = newSize[0].width / contentRect.width;
+
+ const width = newSize[0].width * (1 / probableCssParentScale);
+ const height = newSize[0].height * (1 / probableCssParentScale);
+
+ setSize({
+ width,
+ height,
+ });
+ });
+ }, []);
+
+ const updateSize = useCallback(() => {
+ if (!ref.current) {
+ return;
+ }
+
+ const rect = ref.current.getClientRects();
+ if (!rect[0]) {
+ setSize(null);
+ return;
+ }
+
+ setSize({
+ width: rect[0].width as number,
+ height: rect[0].height as number,
+ });
+ }, [ref]);
+
+ useEffect(() => {
+ if (!observer) {
+ return;
+ }
+
+ updateSize();
+ const {current} = ref;
+ if (ref.current) {
+ observer.observe(ref.current);
+ }
+
+ return (): void => {
+ if (current) {
+ observer.unobserve(current);
+ }
+ };
+ }, [observer, ref, updateSize]);
+
+ useEffect(() => {
+ elementSizeHooks.push(updateSize);
+
+ return () => {
+ elementSizeHooks = elementSizeHooks.filter((e) => e !== updateSize);
+ };
+ }, [updateSize]);
+
+ return size;
+};
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index 2de6b9c873..fe02d6d73a 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -92,7 +92,7 @@ export type BundleState =
checkMultipleRemotionVersions();
export * from './AbsoluteFill.js';
-export * from './animate-image/index.js';
+export * from './animated-image/index.js';
export {Artifact} from './Artifact.js';
export * from './audio/index.js';
export {cancelRender} from './cancel-render.js';
diff --git a/packages/core/src/test/animated-image.test.tsx b/packages/core/src/test/animated-image.test.tsx
index bef2ff84db..a812cfee4a 100644
--- a/packages/core/src/test/animated-image.test.tsx
+++ b/packages/core/src/test/animated-image.test.tsx
@@ -3,7 +3,7 @@
*/
import {render} from '@testing-library/react';
import {describe, expect, test} from 'vitest';
-import {AnimatedImage} from '../animate-image';
+import {AnimatedImage} from '../animated-image';
describe('Render correctly with props', () => {
test('should render with default props', () => {
diff --git a/packages/example/src/AnimatedImage/Gif.tsx b/packages/example/src/AnimatedImage/Gif.tsx
index 7fe90b3582..e230d8e0f6 100644
--- a/packages/example/src/AnimatedImage/Gif.tsx
+++ b/packages/example/src/AnimatedImage/Gif.tsx
@@ -1,7 +1,5 @@
-import {AnimatedImage} from 'remotion';
+import {AnimatedImage, staticFile} from 'remotion';
export const GifAnimatedImage = () => {
- return (
- <AnimatedImage src="https://gist.github.com/nolanlawson/73f15f3fe612b8770e79/raw/be4205effd089b38ccd197de544e6370785f6b5e/chopsticks.gif" />
- );
+ return <AnimatedImage src={staticFile('giphy.gif')} />;
};
diff --git a/packages/gif/src/canvas.tsx b/packages/gif/src/canvas.tsx
index 0b1df0df10..b5a5da819f 100644
--- a/packages/gif/src/canvas.tsx
+++ b/packages/gif/src/canvas.tsx
@@ -38,8 +38,10 @@ const calcArgs = (
canvasSize.width / frameSize.width,
canvasSize.height / frameSize.height,
);
+
const centerX = (canvasSize.width - frameSize.width * ratio) / 2;
const centerY = (canvasSize.height - frameSize.height * ratio) / 2;
+
return [
0,
0,
@@ -59,6 +61,7 @@ const calcArgs = (
);
const centerX = (canvasSize.width - frameSize.width * ratio) / 2;
const centerY = (canvasSize.height - frameSize.height * ratio) / 2;
+
return [
0,
0,
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index dd70342413..83d436353c 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -349,6 +349,9 @@ importers:
'@testing-library/react':
specifier: 14.0.0
+ '@types/dom-webcodecs':
+ specifier: 0.1.11
+ version: 0.1.11
happy-dom:
specifier: 14.5.1
version: 14.5.1