Skip to content

🎥 Make videos programmatically with React

implement GIF looping modes

Jonny Burger45574d8aa3d8
diff --git a/packages/example/src/GifTest/loop-behavior.tsx b/packages/example/src/GifTest/loop-behavior.tsx
new file mode 100644
index 0000000000..25bf999ebf
--- /dev/null
+++ b/packages/example/src/GifTest/loop-behavior.tsx
@@ -0,0 +1,42 @@
+import {Gif} from '@remotion/gif';
+import {Series} from 'remotion';
+
+const GifLoopBehavior: React.FC = () => {
+ return (
+ <Series>
+ <Series.Sequence durationInFrames={180}>
+ <Gif
+ loopBehavior="pause-after-finish"
+ style={{
+ width: 1920,
+ height: 1080,
+ }}
+ src="https://c.tenor.com/pCcL8OOdEBUAAAAC/gifs-away-gif.gif"
+ />
+ </Series.Sequence>
+ <Series.Sequence durationInFrames={180}>
+ <Gif
+ loopBehavior="loop"
+ style={{
+ width: 1920,
+ height: 1080,
+ }}
+ src="https://c.tenor.com/pCcL8OOdEBUAAAAC/gifs-away-gif.gif"
+ />
+ </Series.Sequence>
+ <Series.Sequence durationInFrames={180}>
+ <Gif
+ loopBehavior="unmount-after-finish"
+ fit="fill"
+ style={{
+ width: 1920,
+ height: 1080,
+ }}
+ src="https://c.tenor.com/pCcL8OOdEBUAAAAC/gifs-away-gif.gif"
+ />
+ </Series.Sequence>
+ </Series>
+ );
+};
+
+export default GifLoopBehavior;
diff --git a/packages/example/src/Video.tsx b/packages/example/src/Video.tsx
index 563f7d6a67..a1e0f3dd40 100644
--- a/packages/example/src/Video.tsx
+++ b/packages/example/src/Video.tsx
@@ -548,6 +548,14 @@ export const Index: React.FC = () => {
fps={30}
durationInFrames={150}
/>
+ <Composition
+ id="gif-loop-behavior"
+ lazyComponent={() => import('./GifTest/loop-behavior')}
+ width={1920}
+ height={1080}
+ fps={30}
+ durationInFrames={540}
+ />
</Folder>
<Folder name="og-images">
<Composition
diff --git a/packages/gif/src/GifForDevelopment.tsx b/packages/gif/src/GifForDevelopment.tsx
index 7fb2a23e6f..3a984d1e16 100644
--- a/packages/gif/src/GifForDevelopment.tsx
+++ b/packages/gif/src/GifForDevelopment.tsx
@@ -10,95 +10,113 @@ import {useCurrentGifIndex} from './useCurrentGifIndex';
export const GifForDevelopment = forwardRef<
HTMLCanvasElement,
RemotionGifProps
->(({src, width, height, onError, onLoad, fit = 'fill', ...props}, ref) => {
- const resolvedSrc = new URL(src, window.location.origin).href;
- const [state, update] = useState<GifState>(() => {
- const parsedGif = gifCache.get(resolvedSrc);
+>(
+ (
+ {
+ src,
+ width,
+ height,
+ onError,
+ loopBehavior = 'loop',
+ onLoad,
+ fit = 'fill',
+ ...props
+ },
+ ref
+ ) => {
+ const resolvedSrc = new URL(src, window.location.origin).href;
+ const [state, update] = useState<GifState>(() => {
+ const parsedGif = gifCache.get(resolvedSrc);
- if (parsedGif === undefined) {
- return {
- delays: [],
- frames: [],
- width: 0,
- height: 0,
- };
- }
+ if (parsedGif === undefined) {
+ return {
+ delays: [],
+ frames: [],
+ width: 0,
+ height: 0,
+ };
+ }
- return parsedGif as GifState;
- });
- const [error, setError] = useState<Error | null>(null);
+ return parsedGif as GifState;
+ });
+ const [error, setError] = useState<Error | null>(null);
- const [id] = useState(() =>
- delayRender(`Rendering <Gif/> with src="${resolvedSrc}"`)
- );
+ const [id] = useState(() =>
+ delayRender(`Rendering <Gif/> with src="${resolvedSrc}"`)
+ );
- const currentOnLoad = useRef(onLoad);
- const currentOnError = useRef(onError);
- currentOnLoad.current = onLoad;
- currentOnError.current = onError;
+ const currentOnLoad = useRef(onLoad);
+ const currentOnError = useRef(onError);
+ currentOnLoad.current = onLoad;
+ currentOnError.current = onError;
- useEffect(() => {
- let done = false;
- let aborted = false;
- const {prom, cancel} = parseWithWorker(resolvedSrc);
- const newHandle = delayRender('Loading <Gif /> with src=' + resolvedSrc);
+ useEffect(() => {
+ let done = false;
+ let aborted = false;
+ const {prom, cancel} = parseWithWorker(resolvedSrc);
+ const newHandle = delayRender('Loading <Gif /> with src=' + resolvedSrc);
- prom
- .then((parsed) => {
- currentOnLoad.current?.(parsed);
- update(parsed);
- gifCache.set(resolvedSrc, parsed);
- done = true;
- continueRender(newHandle);
- continueRender(id);
- })
- .catch((err) => {
- if (aborted) {
+ prom
+ .then((parsed) => {
+ currentOnLoad.current?.(parsed);
+ update(parsed);
+ gifCache.set(resolvedSrc, parsed);
+ done = true;
continueRender(newHandle);
- return;
- }
+ continueRender(id);
+ })
+ .catch((err) => {
+ if (aborted) {
+ continueRender(newHandle);
+ return;
+ }
- if (currentOnError.current) {
- currentOnError.current(err);
- } else {
- setError(err);
+ if (currentOnError.current) {
+ currentOnError.current(err);
+ } else {
+ setError(err);
+ }
+ });
+
+ return () => {
+ if (!done) {
+ aborted = true;
+ cancel();
}
- });
- return () => {
- if (!done) {
- aborted = true;
- cancel();
- }
+ continueRender(newHandle);
+ };
+ }, [id, resolvedSrc]);
- continueRender(newHandle);
- };
- }, [id, resolvedSrc]);
+ if (error) {
+ console.error(error.stack);
+ if (isCorsError(error)) {
+ throw new Error(
+ `Failed to render GIF with source ${src}: "${error.message}". You must enable CORS for this URL.`
+ );
+ }
- if (error) {
- console.error(error.stack);
- if (isCorsError(error)) {
throw new Error(
- `Failed to render GIF with source ${src}: "${error.message}". You must enable CORS for this URL.`
+ `Failed to render GIF with source ${src}: "${error.message}".`
);
}
- throw new Error(
- `Failed to render GIF with source ${src}: "${error.message}".`
- );
- }
+ const index = useCurrentGifIndex(state.delays, loopBehavior);
- const index = useCurrentGifIndex(state.delays);
+ if (index === -1) {
+ return null;
+ }
- return (
- <Canvas
- fit={fit}
- index={index}
- frames={state.frames}
- width={width}
- height={height}
- {...props}
- ref={ref}
- />
- );
-});
+ return (
+ <Canvas
+ fit={fit}
+ index={index}
+ frames={state.frames}
+ width={width}
+ height={height}
+ {...props}
+ ref={ref}
+ />
+ );
+ }
+);
diff --git a/packages/gif/src/GifForRendering.tsx b/packages/gif/src/GifForRendering.tsx
index 481ee1bdaa..bfd9cb6e5e 100644
--- a/packages/gif/src/GifForRendering.tsx
+++ b/packages/gif/src/GifForRendering.tsx
@@ -8,7 +8,19 @@ import {parseGif} from './react-tools';
import {useCurrentGifIndex} from './useCurrentGifIndex';
export const GifForRendering = forwardRef<HTMLCanvasElement, RemotionGifProps>(
- ({src, width, height, onLoad, onError, fit = 'fill', ...props}, ref) => {
+ (
+ {
+ src,
+ width,
+ height,
+ onLoad,
+ onError,
+ loopBehavior = 'loop',
+ fit = 'fill',
+ ...props
+ },
+ ref
+ ) => {
const resolvedSrc = new URL(src, window.location.origin).href;
const [state, update] = useState<GifState>(() => {
const parsedGif = gifCache.get(resolvedSrc);
@@ -30,7 +42,7 @@ export const GifForRendering = forwardRef<HTMLCanvasElement, RemotionGifProps>(
delayRender(`Rendering <Gif/> with src="${resolvedSrc}"`)
);
- const index = useCurrentGifIndex(state.delays);
+ const index = useCurrentGifIndex(state.delays, loopBehavior);
const currentOnLoad = useRef(onLoad);
const currentOnError = useRef(onError);
currentOnLoad.current = onLoad;
@@ -87,6 +99,10 @@ export const GifForRendering = forwardRef<HTMLCanvasElement, RemotionGifProps>(
);
}
+ if (index === -1) {
+ return null;
+ }
+
return (
<Canvas
fit={fit}
diff --git a/packages/gif/src/props.ts b/packages/gif/src/props.ts
index e27bd89168..5f2f83d236 100644
--- a/packages/gif/src/props.ts
+++ b/packages/gif/src/props.ts
@@ -1,3 +1,8 @@
+export type GifLoopBehavior =
+ | 'loop'
+ | 'pause-after-finish'
+ | 'unmount-after-finish';
+
export type RemotionGifProps = {
src: string;
width?: number;
@@ -11,6 +16,7 @@ export type RemotionGifProps = {
onError?: (error: Error) => void;
fit?: GifFillMode;
style?: React.CSSProperties;
+ loopBehavior?: GifLoopBehavior;
};
export type GifState = {
diff --git a/packages/gif/src/useCurrentGifIndex.tsx b/packages/gif/src/useCurrentGifIndex.tsx
index 32e94e12eb..c882960334 100644
--- a/packages/gif/src/useCurrentGifIndex.tsx
+++ b/packages/gif/src/useCurrentGifIndex.tsx
@@ -1,7 +1,11 @@
import {useMemo} from 'react';
import {useCurrentFrame, useVideoConfig} from 'remotion';
+import type {GifLoopBehavior} from './props';
-export function useCurrentGifIndex(delays: number[]): number {
+export function useCurrentGifIndex(
+ delays: number[],
+ loopBehavior: GifLoopBehavior
+): number {
const currentFrame = useCurrentFrame();
const videoConfig = useVideoConfig();
@@ -16,23 +20,30 @@ export function useCurrentGifIndex(delays: number[]): number {
return 1;
}, [delays]);
- const index = useMemo(() => {
- if (delays.length === 0) {
- return 0;
- }
+ if (delays.length === 0) {
+ return 0;
+ }
+
+ const time = (currentFrame / videoConfig.fps) * 1000;
- let currentTime = ((currentFrame / videoConfig.fps) * 1000) % duration;
+ if (loopBehavior === 'pause-after-finish' && time >= duration) {
+ return delays.length - 1;
+ }
- for (const [i, delay] of delays.entries()) {
- if (currentTime < delay) {
- return i;
- }
+ if (loopBehavior === 'unmount-after-finish' && time >= duration) {
+ return -1;
+ }
- currentTime -= delay;
+ let currentTime = time % duration;
+
+ for (let i = 0; i < delays.length; i++) {
+ const delay = delays[i];
+ if (currentTime < delay) {
+ return i;
}
- return 0;
- }, [delays, duration, currentFrame, videoConfig]);
+ currentTime -= delay;
+ }
- return index;
+ return 0;
}