Skip to content

🎥 Make videos programmatically with React

Mark explicit timeline cutoffs with square right edges

Jonny Burger56929a9457a2
diff --git a/packages/core/src/CompositionManager.tsx b/packages/core/src/CompositionManager.tsx
index beb5e2e0bb..4ef813b763 100644
--- a/packages/core/src/CompositionManager.tsx
+++ b/packages/core/src/CompositionManager.tsx
@@ -121,6 +121,9 @@ export type SequenceControls = SequenceRegistrationControls & {
};
export type TSequence = {
+ // Optional for compatibility with consumers constructing this exported type.
+ // null means the layer has no explicit endpoint of its own.
+ explicitDurationInFrames?: number | null;
from: number;
trimBefore: number | null;
duration: number;
diff --git a/packages/core/src/Sequence.tsx b/packages/core/src/Sequence.tsx
index c600c8a786..fcf866ab14 100644
--- a/packages/core/src/Sequence.tsx
+++ b/packages/core/src/Sequence.tsx
@@ -64,6 +64,10 @@ export type LayoutAndStyle =
};
export type SequencePropsWithoutDuration = {
+ /**
+ * @deprecated For internal use only.
+ */
+ readonly _remotionInternalExplicitDurationInFrames?: number | null;
readonly children?: React.ReactNode;
readonly width?: number;
readonly height?: number;
@@ -158,6 +162,7 @@ const RegularSequenceRefForwardingFunction: React.ForwardRefRenderFunction<
_remotionInternalPremountDisplay: premountDisplay,
_remotionInternalPostmountDisplay: postmountDisplay,
_remotionInternalIsMedia: isMedia,
+ _remotionInternalExplicitDurationInFrames = durationInFrames,
outlineRef: passedRefForOutline,
cropLeft,
cropRight,
@@ -455,6 +460,12 @@ const RegularSequenceRefForwardingFunction: React.ForwardRefRenderFunction<
controlsSupportsEffects,
]);
+ const explicitDurationInFrames = Number.isFinite(
+ _remotionInternalExplicitDurationInFrames,
+ )
+ ? _remotionInternalExplicitDurationInFrames
+ : null;
+
const getSequenceForRegistration = useCallback((): TSequence => {
if (isMedia) {
if (isMedia.type === 'image') {
@@ -466,6 +477,7 @@ const RegularSequenceRefForwardingFunction: React.ForwardRefRenderFunction<
displayName: timelineClipName,
documentationLink: resolvedDocumentationLink,
duration: actualDurationInFrames,
+ explicitDurationInFrames,
from,
trimBefore: registeredTrimBefore,
id,
@@ -493,6 +505,7 @@ const RegularSequenceRefForwardingFunction: React.ForwardRefRenderFunction<
documentationLink: resolvedDocumentationLink,
doesVolumeChange: isMedia.data.doesVolumeChange,
duration: actualDurationInFrames,
+ explicitDurationInFrames,
from,
trimBefore: registeredTrimBefore,
id,
@@ -521,6 +534,7 @@ const RegularSequenceRefForwardingFunction: React.ForwardRefRenderFunction<
from,
trimBefore: registeredTrimBefore,
duration: actualDurationInFrames,
+ explicitDurationInFrames,
id,
displayName: timelineClipName,
documentationLink: resolvedDocumentationLink,
@@ -545,6 +559,7 @@ const RegularSequenceRefForwardingFunction: React.ForwardRefRenderFunction<
timelineClipName,
parentSequence?.id,
actualDurationInFrames,
+ explicitDurationInFrames,
from,
registeredTrimBefore,
showInTimeline,
diff --git a/packages/example/e2e/timeline-right-edge.test.mts b/packages/example/e2e/timeline-right-edge.test.mts
new file mode 100644
index 0000000000..7df0f5ae6e
--- /dev/null
+++ b/packages/example/e2e/timeline-right-edge.test.mts
@@ -0,0 +1,96 @@
+import fs from 'fs';
+import {expect, test} from '@playwright/test';
+import {rootFile, STUDIO_URL} from './constants.mts';
+import {startStudio, stopStudio} from './studio-server.mts';
+
+test('rounds inherited endings and squares explicit cutoffs', async ({
+ page,
+}) => {
+ await startStudio();
+ try {
+ fs.writeFileSync(
+ rootFile,
+ `
+import React from 'react';
+import {Audio, Video} from '@remotion/media';
+import {AbsoluteFill, Composition, Sequence, Solid, staticFile} from 'remotion';
+const src = staticFile('sine-wave.wav'); // Exactly one second, or 30 frames.
+const Layers = () => <>
+ <AbsoluteFill name="Fill available time" />
+ <AbsoluteFill name="Explicit fill cutoff" durationInFrames={30} />
+ <AbsoluteFill name="Explicit composition match" durationInFrames={180} />
+ <AbsoluteFill name="Fill clipped before own cutoff" durationInFrames={240} />
+ <Sequence name="Fill parent" durationInFrames={30}>
+ <AbsoluteFill name="Inherited fill" />
+ <AbsoluteFill name="Child clipped before own cutoff" durationInFrames={60} />
+ </Sequence>
+ <Solid name="Solid cutoff" color="gray" width={100} height={100} from={27} durationInFrames={9} trimBefore={27} />
+ <Audio name="Natural end" src={src} durationInFrames={30} />
+ <Audio name="Duration cutoff" src={src} durationInFrames={15} />
+ <Sequence name="Short parent" durationInFrames={15}>
+ <Audio name="Parent cutoff" src={src} />
+ </Sequence>
+ <Sequence name="Matching parent" durationInFrames={30}>
+ <Audio name="Matching child" src={src} />
+ </Sequence>
+ <Audio name="Trimmed start" src={src} trimBefore={10} durationInFrames={20} />
+ <Audio name="Trimmed end" src={src} trimAfter={20} />
+ <Audio name="Fast media" src={src} playbackRate={2} durationInFrames={15} />
+ <Audio name="Slow media" src={src} playbackRate={0.5} durationInFrames={60} />
+ <Audio name="Loop" src={src} loop durationInFrames={60} />
+ <Audio name="Frozen" src={src} freeze={0} durationInFrames={30} />
+ <Audio name="Loop without cutoff" src={src} loop />
+ <Audio name="Freeze without cutoff" src={src} freeze={0} />
+ <Audio name="Composition cutoff" src={src} from={165} />
+ <Audio name="Composition match" src={src} from={150} />
+ <Video name="Video natural end" src={staticFile('blush-1x.webm')} durationInFrames={80} muted />
+ <Video name="Video cutoff" src={staticFile('blush-1x.webm')} durationInFrames={79} muted />
+ <Video name="Video without cutoff" src={staticFile('blush-1x.webm')} muted />
+ <Video name="Video held frame" src={staticFile('blush-1x.webm')} durationInFrames={120} muted />
+</>;
+export const E2eTestRoot = () => <Composition id="timeline-edges" component={Layers} durationInFrames={180} fps={30} width={640} height={360} />;
+`,
+ );
+ await page.setViewportSize({width: 1440, height: 1600});
+ await page.goto(`${STUDIO_URL}/timeline-edges`);
+ for (const [name, radius] of [
+ ['Fill available time', '2px'],
+ ['Explicit fill cutoff', '0px'],
+ ['Explicit composition match', '0px'],
+ ['Fill clipped before own cutoff', '2px'],
+ ['Fill parent', '0px'],
+ ['Inherited fill', '2px'],
+ ['Child clipped before own cutoff', '2px'],
+ ['Natural end', '2px'],
+ ['Solid cutoff', '0px'],
+ ['Duration cutoff', '0px'],
+ ['Short parent', '0px'],
+ ['Parent cutoff', '2px'],
+ ['Matching parent', '0px'],
+ ['Matching child', '2px'],
+ ['Trimmed start', '2px'],
+ ['Trimmed end', '0px'],
+ ['Fast media', '2px'],
+ ['Slow media', '2px'],
+ ['Loop', '0px'],
+ ['Frozen', '0px'],
+ ['Loop without cutoff', '2px'],
+ ['Freeze without cutoff', '2px'],
+ ['Composition cutoff', '2px'],
+ ['Composition match', '2px'],
+ ['Video natural end', '2px'],
+ ['Video cutoff', '0px'],
+ ['Video held frame', '0px'],
+ ['Video without cutoff', '2px'],
+ ]) {
+ const layer = page.locator(
+ `[data-timeline-marquee-item][title="${name}"]`,
+ );
+ await layer.scrollIntoViewIfNeeded();
+ await expect(layer).toHaveCSS('border-top-right-radius', radius);
+ await expect(layer).toHaveCSS('border-bottom-right-radius', radius);
+ }
+ } finally {
+ await stopStudio();
+ }
+});
diff --git a/packages/media/src/audio/audio.tsx b/packages/media/src/audio/audio.tsx
index 9f112992ce..f5aa8bd575 100644
--- a/packages/media/src/audio/audio.tsx
+++ b/packages/media/src/audio/audio.tsx
@@ -185,6 +185,17 @@ const AudioInner: React.FC<
layout="none"
from={from ?? 0}
durationInFrames={basicInfo.duration}
+ _remotionInternalExplicitDurationInFrames={Math.min(
+ durationInFrames ?? Infinity,
+ props.trimAfter === undefined || props.loop
+ ? Infinity
+ : Internals.calculateMediaDuration({
+ mediaDurationInFrames: Infinity,
+ trimBefore: props.trimBefore,
+ trimAfter: props.trimAfter,
+ playbackRate: props.playbackRate ?? 1,
+ }),
+ )}
freeze={freeze}
_remotionInternalIsMedia={isMedia}
_remotionInternalPremountDisplay={effectivePremountFor || null}
diff --git a/packages/studio/src/components/Timeline/TimelineSequence.tsx b/packages/studio/src/components/Timeline/TimelineSequence.tsx
index e6ec3eb271..a711d6582a 100644
--- a/packages/studio/src/components/Timeline/TimelineSequence.tsx
+++ b/packages/studio/src/components/Timeline/TimelineSequence.tsx
@@ -31,7 +31,7 @@ import {
TIMELINE_LAYER_HEIGHT_AUDIO,
TIMELINE_PADDING,
} from '../../helpers/timeline-layout';
-import {useMaxMediaDuration} from '../../helpers/use-max-media-duration';
+import {useMediaMetadata} from '../../helpers/use-media-metadata';
import {SetSelectedModalContext} from '../../state/modals';
import {AudioWaveform} from '../AudioWaveform';
import {useConfirmationDialog} from '../ConfirmationDialog';
@@ -44,6 +44,7 @@ import {
getMultiSequenceContextMenuItems,
getSequenceContextMenuItems,
} from './get-sequence-context-menu-items';
+import {getTimelineMediaStartFrame} from './get-timeline-media-start-frame';
import {getTimelineSequenceVisibleLayout} from './get-timeline-sequence-visible-layout';
import {getCurrentFrame} from './imperative-state';
import {LoopedTimelineIndicator} from './LoopedTimelineIndicators';
@@ -425,9 +426,31 @@ const TimelineSequenceInner: React.FC<{
[],
);
- const maxMediaDuration = useMaxMediaDuration(s, video?.fps ?? 30);
- const effectiveMaxMediaDuration = s.loopDisplay ? null : maxMediaDuration;
+ const mediaMetadata = useMediaMetadata(
+ s.type === 'audio' || s.type === 'video' ? s.src : null,
+ );
const extendVideoLastFrame = isVideoWithLastFrameHold(s);
+ const naturalMediaDuration =
+ (s.type === 'audio' || s.type === 'video') &&
+ mediaMetadata !== null &&
+ s.playbackRate > 0
+ ? Math.max(
+ 0,
+ (mediaMetadata.duration * (video?.fps ?? 30) -
+ getTimelineMediaStartFrame({
+ startMediaFrom: s.startMediaFrom,
+ mediaFrameAtSequenceZero: s.mediaFrameAtSequenceZero,
+ sequenceFrameOffset,
+ playbackRate: s.playbackRate,
+ })) /
+ s.playbackRate,
+ )
+ : null;
+ const maxMediaDuration =
+ s.type === 'sequence' || s.type === 'image' || extendVideoLastFrame
+ ? Infinity
+ : naturalMediaDuration;
+ const effectiveMaxMediaDuration = s.loopDisplay ? null : maxMediaDuration;
const {
canOpenInEditor,
@@ -761,8 +784,8 @@ const TimelineSequenceInner: React.FC<{
durationInFrames: displayDurationInFrames,
startFrom: s.loopDisplay ? s.from + s.loopDisplay.startOffset : s.from,
cascadedStart,
- startFromMedia:
- s.type === 'sequence' || s.type === 'image' ? 0 : s.startMediaFrom,
+ // The media duration cap already accounts for trimming and playback speed.
+ startFromMedia: 0,
maxMediaDuration: effectiveMaxMediaDuration,
video,
windowWidth,
@@ -811,6 +834,35 @@ const TimelineSequenceInner: React.FC<{
localStart >= 0 &&
(s.trimBefore ?? 0) === 0;
+ // Compare frame boundaries: fractional media durations still occupy the last frame.
+ const endsAtNaturalMediaDuration =
+ !s.loopDisplay &&
+ s.frozenFrame === null &&
+ (s.type === 'audio' || s.type === 'video') &&
+ s.frozenMediaFrame === null &&
+ naturalMediaDuration !== null &&
+ Number.isFinite(naturalMediaDuration) &&
+ naturalMediaDuration > 0 &&
+ Math.ceil(
+ Math.min(
+ s.duration,
+ video.durationInFrames - s.from,
+ maxMediaDuration ?? Infinity,
+ ),
+ ) === Math.ceil(naturalMediaDuration);
+
+ const endsAtExplicitDuration =
+ s.explicitDurationInFrames !== null &&
+ s.explicitDurationInFrames !== undefined &&
+ Number.isFinite(s.explicitDurationInFrames) &&
+ Math.ceil(s.explicitDurationInFrames - sequenceFrameOffset) <=
+ Math.ceil(
+ Math.min(displayDurationInFrames, video.durationInFrames - s.from),
+ );
+ const showRightBorderRadius =
+ visibleLayout?.rightEdgeVisible === true &&
+ (!endsAtExplicitDuration || endsAtNaturalMediaDuration);
+
const style: React.CSSProperties = useMemo(() => {
return {
background:
@@ -829,8 +881,8 @@ const TimelineSequenceInner: React.FC<{
: TRANSPARENT,
borderTopLeftRadius: showLeftBorderRadius ? 2 : 0,
borderBottomLeftRadius: showLeftBorderRadius ? 2 : 0,
- borderTopRightRadius: visibleLayout?.rightEdgeVisible ? 2 : 0,
- borderBottomRightRadius: visibleLayout?.rightEdgeVisible ? 2 : 0,
+ borderTopRightRadius: showRightBorderRadius ? 2 : 0,
+ borderBottomRightRadius: showRightBorderRadius ? 2 : 0,
position: 'absolute',
height: getTimelineLayerHeight(s.type),
marginLeft: visibleLayout?.marginLeft ?? 0,
@@ -839,7 +891,13 @@ const TimelineSequenceInner: React.FC<{
// Edge handles extend outside the layer; media is clipped separately.
overflow: 'visible',
};
- }, [negativeStartClipped, s.type, showLeftBorderRadius, visibleLayout]);
+ }, [
+ negativeStartClipped,
+ s.type,
+ showLeftBorderRadius,
+ showRightBorderRadius,
+ visibleLayout,
+ ]);
const showRightEdgeDragHandle =
isTimelineSequenceDurationDraggable(s) &&
diff --git a/packages/studio/src/helpers/use-max-media-duration.ts b/packages/studio/src/helpers/use-max-media-duration.ts
deleted file mode 100644
index 1175e335ef..0000000000
--- a/packages/studio/src/helpers/use-max-media-duration.ts
+++ /dev/null
@@ -1,74 +0,0 @@
-import {useEffect, useState} from 'react';
-import {Internals, 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>();
-
-const getCacheKey = (src: string, fps: number) => JSON.stringify([src, fps]);
-
-const getSrc = (s: TSequence) => {
- if (s.type === 'video') {
- return s.src;
- }
-
- if (s.type === 'audio') {
- return s.src;
- }
-
- return null;
-};
-
-export const useMaxMediaDuration = (s: TSequence, fps: number) => {
- const holdsLastFrame = isVideoWithLastFrameHold(s);
- const src = holdsLastFrame ? null : getSrc(s);
- const resolvedSrc = Internals.usePreload(src ?? '');
- const cacheKey = src ? getCacheKey(resolvedSrc, fps) : null;
-
- const [maxMediaDuration, setMaxMediaDuration] = useState(
- cacheKey ? (cache.get(cacheKey) ?? null) : Infinity,
- );
-
- useEffect(() => {
- if (!src || !cacheKey) {
- return;
- }
-
- const cached = cache.get(cacheKey) ?? null;
- setMaxMediaDuration(cached);
-
- if (cached !== null) {
- return;
- }
-
- let cancelled = false;
-
- getMediaMetadata(resolvedSrc)
- .then((metadata) => {
- if (cancelled || !metadata) {
- return;
- }
-
- const duration = Math.floor(metadata.duration * fps);
- cache.set(cacheKey, duration);
- setMaxMediaDuration(duration);
- })
- .catch(() => {
- if (cancelled) {
- return;
- }
-
- setMaxMediaDuration(null);
- });
-
- return () => {
- cancelled = true;
- };
- }, [cacheKey, fps, resolvedSrc, src]);
-
- if (holdsLastFrame) {
- return Infinity;
- }
-
- return maxMediaDuration;
-};