Skip to content

🎥 Make videos programmatically with React

`remotion`: Fix image loading during premount transitions (#8950)

Jonny Burgera86363fe4daa
diff --git a/packages/core/src/Img.tsx b/packages/core/src/Img.tsx
index b6ad0b5e47..b7d8e13d2b 100644
--- a/packages/core/src/Img.tsx
+++ b/packages/core/src/Img.tsx
@@ -1,4 +1,10 @@
-import React, {useCallback, useContext, useLayoutEffect, useRef} from 'react';
+import React, {
+ useCallback,
+ useContext,
+ useLayoutEffect,
+ useRef,
+ useState,
+} from 'react';
import type {IsExact} from './audio/props.js';
import type {ImageFit} from './calculate-image-fit.js';
import {CanvasImage} from './canvas-image/index.js';
@@ -91,6 +97,7 @@ const ImgContent: React.FC<ImgContentProps> = ({
const errors = useRef<Record<string, number>>({});
const {delayPlayback} = useBufferState();
const sequenceContext = useContext(SequenceContext);
+ const [isLoading, setIsLoading] = useState(false);
const _propsValid: IsExact<typeof props, Omit<Expected, 'decoding'>> = true;
@@ -139,6 +146,8 @@ const ImgContent: React.FC<ImgContentProps> = ({
}, []);
const {delayRender, continueRender, cancelRender} = useDelayRender();
+ const isPremounting = Boolean(sequenceContext?.premounting);
+ const isPostmounting = Boolean(sequenceContext?.postmounting);
const didGetError = useCallback(
(e: React.SyntheticEvent<HTMLImageElement, Event>) => {
@@ -187,8 +196,21 @@ const ImgContent: React.FC<ImgContentProps> = ({
);
if (typeof window !== 'undefined') {
- const isPremounting = Boolean(sequenceContext?.premounting);
- const isPostmounting = Boolean(sequenceContext?.postmounting);
+ // eslint-disable-next-line react-hooks/rules-of-hooks
+ useLayoutEffect(() => {
+ if (!pauseWhenLoading || !isLoading || isPremounting || isPostmounting) {
+ return;
+ }
+
+ return delayPlayback().unblock;
+ }, [
+ delayPlayback,
+ isLoading,
+ isPostmounting,
+ isPremounting,
+ pauseWhenLoading,
+ ]);
+
// eslint-disable-next-line react-hooks/rules-of-hooks
useLayoutEffect(() => {
if (window.process?.env?.NODE_ENV === 'test') {
@@ -204,6 +226,7 @@ const ImgContent: React.FC<ImgContentProps> = ({
return;
}
+ setIsLoading(true);
const newHandle = delayRender(
'Loading <Img> with src=' + truncateSrcForLabel(actualSrc),
{
@@ -211,10 +234,6 @@ const ImgContent: React.FC<ImgContentProps> = ({
timeoutInMilliseconds: delayRenderTimeoutInMilliseconds ?? undefined,
},
);
- const unblock =
- pauseWhenLoading && !isPremounting && !isPostmounting
- ? delayPlayback().unblock
- : () => undefined;
let unmounted = false;
@@ -239,7 +258,7 @@ const ImgContent: React.FC<ImgContentProps> = ({
onImageFrame?.(current);
}
- unblock();
+ setIsLoading(false);
continueRender(newHandle);
};
@@ -274,17 +293,12 @@ const ImgContent: React.FC<ImgContentProps> = ({
return () => {
unmounted = true;
current.removeEventListener('load', onComplete);
- unblock();
continueRender(newHandle);
};
}, [
actualSrc,
- delayPlayback,
delayRenderRetries,
delayRenderTimeoutInMilliseconds,
- pauseWhenLoading,
- isPremounting,
- isPostmounting,
onImageFrame,
continueRender,
delayRender,
diff --git a/packages/core/src/canvas-image/CanvasImage.tsx b/packages/core/src/canvas-image/CanvasImage.tsx
index ac4f5bf415..784ecf3770 100644
--- a/packages/core/src/canvas-image/CanvasImage.tsx
+++ b/packages/core/src/canvas-image/CanvasImage.tsx
@@ -56,7 +56,6 @@ type LoadedImage = {
type PendingLoadDelay = {
readonly handle: number;
- readonly unblock: () => void;
continued: boolean;
};
@@ -223,18 +222,27 @@ const CanvasImageContent = forwardRef<
});
const sequenceContext = useContext(SequenceContext);
const pendingLoadDelayRef = useRef<PendingLoadDelay | null>(null);
+ const [isLoadPending, setIsLoadPending] = useState(false);
+ const isPremounting = Boolean(sequenceContext?.premounting);
+ const isPostmounting = Boolean(sequenceContext?.postmounting);
+
+ const continuePendingLoadDelay = useCallback(
+ ({markAsReady}: {readonly markAsReady: boolean}) => {
+ const pending = pendingLoadDelayRef.current;
+ if (!pending || pending.continued) {
+ return;
+ }
- const continuePendingLoadDelay = useCallback(() => {
- const pending = pendingLoadDelayRef.current;
- if (!pending || pending.continued) {
- return;
- }
+ pending.continued = true;
+ if (markAsReady) {
+ setIsLoadPending(false);
+ }
- pending.continued = true;
- pending.unblock();
- continueRender(pending.handle);
- pendingLoadDelayRef.current = null;
- }, [continueRender]);
+ continueRender(pending.handle);
+ pendingLoadDelayRef.current = null;
+ },
+ [continueRender],
+ );
const sourceCanvas = useMemo(() => {
if (typeof document === 'undefined') {
@@ -261,9 +269,25 @@ const CanvasImageContent = forwardRef<
);
useLayoutEffect(() => {
- const isPremounting = Boolean(sequenceContext?.premounting);
- const isPostmounting = Boolean(sequenceContext?.postmounting);
+ if (
+ !pauseWhenLoading ||
+ !isLoadPending ||
+ isPremounting ||
+ isPostmounting
+ ) {
+ return;
+ }
+ return delayPlayback().unblock;
+ }, [
+ delayPlayback,
+ isLoadPending,
+ isPostmounting,
+ isPremounting,
+ pauseWhenLoading,
+ ]);
+
+ useLayoutEffect(() => {
const handle = delayRender(
`Rendering <CanvasImage> with src="${truncateSrcForLabel(actualSrc)}"`,
{
@@ -271,10 +295,6 @@ const CanvasImageContent = forwardRef<
timeoutInMilliseconds: delayRenderTimeoutInMilliseconds ?? undefined,
},
);
- const unblock =
- pauseWhenLoading && !isPremounting && !isPostmounting
- ? delayPlayback().unblock
- : () => undefined;
const controller = new AbortController();
let cancelled = false;
@@ -282,9 +302,9 @@ const CanvasImageContent = forwardRef<
let timeoutId: ReturnType<typeof setTimeout> | null = null;
setLoadedImage(null);
+ setIsLoadPending(true);
pendingLoadDelayRef.current = {
handle,
- unblock,
continued: false,
};
@@ -299,7 +319,7 @@ const CanvasImageContent = forwardRef<
})
.catch((err) => {
if ((err as Error).name === 'AbortError') {
- continuePendingLoadDelay();
+ continuePendingLoadDelay({markAsReady: false});
return;
}
@@ -317,7 +337,7 @@ const CanvasImageContent = forwardRef<
}, backoff);
} else if (onError) {
onError(err as Error);
- continuePendingLoadDelay();
+ continuePendingLoadDelay({markAsReady: true});
} else {
cancelRender(err);
}
@@ -333,21 +353,17 @@ const CanvasImageContent = forwardRef<
}
controller.abort();
- continuePendingLoadDelay();
+ continuePendingLoadDelay({markAsReady: false});
};
}, [
actualSrc,
cancelRender,
continuePendingLoadDelay,
- delayPlayback,
delayRender,
delayRenderRetries,
delayRenderTimeoutInMilliseconds,
maxRetries,
onError,
- pauseWhenLoading,
- sequenceContext?.postmounting,
- sequenceContext?.premounting,
]);
useLayoutEffect(() => {
@@ -420,7 +436,7 @@ const CanvasImageContent = forwardRef<
}
continueRenderOnce();
- continuePendingLoadDelay();
+ continuePendingLoadDelay({markAsReady: true});
},
});
}
@@ -433,7 +449,7 @@ const CanvasImageContent = forwardRef<
if (onError) {
onError(err as Error);
continueRenderOnce();
- continuePendingLoadDelay();
+ continuePendingLoadDelay({markAsReady: true});
} else {
cancelRender(err);
}
diff --git a/packages/core/src/test/Img.test.tsx b/packages/core/src/test/Img.test.tsx
index f437e68c2a..614103a709 100644
--- a/packages/core/src/test/Img.test.tsx
+++ b/packages/core/src/test/Img.test.tsx
@@ -1,6 +1,7 @@
import {afterEach, beforeEach, expect, test} from 'bun:test';
-import {cleanup, fireEvent, render, waitFor} from '@testing-library/react';
+import {act, cleanup, fireEvent, render, waitFor} from '@testing-library/react';
import React from 'react';
+import {BufferingContextReact} from '../buffering.js';
import type {
EffectApplyParams,
EffectDefinition,
@@ -9,6 +10,8 @@ import type {
import {Img, imgSchema} from '../Img.js';
import type {RemotionEnvironment} from '../remotion-environment-context.js';
import {RemotionEnvironmentContext} from '../remotion-environment-context.js';
+import type {SequenceContextType} from '../SequenceContext.js';
+import {SequenceContext} from '../SequenceContext.js';
import {WrapSequenceContext} from './wrap-sequence-context.js';
const drawImageCalls: unknown[][] = [];
@@ -112,17 +115,88 @@ const previewEnvironment: RemotionEnvironment = {
isStudio: false,
};
-const renderImg = (
+const wrapImg = (
element: React.ReactElement,
environment: RemotionEnvironment = previewEnvironment,
) => {
- return render(
+ return (
<RemotionEnvironmentContext.Provider value={environment}>
<WrapSequenceContext>{element}</WrapSequenceContext>
- </RemotionEnvironmentContext.Provider>,
+ </RemotionEnvironmentContext.Provider>
);
};
+const renderImg = (
+ element: React.ReactElement,
+ environment: RemotionEnvironment = previewEnvironment,
+) => {
+ return render(wrapImg(element, environment));
+};
+
+const makeSequenceContext = (premounting: boolean): SequenceContextType => ({
+ absoluteFrom: 0,
+ cumulatedFrom: 0,
+ cumulatedNegativeFrom: 0,
+ durationInFrames: 100,
+ height: 1080,
+ id: 'parent',
+ parentFrom: 0,
+ postmountDisplay: null,
+ postmounting: false,
+ premountDisplay: null,
+ premounting,
+ relativeFrom: 0,
+ width: 1080,
+});
+
+const BufferingEvents: React.FC<{
+ readonly events: string[];
+}> = ({events}) => {
+ const manager = React.useContext(BufferingContextReact);
+
+ React.useLayoutEffect(() => {
+ if (!manager) {
+ throw new Error('Expected BufferingContextReact');
+ }
+
+ const buffering = manager.listenForBuffering(() => {
+ events.push('waiting');
+ });
+ const resume = manager.listenForResume(() => {
+ events.push('resume');
+ });
+
+ return () => {
+ buffering.remove();
+ resume.remove();
+ };
+ }, [events, manager]);
+
+ return null;
+};
+
+const forceNodeEnv = (nodeEnv: string) => {
+ const originalNodeEnv = window.process.env.NODE_ENV;
+ window.process.env.NODE_ENV = nodeEnv;
+
+ return () => {
+ window.process.env.NODE_ENV = originalNodeEnv;
+ };
+};
+
+const imgInSequence = ({
+ events,
+ premounting,
+}: {
+ readonly events?: string[];
+ readonly premounting: boolean;
+}) => (
+ <SequenceContext.Provider value={makeSequenceContext(premounting)}>
+ {events ? <BufferingEvents events={events} /> : null}
+ <Img src="blob:http://localhost/test-image" pauseWhenLoading />
+ </SequenceContext.Provider>
+);
+
test('Img component renders img tag', () => {
const ref = React.createRef<HTMLImageElement>();
renderImg(<Img ref={ref} src={testImgUrl} />);
@@ -168,6 +242,70 @@ test('Img with an empty effects array still renders an img tag', () => {
expect(ref.current?.tagName).toBe('IMG');
});
+test('<Img> does not decode again when premounting ends after loading', async () => {
+ const originalDecode = HTMLImageElement.prototype.decode;
+ const restoreNodeEnv = forceNodeEnv('development');
+ let decodeCalls = 0;
+ HTMLImageElement.prototype.decode = () => {
+ decodeCalls++;
+ return Promise.resolve();
+ };
+
+ try {
+ const {rerender} = render(wrapImg(imgInSequence({premounting: true})));
+
+ await waitFor(() => {
+ expect(decodeCalls).toBe(1);
+ });
+
+ rerender(wrapImg(imgInSequence({premounting: false})));
+
+ expect(decodeCalls).toBe(1);
+ } finally {
+ HTMLImageElement.prototype.decode = originalDecode;
+ restoreNodeEnv();
+ }
+});
+
+test('<Img> buffers playback when premounting ends before loading finishes', async () => {
+ const originalDecode = HTMLImageElement.prototype.decode;
+ const restoreNodeEnv = forceNodeEnv('development');
+ const events: string[] = [];
+ let decodeResolver: (() => void) | null = null;
+ HTMLImageElement.prototype.decode = () =>
+ new Promise<void>((resolve) => {
+ decodeResolver = resolve;
+ });
+
+ try {
+ const {rerender} = render(
+ wrapImg(imgInSequence({events, premounting: true})),
+ );
+
+ await waitFor(() => {
+ expect(decodeResolver).not.toBeNull();
+ });
+ expect(events).toEqual([]);
+
+ rerender(wrapImg(imgInSequence({events, premounting: false})));
+
+ await waitFor(() => {
+ expect(events).toEqual(['waiting']);
+ });
+
+ act(() => {
+ decodeResolver?.();
+ });
+
+ await waitFor(() => {
+ expect(events).toEqual(['waiting', 'resume']);
+ });
+ } finally {
+ HTMLImageElement.prototype.decode = originalDecode;
+ restoreNodeEnv();
+ }
+});
+
test('Img with effects renders through the canvas image path', async () => {
const applyCalls: EffectApplyParams<unknown, unknown>[] = [];
const {container} = renderImg(
diff --git a/packages/core/src/test/canvas-image.test.tsx b/packages/core/src/test/canvas-image.test.tsx
index 7ac607c538..4c953aef85 100644
--- a/packages/core/src/test/canvas-image.test.tsx
+++ b/packages/core/src/test/canvas-image.test.tsx
@@ -1,6 +1,7 @@
import {afterEach, beforeEach, expect, test} from 'bun:test';
-import {cleanup, render, waitFor} from '@testing-library/react';
+import {act, cleanup, render, waitFor} from '@testing-library/react';
import React from 'react';
+import {BufferingContextReact} from '../buffering.js';
import {CanvasImage} from '../canvas-image/index.js';
import type {TSequence} from '../CompositionManager.js';
import type {
@@ -9,6 +10,8 @@ import type {
EffectDescriptor,
} from '../effects/effect-types.js';
import {Internals} from '../internals.js';
+import type {SequenceContextType} from '../SequenceContext.js';
+import {SequenceContext} from '../SequenceContext.js';
import type {SequenceManagerContext} from '../SequenceManager.js';
import {SequenceManager} from '../SequenceManager.js';
import {WrapSequenceContext} from './wrap-sequence-context.js';
@@ -107,6 +110,69 @@ const studioEnv = {
isReadOnlyStudio: false,
};
+const makeSequenceContext = (premounting: boolean): SequenceContextType => ({
+ absoluteFrom: 0,
+ cumulatedFrom: 0,
+ cumulatedNegativeFrom: 0,
+ durationInFrames: 100,
+ height: 1080,
+ id: 'parent',
+ parentFrom: 0,
+ postmountDisplay: null,
+ postmounting: false,
+ premountDisplay: null,
+ premounting,
+ relativeFrom: 0,
+ width: 1080,
+});
+
+const BufferingEvents: React.FC<{
+ readonly events: string[];
+}> = ({events}) => {
+ const manager = React.useContext(BufferingContextReact);
+
+ React.useLayoutEffect(() => {
+ if (!manager) {
+ throw new Error('Expected BufferingContextReact');
+ }
+
+ const buffering = manager.listenForBuffering(() => {
+ events.push('waiting');
+ });
+ const resume = manager.listenForResume(() => {
+ events.push('resume');
+ });
+
+ return () => {
+ buffering.remove();
+ resume.remove();
+ };
+ }, [events, manager]);
+
+ return null;
+};
+
+const wrapCanvasImage = (element: React.ReactElement) => {
+ return (
+ <Internals.RemotionEnvironmentContext value={studioEnv}>
+ <WrapSequenceContext>{element}</WrapSequenceContext>
+ </Internals.RemotionEnvironmentContext>
+ );
+};
+
+const canvasImageInSequence = ({
+ events,
+ premounting,
+}: {
+ readonly events?: string[];
+ readonly premounting: boolean;
+}) => (
+ <SequenceContext.Provider value={makeSequenceContext(premounting)}>
+ {events ? <BufferingEvents events={events} /> : null}
+ <CanvasImage src="test.png" pauseWhenLoading width={100} height={50} />
+ </SequenceContext.Provider>
+);
+
const SequenceRegistrationWrapper: React.FC<{
readonly children: React.ReactNode;
readonly onRegisterSequence: (sequence: TSequence) => void;
@@ -391,6 +457,60 @@ test('<CanvasImage> keeps rendering delayed until the drawn canvas is presented'
expect(getDelayRenderState().remotion_renderReady).toBe(true);
});
+test('<CanvasImage> does not reload when premounting ends after drawing', async () => {
+ const {rerender} = render(
+ wrapCanvasImage(canvasImageInSequence({premounting: true})),
+ );
+
+ await waitFor(() => {
+ expect(getDelayRenderState().remotion_renderReady).toBe(true);
+ });
+ expect(imageLoadCount).toBe(1);
+
+ rerender(wrapCanvasImage(canvasImageInSequence({premounting: false})));
+
+ expect(imageLoadCount).toBe(1);
+});
+
+test('<CanvasImage> buffers playback when premounting ends before drawing finishes', async () => {
+ const events: string[] = [];
+ let decodeResolver: (() => void) | null = null;
+ class DeferredDecodeImage extends MockImage {
+ public decode = () =>
+ new Promise<void>((resolve) => {
+ decodeResolver = resolve;
+ });
+ }
+
+ globalThis.Image = DeferredDecodeImage as unknown as typeof Image;
+
+ const {rerender} = render(
+ wrapCanvasImage(canvasImageInSequence({events, premounting: true})),
+ );
+
+ await waitFor(() => {
+ expect(decodeResolver).not.toBeNull();
+ });
+ expect(events).toEqual([]);
+
+ rerender(
+ wrapCanvasImage(canvasImageInSequence({events, premounting: false})),
+ );
+
+ await waitFor(() => {
+ expect(events).toEqual(['waiting']);
+ });
+
+ act(() => {
+ decodeResolver?.();
+ });
+
+ await waitFor(() => {
+ expect(events).toEqual(['waiting', 'resume']);
+ });
+ expect(imageLoadCount).toBe(1);
+});
+
test('<CanvasImage> does not reload the source image when effect keys change', async () => {
const applyCalls: EffectApplyParams<unknown, unknown>[] = [];
const definition: EffectDefinition<unknown> = {