Skip to content

🎥 Make videos programmatically with React

`remotion`: Add direct premounting to CanvasImage (#9370)

Jonny Burger94695056f147
diff --git a/packages/core/src/canvas-image/CanvasImage.tsx b/packages/core/src/canvas-image/CanvasImage.tsx
index 784ecf3770..5329f8a92b 100644
--- a/packages/core/src/canvas-image/CanvasImage.tsx
+++ b/packages/core/src/canvas-image/CanvasImage.tsx
@@ -19,8 +19,11 @@ import {
useMemoizedEffects,
} from '../effects/use-memoized-effects.js';
import {addSequenceStackTraces} from '../enable-sequence-stack-traces.js';
+import {Freeze} from '../freeze.js';
import {
baseSchema,
+ premountSchema,
+ premountStyleSchema,
transformSchema,
type InteractivitySchema,
} from '../interactivity-schema.js';
@@ -30,11 +33,14 @@ import {SequenceContext} from '../SequenceContext.js';
import {truncateSrcForLabel} from '../truncate-src-for-label.js';
import {useBufferState} from '../use-buffer-state.js';
import {useDelayRender} from '../use-delay-render.js';
+import {usePremounting} from '../use-premounting.js';
import {withInteractivitySchema} from '../with-interactivity-schema.js';
import type {CanvasImageCanvasProps, CanvasImageProps} from './props.js';
export const canvasImageSchema = {
...baseSchema,
+ ...premountSchema,
+ ...premountStyleSchema,
fit: {
type: 'enum',
default: 'fill',
@@ -518,6 +524,10 @@ const CanvasImageInner = forwardRef<
from,
trimBefore,
freeze,
+ premountFor,
+ postmountFor,
+ styleWhilePremounted,
+ styleWhilePostmounted,
hidden,
name,
showInTimeline,
@@ -538,47 +548,71 @@ const CanvasImageInner = forwardRef<
useImperativeHandle(ref, () => {
return actualRef.current as HTMLCanvasElement;
}, []);
+ const {
+ effectivePostmountFor,
+ effectivePremountFor,
+ freezeFrame,
+ isPremountingOrPostmounting,
+ postmountingActive,
+ premountingActive,
+ premountingStyle,
+ } = usePremounting({
+ from: from ?? 0,
+ durationInFrames: durationInFrames ?? Infinity,
+ premountFor: premountFor ?? null,
+ postmountFor: postmountFor ?? null,
+ style: style ?? null,
+ styleWhilePremounted: styleWhilePremounted ?? null,
+ styleWhilePostmounted: styleWhilePostmounted ?? null,
+ hideWhilePremounted: 'display-none',
+ });
return (
- <Sequence
- layout="none"
- from={from ?? 0}
- trimBefore={trimBefore}
- durationInFrames={durationInFrames ?? Infinity}
- freeze={freeze}
- hidden={hidden}
- showInTimeline={showInTimeline ?? true}
- name={name ?? '<CanvasImage>'}
- _remotionInternalDocumentationLink={
- _remotionInternalDocumentationLink ??
- 'https://www.remotion.dev/docs/canvasimage'
- }
- controls={controls}
- _remotionInternalEffects={memoizedEffectDefinitions}
- _remotionInternalIsMedia={{type: 'image', src}}
- _remotionInternalStack={stack}
- outlineRef={outlineRef ?? actualRef}
- >
- <CanvasImageContent
- ref={actualRef}
- src={src}
- width={width}
- height={height}
- fit={fit}
- effects={effects}
+ <Freeze frame={freezeFrame} active={isPremountingOrPostmounting}>
+ <Sequence
+ layout="none"
+ from={from ?? 0}
+ trimBefore={trimBefore}
+ durationInFrames={durationInFrames ?? Infinity}
+ freeze={freeze}
+ hidden={hidden}
+ showInTimeline={showInTimeline ?? true}
+ name={name ?? '<CanvasImage>'}
+ _remotionInternalDocumentationLink={
+ _remotionInternalDocumentationLink ??
+ 'https://www.remotion.dev/docs/canvasimage'
+ }
controls={controls}
- className={className}
- style={style}
- id={id}
- onError={onError}
- pauseWhenLoading={pauseWhenLoading}
- maxRetries={maxRetries}
- delayRenderRetries={delayRenderRetries}
- delayRenderTimeoutInMilliseconds={delayRenderTimeoutInMilliseconds}
- refForOutline={outlineRef ?? null}
- {...canvasProps}
- />
- </Sequence>
+ _remotionInternalEffects={memoizedEffectDefinitions}
+ _remotionInternalIsMedia={{type: 'image', src}}
+ _remotionInternalStack={stack}
+ _remotionInternalPremountDisplay={effectivePremountFor || null}
+ _remotionInternalPostmountDisplay={effectivePostmountFor || null}
+ _remotionInternalIsPremounting={premountingActive}
+ _remotionInternalIsPostmounting={postmountingActive}
+ outlineRef={outlineRef ?? actualRef}
+ >
+ <CanvasImageContent
+ ref={actualRef}
+ src={src}
+ width={width}
+ height={height}
+ fit={fit}
+ effects={effects}
+ controls={controls}
+ className={className}
+ style={premountingStyle ?? undefined}
+ id={id}
+ onError={onError}
+ pauseWhenLoading={pauseWhenLoading}
+ maxRetries={maxRetries}
+ delayRenderRetries={delayRenderRetries}
+ delayRenderTimeoutInMilliseconds={delayRenderTimeoutInMilliseconds}
+ refForOutline={outlineRef ?? null}
+ {...canvasProps}
+ />
+ </Sequence>
+ </Freeze>
);
},
);
diff --git a/packages/core/src/canvas-image/props.ts b/packages/core/src/canvas-image/props.ts
index 0ed6569535..a10372364a 100644
--- a/packages/core/src/canvas-image/props.ts
+++ b/packages/core/src/canvas-image/props.ts
@@ -1,14 +1,18 @@
import type React from 'react';
import type {ImageFit} from '../calculate-image-fit.js';
import type {EffectsProp} from '../effects/effect-types.js';
-import type {InteractiveBaseProps} from '../Interactive.js';
+import type {
+ InteractiveBaseProps,
+ InteractivePremountProps,
+} from '../Interactive.js';
-type CanvasImageSequenceProps = InteractiveBaseProps & {
- /**
- * @deprecated For internal use only.
- */
- readonly stack?: string;
-};
+type CanvasImageSequenceProps = InteractiveBaseProps &
+ InteractivePremountProps & {
+ /**
+ * @deprecated For internal use only.
+ */
+ readonly stack?: string;
+ };
export type CanvasImageCanvasProps = Omit<
React.CanvasHTMLAttributes<HTMLCanvasElement>,
diff --git a/packages/core/src/test/canvas-image.test.tsx b/packages/core/src/test/canvas-image.test.tsx
index 78a0fd7f13..2d7ad890b0 100644
--- a/packages/core/src/test/canvas-image.test.tsx
+++ b/packages/core/src/test/canvas-image.test.tsx
@@ -2,6 +2,7 @@ import {afterEach, beforeEach, expect, test} from 'bun:test';
import {act, cleanup, render, waitFor} from '@testing-library/react';
import React from 'react';
import {BufferingContextReact} from '../buffering.js';
+import {canvasImageSchema} from '../canvas-image/CanvasImage.js';
import {CanvasImage} from '../canvas-image/index.js';
import type {TSequence} from '../CompositionManager.js';
import type {
@@ -151,10 +152,15 @@ const BufferingEvents: React.FC<{
return null;
};
-const wrapCanvasImage = (element: React.ReactElement) => {
+const wrapCanvasImage = (
+ element: React.ReactElement,
+ currentFrame: number = 0,
+) => {
return (
<Internals.RemotionEnvironmentContext value={studioEnv}>
- <WrapSequenceContext>{element}</WrapSequenceContext>
+ <WrapSequenceContext currentFrame={currentFrame}>
+ {element}
+ </WrapSequenceContext>
</Internals.RemotionEnvironmentContext>
);
};
@@ -270,6 +276,128 @@ test('<CanvasImage> registers its canvas as the outline ref', async () => {
});
});
+test('<CanvasImage> exposes non-keyframable premounting schema fields', () => {
+ expect(canvasImageSchema.premountFor.keyframable).toBe(false);
+ expect(canvasImageSchema.postmountFor.keyframable).toBe(false);
+ expect(canvasImageSchema.styleWhilePremounted.type).toBe('hidden');
+ expect(canvasImageSchema.styleWhilePostmounted.type).toBe('hidden');
+});
+
+test('<CanvasImage> hides the canvas while premounted and postmounted', async () => {
+ const premounted = render(
+ wrapCanvasImage(
+ <CanvasImage
+ src="test.png"
+ from={10}
+ durationInFrames={20}
+ premountFor={10}
+ style={{opacity: 0.5}}
+ />,
+ ),
+ );
+ const premountedStyle = premounted.container
+ .querySelector('canvas')
+ ?.getAttribute('style');
+ expect(premountedStyle).toContain('display: none');
+ expect(premountedStyle).toContain('pointer-events: none');
+ expect(premountedStyle).toContain('opacity: 0.5');
+ await waitFor(() => {
+ expect(getDelayRenderState().remotion_renderReady).toBe(true);
+ });
+ premounted.unmount();
+
+ const postmounted = render(
+ wrapCanvasImage(
+ <CanvasImage
+ src="test.png"
+ from={10}
+ durationInFrames={20}
+ postmountFor={10}
+ />,
+ 35,
+ ),
+ );
+ const postmountedStyle = postmounted.container
+ .querySelector('canvas')
+ ?.getAttribute('style');
+ expect(postmountedStyle).toContain('display: none');
+ expect(postmountedStyle).toContain('pointer-events: none');
+ await waitFor(() => {
+ expect(getDelayRenderState().remotion_renderReady).toBe(true);
+ });
+});
+
+test('<CanvasImage> allows overriding the premount and postmount styles', async () => {
+ const premounted = render(
+ wrapCanvasImage(
+ <CanvasImage
+ src="test.png"
+ from={10}
+ durationInFrames={20}
+ premountFor={10}
+ styleWhilePremounted={{display: 'block', opacity: 0.25}}
+ />,
+ ),
+ );
+ const premountedStyle = premounted.container
+ .querySelector('canvas')
+ ?.getAttribute('style');
+ expect(premountedStyle).toContain('display: block');
+ expect(premountedStyle).toContain('opacity: 0.25');
+ await waitFor(() => {
+ expect(getDelayRenderState().remotion_renderReady).toBe(true);
+ });
+ premounted.unmount();
+
+ const postmounted = render(
+ wrapCanvasImage(
+ <CanvasImage
+ src="test.png"
+ from={10}
+ durationInFrames={20}
+ postmountFor={10}
+ styleWhilePostmounted={{display: 'block', opacity: 0.75}}
+ />,
+ 35,
+ ),
+ );
+ const postmountedStyle = postmounted.container
+ .querySelector('canvas')
+ ?.getAttribute('style');
+ expect(postmountedStyle).toContain('display: block');
+ expect(postmountedStyle).toContain('opacity: 0.75');
+ await waitFor(() => {
+ expect(getDelayRenderState().remotion_renderReady).toBe(true);
+ });
+});
+
+test('<CanvasImage> registers premount and postmount ranges once', async () => {
+ const registeredSequences: TSequence[] = [];
+
+ render(
+ <SequenceRegistrationWrapper
+ onRegisterSequence={(sequence) => {
+ registeredSequences.push(sequence);
+ }}
+ >
+ <CanvasImage
+ src="test.png"
+ from={10}
+ durationInFrames={20}
+ premountFor={10}
+ postmountFor={5}
+ />
+ </SequenceRegistrationWrapper>,
+ );
+
+ await waitFor(() => {
+ expect(registeredSequences).toHaveLength(1);
+ });
+ expect(registeredSequences[0].type).toBe('image');
+ expect(registeredSequences[0].premountDisplay).toBe(10);
+ expect(registeredSequences[0].postmountDisplay).toBe(5);
+});
+
test('<CanvasImage> applies contain fit when drawing into the source canvas', async () => {
render(
<WrapSequenceContext>
diff --git a/packages/docs/docs/canvasimage.mdx b/packages/docs/docs/canvasimage.mdx
index 7ff3f5ba9e..c4c6c07bbd 100644
--- a/packages/docs/docs/canvasimage.mdx
+++ b/packages/docs/docs/canvasimage.mdx
@@ -67,6 +67,24 @@ The HTML `id` attribute to apply to the `<canvas>` element.
Inline styles to apply to the `<canvas>` element.
+### `premountFor?`<AvailableFrom v="4.0.495" />
+
+Mounts the canvas for the specified number of frames before its `from` frame. The canvas carries `display: none` and is frozen at its first frame while premounted.
+
+Use this prop to let the image load, decode, and prepare its effects before it becomes visible. See [Premounting](/docs/player/premounting).
+
+### `postmountFor?`<AvailableFrom v="4.0.495" />
+
+Keeps the canvas mounted for the specified number of frames after its duration has ended. The canvas is invisible and frozen at its final frame while postmounted.
+
+### `styleWhilePremounted?`<AvailableFrom v="4.0.495" />
+
+CSS styles applied to the canvas while it is premounted. These styles override the default `display: none` and `pointer-events: none` styles.
+
+### `styleWhilePostmounted?`<AvailableFrom v="4.0.495" />
+
+CSS styles applied to the canvas while it is postmounted. These styles override the default `display: none` and `pointer-events: none` styles.
+
### `onError?`
Called when the image cannot be loaded, decoded, or drawn after all retries are exhausted.
diff --git a/packages/studio/src/components/Timeline/TimelineSequence.tsx b/packages/studio/src/components/Timeline/TimelineSequence.tsx
index 90dce47833..5826c549ec 100644
--- a/packages/studio/src/components/Timeline/TimelineSequence.tsx
+++ b/packages/studio/src/components/Timeline/TimelineSequence.tsx
@@ -39,6 +39,7 @@ import {useSelectAsset} from '../use-select-asset';
import {disableSequenceInteractivity} from './disable-sequence-interactivity';
import {duplicateSequencesFromSource} from './duplicate-selected-timeline-item';
import {getSequenceContextMenuItems} from './get-sequence-context-menu-items';
+import {getTimelineMediaVisualizationLayout} from './get-timeline-media-visualization-layout';
import {LoopedTimelineIndicator} from './LoopedTimelineIndicators';
import {getTimelineAssetLinkInfo} from './timeline-asset-link';
import {TimelineImageInfo} from './TimelineImageInfo';
@@ -559,6 +560,20 @@ const TimelineSequenceInner: React.FC<{
video,
windowWidth,
]);
+ const mediaVisualizationLayout = useMemo(() => {
+ return getTimelineMediaVisualizationLayout({
+ visualizationWidth: width,
+ premountWidth: premountWidth ?? 0,
+ postmountWidth: postmountWidth ?? 0,
+ });
+ }, [postmountWidth, premountWidth, width]);
+ const mediaVisualizationStyle = useMemo((): React.CSSProperties => {
+ return {
+ width: mediaVisualizationLayout.width,
+ marginLeft: mediaVisualizationLayout.marginLeft,
+ height: '100%',
+ };
+ }, [mediaVisualizationLayout]);
const style: React.CSSProperties = useMemo(() => {
return {
@@ -620,17 +635,19 @@ const TimelineSequenceInner: React.FC<{
}
>
{s.type === 'audio' ? (
- <AudioWaveform
- src={s.src}
- height={TIMELINE_LAYER_HEIGHT_AUDIO}
- doesVolumeChange={s.doesVolumeChange}
- visualizationWidth={width}
- startFrom={s.startMediaFrom}
- durationInFrames={s.duration}
- volume={s.volume}
- playbackRate={s.playbackRate}
- loopDisplay={s.loopDisplay}
- />
+ <div style={mediaVisualizationStyle}>
+ <AudioWaveform
+ src={s.src}
+ height={TIMELINE_LAYER_HEIGHT_AUDIO}
+ doesVolumeChange={s.doesVolumeChange}
+ visualizationWidth={mediaVisualizationLayout.width}
+ startFrom={s.startMediaFrom}
+ durationInFrames={s.duration}
+ volume={s.volume}
+ playbackRate={s.playbackRate}
+ loopDisplay={s.loopDisplay}
+ />
+ </div>
) : null}
{s.type === 'video' ? (
<TimelineVideoInfo
@@ -651,7 +668,12 @@ const TimelineSequenceInner: React.FC<{
/>
) : null}
{s.type === 'image' ? (
- <TimelineImageInfo src={s.src} visualizationWidth={width} />
+ <div style={mediaVisualizationStyle}>
+ <TimelineImageInfo
+ src={s.src}
+ visualizationWidth={mediaVisualizationLayout.width}
+ />
+ </div>
) : null}
{s.loopDisplay === undefined ? null : (
<LoopedTimelineIndicator loops={s.loopDisplay.numberOfTimes} />
diff --git a/packages/studio/src/components/Timeline/get-timeline-media-visualization-layout.ts b/packages/studio/src/components/Timeline/get-timeline-media-visualization-layout.ts
new file mode 100644
index 0000000000..a517cbf9a2
--- /dev/null
+++ b/packages/studio/src/components/Timeline/get-timeline-media-visualization-layout.ts
@@ -0,0 +1,14 @@
+export const getTimelineMediaVisualizationLayout = ({
+ visualizationWidth,
+ premountWidth,
+ postmountWidth,
+}: {
+ readonly visualizationWidth: number;
+ readonly premountWidth: number;
+ readonly postmountWidth: number;
+}) => {
+ return {
+ marginLeft: premountWidth,
+ width: Math.max(0, visualizationWidth - premountWidth - postmountWidth),
+ };
+};
diff --git a/packages/studio/src/components/Timeline/get-timeline-video-info-widths.ts b/packages/studio/src/components/Timeline/get-timeline-video-info-widths.ts
index 4e55b3c5a8..165e426ad1 100644
--- a/packages/studio/src/components/Timeline/get-timeline-video-info-widths.ts
+++ b/packages/studio/src/components/Timeline/get-timeline-video-info-widths.ts
@@ -1,3 +1,5 @@
+import {getTimelineMediaVisualizationLayout} from './get-timeline-media-visualization-layout';
+
export const getTimelineVideoInfoWidths = ({
visualizationWidth,
naturalWidth,
@@ -9,10 +11,16 @@ export const getTimelineVideoInfoWidths = ({
premountWidth: number;
postmountWidth: number;
}) => {
- const mountWidth = premountWidth + postmountWidth;
-
return {
- mediaVisualizationWidth: Math.max(0, visualizationWidth - mountWidth),
- mediaNaturalWidth: Math.max(0, naturalWidth - mountWidth),
+ mediaVisualizationWidth: getTimelineMediaVisualizationLayout({
+ visualizationWidth,
+ premountWidth,
+ postmountWidth,
+ }).width,
+ mediaNaturalWidth: getTimelineMediaVisualizationLayout({
+ visualizationWidth: naturalWidth,
+ premountWidth,
+ postmountWidth,
+ }).width,
};
};
diff --git a/packages/studio/src/test/timeline-video-info.test.ts b/packages/studio/src/test/timeline-video-info.test.ts
index 36d68a453d..3eeb84d677 100644
--- a/packages/studio/src/test/timeline-video-info.test.ts
+++ b/packages/studio/src/test/timeline-video-info.test.ts
@@ -1,6 +1,7 @@
import {afterEach, expect, test} from 'bun:test';
import type {InteractivitySchema, SequenceControls} from 'remotion';
import {getTimelineMediaStartFrame} from '../components/Timeline/get-timeline-media-start-frame';
+import {getTimelineMediaVisualizationLayout} from '../components/Timeline/get-timeline-media-visualization-layout';
import {getTimelineVideoInfoWidths} from '../components/Timeline/get-timeline-video-info-widths';
import {
getTimelineAssetSrcFromSchema,
@@ -91,6 +92,32 @@ test('video timeline thumbnails ignore premount and postmount width', () => {
expect(withPremount).toEqual(withoutPremount);
});
+test('timeline media visualizations exclude premount and postmount width', () => {
+ expect(
+ getTimelineMediaVisualizationLayout({
+ visualizationWidth: 510,
+ premountWidth: 110,
+ postmountWidth: 20,
+ }),
+ ).toEqual({
+ marginLeft: 110,
+ width: 380,
+ });
+});
+
+test('timeline media visualization widths never go negative', () => {
+ expect(
+ getTimelineMediaVisualizationLayout({
+ visualizationWidth: 100,
+ premountWidth: 70,
+ postmountWidth: 70,
+ }),
+ ).toEqual({
+ marginLeft: 70,
+ width: 0,
+ });
+});
+
test('video timeline thumbnail widths never go negative', () => {
expect(
getTimelineVideoInfoWidths({