π₯ Make videos programmatically with React
`@remotion/media`: Redraw video effects when effect chain updates (#7463)
Jonny Burger77f9f0430dbf
diff --git a/packages/example/src/EffectsTestbed/VideoEffectsFastRefresh.tsx b/packages/example/src/EffectsTestbed/VideoEffectsFastRefresh.tsxnew file mode 100644index 0000000000..2929fb2a51--- /dev/null+++ b/packages/example/src/EffectsTestbed/VideoEffectsFastRefresh.tsx@@ -0,0 +1,141 @@+/**+ * Minimal repro for https://github.com/remotion-dev/remotion/issues/7449+ *+ * `<Video>` does not fast-refresh effects when `tint()` params change in code.+ *+ * Repro:+ * 1. `cd packages/example && bun run dev`+ * 2. Open composition `video-effects-fast-refresh`+ * 3. Pause playback (space)+ * 4. Change `TINT_COLOR` or `TINT_AMOUNT` below and save+ * 5. Expected: the video tint updates immediately+ * 6. Bug: the canvas keeps the old tint until you seek or remount+ */+import {tint} from '@remotion/effects/tint';+import {Video} from '@remotion/media';+import React from 'react';+import {AbsoluteFill, Solid, staticFile} from 'remotion';++// --- Edit these values and save to test fast refresh ---+const TINT_COLOR = '#ff5fa2';+const TINT_AMOUNT = 0.2;+// -------------------------------------------------------++const SAMPLE_VIDEO = staticFile('bigbuckbunny.mp4');++const panelStyle: React.CSSProperties = {+ flex: 1,+ position: 'relative',+ border: '2px solid #334155',+ borderRadius: 12,+ overflow: 'hidden',+ backgroundColor: '#000',+ minWidth: 0,+};++const labelStyle: React.CSSProperties = {+ position: 'absolute',+ top: 12,+ left: 12,+ right: 12,+ zIndex: 2,+ fontFamily: 'monospace',+ fontSize: 14,+ color: '#f8fafc',+ backgroundColor: 'rgba(2, 6, 23, 0.85)',+ padding: '10px 12px',+ borderRadius: 8,+ lineHeight: 1.5,+ pointerEvents: 'none',+};++const mediaStyle: React.CSSProperties = {+ width: '100%',+ height: '100%',+};++export const VideoEffectsFastRefresh: React.FC = () => {+ return (+ <AbsoluteFill+ style={{+ backgroundColor: '#020617',+ padding: 24,+ gap: 16,+ display: 'flex',+ flexDirection: 'column',+ }}+ >+ <div+ style={{+ fontFamily: 'monospace',+ fontSize: 22,+ color: '#f8fafc',+ fontWeight: 700,+ }}+ >+ #7449 β Video effects fast refresh+ </div>+ <div+ style={{+ fontFamily: 'monospace',+ fontSize: 13,+ color: '#94a3b8',+ lineHeight: 1.6,+ }}+ >+ Pause, edit <code style={{color: '#f472b6'}}>TINT_COLOR</code> /{' '}+ <code style={{color: '#f472b6'}}>TINT_AMOUNT</code> in{' '}+ <code style={{color: '#f472b6'}}>+ EffectsTestbed/VideoEffectsFastRefresh.tsx+ </code>+ , save. Video should redraw with the new tint immediately.+ </div>+ <div+ style={{+ flex: 1,+ display: 'flex',+ flexDirection: 'row',+ gap: 16,+ minHeight: 0,+ }}+ >+ <div style={panelStyle}>+ <div style={labelStyle}>+ <div style={{fontWeight: 700, marginBottom: 4}}>+ <Video> (bug surface)+ </div>+ <div>+ tint({`{color: '${TINT_COLOR}', amount: ${TINT_AMOUNT}}`})+ </div>+ </div>+ <Video+ src={SAMPLE_VIDEO}+ style={mediaStyle}+ muted+ loop+ objectFit="cover"+ _experimentalEffects={[tint({color: TINT_COLOR, amount: 0.57})]}+ />+ </div>+ <div style={panelStyle}>+ <div style={labelStyle}>+ <div style={{fontWeight: 700, marginBottom: 4}}>+ <Solid> (control)+ </div>+ <div>+ Same tint β if this updates but Video does not, the bug is+ Video-specific.+ </div>+ </div>+ <Solid+ width={1920}+ height={1080}+ color="#3b82f6"+ style={mediaStyle}+ _experimentalEffects={[tint({color: TINT_COLOR, amount: 0.2})]}+ />+ </div>+ </div>+ </AbsoluteFill>+ );+};diff --git a/packages/example/src/Root.tsx b/packages/example/src/Root.tsxindex e5fa6f0725..15657c48c2 100644--- a/packages/example/src/Root.tsx+++ b/packages/example/src/Root.tsx@@ -160,6 +160,7 @@ import Amplify from './AudioTesting/Amplify';import {BrowserTest} from './BrowserTest';import {EdgeBlur} from './EdgeBlur/EdgeBlur';import {EffectsTestbed} from './EffectsTestbed/EffectsTestbed';+import {VideoEffectsFastRefresh} from './EffectsTestbed/VideoEffectsFastRefresh';import {Empty} from './Empty';import {JumpCuts, SAMPLE_SECTIONS, calculateMetadataJumpCuts} from './JumpCuts';import {LightLeakExample} from './LightLeak';@@ -2133,6 +2134,14 @@ export const Index: React.FC = () => {fps={30}durationInFrames={300}/>+ <Composition+ id="video-effects-fast-refresh"+ component={VideoEffectsFastRefresh}+ width={1920}+ height={1080}+ fps={30}+ durationInFrames={300}+ /></Folder><Compositionid="experimental-controls-showcase"diff --git a/packages/media/src/media-player.ts b/packages/media/src/media-player.tsindex 41a111ec21..423a13bbc9 100644--- a/packages/media/src/media-player.ts+++ b/packages/media/src/media-player.ts@@ -779,6 +779,10 @@ export class MediaPlayer {this.onVideoFrameCallback = callback;}+ public async redrawVideoEffects(): Promise<void> {+ await this.videoIteratorManager?.redrawCurrentFrame();+ }+private drawDebugOverlay = () => {if (!this.debugOverlay) return;if (this.context && this.canvas) {diff --git a/packages/media/src/test/video-iterator-manager.test.ts b/packages/media/src/test/video-iterator-manager.test.tsindex eb81a306b4..54f928a351 100644--- a/packages/media/src/test/video-iterator-manager.test.ts+++ b/packages/media/src/test/video-iterator-manager.test.ts@@ -124,3 +124,39 @@ test('rapid sequential seeks should not cause overlapping blocks', async () => {expect(maxConcurrentBlocks).toBe(1);expect(activeBlocks).toBe(0);});++test('redrawCurrentFrame should not create a new video iterator', async () => {+ const {videoTrack} = await prepare();++ const manager = await videoIteratorManager({+ videoTrack,+ delayPlaybackHandleIfNotPremounting: () => ({+ unblock: () => {},+ [Symbol.dispose]: () => {},+ }),+ context: null,+ canvas: null,+ getOnVideoFrameCallback: () => null,+ logLevel: 'error',+ drawDebugOverlay: () => {},+ getLoopSegmentMediaEndTimestamp: () => {+ throw new Error('not implemented');+ },+ getStartTime: () => {+ throw new Error('not implemented');+ },+ getIsLooping: () => false,+ getEffects: () => [],+ getEffectChainState: () => null,+ });++ const nonceManager = makeNonceManager();++ await manager.startVideoIterator(0, nonceManager.createAsyncOperation());+ expect(manager.getVideoIteratorsCreated()).toBe(1);++ await manager.redrawCurrentFrame();+ await manager.redrawCurrentFrame();++ expect(manager.getVideoIteratorsCreated()).toBe(1);+});diff --git a/packages/media/src/video-iterator-manager.ts b/packages/media/src/video-iterator-manager.tsindex a130ae34f8..d33591913a 100644--- a/packages/media/src/video-iterator-manager.ts+++ b/packages/media/src/video-iterator-manager.ts@@ -50,6 +50,11 @@ export const videoIteratorManager = async ({let videoFrameIterator: VideoIterator | null = null;let framesRendered = 0;let currentDelayHandle: {unblock: () => void} | null = null;+ let lastDrawnFrame: WrappedCanvas | null = null;++ const clearLastDrawnFrame = () => {+ lastDrawnFrame = null;+ };if (canvas) {const displayWidth = await videoTrack.getDisplayWidth();@@ -69,7 +74,7 @@ export const videoIteratorManager = async ({const prewarmedVideoIteratorCache =makePrewarmedVideoIteratorCache(canvasSink);- const drawFrame = async (frame: WrappedCanvas): Promise<void> => {+ const paintFrame = async (frame: WrappedCanvas): Promise<void> => {if (context && canvas) {const effects = getEffects();const chainState = getEffectChainState(canvas.width, canvas.height);@@ -91,6 +96,11 @@ export const videoIteratorManager = async ({context.drawImage(frame.canvas, 0, 0);}}+ };++ const drawFrame = async (frame: WrappedCanvas): Promise<void> => {+ await paintFrame(frame);+ lastDrawnFrame = frame;framesRendered++;@@ -106,10 +116,30 @@ export const videoIteratorManager = async ({);};+ const redrawCurrentFrame = async (): Promise<void> => {+ if (!lastDrawnFrame) {+ return;+ }++ await paintFrame(lastDrawnFrame);++ drawDebugOverlay();+ const callback = getOnVideoFrameCallback();+ if (callback) {+ callback(lastDrawnFrame.canvas);+ }++ Internals.Log.trace(+ {logLevel, tag: '@remotion/media'},+ `[MediaPlayer] Redrew frame ${lastDrawnFrame.timestamp.toFixed(3)}s with updated effects`,+ );+ };+const startVideoIterator = async (timeToSeek: number,nonce: Nonce,): Promise<void> => {+ clearLastDrawnFrame();videoFrameIterator?.destroy();using delayHandle = delayPlaybackHandleIfNotPremounting();currentDelayHandle = delayHandle;@@ -177,6 +207,7 @@ export const videoIteratorManager = async ({getVideoIteratorsCreated: () => videoIteratorsCreated,seek,destroy: () => {+ clearLastDrawnFrame();prewarmedVideoIteratorCache.destroy();videoFrameIterator?.destroy();if (context && canvas) {@@ -192,6 +223,7 @@ export const videoIteratorManager = async ({},getVideoFrameIterator: () => videoFrameIterator,drawFrame,+ redrawCurrentFrame,getFramesRendered: () => framesRendered,};};diff --git a/packages/media/src/video/video-for-preview.tsx b/packages/media/src/video/video-for-preview.tsxindex eb35c8743c..2ceb4ed9ea 100644--- a/packages/media/src/video/video-for-preview.tsx+++ b/packages/media/src/video/video-for-preview.tsx@@ -466,6 +466,17 @@ const VideoForPreviewAssertedShowing: React.FC<mediaPlayer.setVideoFrameCallback(onVideoFrame ?? null);}, [onVideoFrame, mediaPlayerReady]);+ useLayoutEffect(() => {+ const mediaPlayer = mediaPlayerRef.current;+ if (!mediaPlayer || !mediaPlayerReady) {+ return;+ }++ mediaPlayer.redrawVideoEffects().catch(() => {+ // Player may have been disposed between layout and the async redraw.+ });+ }, [_experimentalEffects, mediaPlayerReady, mediaPlayerRef]);+const actualStyle: React.CSSProperties = useMemo(() => {return {...style,