Skip to content

🎥 Make videos programmatically with React

without variable FPS

Jonny Burger2b95162434e7
diff --git a/packages/core/src/animated-image/AnimatedImage.tsx b/packages/core/src/animated-image/AnimatedImage.tsx
index f2757162ec..9275c39903 100644
--- a/packages/core/src/animated-image/AnimatedImage.tsx
+++ b/packages/core/src/animated-image/AnimatedImage.tsx
@@ -1,7 +1,17 @@
-// @ts-nocheck
-import {forwardRef, useEffect, useState} from 'react';
+import {
+ forwardRef,
+ useEffect,
+ useImperativeHandle,
+ useRef,
+ useState,
+} from 'react';
+import {cancelRender} from '../cancel-render.js';
import {delayRender} from '../delay-render.js';
+import {useCurrentFrame} from '../use-current-frame.js';
+import type {AnimatedImageCanvasRef} from './canvas';
import {Canvas} from './canvas';
+import type {RemotionImageDecoder} from './decode-image.js';
+import {decodeImage} from './decode-image.js';
import type {RemotionAnimatedImageProps} from './props';
import {resolveAnimatedImageSource} from './resolve-image-source';
@@ -21,129 +31,63 @@ export const AnimatedImage = forwardRef<
fit = 'fill',
...props
},
- ref,
+ canvasRef,
) => {
const resolvedSrc = resolveAnimatedImageSource(src);
- const [imageDecoder, setImageDecoder] = useState<ImageDecoder | null>(null);
- const [imageIndex, setImageIndex] = useState(0);
- const [frames, setFrames] = useState<ImageData[]>([]);
+ const [imageDecoder, setImageDecoder] =
+ useState<RemotionImageDecoder | null>(null);
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.',
- );
- }
+ const ref = useRef<AnimatedImageCanvasRef>(null);
- let aborted = false;
+ useImperativeHandle(canvasRef, () => {
+ const c = ref.current?.getCanvas();
+ if (!c) {
+ throw new Error('Canvas ref is not set');
+ }
- fetch(resolvedSrc, {mode: 'no-cors'})
- .then((res) => res.body)
- .then((body) => {
- if (aborted) return;
+ return c;
+ }, []);
- return new ImageDecoder({
- data: body,
- type: 'image/gif',
- });
- })
- .then((decoder) => {
- console.log({decoder});
- if (aborted) return;
- setImageDecoder(decoder);
- // onLoad?.();
- // continueRender(id);
+ useEffect(() => {
+ const controller = new AbortController();
+ decodeImage(resolvedSrc, controller.signal)
+ .then((d) => {
+ setImageDecoder(d);
})
.catch((err) => {
- if (aborted) return;
- onError?.(err);
+ if ((err as Error).name === 'AbortError') {
+ return;
+ }
+
+ // TODO: Allow to catch error
+ cancelRender(err);
});
return () => {
- aborted = true;
+ controller.abort();
};
}, [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 frame = useCurrentFrame();
- 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);
+ useEffect(() => {
+ if (!imageDecoder) {
+ return;
+ }
- return () => {
- if (animationFrameId) {
- cancelAnimationFrame(animationFrameId);
- }
- };
- }, [imageDecoder, imageIndex, loopBehavior, playbackRate]);
+ imageDecoder
+ .getFrame(frame % imageDecoder.frameCount)
+ .then((videoFrame) => {
+ ref.current?.draw(videoFrame.image);
+ });
+ }, [frame, imageDecoder]);
return (
- <Canvas
- ref={ref}
- index={imageIndex}
- frames={frames}
- width={width}
- height={height}
- fit={fit}
- {...props}
- />
+ <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 785a2c70c0..451dc3a194 100644
--- a/packages/core/src/animated-image/canvas.tsx
+++ b/packages/core/src/animated-image/canvas.tsx
@@ -1,13 +1,5 @@
-// @ts-nocheck
-import {
- forwardRef,
- useEffect,
- useImperativeHandle,
- useRef,
- useState,
-} from 'react';
+import React, {useCallback, useImperativeHandle, useRef} from 'react';
import type {AnimatedImageFillMode} from './props';
-import {useElementSize} from './use-element-size';
const calcArgs = (
fit: AnimatedImageFillMode,
@@ -80,84 +72,78 @@ const calcArgs = (
}
};
-const makeCanvas = () => {
- if (typeof document === 'undefined') {
- return null;
- }
+type Props = {
+ readonly width?: number;
- const canvas = document.createElement('canvas');
- const ctx = canvas.getContext('2d');
+ readonly height?: number;
+ readonly fit: AnimatedImageFillMode;
- canvas.width = 0;
- canvas.height = 0;
+ readonly className?: string;
- return ctx;
+ readonly style?: React.CSSProperties;
};
-type Props = {
- index: number;
- frames: ImageData[];
- width?: number;
- height?: number;
- fit: AnimatedImageFillMode;
- className?: string;
- style?: React.CSSProperties;
+export type AnimatedImageCanvasRef = {
+ readonly draw: (imageData: VideoFrame) => void;
+ readonly getCanvas: () => HTMLCanvasElement | null;
};
-export const Canvas = forwardRef(
- ({index, frames, width, height, fit, className, style}: Props, ref) => {
- const canvasRef = useRef<HTMLCanvasElement>(null);
- const [tempCtx] = useState(() => {
- return makeCanvas();
- });
+const CanvasRefForwardingFunction: React.ForwardRefRenderFunction<
+ AnimatedImageCanvasRef,
+ Props
+> = ({width, height, fit, className, style}, ref) => {
+ const canvasRef = useRef<HTMLCanvasElement>(null);
- const size = useElementSize(canvasRef);
+ const draw = useCallback(
+ (imageData: VideoFrame) => {
+ const canvas = canvasRef.current;
+ const canvasWidth = width ?? imageData.displayWidth;
+ const canvasHeight = height ?? imageData.displayHeight;
- useImperativeHandle(
- ref,
- () => {
- return canvasRef.current as HTMLCanvasElement;
- },
- [],
- );
-
- useEffect(() => {
- if (!size) {
- return;
+ if (!canvas) {
+ throw new Error('Canvas ref is not set');
}
- 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 (!ctx) {
+ throw new Error('Could not get 2d context');
+ }
- 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);
+ canvas.width = canvasWidth;
+ canvas.height = canvasHeight;
+
+ ctx.drawImage(
+ imageData,
+ ...calcArgs(
+ fit,
+ {
+ height: imageData.displayHeight,
+ width: imageData.displayWidth,
+ },
+ {
+ width: canvasWidth,
+ height: canvasHeight,
+ },
+ ),
+ );
+ },
+ [fit, height, width],
+ );
+
+ useImperativeHandle(ref, () => {
+ return {
+ draw,
+ getCanvas: () => {
+ if (!canvasRef.current) {
+ throw new Error('Canvas ref is not set');
}
- 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}
- />
- );
- },
-);
+ return canvasRef.current;
+ },
+ };
+ }, [draw]);
+
+ return <canvas ref={canvasRef} className={className} style={style} />;
+};
+
+export const Canvas = React.forwardRef(CanvasRefForwardingFunction);
diff --git a/packages/core/src/animated-image/decode-image.ts b/packages/core/src/animated-image/decode-image.ts
new file mode 100644
index 0000000000..7572d528e7
--- /dev/null
+++ b/packages/core/src/animated-image/decode-image.ts
@@ -0,0 +1,43 @@
+export type RemotionImageDecoder = {
+ getFrame: (i: number) => Promise<ImageDecodeResult>;
+ frameCount: number;
+};
+
+export const decodeImage = async (
+ resolvedSrc: string,
+ signal: AbortSignal,
+): Promise<RemotionImageDecoder> => {
+ if (typeof ImageDecoder === 'undefined') {
+ throw new Error(
+ 'Your browser does not support the WebCodecs ImageDecoder API.',
+ );
+ }
+
+ const res = await fetch(resolvedSrc, {signal});
+ const {body} = res;
+
+ if (!body) {
+ throw new Error('Got no body');
+ }
+
+ const decoder = new ImageDecoder({
+ data: body,
+ type: res.headers.get('Content-Type') || 'image/gif',
+ });
+ await decoder.completed;
+ const {selectedTrack} = decoder.tracks;
+ if (!selectedTrack) {
+ throw new Error('No selected track');
+ }
+
+ return {
+ getFrame: async (i: number) => {
+ const frame = await decoder.decode({
+ frameIndex: i,
+ completeFramesOnly: true,
+ });
+ return frame;
+ },
+ frameCount: selectedTrack.frameCount,
+ };
+};
diff --git a/packages/core/src/animated-image/use-element-size.tsx b/packages/core/src/animated-image/use-element-size.tsx
deleted file mode 100644
index a90e6909af..0000000000
--- a/packages/core/src/animated-image/use-element-size.tsx
+++ /dev/null
@@ -1,94 +0,0 @@
-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;
-};