Skip to content

πŸŽ₯ Make videos programmatically with React

`@remotion/gif`: Integrate effect system with `<Gif>`

Jonny Burgeref27cea0907c
diff --git a/packages/example/src/Gif/GifEffects.tsx b/packages/example/src/Gif/GifEffects.tsx
new file mode 100644
index 0000000000..875ae89a5a
--- /dev/null
+++ b/packages/example/src/Gif/GifEffects.tsx
@@ -0,0 +1,218 @@
+import {blur} from '@remotion/effects/blur';
+import {halftone} from '@remotion/effects/halftone';
+import {tint} from '@remotion/effects/tint';
+import {wave} from '@remotion/effects/wave';
+import {Gif} from '@remotion/gif';
+import {StudioInternals} from '@remotion/studio';
+import React from 'react';
+import {
+ AbsoluteFill,
+ staticFile,
+ useCurrentFrame,
+ useVideoConfig,
+} from 'remotion';
+
+const GIF_SRC = staticFile('giphy.gif');
+
+const Tile: React.FC<{
+ readonly title: string;
+ readonly subtitle: string;
+ readonly children: React.ReactNode;
+}> = ({title, subtitle, children}) => {
+ return (
+ <div
+ style={{
+ flex: 1,
+ display: 'flex',
+ flexDirection: 'column',
+ border: '1px solid #1f2937',
+ borderRadius: 12,
+ overflow: 'hidden',
+ backgroundColor: '#000',
+ minWidth: 0,
+ minHeight: 0,
+ }}
+ >
+ <div
+ style={{
+ padding: '10px 14px',
+ backgroundColor: '#0b1220',
+ borderBottom: '1px solid #1f2937',
+ display: 'flex',
+ flexDirection: 'column',
+ gap: 2,
+ }}
+ >
+ <div
+ style={{
+ fontFamily: 'monospace',
+ fontSize: 18,
+ color: '#f8fafc',
+ fontWeight: 700,
+ }}
+ >
+ {title}
+ </div>
+ <div
+ style={{
+ fontFamily: 'monospace',
+ fontSize: 12,
+ color: '#94a3b8',
+ }}
+ >
+ {subtitle}
+ </div>
+ </div>
+ <div
+ style={{
+ flex: 1,
+ position: 'relative',
+ overflow: 'hidden',
+ }}
+ >
+ {children}
+ </div>
+ </div>
+ );
+};
+
+const tileGifStyle: React.CSSProperties = {
+ width: '100%',
+ height: '100%',
+};
+
+const AnimatedBlurGif: React.FC = () => {
+ const frame = useCurrentFrame();
+ const {fps} = useVideoConfig();
+
+ const t = (frame / fps) * Math.PI * 2 * 0.35;
+ const blurRadius = 9 + 9 * Math.sin(t);
+
+ return (
+ <Gif
+ src={GIF_SRC}
+ fit="contain"
+ style={tileGifStyle}
+ _experimentalEffects={[blur({radius: blurRadius})]}
+ />
+ );
+};
+
+const AnimatedWaveGif: React.FC = () => {
+ const frame = useCurrentFrame();
+ const evolution = frame * 0.2;
+
+ return (
+ <Gif
+ src={GIF_SRC}
+ fit="contain"
+ style={tileGifStyle}
+ _experimentalEffects={[
+ wave({
+ amplitude: 22,
+ wavelength: 180,
+ evolution,
+ sliceWidth: 4,
+ background: '#020617',
+ }),
+ ]}
+ />
+ );
+};
+
+const StackedGif: React.FC = () => {
+ const frame = useCurrentFrame();
+ const evolution = frame * 0.2;
+
+ return (
+ <Gif
+ src={GIF_SRC}
+ fit="contain"
+ style={tileGifStyle}
+ _experimentalEffects={[
+ tint({color: '#ff5fa2', amount: 0.4}),
+ wave({
+ amplitude: 12,
+ wavelength: 160,
+ evolution,
+ sliceWidth: 4,
+ background: '#020617',
+ }),
+ blur({radius: 6}),
+ ]}
+ />
+ );
+};
+
+const Comp: React.FC = () => {
+ return (
+ <AbsoluteFill
+ style={{
+ backgroundColor: '#020617',
+ padding: 24,
+ gap: 16,
+ display: 'flex',
+ flexDirection: 'column',
+ }}
+ >
+ <div
+ style={{
+ fontFamily: 'monospace',
+ fontSize: 28,
+ color: '#f8fafc',
+ fontWeight: 700,
+ }}
+ >
+ @remotion/gif effects testbed
+ </div>
+ <div style={{flex: 1, display: 'flex', flexDirection: 'row', gap: 16}}>
+ <Tile title="baseline" subtitle="no effects">
+ <Gif src={GIF_SRC} fit="contain" style={tileGifStyle} />
+ </Tile>
+ <Tile title="tint" subtitle="color: '#ff5fa2', amount: 0.6">
+ <Gif
+ src={GIF_SRC}
+ fit="contain"
+ style={tileGifStyle}
+ _experimentalEffects={[tint({color: '#ff5fa2', amount: 0.6})]}
+ />
+ </Tile>
+ <Tile title="halftone" subtitle="circles, dotSize 12, on luminance">
+ <Gif
+ src={GIF_SRC}
+ fit="contain"
+ style={tileGifStyle}
+ _experimentalEffects={[
+ halftone({
+ shape: 'circle',
+ dotSize: 12,
+ dotSpacing: 12,
+ color: '#000',
+ }),
+ ]}
+ />
+ </Tile>
+ </div>
+ <div style={{flex: 1, display: 'flex', flexDirection: 'row', gap: 16}}>
+ <Tile title="blur" subtitle="separable Gaussian, animated 0β†’18">
+ <AnimatedBlurGif />
+ </Tile>
+ <Tile title="wave" subtitle="amplitude 22, evolution from frame">
+ <AnimatedWaveGif />
+ </Tile>
+ <Tile title="tint + wave + blur" subtitle="effect chain">
+ <StackedGif />
+ </Tile>
+ </div>
+ </AbsoluteFill>
+ );
+};
+
+export const GifEffectsTestbed = StudioInternals.createComposition({
+ component: Comp,
+ id: 'gif-effects-testbed',
+ width: 1920,
+ height: 1080,
+ durationInFrames: 300,
+ fps: 30,
+});
diff --git a/packages/example/src/Root.tsx b/packages/example/src/Root.tsx
index b920c55756..773e12ca25 100644
--- a/packages/example/src/Root.tsx
+++ b/packages/example/src/Root.tsx
@@ -38,6 +38,7 @@ import {FontDemo} from './Fonts';
import {Framer} from './Framer';
import {FreezeExample} from './Freeze/FreezeExample';
import {FreezePortion} from './FreezePortion/FreezePortion';
+import {GifEffectsTestbed} from './Gif/GifEffects';
import {GoogleFontsCjk} from './GoogleFontsCjk/GoogleFontsCjk';
import {Green} from './Green';
import {HlsDemo} from './Hls/HlsDemo';
@@ -1665,6 +1666,7 @@ export const Index: React.FC = () => {
durationInFrames={150}
/>
<RiveEffectsTestbed />
+ <GifEffectsTestbed />
</Folder>
<Folder name="Premount">
<Composition
diff --git a/packages/gif/src/Gif.tsx b/packages/gif/src/Gif.tsx
index 62be058685..abf6b49957 100644
--- a/packages/gif/src/Gif.tsx
+++ b/packages/gif/src/Gif.tsx
@@ -4,6 +4,7 @@ import {
Sequence,
useRemotionEnvironment,
useVideoConfig,
+ type EffectsProp,
type SequenceControls,
type SequenceProps,
type SequenceSchema,
@@ -12,12 +13,20 @@ import {GifForDevelopment} from './GifForDevelopment';
import {GifForRendering} from './GifForRendering';
import type {RemotionGifProps} from './props';
+const {
+ addSequenceStackTraces,
+ useMemoizedEffectDefinitions,
+ useMemoizedEffects,
+ wrapInSchema,
+} = Internals;
+
export type GifProps = Omit<
SequenceProps,
'children' | 'durationInFrames' | 'layout'
> &
RemotionGifProps & {
readonly durationInFrames?: number;
+ readonly _experimentalEffects?: EffectsProp;
};
/*
@@ -51,6 +60,7 @@ const GifInner = ({
durationInFrames,
style,
_experimentalControls: controls,
+ _experimentalEffects: effects = [],
ref,
...sequenceProps
}: GifProps & {
@@ -61,7 +71,15 @@ const GifInner = ({
const {durationInFrames: videoDuration} = useVideoConfig();
const resolvedDuration = durationInFrames ?? videoDuration;
- const gifProps: RemotionGifProps = {
+ const memoizedEffectDefinitions = useMemoizedEffectDefinitions(effects);
+ const memoizedEffects = useMemoizedEffects({
+ effects,
+ overrideId: controls?.overrideId ?? null,
+ });
+
+ const gifProps: RemotionGifProps & {
+ readonly effects: typeof memoizedEffects;
+ } = {
src,
width,
height,
@@ -73,6 +91,7 @@ const GifInner = ({
id,
delayRenderTimeoutInMilliseconds,
style,
+ effects: memoizedEffects,
};
const inner = env.isRendering ? (
@@ -87,6 +106,7 @@ const GifInner = ({
durationInFrames={resolvedDuration}
name="<Gif>"
_experimentalControls={controls}
+ _experimentalEffects={memoizedEffectDefinitions}
{...sequenceProps}
>
{inner}
@@ -94,8 +114,8 @@ const GifInner = ({
);
};
-export const Gif = Internals.wrapInSchema(GifInner, gifSchema);
+export const Gif = wrapInSchema(GifInner, gifSchema);
Gif.displayName = 'Gif';
-Internals.addSequenceStackTraces(Gif);
+addSequenceStackTraces(Gif);
diff --git a/packages/gif/src/GifForDevelopment.tsx b/packages/gif/src/GifForDevelopment.tsx
index 61d6f483a5..a2769e2ca7 100644
--- a/packages/gif/src/GifForDevelopment.tsx
+++ b/packages/gif/src/GifForDevelopment.tsx
@@ -1,5 +1,6 @@
/* eslint-disable no-console */
import {forwardRef, useEffect, useRef, useState} from 'react';
+import type {EffectDefinitionAndStack} from 'remotion';
import {Canvas} from './canvas';
import {manuallyManagedGifCache, volatileGifCache} from './gif-cache';
import {isCorsError} from './is-cors-error';
@@ -10,7 +11,9 @@ import {useCurrentGifIndex} from './useCurrentGifIndex';
export const GifForDevelopment = forwardRef<
HTMLCanvasElement,
- RemotionGifProps
+ RemotionGifProps & {
+ readonly effects: EffectDefinitionAndStack<unknown>[];
+ }
>(
(
{
@@ -22,6 +25,7 @@ export const GifForDevelopment = forwardRef<
playbackRate = 1,
onLoad,
fit = 'fill',
+ effects,
...props
},
ref,
@@ -112,6 +116,7 @@ export const GifForDevelopment = forwardRef<
frames={state.frames}
width={width}
height={height}
+ effects={effects}
{...props}
ref={ref}
/>
diff --git a/packages/gif/src/GifForRendering.tsx b/packages/gif/src/GifForRendering.tsx
index b16a5e16c8..f82040bf83 100644
--- a/packages/gif/src/GifForRendering.tsx
+++ b/packages/gif/src/GifForRendering.tsx
@@ -1,5 +1,6 @@
import {forwardRef, useEffect, useRef, useState} from 'react';
import {Internals, useDelayRender} from 'remotion';
+import type {EffectDefinitionAndStack} from 'remotion';
import {Canvas} from './canvas';
import {volatileGifCache} from './gif-cache';
import {isCorsError} from './is-cors-error';
@@ -8,7 +9,12 @@ import {parseGif} from './react-tools';
import {resolveGifSource} from './resolve-gif-source';
import {useCurrentGifIndex} from './useCurrentGifIndex';
-export const GifForRendering = forwardRef<HTMLCanvasElement, RemotionGifProps>(
+export const GifForRendering = forwardRef<
+ HTMLCanvasElement,
+ RemotionGifProps & {
+ readonly effects: EffectDefinitionAndStack<unknown>[];
+ }
+>(
(
{
src,
@@ -20,6 +26,7 @@ export const GifForRendering = forwardRef<HTMLCanvasElement, RemotionGifProps>(
playbackRate = 1,
fit = 'fill',
delayRenderTimeoutInMilliseconds,
+ effects,
...props
},
ref,
@@ -152,6 +159,7 @@ export const GifForRendering = forwardRef<HTMLCanvasElement, RemotionGifProps>(
frames={state.frames}
width={width}
height={height}
+ effects={effects}
{...props}
ref={ref}
/>
diff --git a/packages/gif/src/canvas.tsx b/packages/gif/src/canvas.tsx
index 0930969270..7d43112a0e 100644
--- a/packages/gif/src/canvas.tsx
+++ b/packages/gif/src/canvas.tsx
@@ -3,12 +3,17 @@ import {
forwardRef,
useEffect,
useImperativeHandle,
+ useMemo,
useRef,
useState,
} from 'react';
+import type {EffectDefinitionAndStack} from 'remotion';
+import {Internals, useDelayRender} from 'remotion';
import type {GifFillMode} from './props';
import {useElementSize} from './use-element-size';
+const {runEffectChain, useEffectChainState} = Internals;
+
const calcArgs = (
fit: GifFillMode,
frameSize: {
@@ -102,15 +107,38 @@ type Props = {
readonly fit: GifFillMode;
readonly className?: string;
readonly style?: React.CSSProperties;
+ readonly effects: EffectDefinitionAndStack<unknown>[];
};
export const Canvas = forwardRef(
- ({index, frames, width, height, fit, className, style}: Props, ref) => {
+ (
+ {index, frames, width, height, fit, className, style, effects}: Props,
+ ref,
+ ) => {
const canvasRef = useRef<HTMLCanvasElement>(null);
const [tempCtx] = useState(() => {
return makeCanvas();
});
+ const sourceCanvas = useMemo(() => {
+ if (typeof document === 'undefined') {
+ return null;
+ }
+
+ return document.createElement('canvas');
+ }, []);
+
+ const effectOutputCanvas = useMemo(() => {
+ if (typeof document === 'undefined') {
+ return null;
+ }
+
+ return document.createElement('canvas');
+ }, []);
+
+ const chainState = useEffectChainState();
+ const {delayRender, continueRender} = useDelayRender();
+
const size = useElementSize(canvasRef);
useImperativeHandle(ref, () => {
@@ -123,28 +151,141 @@ export const Canvas = forwardRef(
}
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(
+ const outputCanvas = canvasRef.current;
+ const outputCtx = outputCanvas?.getContext('2d');
+ if (!imageData || !tempCtx || !outputCtx || !outputCanvas) {
+ return;
+ }
+
+ if (
+ tempCtx.canvas.width < imageData.width ||
+ tempCtx.canvas.height < imageData.height
+ ) {
+ tempCtx.canvas.width = imageData.width;
+ tempCtx.canvas.height = imageData.height;
+ }
+
+ const layoutWidth = width ?? size.width;
+ const layoutHeight = height ?? size.height;
+
+ if (layoutWidth <= 0 || layoutHeight <= 0) {
+ return;
+ }
+
+ if (size.width > 0 && size.height > 0) {
+ outputCtx.clearRect(0, 0, size.width, size.height);
+ tempCtx.clearRect(0, 0, tempCtx.canvas.width, tempCtx.canvas.height);
+ }
+
+ tempCtx.putImageData(imageData, 0, 0);
+
+ const frameSize = {
+ width: imageData.width,
+ height: imageData.height,
+ };
+ const layoutSize = {
+ width: layoutWidth,
+ height: layoutHeight,
+ };
+
+ if (effects.length === 0) {
+ outputCtx.drawImage(
tempCtx.canvas,
- ...calcArgs(fit, imageData, {width: size.width, height: size.height}),
+ ...calcArgs(fit, frameSize, layoutSize),
);
+ return;
+ }
+
+ if (!sourceCanvas || !effectOutputCanvas) {
+ return;
+ }
+
+ // Effects run at the GIF's intrinsic pixel dimensions; fit is applied
+ // when compositing onto the layout-sized output canvas.
+ if (
+ sourceCanvas.width !== frameSize.width ||
+ sourceCanvas.height !== frameSize.height
+ ) {
+ sourceCanvas.width = frameSize.width;
+ sourceCanvas.height = frameSize.height;
+ }
+
+ if (
+ effectOutputCanvas.width !== frameSize.width ||
+ effectOutputCanvas.height !== frameSize.height
+ ) {
+ effectOutputCanvas.width = frameSize.width;
+ effectOutputCanvas.height = frameSize.height;
+ }
+
+ const sourceCtx = sourceCanvas.getContext('2d');
+ if (!sourceCtx) {
+ return;
}
- }, [index, frames, fit, tempCtx, size]);
+
+ sourceCtx.clearRect(0, 0, frameSize.width, frameSize.height);
+ sourceCtx.putImageData(imageData, 0, 0);
+
+ const state = chainState.get(frameSize.width, frameSize.height);
+ if (!state) {
+ return;
+ }
+
+ if (
+ outputCanvas.width !== layoutWidth ||
+ outputCanvas.height !== layoutHeight
+ ) {
+ outputCanvas.width = layoutWidth;
+ outputCanvas.height = layoutHeight;
+ }
+
+ const effectChainHandle = delayRender('Rendering <Gif/> effect chain');
+
+ let cancelled = false;
+
+ runEffectChain({
+ state,
+ source: sourceCanvas,
+ effects,
+ output: effectOutputCanvas,
+ width: frameSize.width,
+ height: frameSize.height,
+ })
+ .then((completed: boolean) => {
+ if (cancelled || !completed) {
+ return;
+ }
+
+ outputCtx.clearRect(0, 0, layoutWidth, layoutHeight);
+ outputCtx.drawImage(
+ effectOutputCanvas,
+ ...calcArgs(fit, frameSize, layoutSize),
+ );
+ continueRender(effectChainHandle);
+ })
+ .catch((err: unknown) => {
+ throw err;
+ });
+
+ return () => {
+ cancelled = true;
+ continueRender(effectChainHandle);
+ };
+ }, [
+ index,
+ frames,
+ fit,
+ tempCtx,
+ size,
+ width,
+ height,
+ effects,
+ sourceCanvas,
+ effectOutputCanvas,
+ chainState,
+ delayRender,
+ continueRender,
+ ]);
return (
<canvas