π₯ Make videos programmatically with React
Add _experimentalEffects support to AnimatedImage
JonnyBurgerffba512e3fc9
diff --git a/packages/core/src/animated-image/AnimatedImage.tsx b/packages/core/src/animated-image/AnimatedImage.tsxindex 6e25144f48..721b1756f0 100644--- a/packages/core/src/animated-image/AnimatedImage.tsx+++ b/packages/core/src/animated-image/AnimatedImage.tsx@@ -9,6 +9,11 @@ import {} from 'react';import {cancelRender} from '../cancel-render.js';import type {SequenceControls} from '../CompositionManager.js';+import type {EffectsProp} from '../effects/effect-types.js';+import {+ useMemoizedEffectDefinitions,+ useMemoizedEffects,+} from '../effects/use-memoized-effects.js';import {addSequenceStackTraces} from '../enable-sequence-stack-traces.js';import {hiddenField,@@ -40,9 +45,14 @@ const animatedImageSchema = {hidden: hiddenField,} as const satisfies SequenceSchema;+type AnimatedImageContentProps = RemotionAnimatedImageProps & {+ readonly effects: EffectsProp;+ readonly controls: SequenceControls | undefined;+};+const AnimatedImageContent = forwardRef<HTMLCanvasElement,- RemotionAnimatedImageProps+ AnimatedImageContentProps>(({@@ -53,6 +63,8 @@ const AnimatedImageContent = forwardRef<loopBehavior = 'loop',playbackRate = 1,fit = 'fill',+ effects,+ controls,...props},canvasRef,@@ -84,6 +96,11 @@ const AnimatedImageContent = forwardRef<const ref = useRef<AnimatedImageCanvasRef>(null);+ const memoizedEffects = useMemoizedEffects({+ effects,+ overrideId: controls?.overrideId ?? null,+ });+useImperativeHandle(canvasRef, () => {const c = ref.current?.getCanvas();if (!c) {@@ -142,20 +159,31 @@ const AnimatedImageContent = forwardRef<`Rendering frame at ${currentTime} of <AnimatedImage src="${src}"/>`,);+ let cancelled = false;+imageDecoder.getFrame(currentTime, loopBehavior)- .then((videoFrame) => {- if (mountState.current.isMounted) {- if (videoFrame === null) {- ref.current?.clear();- } else {- ref.current?.draw(videoFrame.frame!);- }+ .then(async (videoFrame) => {+ if (!mountState.current.isMounted || cancelled) {+ return;}- continueRender(delay);+ if (videoFrame === null) {+ ref.current?.clear();+ continueRender(delay);+ return;+ }++ const completed = await ref.current?.draw(videoFrame.frame!);+ if (completed && !cancelled) {+ continueRender(delay);+ }}).catch((err) => {+ if (cancelled) {+ return;+ }+if (onError) {onError(err as Error);continueRender(delay);@@ -163,6 +191,11 @@ const AnimatedImageContent = forwardRef<cancelRender(err);}});++ return () => {+ cancelled = true;+ continueRender(delay);+ };}, [currentTime,imageDecoder,@@ -171,10 +204,21 @@ const AnimatedImageContent = forwardRef<src,continueRender,delayRender,+ memoizedEffects,+ fit,+ width,+ height,]);return (- <Canvas ref={ref} width={width} height={height} fit={fit} {...props} />+ <Canvas+ ref={ref}+ width={width}+ height={height}+ fit={fit}+ effects={memoizedEffects}+ {...props}+ />);},);@@ -193,6 +237,7 @@ const AnimatedImageInner = ({className,style,durationInFrames,+ _experimentalEffects: effects = [],_experimentalControls: controls,ref,...sequenceProps@@ -203,6 +248,8 @@ const AnimatedImageInner = ({const {durationInFrames: videoDuration} = useVideoConfig();const resolvedDuration = durationInFrames ?? videoDuration;+ const memoizedEffectDefinitions = useMemoizedEffectDefinitions(effects);+const animatedImageProps: RemotionAnimatedImageProps = {src,width,@@ -222,9 +269,15 @@ const AnimatedImageInner = ({durationInFrames={resolvedDuration}name="<AnimatedImage>"_experimentalControls={controls}+ _experimentalEffects={memoizedEffectDefinitions}{...sequenceProps}>- <AnimatedImageContent {...animatedImageProps} ref={ref} />+ <AnimatedImageContent+ {...animatedImageProps}+ effects={effects}+ controls={controls}+ ref={ref}+ /></Sequence>);};diff --git a/packages/core/src/animated-image/canvas.tsx b/packages/core/src/animated-image/canvas.tsxindex dea6e88cf8..2895e9d16d 100644--- a/packages/core/src/animated-image/canvas.tsx+++ b/packages/core/src/animated-image/canvas.tsx@@ -1,4 +1,7 @@-import React, {useCallback, useImperativeHandle, useRef} from 'react';+import React, {useCallback, useImperativeHandle, useMemo, useRef} from 'react';+import type {EffectDefinitionAndStack} from '../effects/effect-types.js';+import {runEffectChain} from '../effects/run-effect-chain.js';+import {useEffectChainState} from '../effects/use-effect-chain-state.js';import type {AnimatedImageFillMode} from './props';const calcArgs = (@@ -81,10 +84,11 @@ type Props = {readonly className?: string;readonly style?: React.CSSProperties;+ readonly effects: EffectDefinitionAndStack<unknown>[];};export type AnimatedImageCanvasRef = {- readonly draw: (imageData: VideoFrame) => void;+ readonly draw: (imageData: VideoFrame) => Promise<boolean>;readonly getCanvas: () => HTMLCanvasElement | null;clear: () => void;};@@ -92,11 +96,20 @@ export type AnimatedImageCanvasRef = {const CanvasRefForwardingFunction: React.ForwardRefRenderFunction<AnimatedImageCanvasRef,Props-> = ({width, height, fit, className, style}, ref) => {+> = ({width, height, fit, className, style, effects}, ref) => {const canvasRef = useRef<HTMLCanvasElement>(null);+ const chainState = useEffectChainState();++ const sourceCanvas = useMemo(() => {+ if (typeof document === 'undefined') {+ return null;+ }++ return document.createElement('canvas');+ }, []);const draw = useCallback(- (imageData: VideoFrame) => {+ async (imageData: VideoFrame) => {const canvas = canvasRef.current;const canvasWidth = width ?? imageData.displayWidth;const canvasHeight = height ?? imageData.displayHeight;@@ -105,15 +118,19 @@ const CanvasRefForwardingFunction: React.ForwardRefRenderFunction<throw new Error('Canvas ref is not set');}- const ctx = canvasRef.current?.getContext('2d');- if (!ctx) {- throw new Error('Could not get 2d context');+ if (!sourceCanvas) {+ throw new Error('Source canvas is not available');}- canvas.width = canvasWidth;- canvas.height = canvasHeight;+ sourceCanvas.width = canvasWidth;+ sourceCanvas.height = canvasHeight;- ctx.drawImage(+ const sourceCtx = sourceCanvas.getContext('2d');+ if (!sourceCtx) {+ throw new Error('Could not get 2d context for source canvas');+ }++ sourceCtx.drawImage(imageData,...calcArgs(fit,@@ -127,8 +144,20 @@ const CanvasRefForwardingFunction: React.ForwardRefRenderFunction<},),);++ canvas.width = canvasWidth;+ canvas.height = canvasHeight;++ return runEffectChain({+ state: chainState.get(canvasWidth, canvasHeight)!,+ source: sourceCanvas,+ effects,+ output: canvas,+ width: canvasWidth,+ height: canvasHeight,+ });},- [fit, height, width],+ [chainState, effects, fit, height, sourceCanvas, width],);useImperativeHandle(ref, () => {diff --git a/packages/core/src/animated-image/props.ts b/packages/core/src/animated-image/props.tsindex e41c805b9d..56b9e83b9e 100644--- a/packages/core/src/animated-image/props.ts+++ b/packages/core/src/animated-image/props.ts@@ -1,3 +1,4 @@+import type {EffectsProp} from '../effects/effect-types.js';import type {SequenceProps} from '../Sequence.js';export type RemotionAnimatedImageLoopBehavior =@@ -20,10 +21,11 @@ export type RemotionAnimatedImageProps = {export type AnimatedImageProps = Omit<SequenceProps,- 'children' | 'durationInFrames' | 'layout'+ 'children' | 'durationInFrames' | 'layout' | '_experimentalEffects'> &RemotionAnimatedImageProps & {readonly durationInFrames?: number;+ readonly _experimentalEffects?: EffectsProp;};export type AnimatedImageFillMode = 'contain' | 'cover' | 'fill';diff --git a/packages/example/src/AnimatedImage/Effects.tsx b/packages/example/src/AnimatedImage/Effects.tsxnew file mode 100644index 0000000000..3d5c02d308--- /dev/null+++ b/packages/example/src/AnimatedImage/Effects.tsx@@ -0,0 +1,93 @@+import {blur} from '@remotion/effects/blur';+import {tint} from '@remotion/effects/tint';+import {StudioInternals} from '@remotion/studio';+import React from 'react';+import {+ AbsoluteFill,+ AnimatedImage,+ staticFile,+ useCurrentFrame,+ useVideoConfig,+} from 'remotion';++const IMAGE_SIZE = 420;++/** Pixels β blur oscillates between these bounds. */+const BLUR_MIN_PX = 0;+const BLUR_MAX_PX = 18;+/** Blur animation speed (full sine cycles per second). */+const BLUR_CYCLES_PER_SECOND = 0.35;++const labelStyle: React.CSSProperties = {+ fontFamily: 'sans-serif',+ fontSize: 28,+ fontWeight: 700,+ color: '#f8fafc',+ marginTop: 16,+ textAlign: 'center',+};++const columnStyle: React.CSSProperties = {+ display: 'flex',+ flexDirection: 'column',+ alignItems: 'center',+};++/**+ * `<AnimatedImage>` with `_experimentalEffects` β animated blur + tint.+ * Composition id: `animated-image-effects`.+ */+const Comp: React.FC = () => {+ const frame = useCurrentFrame();+ const {fps} = useVideoConfig();++ const t = (frame / fps) * Math.PI * 2 * BLUR_CYCLES_PER_SECOND;+ const blurRadius =+ BLUR_MIN_PX + (BLUR_MAX_PX - BLUR_MIN_PX) * (0.5 + 0.5 * Math.sin(t));++ return (+ <AbsoluteFill+ style={{+ backgroundColor: '#1a1a2e',+ justifyContent: 'center',+ alignItems: 'center',+ flexDirection: 'row',+ gap: 64,+ }}+ >+ <div style={columnStyle}>+ <AnimatedImage+ src={staticFile('giphy.gif')}+ width={IMAGE_SIZE}+ height={IMAGE_SIZE}+ fit="contain"+ style={{borderRadius: 16}}+ />+ <div style={labelStyle}>No effects</div>+ </div>+ <div style={columnStyle}>+ <AnimatedImage+ src={staticFile('giphy.gif')}+ width={IMAGE_SIZE}+ height={IMAGE_SIZE}+ fit="contain"+ style={{borderRadius: 16}}+ _experimentalEffects={[+ blur({radius: blurRadius}),+ tint({color: '#ff5fa2', amount: 0.35}),+ ]}+ />+ <div style={labelStyle}>blur + tint</div>+ </div>+ </AbsoluteFill>+ );+};++export const AnimatedImageEffects = StudioInternals.createComposition({+ component: Comp,+ id: 'animated-image-effects',+ width: 1280,+ height: 720,+ durationInFrames: 150,+ fps: 30,+});diff --git a/packages/example/src/Root.tsx b/packages/example/src/Root.tsxindex 6ff397c174..e5fa6f0725 100644--- a/packages/example/src/Root.tsx+++ b/packages/example/src/Root.tsx@@ -149,6 +149,7 @@ import {ThreeDCheck} from './3DCheck';import {ThreeDContext} from './3DContext';import {ThreeDSvgContent} from './3DSvgContent';import {AnimatedImages} from './AnimatedImage/Avif';+import {AnimatedImageEffects} from './AnimatedImage/Effects';import {AudioSmoothnessBufferInterruptionComp} from './AudioSmoothness/BufferInterruption';import {AudioSmoothnessLoopedAudioComp} from './AudioSmoothness/LoopedAudio';import {AudioSmoothnessNewVideoComp} from './AudioSmoothness/NewVideo';@@ -1150,6 +1151,7 @@ export const Index: React.FC = () => {</Folder><Folder name="AnimatedImage"><AnimatedImages />+ <AnimatedImageEffects /></Folder><Folder name="still-tests"><Still