Skip to content

πŸŽ₯ Make videos programmatically with React

siick

Jonny Burgera1a75ffa9736
diff --git a/packages/canvas-effects/src/halftone.ts b/packages/canvas-effects/src/halftone.ts
new file mode 100644
index 0000000000..3ec070617e
--- /dev/null
+++ b/packages/canvas-effects/src/halftone.ts
@@ -0,0 +1,243 @@
+import {createDescriptor, defineEffect} from 'remotion';
+
+export type HalftoneShape = 'circle' | 'square' | 'line';
+export type HalftoneSampling = 'bilinear' | 'nearest';
+
+export type HalftoneParams = {
+ readonly shape?: HalftoneShape;
+ readonly dotSize?: number;
+ readonly rotation?: number;
+ readonly offsetX?: number;
+ readonly offsetY?: number;
+ readonly sampling?: HalftoneSampling;
+ readonly foreground?: string;
+ readonly background?: string;
+};
+
+type HalftoneResolved = {
+ shape: HalftoneShape;
+ dotSize: number;
+ rotation: number;
+ offsetX: number;
+ offsetY: number;
+ sampling: HalftoneSampling;
+ foreground: string;
+ background: string;
+};
+
+const resolve = (p: HalftoneParams): HalftoneResolved => ({
+ shape: p.shape ?? 'circle',
+ dotSize: p.dotSize ?? 10,
+ rotation: p.rotation ?? 0,
+ offsetX: p.offsetX ?? 0,
+ offsetY: p.offsetY ?? 0,
+ sampling: p.sampling ?? 'bilinear',
+ foreground: p.foreground ?? 'black',
+ background: p.background ?? 'white',
+});
+
+type SampleState = {
+ sourceCanvas: HTMLCanvasElement;
+ sourceCtx: CanvasRenderingContext2D;
+};
+
+type SampleOpts = {
+ data: Uint8ClampedArray;
+ sw: number;
+ sh: number;
+ x: number;
+ y: number;
+ sampling: HalftoneSampling;
+};
+
+const sampleLuminance = ({
+ data,
+ sw,
+ sh,
+ x,
+ y,
+ sampling,
+}: SampleOpts): number => {
+ if (sampling === 'nearest') {
+ const px = Math.min(Math.max(Math.round(x), 0), sw - 1);
+ const py = Math.min(Math.max(Math.round(y), 0), sh - 1);
+ const i = (py * sw + px) * 4;
+ return (data[i] * 0.299 + data[i + 1] * 0.587 + data[i + 2] * 0.114) / 255;
+ }
+
+ const x0 = Math.floor(x);
+ const y0 = Math.floor(y);
+ const x1 = Math.min(x0 + 1, sw - 1);
+ const y1 = Math.min(y0 + 1, sh - 1);
+ const fx = x - x0;
+ const fy = y - y0;
+
+ const cx0 = Math.max(x0, 0);
+ const cy0 = Math.max(y0, 0);
+
+ const i00 = (cy0 * sw + cx0) * 4;
+ const i10 = (cy0 * sw + x1) * 4;
+ const i01 = (y1 * sw + cx0) * 4;
+ const i11 = (y1 * sw + x1) * 4;
+
+ const l00 =
+ (data[i00] * 0.299 + data[i00 + 1] * 0.587 + data[i00 + 2] * 0.114) / 255;
+ const l10 =
+ (data[i10] * 0.299 + data[i10 + 1] * 0.587 + data[i10 + 2] * 0.114) / 255;
+ const l01 =
+ (data[i01] * 0.299 + data[i01 + 1] * 0.587 + data[i01 + 2] * 0.114) / 255;
+ const l11 =
+ (data[i11] * 0.299 + data[i11 + 1] * 0.587 + data[i11 + 2] * 0.114) / 255;
+
+ const top = l00 + (l10 - l00) * fx;
+ const bottom = l01 + (l11 - l01) * fx;
+ return top + (bottom - top) * fy;
+};
+
+const halftoneDef = defineEffect<HalftoneParams, SampleState>({
+ type: 'remotion/halftone',
+ backend: '2d',
+ setup: () => {
+ const sourceCanvas = document.createElement('canvas');
+ const sourceCtx = sourceCanvas.getContext('2d', {
+ willReadFrequently: true,
+ colorSpace: 'srgb',
+ });
+ if (!sourceCtx) {
+ throw new Error(
+ 'Failed to acquire 2D context for halftone sampling canvas.',
+ );
+ }
+
+ return {sourceCanvas, sourceCtx};
+ },
+ apply: ({source, target, width, height, params, state}) => {
+ const ctx = target.getContext('2d');
+ if (!ctx) {
+ throw new Error(
+ 'Failed to acquire 2D context for halftone effect. The canvas may have been assigned a different context type.',
+ );
+ }
+
+ const r = resolve(params);
+
+ const {sourceCanvas, sourceCtx} = state;
+ if (sourceCanvas.width !== width || sourceCanvas.height !== height) {
+ sourceCanvas.width = width;
+ sourceCanvas.height = height;
+ }
+
+ sourceCtx.clearRect(0, 0, width, height);
+ sourceCtx.drawImage(source, 0, 0, width, height);
+ const {data} = sourceCtx.getImageData(0, 0, width, height);
+
+ ctx.clearRect(0, 0, width, height);
+ ctx.fillStyle = r.background;
+ ctx.fillRect(0, 0, width, height);
+ ctx.fillStyle = r.foreground;
+
+ const rad = (r.rotation * Math.PI) / 180;
+ const cosR = Math.cos(rad);
+ const sinR = Math.sin(rad);
+
+ const size = r.dotSize;
+ const halfSize = size / 2;
+
+ // Compute grid bounds: rotate the four canvas corners into grid space,
+ // then iterate over the bounding box of those rotated corners so every
+ // visible cell is covered regardless of rotation angle.
+ const cx = width / 2;
+ const cy = height / 2;
+
+ const corners = [
+ [0, 0],
+ [width, 0],
+ [0, height],
+ [width, height],
+ ];
+ let minGx = Infinity;
+ let maxGx = -Infinity;
+ let minGy = Infinity;
+ let maxGy = -Infinity;
+ for (const [px, py] of corners) {
+ const dx = px - cx;
+ const dy = py - cy;
+ const gx = dx * cosR + dy * sinR;
+ const gy = -dx * sinR + dy * cosR;
+ minGx = Math.min(minGx, gx);
+ maxGx = Math.max(maxGx, gx);
+ minGy = Math.min(minGy, gy);
+ maxGy = Math.max(maxGy, gy);
+ }
+
+ const startCol = Math.floor((minGx + r.offsetX) / size) - 1;
+ const endCol = Math.ceil((maxGx + r.offsetX) / size) + 1;
+ const startRow = Math.floor((minGy + r.offsetY) / size) - 1;
+ const endRow = Math.ceil((maxGy + r.offsetY) / size) + 1;
+
+ for (let row = startRow; row <= endRow; row++) {
+ for (let col = startCol; col <= endCol; col++) {
+ const gridX = col * size - r.offsetX;
+ const gridY = row * size - r.offsetY;
+
+ const sampleX = cx + gridX * cosR - gridY * sinR;
+ const sampleY = cy + gridX * sinR + gridY * cosR;
+
+ if (
+ sampleX < -size ||
+ sampleX > width + size ||
+ sampleY < -size ||
+ sampleY > height + size
+ ) {
+ continue;
+ }
+
+ const lum = sampleLuminance({
+ data,
+ sw: width,
+ sh: height,
+ x: sampleX,
+ y: sampleY,
+ sampling: r.sampling,
+ });
+
+ // Darker pixels β†’ larger dots (1 - luminance)
+ const dotScale = 1 - lum;
+ if (dotScale <= 0.01) {
+ continue;
+ }
+
+ const dotX = cx + gridX * cosR - gridY * sinR;
+ const dotY = cy + gridX * sinR + gridY * cosR;
+
+ if (r.shape === 'circle') {
+ const radius = halfSize * dotScale;
+ ctx.beginPath();
+ ctx.arc(dotX, dotY, radius, 0, Math.PI * 2);
+ ctx.fill();
+ } else if (r.shape === 'square') {
+ const s = size * dotScale;
+ ctx.save();
+ ctx.translate(dotX, dotY);
+ ctx.rotate(-rad);
+ ctx.fillRect(-s / 2, -s / 2, s, s);
+ ctx.restore();
+ } else {
+ // 'line': horizontal stripe in grid space, height scales with luminance
+ const lineHeight = size * dotScale;
+ ctx.save();
+ ctx.translate(dotX, dotY);
+ ctx.rotate(-rad);
+ ctx.fillRect(-halfSize, -lineHeight / 2, size, lineHeight);
+ ctx.restore();
+ }
+ }
+ }
+ },
+});
+
+// Halftone effect inspired by m's Halftone for After Effects. Converts
+// luminance into a grid of dots, squares, or lines. `sampling` controls
+// interpolation when reading luminance between pixel centres.
+export const halftone = (params: HalftoneParams = {}) =>
+ createDescriptor(halftoneDef, params);
diff --git a/packages/canvas-effects/src/index.ts b/packages/canvas-effects/src/index.ts
index c6dafe7660..b411a4c406 100644
--- a/packages/canvas-effects/src/index.ts
+++ b/packages/canvas-effects/src/index.ts
@@ -4,6 +4,12 @@ export type {
BlurParams,
BlurVerticalParams,
} from './blur/index.js';
+export {halftone} from './halftone.js';
+export type {
+ HalftoneParams,
+ HalftoneSampling,
+ HalftoneShape,
+} from './halftone.js';
export {tint} from './tint.js';
export type {TintParams} from './tint.js';
export {wave} from './wave.js';
diff --git a/packages/core/src/HtmlInCanvas.tsx b/packages/core/src/HtmlInCanvas.tsx
index e90e4d08c7..cd4d4d4b12 100644
--- a/packages/core/src/HtmlInCanvas.tsx
+++ b/packages/core/src/HtmlInCanvas.tsx
@@ -1,11 +1,7 @@
import React, {useCallback, useEffect, useRef, useState} from 'react';
import type {EffectsProp} from './canvas-effects/effect-types.js';
-import type {EffectChainState} from './canvas-effects/run-effect-chain.js';
-import {
- cleanupEffectChainState,
- createEffectChainState,
- runEffectChain,
-} from './canvas-effects/run-effect-chain.js';
+import {runEffectChain} from './canvas-effects/run-effect-chain.js';
+import {useEffectChainState} from './canvas-effects/use-effect-chain-state.js';
import type {SequenceControls} from './CompositionManager.js';
import {addSequenceStackTraces} from './enable-sequence-stack-traces.js';
import type {SequenceSchema} from './sequence-field-schema.js';
@@ -120,21 +116,7 @@ const HtmlInCanvasInner: React.FC<
null,
);
- const chainStateRef = useRef<EffectChainState | null>(null);
- const sizeRef = useRef<{width: number; height: number} | null>(null);
-
- if (
- !sizeRef.current ||
- sizeRef.current.width !== width ||
- sizeRef.current.height !== height
- ) {
- if (chainStateRef.current) {
- cleanupEffectChainState(chainStateRef.current);
- }
-
- chainStateRef.current = createEffectChainState(width, height);
- sizeRef.current = {width, height};
- }
+ const chainState = useEffectChainState(width, height);
// Refs so the paint handler always reads fresh values.
const effectsRef = useRef(effects);
@@ -155,7 +137,6 @@ const HtmlInCanvasInner: React.FC<
const sourceCanvas =
sourceCanvasRef.current as HTMLCanvasWithLayoutSubtree | null;
const sceneEl = sceneRef.current;
- const chainState = chainStateRef.current;
const output = outputCanvas;
const handle = pendingHandleRef.current;
@@ -204,7 +185,7 @@ const HtmlInCanvasInner: React.FC<
.catch((err) => {
cancelRender(err);
});
- }, [outputCanvas, continueRender, cancelRender]);
+ }, [outputCanvas, chainState, continueRender, cancelRender]);
// Set up layoutSubtree and persistent paint listener.
useEffect(() => {
@@ -253,15 +234,6 @@ const HtmlInCanvasInner: React.FC<
};
}, [frame, delayRender, continueRender]);
- // Cleanup chain state on unmount.
- useEffect(() => {
- return () => {
- if (chainStateRef.current) {
- cleanupEffectChainState(chainStateRef.current);
- }
- };
- }, []);
-
return (
<Sequence
durationInFrames={resolvedDuration}
diff --git a/packages/core/src/canvas-effects/Solid.tsx b/packages/core/src/canvas-effects/Solid.tsx
index bd5ae04239..0d11523f20 100644
--- a/packages/core/src/canvas-effects/Solid.tsx
+++ b/packages/core/src/canvas-effects/Solid.tsx
@@ -1,13 +1,9 @@
-import React, {useEffect, useMemo, useRef, useState} from 'react';
+import React, {useEffect, useMemo, useState} from 'react';
import {useCurrentFrame} from '../use-current-frame.js';
import {useDelayRender} from '../use-delay-render.js';
import type {EffectsProp} from './effect-types.js';
-import {
- cleanupEffectChainState,
- createEffectChainState,
- runEffectChain,
-} from './run-effect-chain.js';
-import type {EffectChainState} from './run-effect-chain.js';
+import {runEffectChain} from './run-effect-chain.js';
+import {useEffectChainState} from './use-effect-chain-state.js';
export type SolidProps = {
readonly color: string;
@@ -46,25 +42,11 @@ export const Solid: React.FC<SolidProps> = ({
return canvas;
}, []);
- const chainStateRef = useRef<EffectChainState | null>(null);
- const sizeRef = useRef<{width: number; height: number} | null>(null);
-
- if (
- !sizeRef.current ||
- sizeRef.current.width !== width ||
- sizeRef.current.height !== height
- ) {
- if (chainStateRef.current) {
- cleanupEffectChainState(chainStateRef.current);
- }
-
- chainStateRef.current = createEffectChainState(width, height);
- sizeRef.current = {width, height};
- }
+ const chainState = useEffectChainState(width, height);
// Fill source and run effect chain on every frame / color change.
useEffect(() => {
- if (!outputCanvas || !sourceCanvas || !chainStateRef.current) {
+ if (!outputCanvas || !sourceCanvas || !chainState) {
return;
}
@@ -82,7 +64,7 @@ export const Solid: React.FC<SolidProps> = ({
ctx.fillRect(0, 0, 1, 1);
runEffectChain({
- state: chainStateRef.current,
+ state: chainState,
source: sourceCanvas,
effects,
output: outputCanvas,
@@ -103,13 +85,13 @@ export const Solid: React.FC<SolidProps> = ({
return () => {
continueRender(handle);
};
- // eslint-disable-next-line react-hooks/exhaustive-deps
}, [
frame,
color,
effects,
outputCanvas,
sourceCanvas,
+ chainState,
width,
height,
pixelRatio,
@@ -118,15 +100,6 @@ export const Solid: React.FC<SolidProps> = ({
cancelRender,
]);
- // Cleanup chain state on unmount.
- useEffect(() => {
- return () => {
- if (chainStateRef.current) {
- cleanupEffectChainState(chainStateRef.current);
- }
- };
- }, []);
-
return (
<canvas
ref={setOutputCanvas}
diff --git a/packages/core/src/canvas-effects/use-effect-chain-state.ts b/packages/core/src/canvas-effects/use-effect-chain-state.ts
new file mode 100644
index 0000000000..98926fabb0
--- /dev/null
+++ b/packages/core/src/canvas-effects/use-effect-chain-state.ts
@@ -0,0 +1,37 @@
+import {useEffect, useRef} from 'react';
+import type {EffectChainState} from './run-effect-chain.js';
+import {
+ cleanupEffectChainState,
+ createEffectChainState,
+} from './run-effect-chain.js';
+
+export const useEffectChainState = (
+ width: number,
+ height: number,
+): EffectChainState | null => {
+ const chainStateRef = useRef<EffectChainState | null>(null);
+ const sizeRef = useRef<{width: number; height: number} | null>(null);
+
+ if (
+ !sizeRef.current ||
+ sizeRef.current.width !== width ||
+ sizeRef.current.height !== height
+ ) {
+ if (chainStateRef.current) {
+ cleanupEffectChainState(chainStateRef.current);
+ }
+
+ chainStateRef.current = createEffectChainState(width, height);
+ sizeRef.current = {width, height};
+ }
+
+ useEffect(() => {
+ return () => {
+ if (chainStateRef.current) {
+ cleanupEffectChainState(chainStateRef.current);
+ }
+ };
+ }, []);
+
+ return chainStateRef.current;
+};
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index f212dc55e1..a96485c92a 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -141,7 +141,7 @@ export {
Solid,
SolidProps,
} from './canvas-effects/index.js';
-import {HtmlInCanvas} from './HtmlInCanvas.js';
+export {HtmlInCanvas} from './HtmlInCanvas.js';
export type {HtmlInCanvasProps} from './HtmlInCanvas.js';
export type {AnyZodObject} from './any-zod-type.js';
export {Artifact} from './Artifact.js';
@@ -234,11 +234,6 @@ export const Experimental = {
* @see [Documentation](https://www.remotion.dev/docs/null)
*/
Null,
- /**
- * @description Rasterizes its DOM children into a canvas using the WICG html-in-canvas proposal, then runs the result through a canvas-effect chain. Requires Chrome Canary with chrome://flags/#canvas-draw-element enabled.
- * @see [Documentation](https://www.remotion.dev/docs/canvas-effects/html-in-canvas)
- */
- HtmlInCanvas,
useIsPlayer,
};
diff --git a/packages/core/src/internals.ts b/packages/core/src/internals.ts
index d8eedfaa67..9e47cb0e38 100644
--- a/packages/core/src/internals.ts
+++ b/packages/core/src/internals.ts
@@ -23,6 +23,8 @@ import {
CanUseRemotionHooks,
CanUseRemotionHooksProvider,
} from './CanUseRemotionHooks.js';
+import {runEffectChain} from './canvas-effects/run-effect-chain.js';
+import {useEffectChainState} from './canvas-effects/use-effect-chain-state.js';
import {CompositionRenderErrorContext} from './composition-render-error-context.js';
import {type CompProps} from './Composition.js';
import type {
@@ -166,6 +168,7 @@ import {
RemotionContextProvider,
useRemotionContexts,
} from './wrap-remotion-context.js';
+export type {EffectChainState} from './canvas-effects/run-effect-chain.js';
// needs to be in core package so gets deduplicated in studio
const compositionSelectorRef = createRef<{
@@ -283,6 +286,8 @@ export const Internals = {
RenderAssetManagerProvider,
getEffectiveVisualModeValue,
CompositionRenderErrorContext,
+ useEffectChainState,
+ runEffectChain,
} as const;
export type {
diff --git a/packages/example/src/HtmlInCanvas/index.tsx b/packages/example/src/HtmlInCanvas/index.tsx
index 2cdb22e2dd..7e455d7481 100644
--- a/packages/example/src/HtmlInCanvas/index.tsx
+++ b/packages/example/src/HtmlInCanvas/index.tsx
@@ -2,7 +2,7 @@ import {blur, tint, wave} from '@remotion/canvas-effects';
import React from 'react';
import {
AbsoluteFill,
- Experimental,
+ HtmlInCanvas,
interpolate,
useCurrentFrame,
useVideoConfig,
@@ -56,7 +56,7 @@ export const HtmlInCanvasDemo: React.FC = () => {
return (
<AbsoluteFill style={{backgroundColor: 'black'}}>
- <Experimental.HtmlInCanvas
+ <HtmlInCanvas
width={width}
height={height}
effects={[
@@ -66,7 +66,7 @@ export const HtmlInCanvasDemo: React.FC = () => {
]}
>
<Scene />
- </Experimental.HtmlInCanvas>
+ </HtmlInCanvas>
</AbsoluteFill>
);
};
diff --git a/packages/media/src/audio/audio-for-preview.tsx b/packages/media/src/audio/audio-for-preview.tsx
index 88e132cad7..a00d84efc9 100644
--- a/packages/media/src/audio/audio-for-preview.tsx
+++ b/packages/media/src/audio/audio-for-preview.tsx
@@ -252,6 +252,9 @@ const AudioForPreviewAssertedShowing: React.FC<
sequenceOffset: initialSequenceOffset.current,
credentials,
tagType: 'audio',
+ getEffects: () => [],
+ getEffectChainState: () => null,
+ getCurrentFrame: () => 0,
});
mediaPlayerRef.current = player;
diff --git a/packages/media/src/media-player.ts b/packages/media/src/media-player.ts
index d3ec3f30dd..df452214dd 100644
--- a/packages/media/src/media-player.ts
+++ b/packages/media/src/media-player.ts
@@ -1,7 +1,9 @@
import {ALL_FORMATS, Input, UrlSource} from 'mediabunny';
import type {LogLevel, useBufferState} from 'remotion';
+import type {EffectChainState} from 'remotion';
import {Internals} from 'remotion';
import type {ScheduleAudioNodeResult} from 'remotion';
+import type {EffectsProp} from 'remotion';
import {
audioIteratorManager,
type AudioIteratorManager,
@@ -66,6 +68,10 @@ export class MediaPlayer {
private onVideoFrameCallback: null | ((frame: CanvasImageSource) => void) =
null;
+ private getEffects: () => EffectsProp;
+ private getEffectChainState: () => EffectChainState | null;
+ private getCurrentFrame: () => number;
+
private initializationPromise: Promise<MediaPlayerInitResult> | null = null;
private bufferState: ReturnType<typeof useBufferState>;
@@ -96,6 +102,9 @@ export class MediaPlayer {
sequenceOffset,
credentials,
tagType,
+ getEffects,
+ getEffectChainState,
+ getCurrentFrame,
}: {
canvas: HTMLCanvasElement | OffscreenCanvas | null;
src: string;
@@ -118,6 +127,9 @@ export class MediaPlayer {
sequenceOffset: number;
credentials: RequestCredentials | undefined;
tagType: 'audio' | 'video';
+ getEffects: () => EffectsProp;
+ getEffectChainState: () => EffectChainState | null;
+ getCurrentFrame: () => number;
}) {
this.canvas = canvas ?? null;
this.src = src;
@@ -151,6 +163,9 @@ export class MediaPlayer {
formats: ALL_FORMATS,
});
this.tagType = tagType;
+ this.getEffects = getEffects;
+ this.getEffectChainState = getEffectChainState;
+ this.getCurrentFrame = getCurrentFrame;
if (canvas) {
const context = canvas.getContext('2d', {
@@ -291,6 +306,9 @@ export class MediaPlayer {
this.getLoopSegmentMediaEndTimestamp(),
getStartTime: () => this.getStartTime(),
getIsLooping: () => this.loop,
+ getEffects: this.getEffects,
+ getEffectChainState: this.getEffectChainState,
+ getCurrentFrame: this.getCurrentFrame,
});
}
diff --git a/packages/media/src/test/media-player.test.ts b/packages/media/src/test/media-player.test.ts
index 954db1518c..ce7380030f 100644
--- a/packages/media/src/test/media-player.test.ts
+++ b/packages/media/src/test/media-player.test.ts
@@ -56,6 +56,9 @@ test('dispose should immediately unblock playback delays', async () => {
sequenceOffset: 0,
credentials: undefined,
tagType: 'video',
+ getEffects: () => [],
+ getEffectChainState: () => null,
+ getCurrentFrame: () => 0,
});
await player.initialize(0, false);
diff --git a/packages/media/src/test/trim-change-seek.test.ts b/packages/media/src/test/trim-change-seek.test.ts
index 06560d6924..5985186f6f 100644
--- a/packages/media/src/test/trim-change-seek.test.ts
+++ b/packages/media/src/test/trim-change-seek.test.ts
@@ -24,6 +24,9 @@ test('setTrimBefore and setTrimAfter should update frame when paused', async ()
sequenceOffset: 0,
credentials: undefined,
tagType: 'video',
+ getEffects: () => [],
+ getEffectChainState: () => null,
+ getCurrentFrame: () => 0,
});
await player.initialize(0, false);
diff --git a/packages/media/src/test/video-iterator-manager.test.ts b/packages/media/src/test/video-iterator-manager.test.ts
index 2e7fcf43ba..318ddd4099 100644
--- a/packages/media/src/test/video-iterator-manager.test.ts
+++ b/packages/media/src/test/video-iterator-manager.test.ts
@@ -48,6 +48,9 @@ test('seek should not cause overlapping block/unblock cycles', async () => {
throw new Error('not implemented');
},
getIsLooping: () => false,
+ getEffects: () => [],
+ getEffectChainState: () => null,
+ getCurrentFrame: () => 0,
});
const nonceManager = makeNonceManager();
@@ -99,6 +102,9 @@ test('rapid sequential seeks should not cause overlapping blocks', async () => {
throw new Error('not implemented');
},
getIsLooping: () => false,
+ getEffects: () => [],
+ getEffectChainState: () => null,
+ getCurrentFrame: () => 0,
});
const nonceManager = makeNonceManager();
diff --git a/packages/media/src/test/video-with-no-frames-in-beginning.test.ts b/packages/media/src/test/video-with-no-frames-in-beginning.test.ts
index 5d1e816df0..624ed2403e 100644
--- a/packages/media/src/test/video-with-no-frames-in-beginning.test.ts
+++ b/packages/media/src/test/video-with-no-frames-in-beginning.test.ts
@@ -40,6 +40,9 @@ test('in preview, should properly buffer and draw frames', async (t) => {
drawDebugOverlay: () => {},
logLevel: 'info',
getOnVideoFrameCallback: () => null,
+ getEffects: () => [],
+ getEffectChainState: () => null,
+ getCurrentFrame: () => 0,
});
const nonceManager = makeNonceManager();
diff --git a/packages/media/src/video-iterator-manager.ts b/packages/media/src/video-iterator-manager.ts
index b4780aa50c..df412d0f22 100644
--- a/packages/media/src/video-iterator-manager.ts
+++ b/packages/media/src/video-iterator-manager.ts
@@ -1,6 +1,6 @@
import type {InputVideoTrack, WrappedCanvas} from 'mediabunny';
import {CanvasSink} from 'mediabunny';
-import type {LogLevel} from 'remotion';
+import type {EffectChainState, EffectsProp, LogLevel} from 'remotion';
import {Internals} from 'remotion';
import type {DelayPlaybackIfNotPremounting} from './delay-playback-if-not-premounting';
import type {Nonce} from './nonce-manager';
@@ -10,6 +10,8 @@ import {
type VideoIterator,
} from './video/video-preview-iterator';
+const {runEffectChain} = Internals;
+
export const videoIteratorManager = ({
delayPlaybackHandleIfNotPremounting,
canvas,
@@ -21,6 +23,9 @@ export const videoIteratorManager = ({
getLoopSegmentMediaEndTimestamp,
getStartTime,
getIsLooping,
+ getEffects,
+ getEffectChainState,
+ getCurrentFrame,
}: {
videoTrack: InputVideoTrack;
delayPlaybackHandleIfNotPremounting: () => DelayPlaybackIfNotPremounting;
@@ -32,6 +37,9 @@ export const videoIteratorManager = ({
getLoopSegmentMediaEndTimestamp: () => number;
getStartTime: () => number;
getIsLooping: () => boolean;
+ getEffects: () => EffectsProp;
+ getEffectChainState: () => EffectChainState | null;
+ getCurrentFrame: () => number;
}) => {
let videoIteratorsCreated = 0;
let videoFrameIterator: VideoIterator | null = null;
@@ -57,10 +65,29 @@ export const videoIteratorManager = ({
const prewarmedVideoIteratorCache =
makePrewarmedVideoIteratorCache(canvasSink);
- const drawFrame = (frame: WrappedCanvas): void => {
+ const drawFrame = async (frame: WrappedCanvas): Promise<void> => {
if (context && canvas) {
- context.clearRect(0, 0, canvas.width, canvas.height);
- context.drawImage(frame.canvas, 0, 0);
+ const effects = getEffects();
+ const chainState = getEffectChainState();
+ if (
+ effects.length > 0 &&
+ chainState &&
+ canvas instanceof HTMLCanvasElement
+ ) {
+ await runEffectChain({
+ state: chainState,
+ source: frame.canvas,
+ effects,
+ output: canvas,
+ frame: getCurrentFrame(),
+ width: canvas.width,
+ height: canvas.height,
+ pixelRatio: 1,
+ });
+ } else {
+ context.clearRect(0, 0, canvas.width, canvas.height);
+ context.drawImage(frame.canvas, 0, 0);
+ }
}
framesRendered++;
@@ -109,7 +136,7 @@ export const videoIteratorManager = ({
return;
}
- drawFrame(iterator.initialFrame);
+ await drawFrame(iterator.initialFrame);
};
const seek = async ({newTime, nonce}: {newTime: number; nonce: Nonce}) => {
@@ -132,7 +159,7 @@ export const videoIteratorManager = ({
// frame might be better than what we currently have
// TODO: check if this is actually true
if (videoSatisfyResult.type === 'satisfied') {
- drawFrame(videoSatisfyResult.frame);
+ await drawFrame(videoSatisfyResult.frame);
return;
}
diff --git a/packages/media/src/video/props.ts b/packages/media/src/video/props.ts
index bdd2ffb543..9ad885543e 100644
--- a/packages/media/src/video/props.ts
+++ b/packages/media/src/video/props.ts
@@ -4,6 +4,7 @@ import type {
OnVideoFrame,
VolumeProp,
} from 'remotion';
+import type {EffectsProp} from 'remotion';
import type {MediaOnError} from '../on-error';
export type MediaErrorEvent = {
@@ -67,6 +68,7 @@ type OptionalVideoProps = {
credentials: RequestCredentials | undefined;
objectFit: VideoObjectFit;
_experimentalInitiallyDrawCachedFrame: boolean;
+ effects: EffectsProp;
};
export type InnerVideoProps = MandatoryVideoProps &
diff --git a/packages/media/src/video/video-for-preview.tsx b/packages/media/src/video/video-for-preview.tsx
index c7b04e4785..682b0c4c8c 100644
--- a/packages/media/src/video/video-for-preview.tsx
+++ b/packages/media/src/video/video-for-preview.tsx
@@ -7,6 +7,7 @@ import React, {
useState,
} from 'react';
import type {
+ EffectsProp,
LogLevel,
LoopVolumeCurveBehavior,
SequenceControls,
@@ -41,6 +42,7 @@ const {
usePreload,
SequenceContext,
SequenceVisibilityToggleContext,
+ useEffectChainState,
} = Internals;
type VideoForPreviewProps = {
@@ -68,6 +70,7 @@ type VideoForPreviewProps = {
readonly credentials: RequestCredentials | undefined;
readonly objectFit: VideoObjectFit;
readonly _experimentalInitiallyDrawCachedFrame: boolean;
+ readonly effects: EffectsProp;
};
type VideoForPreviewAssertedShowingProps = VideoForPreviewProps & {
@@ -102,6 +105,7 @@ const VideoForPreviewAssertedShowing: React.FC<
controls,
objectFit: objectFitProp,
_experimentalInitiallyDrawCachedFrame,
+ effects,
}) => {
const src = usePreload(unpreloadedSrc);
@@ -145,6 +149,17 @@ const VideoForPreviewAssertedShowing: React.FC<
warnAboutTooHighVolume(userPreferredVolume);
+ const effectChainState = useEffectChainState(
+ videoConfig.width,
+ videoConfig.height,
+ );
+ const effectsRef = useRef(effects);
+ effectsRef.current = effects;
+ const effectChainStateRef = useRef(effectChainState);
+ effectChainStateRef.current = effectChainState;
+ const frameRef = useRef(frame);
+ frameRef.current = frame;
+
const parentSequence = useContext(SequenceContext);
const isPremounting = Boolean(parentSequence?.premounting);
const isPostmounting = Boolean(parentSequence?.postmounting);
@@ -303,6 +318,9 @@ const VideoForPreviewAssertedShowing: React.FC<
sequenceOffset: initialSequenceOffset.current,
credentials,
tagType: 'video',
+ getEffects: () => effectsRef.current,
+ getEffectChainState: () => effectChainStateRef.current,
+ getCurrentFrame: () => frameRef.current,
});
mediaPlayerRef.current = player;
diff --git a/packages/media/src/video/video.tsx b/packages/media/src/video/video.tsx
index 18f333866b..9e18d54e55 100644
--- a/packages/media/src/video/video.tsx
+++ b/packages/media/src/video/video.tsx
@@ -88,6 +88,7 @@ const InnerVideo: React.FC<
controls,
objectFit,
_experimentalInitiallyDrawCachedFrame,
+ effects,
}) => {
const environment = useRemotionEnvironment();
@@ -176,6 +177,7 @@ const InnerVideo: React.FC<
credentials={credentials}
controls={controls}
objectFit={objectFit}
+ effects={effects}
_experimentalInitiallyDrawCachedFrame={
_experimentalInitiallyDrawCachedFrame
}
@@ -216,6 +218,7 @@ const VideoInner: React.FC<
controls,
objectFit,
_experimentalInitiallyDrawCachedFrame,
+ effects,
from,
durationInFrames,
}) => {
@@ -262,6 +265,7 @@ const VideoInner: React.FC<
_experimentalInitiallyDrawCachedFrame={
_experimentalInitiallyDrawCachedFrame ?? false
}
+ effects={effects ?? []}
/>
</Sequence>
);