Skip to content

🎥 Make videos programmatically with React

`remotion`: Refactor `useImageInTimeline`

Jonny Burger3ec4cea53879
diff --git a/packages/core/src/Img.tsx b/packages/core/src/Img.tsx
index 98421e7942..e2a04e58e6 100644
--- a/packages/core/src/Img.tsx
+++ b/packages/core/src/Img.tsx
@@ -3,10 +3,11 @@ import React, {
useContext,
useImperativeHandle,
useLayoutEffect,
+ useMemo,
useRef,
- useState,
} from 'react';
import type {IsExact} from './audio/props.js';
+import {useMediaStartsAt} from './audio/use-audio-frame.js';
import type {SequenceControls} from './CompositionManager.js';
import {addSequenceStackTraces} from './enable-sequence-stack-traces.js';
import {getCrossOriginValue} from './get-cross-origin-value.js';
@@ -15,11 +16,14 @@ import {
hiddenField,
sequenceVisualStyleSchema,
} from './sequence-field-schema.js';
+import type {SequenceProps} from './Sequence.js';
+import {Sequence} from './Sequence.js';
import {SequenceContext} from './SequenceContext.js';
import {useBufferState} from './use-buffer-state.js';
import {useDelayRender} from './use-delay-render.js';
-import {useImageInTimeline} from './use-media-in-timeline.js';
+import {useBasicMediaInTimeline} from './use-media-in-timeline.js';
import {useRemotionEnvironment} from './use-remotion-environment.js';
+import {useVideoConfig} from './use-video-config.js';
import {wrapInSchema} from './wrap-in-schema.js';
function exponentialBackoff(errorCount: number): number {
@@ -57,7 +61,7 @@ export type ImgProps = NativeImgProps & {
* @deprecated For internal use only
*/
readonly stack?: string;
-};
+} & Pick<SequenceProps, 'durationInFrames' | 'from' | 'hidden'>;
type Expected = Omit<
NativeImgProps,
@@ -66,7 +70,7 @@ type Expected = Omit<
type ImgContentProps = Omit<
ImgProps,
- 'hidden' | 'name' | 'stack' | 'showInTimeline'
+ 'hidden' | 'name' | 'stack' | 'showInTimeline' | 'from' | 'durationInFrames'
>;
const ImgContent: React.FC<ImgContentProps> = ({
@@ -305,38 +309,64 @@ const ImgInner: React.FC<
stack,
showInTimeline,
src,
+ from,
+ durationInFrames,
_experimentalControls: controls,
...props
}) => {
- const sequenceContext = useContext(SequenceContext);
- const [timelineId] = useState(() => String(Math.random()));
+ const videoConfig = useVideoConfig();
+ const mediaStartsAt = useMediaStartsAt();
if (!src) {
throw new Error('No "src" prop was passed to <Img>.');
}
- const stackRef = useRef<string | null>(null);
- stackRef.current = stack ?? null;
-
- const getStack = useCallback(() => stackRef.current, []);
+ const sequenceDurationInFrames = Math.min(
+ durationInFrames ?? Infinity,
+ Math.max(0, videoConfig.durationInFrames - (from ?? 0)),
+ );
- useImageInTimeline({
+ const basicInfo = useBasicMediaInTimeline({
+ volume: undefined,
+ mediaVolume: 0,
+ mediaType: 'image',
src,
displayName: name ?? null,
- id: timelineId,
- getStack,
- showInTimeline: showInTimeline ?? true,
- premountDisplay: sequenceContext?.premountDisplay ?? null,
- postmountDisplay: sequenceContext?.postmountDisplay ?? null,
- loopDisplay: undefined,
- controls: controls ?? null,
+ trimBefore: undefined,
+ trimAfter: undefined,
+ playbackRate: 1,
+ sequenceDurationInFrames,
+ mediaStartsAt,
+ loop: false,
});
- if (hidden) {
+ const isMedia = useMemo(
+ () => ({
+ type: 'image' as const,
+ data: basicInfo,
+ }),
+ [basicInfo],
+ );
+
+ if (sequenceDurationInFrames === 0) {
return null;
}
- return <ImgContent src={src} {...props} />;
+ return (
+ <Sequence
+ layout="none"
+ from={from ?? 0}
+ durationInFrames={basicInfo.duration}
+ _remotionInternalStack={stack}
+ _remotionInternalIsMedia={isMedia}
+ name={name ?? basicInfo.finalDisplayName}
+ _experimentalControls={controls}
+ showInTimeline={showInTimeline ?? true}
+ hidden={hidden}
+ >
+ <ImgContent src={src} {...props} />
+ </Sequence>
+ );
};
const imgSchema = {
diff --git a/packages/core/src/Sequence.tsx b/packages/core/src/Sequence.tsx
index dc5ba355b6..1c4dc74113 100644
--- a/packages/core/src/Sequence.tsx
+++ b/packages/core/src/Sequence.tsx
@@ -82,7 +82,7 @@ export type SequencePropsWithoutDuration = {
* @deprecated For internal use only.
*/
readonly _remotionInternalIsMedia?: {
- type: 'video' | 'audio';
+ type: 'video' | 'audio' | 'image';
data: BasicMediaInTimelineReturnType;
};
} & LayoutAndStyle;
@@ -238,28 +238,50 @@ const RegularSequenceRefForwardingFunction: React.ForwardRefRenderFunction<
}
if (isMedia) {
- registerSequence({
- type: isMedia.type,
- controls: controls ?? null,
- effects: _remotionInternalEffects ?? [],
- displayName: timelineClipName,
- doesVolumeChange: isMedia.data.doesVolumeChange,
- duration: actualDurationInFrames,
- from,
- id,
- loopDisplay,
- nonce: nonce.get(),
- parent: parentSequence?.id ?? null,
- playbackRate: isMedia.data.playbackRate,
- postmountDisplay: postmountDisplay ?? null,
- premountDisplay: premountDisplay ?? null,
- rootId,
- showInTimeline,
- src: isMedia.data.src,
- getStack: () => stackRef.current,
- startMediaFrom: isMedia.data.startMediaFrom,
- volume: isMedia.data.volumes,
- });
+ if (isMedia.type === 'image') {
+ registerSequence({
+ type: 'image',
+ controls: controls ?? null,
+ effects: _remotionInternalEffects ?? [],
+ displayName: timelineClipName,
+ duration: actualDurationInFrames,
+ from,
+ id,
+ loopDisplay,
+ nonce: nonce.get(),
+ parent: parentSequence?.id ?? null,
+ postmountDisplay: postmountDisplay ?? null,
+ premountDisplay: premountDisplay ?? null,
+ rootId,
+ showInTimeline,
+ src: isMedia.data.src,
+ getStack: () => stackRef.current,
+ });
+ } else {
+ registerSequence({
+ type: isMedia.type,
+ controls: controls ?? null,
+ effects: _remotionInternalEffects ?? [],
+ displayName: timelineClipName,
+ doesVolumeChange: isMedia.data.doesVolumeChange,
+ duration: actualDurationInFrames,
+ from,
+ id,
+ loopDisplay,
+ nonce: nonce.get(),
+ parent: parentSequence?.id ?? null,
+ playbackRate: isMedia.data.playbackRate,
+ postmountDisplay: postmountDisplay ?? null,
+ premountDisplay: premountDisplay ?? null,
+ rootId,
+ showInTimeline,
+ src: isMedia.data.src,
+ getStack: () => stackRef.current,
+ startMediaFrom: isMedia.data.startMediaFrom,
+ volume: isMedia.data.volumes,
+ });
+ }
+
return () => {
unregisterSequence(id);
};
diff --git a/packages/core/src/use-media-in-timeline.ts b/packages/core/src/use-media-in-timeline.ts
index 02dd0942c7..e3a3cd1c69 100644
--- a/packages/core/src/use-media-in-timeline.ts
+++ b/packages/core/src/use-media-in-timeline.ts
@@ -1,6 +1,6 @@
import {useContext, useEffect, useMemo, useState} from 'react';
import {useMediaStartsAt} from './audio/use-audio-frame.js';
-import type {LoopDisplay, SequenceControls} from './CompositionManager.js';
+import type {LoopDisplay} from './CompositionManager.js';
import {getAssetDisplayName} from './get-asset-file-name.js';
import {getTimelineDuration} from './get-timeline-duration.js';
import {useNonce} from './nonce.js';
@@ -128,103 +128,6 @@ export type BasicMediaInTimelineReturnType = ReturnType<
typeof useBasicMediaInTimeline
>;
-export const useImageInTimeline = ({
- src,
- displayName,
- id,
- getStack,
- showInTimeline,
- premountDisplay,
- postmountDisplay,
- loopDisplay,
- controls,
-}: {
- src: string | undefined;
- displayName: string | null;
- id: string;
- getStack: () => string | null;
- showInTimeline: boolean;
- premountDisplay: number | null;
- postmountDisplay: number | null;
- loopDisplay: LoopDisplay | undefined;
- controls: SequenceControls | null;
-}) => {
- const parentSequence = useContext(SequenceContext);
- const {registerSequence, unregisterSequence} = useContext(SequenceManager);
-
- const {durationInFrames} = useVideoConfig();
- const mediaStartsAt = useMediaStartsAt();
- const {duration, nonce, rootId, finalDisplayName} = useBasicMediaInTimeline({
- volume: undefined,
- mediaVolume: 0,
- mediaType: 'image',
- src,
- displayName,
- trimAfter: undefined,
- trimBefore: undefined,
- playbackRate: 1,
- sequenceDurationInFrames: durationInFrames,
- mediaStartsAt,
- loop: false,
- });
-
- const {isStudio} = useRemotionEnvironment();
-
- useEffect(() => {
- if (!src) {
- throw new Error('No src passed');
- }
-
- if (!isStudio && window.process?.env?.NODE_ENV !== 'test') {
- return;
- }
-
- if (!showInTimeline) {
- return;
- }
-
- registerSequence({
- type: 'image',
- src,
- id,
- duration,
- from: 0,
- parent: parentSequence?.id ?? null,
- displayName: finalDisplayName,
- rootId,
- showInTimeline: true,
- nonce: nonce.get(),
- loopDisplay,
- getStack,
- premountDisplay,
- postmountDisplay,
- controls,
- effects: [],
- });
-
- return () => {
- unregisterSequence(id);
- };
- }, [
- duration,
- id,
- parentSequence,
- src,
- registerSequence,
- unregisterSequence,
- nonce,
- getStack,
- showInTimeline,
- premountDisplay,
- postmountDisplay,
- isStudio,
- loopDisplay,
- rootId,
- finalDisplayName,
- controls,
- ]);
-};
-
export const useMediaInTimeline = ({
volume,
mediaVolume,
diff --git a/packages/docs/docs/img.mdx b/packages/docs/docs/img.mdx
index 520434711e..2a9ff8665d 100644
--- a/packages/docs/docs/img.mdx
+++ b/packages/docs/docs/img.mdx
@@ -11,6 +11,38 @@ If you use `<Img>`, Remotion will ensure that the image is loaded before renderi
## API
+### `from?`<AvailableFrom v="4.0.445" />
+
+At which frame this clip should start relative to the parent timeline. Default is `0`. Same meaning as [`from`](/docs/sequence#from) on [`<Sequence>`](/docs/sequence).
+
+### `durationInFrames?`<AvailableFrom v="4.0.445" />
+
+For how many frames the clip stays mounted. Default is `Infinity`. Same meaning as [`durationInFrames`](/docs/sequence#durationinframes) on [`<Sequence>`](/docs/sequence).
+
+:::note
+You can still wrap `<Img>` in an outer [`<Sequence>`](/docs/sequence). Timing [cascades](/docs/sequence#cascading) like nested sequences.
+:::
+
+```tsx twoslash title="Clip starting at frame 30, lasting 90 frames"
+import {AbsoluteFill, Img, staticFile} from 'remotion';
+
+export const MyComp: React.FC = () => {
+ return (
+ <AbsoluteFill>
+ <Img from={30} durationInFrames={90} src={staticFile('hi.png')} />
+ </AbsoluteFill>
+ );
+};
+```
+
+### `hidden?`<AvailableFrom v="4.0.445" />
+
+If set to `true`, the image is not rendered and does not appear in the timeline. Same meaning as [`hidden`](/docs/sequence#hidden) on [`<Sequence>`](/docs/sequence).
+
+### `name?`
+
+A label for the clip in the Remotion Studio timeline. If not specified, the filename is used.
+
### `src`
[Put an image into the `public/` folder](/docs/assets) and use [`staticFile()`](/docs/staticfile) to reference it.