🎥 Make videos programmatically with React
`@remotion/studio`: Display held video frames in timeline (#9434)
Jonny Burger1102be048f3a
diff --git a/packages/example/public/drums-drumsticks.mp4 b/packages/example/public/drums-drumsticks.mp4new file mode 100644index 0000000000..5628b3e567Binary files /dev/null and b/packages/example/public/drums-drumsticks.mp4 differdiff --git a/packages/example/src/MediaTimelineTestbed.tsx b/packages/example/src/MediaTimelineTestbed.tsxnew file mode 100644index 0000000000..d1ff45aef1--- /dev/null+++ b/packages/example/src/MediaTimelineTestbed.tsx@@ -0,0 +1,54 @@+import {Video} from '@remotion/media';+import type {CSSProperties} from 'react';+import {AbsoluteFill, staticFile} from 'remotion';++const src = staticFile('drums-drumsticks.mp4');++const MEDIA_DURATION_IN_FRAMES = 51;++const videoStyle = (left: number, top: number): CSSProperties => ({+ left,+ top,+ width: 640,+ height: 360,+});++export const MediaTimelineTestbed = () => {+ return (+ <AbsoluteFill style={{backgroundColor: 'black'}}>+ <Video name="No durationInFrames" src={src} style={videoStyle(0, 0)} />+ <Video+ name="durationInFrames set to media duration"+ src={src}+ durationInFrames={MEDIA_DURATION_IN_FRAMES}+ style={videoStyle(640, 0)}+ />+ <Video+ name="No durationInFrames, trimBefore 30"+ src={src}+ trimBefore={30}+ style={videoStyle(1280, 0)}+ />+ <Video+ name="No durationInFrames, playbackRate 2"+ src={src}+ playbackRate={2}+ style={videoStyle(0, 360)}+ />+ <Video+ name="Media duration, playbackRate 2"+ src={src}+ durationInFrames={MEDIA_DURATION_IN_FRAMES}+ playbackRate={2}+ style={videoStyle(640, 360)}+ />+ <Video+ name="No durationInFrames, trimBefore 30, playbackRate 2"+ src={src}+ trimBefore={30}+ playbackRate={2}+ style={videoStyle(1280, 360)}+ />+ </AbsoluteFill>+ );+};diff --git a/packages/example/src/Root.tsx b/packages/example/src/Root.tsxindex af181d1f02..742a71737e 100644--- a/packages/example/src/Root.tsx+++ b/packages/example/src/Root.tsx@@ -220,6 +220,7 @@ import {JumpCuts, SAMPLE_SECTIONS, calculateMetadataJumpCuts} from './JumpCuts';import {LightLeakExample} from './LightLeak';import {LightLeakAnimatedSize} from './LightLeak/AnimatedSize';import {LoopDisplayTestComp} from './LoopDisplayTest';+import {MediaTimelineTestbed} from './MediaTimelineTestbed';import {NewAudioExample} from './NewAudio/NewAudio';import {NewVideoComp, PremountSequenceVideoComp} from './NewVideo';import {ObjectFitTestComp} from './ObjectFitTest';@@ -2720,6 +2721,14 @@ export const Index: React.FC = () => {durationInFrames={366}/></Folder>+ <Composition+ id="media-timeline-testbed"+ component={MediaTimelineTestbed}+ width={1920}+ height={720}+ fps={60}+ durationInFrames={180}+ /><Folder name="VisualModeTests"><Compositionid="fast-updates"diff --git a/packages/studio/src/components/Timeline/TimelineSequence.tsx b/packages/studio/src/components/Timeline/TimelineSequence.tsxindex 5826c549ec..c4a57922b3 100644--- a/packages/studio/src/components/Timeline/TimelineSequence.tsx+++ b/packages/studio/src/components/Timeline/TimelineSequence.tsx@@ -23,6 +23,7 @@ import {} from '../../helpers/get-timeline-sequence-layout';import type {SequenceNodePathInfo} from '../../helpers/get-timeline-sequence-sort-key';import {studioInteractivityEnabled} from '../../helpers/interactivity-enabled';+import {isVideoWithLastFrameHold} from '../../helpers/is-video-with-last-frame-hold';import {openOriginalPositionInEditor} from '../../helpers/open-in-editor';import {getTimelineLayerHeight,@@ -262,6 +263,7 @@ const TimelineSequenceInner: React.FC<{const maxMediaDuration = useMaxMediaDuration(s, video?.fps ?? 30);const effectiveMaxMediaDuration = s.loopDisplay ? null : maxMediaDuration;+ const extendVideoLastFrame = isVideoWithLastFrameHold(s);const originalLocation = useResolveStackAndReactToChange(s.getStack);const validatedLocation = useMemo(() => {@@ -665,6 +667,7 @@ const TimelineSequenceInner: React.FC<{postmountWidth={postmountWidth ?? 0}loopDisplay={s.loopDisplay}frozenMediaFrame={s.frozenMediaFrame}+ extendLastFrame={extendVideoLastFrame}/>) : null}{s.type === 'image' ? (diff --git a/packages/studio/src/components/Timeline/TimelineVideoInfo.tsx b/packages/studio/src/components/Timeline/TimelineVideoInfo.tsxindex d3b8b2b548..5b648c1020 100644--- a/packages/studio/src/components/Timeline/TimelineVideoInfo.tsx+++ b/packages/studio/src/components/Timeline/TimelineVideoInfo.tsx@@ -61,6 +61,7 @@ export const TimelineVideoInfo: React.FC<{readonly postmountWidth: number;readonly loopDisplay: LoopDisplay | undefined;readonly frozenMediaFrame: number | null;+ readonly extendLastFrame: boolean;}> = ({src,visualizationWidth,@@ -76,6 +77,7 @@ export const TimelineVideoInfo: React.FC<{postmountWidth,loopDisplay,frozenMediaFrame,+ extendLastFrame,}) => {const {fps} = useVideoConfig();const ref = useRef<HTMLDivElement>(null);@@ -187,6 +189,7 @@ export const TimelineVideoInfo: React.FC<{}extractFrames({+ repeatLastFrame: extendLastFrame,timestampsInSeconds: ({track,}: {@@ -324,6 +327,7 @@ export const TimelineVideoInfo: React.FC<{}extractFrames({+ repeatLastFrame: extendLastFrame,timestampsInSeconds: ({track,}: {@@ -431,6 +435,7 @@ export const TimelineVideoInfo: React.FC<{}, [durationInFrames,error,+ extendLastFrame,fps,frozenMediaFrame,loopDisplay,diff --git a/packages/studio/src/helpers/is-video-with-last-frame-hold.ts b/packages/studio/src/helpers/is-video-with-last-frame-hold.tsnew file mode 100644index 0000000000..5edfba41c1--- /dev/null+++ b/packages/studio/src/helpers/is-video-with-last-frame-hold.ts@@ -0,0 +1,8 @@+import type {TSequence} from 'remotion';++export const isVideoWithLastFrameHold = (sequence: TSequence) => {+ return (+ sequence.type === 'video' &&+ sequence.controls?.componentIdentity === 'dev.remotion.media.Video'+ );+};diff --git a/packages/studio/src/helpers/use-max-media-duration.ts b/packages/studio/src/helpers/use-max-media-duration.tsindex 65f7aa4888..51c2bd8888 100644--- a/packages/studio/src/helpers/use-max-media-duration.ts+++ b/packages/studio/src/helpers/use-max-media-duration.ts@@ -1,5 +1,6 @@import {useEffect, useState} from 'react';import {type TSequence} from 'remotion';+import {isVideoWithLastFrameHold} from './is-video-with-last-frame-hold';import {getMediaMetadata} from './use-media-metadata';const cache = new Map<string, number>();@@ -19,7 +20,8 @@ const getSrc = (s: TSequence) => {};export const useMaxMediaDuration = (s: TSequence, fps: number) => {- const src = getSrc(s);+ const holdsLastFrame = isVideoWithLastFrameHold(s);+ const src = holdsLastFrame ? null : getSrc(s);const cacheKey = src ? getCacheKey(src, fps) : null;const [maxMediaDuration, setMaxMediaDuration] = useState(@@ -63,8 +65,8 @@ export const useMaxMediaDuration = (s: TSequence, fps: number) => {};}, [cacheKey, fps, src]);- if (maxMediaDuration !== null && (s.type === 'audio' || s.type === 'video')) {- return maxMediaDuration;+ if (holdsLastFrame) {+ return Infinity;}return maxMediaDuration;diff --git a/packages/studio/src/test/timeline-video-info.test.ts b/packages/studio/src/test/timeline-video-info.test.tsindex 3eeb84d677..bd9ff6d729 100644--- a/packages/studio/src/test/timeline-video-info.test.ts+++ b/packages/studio/src/test/timeline-video-info.test.ts@@ -1,5 +1,5 @@import {afterEach, expect, test} from 'bun:test';-import type {InteractivitySchema, SequenceControls} from 'remotion';+import type {InteractivitySchema, SequenceControls, TSequence} 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';@@ -11,6 +11,7 @@ import {} from '../components/Timeline/timeline-asset-link';import {getTimelineVideoFilmstripTimes} from '../components/Timeline/timeline-video-filmstrip-times';import {isStaticFileAssetValue} from '../components/Timeline/TimelineAssetField';+import {isVideoWithLastFrameHold} from '../helpers/is-video-with-last-frame-hold';type TestWindow = Pick<Window,@@ -132,6 +133,24 @@ test('video timeline thumbnail widths never go negative', () => {});});+test('@remotion/media Video holds its last frame', () => {+ expect(+ isVideoWithLastFrameHold({+ type: 'video',+ controls: {+ componentIdentity: 'dev.remotion.media.Video',+ },+ } as TSequence),+ ).toBe(true);++ expect(+ isVideoWithLastFrameHold({+ type: 'video',+ controls: null,+ } as TSequence),+ ).toBe(false);+});+test('video timeline filmstrip range starts at the registered media frame', () => {expect(getTimelineVideoFilmstripTimes({diff --git a/packages/timeline-utils/src/clamp-timestamps-to-duration.ts b/packages/timeline-utils/src/clamp-timestamps-to-duration.tsnew file mode 100644index 0000000000..b18c7b7fa0--- /dev/null+++ b/packages/timeline-utils/src/clamp-timestamps-to-duration.ts@@ -0,0 +1,20 @@+const LAST_FRAME_EPSILON_IN_SECONDS = 1 / 1_000_000;++export const clampTimestampsToDuration = ({+ timestamps,+ durationInSeconds,+}: {+ readonly timestamps: readonly number[];+ readonly durationInSeconds: number | null;+}): number[] => {+ if (durationInSeconds === null) {+ return [...timestamps];+ }++ const lastTimestamp = Math.max(+ 0,+ durationInSeconds - LAST_FRAME_EPSILON_IN_SECONDS,+ );++ return timestamps.map((timestamp) => Math.min(timestamp, lastTimestamp));+};diff --git a/packages/timeline-utils/src/extract-frames.ts b/packages/timeline-utils/src/extract-frames.tsindex 6e44711554..47ee62ea27 100644--- a/packages/timeline-utils/src/extract-frames.ts+++ b/packages/timeline-utils/src/extract-frames.ts@@ -6,6 +6,7 @@ import {UrlSource,VideoSampleSink,} from 'mediabunny';+import {clampTimestampsToDuration} from './clamp-timestamps-to-duration';import {getDurationOrCompute} from './get-duration-or-compute';type Options = {@@ -23,6 +24,7 @@ export type ExtractFramesProps = {timestampsInSeconds: number[] | ExtractFramesTimestampsInSecondsFn;onVideoSample: (sample: VideoSample) => void;signal?: AbortSignal;+ repeatLastFrame?: boolean;};export async function extractFrames({@@ -30,6 +32,7 @@ export async function extractFrames({timestampsInSeconds,onVideoSample,signal,+ repeatLastFrame = false,}: ExtractFramesProps): Promise<void> {const input = new Input({formats: ALL_FORMATS,@@ -68,7 +71,7 @@ export async function extractFrames({);}- const timestamps =+ const requestedTimestamps =typeof timestampsInSeconds === 'function'? await timestampsInSeconds({track: {@@ -79,6 +82,12 @@ export async function extractFrames({durationInSeconds,}): timestampsInSeconds;+ const timestamps = repeatLastFrame+ ? clampTimestampsToDuration({+ timestamps: requestedTimestamps,+ durationInSeconds,+ })+ : requestedTimestamps;if (timestamps.length === 0) {return;diff --git a/packages/timeline-utils/src/index.ts b/packages/timeline-utils/src/index.tsindex bc6c3dad38..603042efcf 100644--- a/packages/timeline-utils/src/index.ts+++ b/packages/timeline-utils/src/index.ts@@ -14,6 +14,7 @@ export {} from './audio-waveform/waveform-peak-processor';export {drawRepeatingImageThumbnail} from './image-thumbnail/draw-repeating-image-thumbnail';export {getScaledImageThumbnailDimensions} from './image-thumbnail/get-scaled-image-thumbnail-dimensions';+export {clampTimestampsToDuration} from './clamp-timestamps-to-duration';export {extractFrames} from './extract-frames';export type {ExtractFramesProps,diff --git a/packages/timeline-utils/src/test/clamp-timestamps-to-duration.test.ts b/packages/timeline-utils/src/test/clamp-timestamps-to-duration.test.tsnew file mode 100644index 0000000000..5bd0b5db02--- /dev/null+++ b/packages/timeline-utils/src/test/clamp-timestamps-to-duration.test.ts@@ -0,0 +1,21 @@+import {expect, test} from 'bun:test';+import {clampTimestampsToDuration} from '../clamp-timestamps-to-duration';++test('clamps timestamps after the media duration to the final media instant', () => {+ expect(+ clampTimestampsToDuration({+ timestamps: [0, 0.5, 1, 2],+ durationInSeconds: 1,+ }),+ ).toEqual([0, 0.5, 0.999999, 0.999999]);+});++test('does not clamp timestamps when the duration is unknown', () => {+ const timestamps = [0, 1, 2];+ expect(+ clampTimestampsToDuration({+ timestamps,+ durationInSeconds: null,+ }),+ ).toEqual(timestamps);+});