Skip to content

🎥 Make videos programmatically with React

remotion.dev/trim (#8845)

Jonny Burger03b11a92a098
diff --git a/bun.lock b/bun.lock
index f026a84c25..fe816a4900 100644
--- a/bun.lock
+++ b/bun.lock
@@ -338,6 +338,7 @@
"@remotion/paths": "workspace:*",
"@remotion/player": "workspace:*",
"@remotion/shapes": "workspace:*",
+ "@remotion/timeline-utils": "workspace:*",
"@remotion/whisper-web": "workspace:*",
"@vercel/remix": "2.16.7",
"@vidstack/react": "1.12.13",
diff --git a/packages/convert/app/components/AlternativePickFileOptions.tsx b/packages/convert/app/components/AlternativePickFileOptions.tsx
index cb94b5f8e6..04a7397768 100644
--- a/packages/convert/app/components/AlternativePickFileOptions.tsx
+++ b/packages/convert/app/components/AlternativePickFileOptions.tsx
@@ -8,7 +8,7 @@ export const AlternativePickFileOptions: React.FC<{
return (
<div className="flex flex-row items-center justify-center gap-3">
<Button
- className="font-brand text-brand rounded-full text-sm h-10"
+ className="font-brand text-black rounded-full text-sm h-10"
onClick={onSampleFile}
>
Use a sample file
diff --git a/packages/convert/app/components/ConvertUi.tsx b/packages/convert/app/components/ConvertUi.tsx
index e1551384de..32be2c31c7 100644
--- a/packages/convert/app/components/ConvertUi.tsx
+++ b/packages/convert/app/components/ConvertUi.tsx
@@ -61,7 +61,12 @@ const ConvertUI = ({
tracks,
setSrc,
durationInSeconds,
+ fps,
action,
+ trim,
+ setTrim,
+ trimInFrame,
+ trimOutFrame,
enableRotateOrMirror,
setEnableRotateOrMirror,
userRotation,
@@ -87,9 +92,14 @@ const ConvertUI = ({
readonly videoThumbnailRef: React.RefObject<VideoThumbnailRef | null>;
readonly dimensions: Dimensions | null | undefined;
readonly durationInSeconds: number | null;
+ readonly fps: number | null | undefined;
readonly rotation: number | null;
readonly inputContainer: InputFormat;
readonly action: RouteAction;
+ readonly trim: boolean;
+ readonly setTrim: React.Dispatch<React.SetStateAction<boolean>>;
+ readonly trimInFrame: number | null;
+ readonly trimOutFrame: number | null;
readonly name: string;
readonly input: Input;
readonly enableRotateOrMirror: RotateOrMirrorOrCropState;
@@ -252,6 +262,16 @@ const ConvertUI = ({
const conversion = await Conversion.init({
input,
output,
+ trim:
+ trim && fps
+ ? {
+ start: trimInFrame === null ? undefined : trimInFrame / fps,
+ end:
+ trimOutFrame === null
+ ? undefined
+ : (trimOutFrame + 1) / fps,
+ }
+ : undefined,
video: (videoTrack) => {
const operation = getActualVideoOperation({
enableConvert,
@@ -423,6 +443,10 @@ const ConvertUI = ({
outputContainer,
resizeOperation,
supportedConfigs,
+ fps,
+ trim,
+ trimInFrame,
+ trimOutFrame,
userRotation,
videoOperationSelection,
crop,
@@ -586,6 +610,7 @@ const ConvertUI = ({
videoConfigIndexSelection: videoOperationSelection,
enableConvert,
enableRotateOrMirror,
+ enableTrim: trim,
});
const canPixelManipulate = canRotateOrMirror({
@@ -718,6 +743,22 @@ const ConvertUI = ({
);
}
+ if (section === 'trim') {
+ return (
+ <div key="trim">
+ <ConvertUiSection active={trim} setActive={setTrim}>
+ Trim
+ </ConvertUiSection>
+ {trim ? (
+ <div className="text-gray-700 text-sm mt-2">
+ Use the handles below the player to choose the start and end
+ of the video.
+ </div>
+ ) : null}
+ </div>
+ );
+ }
+
if (section === 'resize') {
return (
<div key="resize">
diff --git a/packages/convert/app/components/FileAvailable.tsx b/packages/convert/app/components/FileAvailable.tsx
index e15ad1837e..f90f44798e 100644
--- a/packages/convert/app/components/FileAvailable.tsx
+++ b/packages/convert/app/components/FileAvailable.tsx
@@ -32,6 +32,10 @@ export const FileAvailable: React.FC<{
useState<RotateOrMirrorOrCropState>(() =>
defaultRotateOrMirorState(routeAction),
);
+ const [enableTrim, setEnableTrim] = useState(
+ () =>
+ routeAction.type === 'generic-trim' || routeAction.type === 'trim-format',
+ );
const probeResult = useProbe({
src,
@@ -48,6 +52,8 @@ export const FileAvailable: React.FC<{
height: Infinity,
};
});
+ const [trimInFrame, setTrimInFrame] = useState<number | null>(null);
+ const [trimOutFrame, setTrimOutFrame] = useState<number | null>(null);
const [waveform, setWaveform] = useState<number[]>([]);
@@ -75,6 +81,11 @@ export const FileAvailable: React.FC<{
isAudio={isAudio}
waveform={waveform}
crop={enableRotateOrMirrow === 'crop'}
+ trim={enableTrim}
+ trimInFrame={trimInFrame}
+ trimOutFrame={trimOutFrame}
+ setTrimInFrame={setTrimInFrame}
+ setTrimOutFrame={setTrimOutFrame}
setUnclampedRect={setCropOperation}
unclampedRect={cropOperation}
dimensions={probeResult.dimensions}
@@ -122,6 +133,11 @@ export const FileAvailable: React.FC<{
dimensions={probeResult.dimensions}
durationInSeconds={probeResult.durationInSeconds ?? null}
action={routeAction}
+ trim={enableTrim}
+ setTrim={setEnableTrim}
+ trimInFrame={trimInFrame}
+ trimOutFrame={trimOutFrame}
+ fps={probeResult.fps}
enableRotateOrMirror={enableRotateOrMirrow}
setEnableRotateOrMirror={setEnableRotateOrMirror}
userRotation={actualUserRotation}
diff --git a/packages/convert/app/components/LoadFromUrl.tsx b/packages/convert/app/components/LoadFromUrl.tsx
index d5cd83f711..e6b7e9bfa3 100644
--- a/packages/convert/app/components/LoadFromUrl.tsx
+++ b/packages/convert/app/components/LoadFromUrl.tsx
@@ -57,7 +57,7 @@ export const LoadFromUrl: React.FC = () => {
return (
<>
<RemotionButton
- className="font-brand text-brand rounded-full text-sm h-10"
+ className="font-brand text-black rounded-full text-sm h-10"
onClick={onOpenUrl}
>
Load from URL
diff --git a/packages/convert/app/components/MediaPlayer.tsx b/packages/convert/app/components/MediaPlayer.tsx
index 6da8e473e4..4e5024477b 100644
--- a/packages/convert/app/components/MediaPlayer.tsx
+++ b/packages/convert/app/components/MediaPlayer.tsx
@@ -13,6 +13,7 @@ import type {Source} from '~/lib/convert-state';
import {cn} from '~/lib/utils';
import {AudioWaveForm, AudioWaveformContainer} from './AudioWaveform';
import {CropUI} from './crop-ui/CropUi';
+import {Filmstrip} from './player/filmstrip';
export const getPlayerFps = (fps: number | null | undefined) => {
if (typeof fps !== 'number' || !Number.isFinite(fps) || fps <= 0) {
@@ -103,6 +104,11 @@ export function VideoPlayer({
isAudio,
waveform,
crop,
+ trim,
+ trimInFrame,
+ trimOutFrame,
+ setTrimInFrame,
+ setTrimOutFrame,
setUnclampedRect,
unclampedRect,
dimensions,
@@ -114,6 +120,11 @@ export function VideoPlayer({
readonly waveform: number[];
readonly isAudio: boolean;
readonly crop: boolean;
+ readonly trim: boolean;
+ readonly trimInFrame: number | null;
+ readonly trimOutFrame: number | null;
+ readonly setTrimInFrame: React.Dispatch<React.SetStateAction<number | null>>;
+ readonly setTrimOutFrame: React.Dispatch<React.SetStateAction<number | null>>;
readonly unclampedRect: CropRectangle;
readonly dimensions: Dimensions | null | undefined;
readonly durationInSeconds: number | null | undefined;
@@ -135,6 +146,28 @@ export function VideoPlayer({
const playerDimensions = isAudio
? {width: 732, height: 197}
: (dimensions ?? null);
+ const actualInFrame =
+ trim &&
+ trimInFrame !== null &&
+ durationInFrames &&
+ trimInFrame > 0 &&
+ trimInFrame <= durationInFrames - 1
+ ? trimInFrame
+ : null;
+ const actualOutFrame =
+ trim && trimOutFrame !== null && durationInFrames
+ ? (() => {
+ const minimumPreviewOutFrame = (actualInFrame ?? 0) + 1;
+ const previewOutFrame = Math.max(
+ trimOutFrame,
+ minimumPreviewOutFrame,
+ );
+
+ return previewOutFrame < durationInFrames - 1
+ ? previewOutFrame
+ : null;
+ })()
+ : null;
useEffect(() => {
const {current} = playerRef;
@@ -187,6 +220,8 @@ export function VideoPlayer({
compositionWidth={playerDimensions.width}
compositionHeight={playerDimensions.height}
fps={playerFps}
+ inFrame={actualInFrame}
+ outFrame={actualOutFrame}
controls={!crop}
acknowledgeRemotionLicense
style={{width: '100%'}}
@@ -212,6 +247,23 @@ export function VideoPlayer({
/>
) : null}
</div>
+ {!isAudio &&
+ trim &&
+ videoSourceUrl &&
+ durationInSeconds &&
+ durationInFrames ? (
+ <Filmstrip
+ src={videoSourceUrl}
+ durationInSeconds={durationInSeconds}
+ durationInFrames={durationInFrames}
+ inFrame={trimInFrame}
+ outFrame={trimOutFrame}
+ onTrim={(nextTrim) => {
+ setTrimInFrame(nextTrim.inFrame);
+ setTrimOutFrame(nextTrim.outFrame);
+ }}
+ />
+ ) : null}
</div>
);
}
diff --git a/packages/convert/app/components/get-supported-configs.tsx b/packages/convert/app/components/get-supported-configs.tsx
index afcd6f65f6..72eca0d385 100644
--- a/packages/convert/app/components/get-supported-configs.tsx
+++ b/packages/convert/app/components/get-supported-configs.tsx
@@ -78,6 +78,14 @@ const shouldPrioritizeVideoCopyOverReencode = (routeAction: RouteAction) => {
return false;
}
+ if (routeAction.type === 'generic-trim') {
+ return false;
+ }
+
+ if (routeAction.type === 'trim-format') {
+ return false;
+ }
+
if (routeAction.type === 'timing-editor') {
return true;
}
diff --git a/packages/convert/app/components/player/filmstrip.tsx b/packages/convert/app/components/player/filmstrip.tsx
new file mode 100644
index 0000000000..1ed8fbc9b8
--- /dev/null
+++ b/packages/convert/app/components/player/filmstrip.tsx
@@ -0,0 +1,513 @@
+import {Button} from '@remotion/design';
+import {renderFrameStripToCanvas} from '@remotion/timeline-utils';
+import {Minus, Plus} from 'lucide-react';
+import {useEffect, useRef, useState} from 'react';
+import {useElementSize} from './use-element-size';
+
+const FILMSTRIP_HEIGHT = 48;
+const HANDLE_WIDTH = 14;
+
+const clamp = (value: number, min: number, max: number) => {
+ return Math.min(Math.max(value, min), max);
+};
+
+const formatTimestamp = (seconds: number) => {
+ const clamped = Math.max(0, seconds);
+ const hours = Math.floor(clamped / 3600);
+ const minutes = Math.floor((clamped % 3600) / 60);
+ const secondsLeft = clamped % 60;
+ const formattedSeconds = secondsLeft.toFixed(3).padStart(6, '0');
+
+ if (hours > 0) {
+ return `${hours}:${String(minutes).padStart(2, '0')}:${formattedSeconds}`;
+ }
+
+ return `${minutes}:${formattedSeconds}`;
+};
+
+const getFrameFromPointer = ({
+ clientX,
+ durationInFrames,
+ element,
+}: {
+ clientX: number;
+ durationInFrames: number;
+ element: HTMLDivElement;
+}) => {
+ const rect = element.getBoundingClientRect();
+ const originRailWidth = Math.max(1, rect.width - HANDLE_WIDTH * 2);
+ const progress = clamp(
+ (clientX - rect.left - HANDLE_WIDTH) / originRailWidth,
+ 0,
+ 1,
+ );
+
+ return Math.round(progress * (durationInFrames - 1));
+};
+
+const getOriginX = ({
+ durationInFrames,
+ frame,
+ width,
+}: {
+ durationInFrames: number;
+ frame: number;
+ width: number;
+}) => {
+ const progress = frame / (durationInFrames - 1);
+ const originRailWidth = Math.max(1, width - HANDLE_WIDTH * 2);
+
+ return HANDLE_WIDTH + progress * originRailWidth;
+};
+
+const FrameStepButton: React.FC<{
+ readonly 'aria-label': string;
+ readonly disabled: boolean;
+ readonly icon: 'minus' | 'plus';
+ readonly onClick: () => void;
+}> = ({'aria-label': ariaLabel, disabled, icon, onClick}) => {
+ const Icon = icon === 'minus' ? Minus : Plus;
+
+ return (
+ <Button
+ aria-label={ariaLabel}
+ className="h-6 w-6 rounded-full px-0 text-xs"
+ depth={0.5}
+ disabled={disabled}
+ onClick={onClick}
+ >
+ <Icon aria-hidden className="h-3 w-3" strokeWidth={3} />
+ </Button>
+ );
+};
+
+export const Filmstrip: React.FC<{
+ readonly src: string;
+ readonly durationInSeconds: number;
+ readonly durationInFrames: number;
+ readonly inFrame: number | null;
+ readonly outFrame: number | null;
+ readonly onTrim: (trim: {
+ inFrame: number | null;
+ outFrame: number | null;
+ }) => void;
+}> = ({
+ src,
+ durationInSeconds,
+ durationInFrames,
+ inFrame,
+ outFrame,
+ onTrim,
+}) => {
+ const wrapperRef = useRef<HTMLDivElement>(null);
+ const canvasRef = useRef<HTMLCanvasElement>(null);
+ const dragPointerOffsetRef = useRef(0);
+ const size = useElementSize(wrapperRef);
+ const [dragging, setDragging] = useState<'in' | 'out' | null>(null);
+ const currentInFrame = inFrame ?? 0;
+ const currentOutFrame = outFrame ?? durationInFrames - 1;
+ const minimumFrameDistance = 0;
+
+ const setInFrameFromPointer = (clientX: number) => {
+ const {current} = wrapperRef;
+ if (!current) {
+ return;
+ }
+
+ const frame = getFrameFromPointer({
+ clientX,
+ durationInFrames,
+ element: current,
+ });
+ const maxInFrame = currentOutFrame - minimumFrameDistance;
+ const nextInFrame = clamp(frame, 0, maxInFrame);
+
+ onTrim({inFrame: nextInFrame === 0 ? null : nextInFrame, outFrame});
+ };
+
+ const setOutFrameFromPointer = (clientX: number) => {
+ const {current} = wrapperRef;
+ if (!current) {
+ return;
+ }
+
+ const frame = getFrameFromPointer({
+ clientX,
+ durationInFrames,
+ element: current,
+ });
+ const minOutFrame = currentInFrame + minimumFrameDistance;
+ const nextOutFrame = clamp(frame, minOutFrame, durationInFrames - 1);
+
+ onTrim({
+ inFrame,
+ outFrame: nextOutFrame === durationInFrames - 1 ? null : nextOutFrame,
+ });
+ };
+
+ const setInFrame = (frame: number) => {
+ onTrim({
+ inFrame: frame === 0 ? null : frame,
+ outFrame,
+ });
+ };
+
+ const setOutFrame = (frame: number) => {
+ onTrim({
+ inFrame,
+ outFrame: frame === durationInFrames - 1 ? null : frame,
+ });
+ };
+
+ const moveInFrame = (delta: number) => {
+ setInFrame(
+ clamp(currentInFrame + delta, 0, currentOutFrame - minimumFrameDistance),
+ );
+ };
+
+ const moveOutFrame = (delta: number) => {
+ setOutFrame(
+ clamp(
+ currentOutFrame + delta,
+ currentInFrame + minimumFrameDistance,
+ durationInFrames - 1,
+ ),
+ );
+ };
+
+ const clampDragOriginClientX = (
+ clientX: number,
+ handle: 'in' | 'out',
+ element: HTMLDivElement,
+ ) => {
+ const rect = element.getBoundingClientRect();
+ const minFrame = handle === 'in' ? 0 : currentInFrame;
+ const maxFrame = handle === 'in' ? currentOutFrame : durationInFrames - 1;
+ const minClientX =
+ rect.left +
+ getOriginX({
+ durationInFrames,
+ frame: minFrame,
+ width: rect.width,
+ });
+ const maxClientX =
+ rect.left +
+ getOriginX({
+ durationInFrames,
+ frame: maxFrame,
+ width: rect.width,
+ });
+
+ return clamp(clientX, minClientX, maxClientX);
+ };
+
+ const setDragPointerOffset = (
+ clientX: number,
+ handle: 'in' | 'out',
+ element: HTMLDivElement,
+ ) => {
+ const rect = element.getBoundingClientRect();
+ const frame = handle === 'in' ? currentInFrame : currentOutFrame;
+ const trimMarkX =
+ rect.left +
+ getOriginX({
+ durationInFrames,
+ frame,
+ width: rect.width,
+ });
+
+ dragPointerOffsetRef.current = clientX - trimMarkX;
+ };
+
+ useEffect(() => {
+ if (dragging === null) {
+ return;
+ }
+
+ const onPointerMove = (event: PointerEvent) => {
+ const {current} = wrapperRef;
+ if (!current) {
+ return;
+ }
+
+ const clientX = clampDragOriginClientX(
+ event.clientX - dragPointerOffsetRef.current,
+ dragging,
+ current,
+ );
+
+ if (dragging === 'in') {
+ setInFrameFromPointer(clientX);
+ } else {
+ setOutFrameFromPointer(clientX);
+ }
+ };
+
+ const onPointerUp = () => {
+ dragPointerOffsetRef.current = 0;
+ setDragging(null);
+ };
+
+ window.addEventListener('pointermove', onPointerMove);
+ window.addEventListener('pointerup', onPointerUp);
+ window.addEventListener('pointercancel', onPointerUp);
+
+ return () => {
+ window.removeEventListener('pointermove', onPointerMove);
+ window.removeEventListener('pointerup', onPointerUp);
+ window.removeEventListener('pointercancel', onPointerUp);
+ };
+ });
+
+ useEffect(() => {
+ const canvas = canvasRef.current;
+ const canvasWidth = size?.width;
+ if (!canvas || !canvasWidth) {
+ return;
+ }
+
+ const controller = new AbortController();
+
+ renderFrameStripToCanvas({
+ canvas,
+ src,
+ fromSeconds: 0,
+ toSeconds: durationInSeconds,
+ width: canvasWidth,
+ frameHeight: FILMSTRIP_HEIGHT,
+ devicePixelRatio: window.devicePixelRatio,
+ signal: controller.signal,
+ }).catch(() => undefined);
+
+ return () => {
+ controller.abort();
+ };
+ }, [durationInSeconds, size?.width, src]);
+
+ if (
+ durationInSeconds <= 0 ||
+ !Number.isFinite(durationInSeconds) ||
+ durationInFrames <= 1
+ ) {
+ return null;
+ }
+
+ const inProgress = currentInFrame / (durationInFrames - 1);
+ const outProgress = currentOutFrame / (durationInFrames - 1);
+ const startTimestamp = formatTimestamp(
+ (currentInFrame / durationInFrames) * durationInSeconds,
+ );
+ const endTimestamp = formatTimestamp(
+ ((currentOutFrame + 1) / durationInFrames) * durationInSeconds,
+ );
+ const stripWidth = size?.width;
+ const startOriginX = stripWidth
+ ? getOriginX({
+ durationInFrames,
+ frame: currentInFrame,
+ width: stripWidth,
+ })
+ : null;
+ const endOriginX = stripWidth
+ ? getOriginX({
+ durationInFrames,
+ frame: currentOutFrame,
+ width: stripWidth,
+ })
+ : null;
+ const startHandleLeft =
+ startOriginX === null
+ ? `calc(${inProgress * 100}% - ${inProgress * HANDLE_WIDTH * 2}px)`
+ : startOriginX - HANDLE_WIDTH;
+ const endHandleLeft =
+ endOriginX === null
+ ? `calc(${outProgress * 100}% + ${HANDLE_WIDTH - outProgress * HANDLE_WIDTH * 2}px)`
+ : endOriginX;
+ const activeAreaLeft = startHandleLeft;
+ const activeAreaWidth =
+ startOriginX === null || endOriginX === null
+ ? `calc(${(outProgress - inProgress) * 100}% + ${
+ HANDLE_WIDTH * 2 - (outProgress - inProgress) * HANDLE_WIDTH * 2
+ }px)`
+ : endOriginX - startOriginX + HANDLE_WIDTH * 2;
+ const rightInactiveLeft =
+ endOriginX === null
+ ? `calc(${outProgress * 100}% + ${
+ HANDLE_WIDTH * 2 - outProgress * HANDLE_WIDTH * 2
+ }px)`
+ : endOriginX + HANDLE_WIDTH;
+ const rightInactiveWidth =
+ stripWidth === undefined || endOriginX === null
+ ? `calc(${(1 - outProgress) * 100}% - ${
+ (1 - outProgress) * HANDLE_WIDTH * 2
+ }px)`
+ : stripWidth - endOriginX - HANDLE_WIDTH;
+
+ return (
+ <div className="mt-2 w-full">
+ <div
+ ref={wrapperRef}
+ className="relative h-12 w-full touch-none overflow-hidden rounded-md border border-zinc-900 bg-black shadow-sm"
+ onPointerCancel={() => setDragging(null)}
+ >
+ <canvas
+ ref={canvasRef}
+ className="block h-full w-full opacity-95"
+ style={{height: FILMSTRIP_HEIGHT}}
+ />
+ <div
+ className="pointer-events-none absolute top-0 h-full bg-black/45"
+ style={{left: 0, width: activeAreaLeft}}
+ />
+ <div
+ className="pointer-events-none absolute top-0 h-full bg-black/45"
+ style={{
+ left: rightInactiveLeft,
+ width: rightInactiveWidth,
+ }}
+ />
+ <div
+ className="border-brand pointer-events-none absolute top-0 h-full rounded-md border-2"
+ style={{
+ left: activeAreaLeft,
+ width: activeAreaWidth,
+ }}
+ />
+ <div
+ aria-label="Trim start"
+ aria-valuemax={currentOutFrame - minimumFrameDistance}
+ aria-valuemin={0}
+ aria-valuenow={currentInFrame}
+ className="bg-brand absolute top-0 h-full cursor-ew-resize overflow-hidden rounded-l-md border-r border-blue-800"
+ role="slider"
+ style={{
+ left: startHandleLeft,
+ width: HANDLE_WIDTH,
+ }}
+ tabIndex={0}
+ onContextMenu={() => {
+ setDragging(null);
+ }}
+ onPointerDown={(event) => {
+ if (event.button !== 0) {
+ setDragging(null);
+ return;
+ }
+
+ const {current} = wrapperRef;
+ if (!current) {
+ return;
+ }
+
+ event.stopPropagation();
+ setDragPointerOffset(event.clientX, 'in', current);
+ setDragging('in');
+ }}
+ onKeyDown={(event) => {
+ if (event.key === 'ArrowLeft') {
+ event.preventDefault();
+ moveInFrame(-1);
+ }
+
+ if (event.key === 'ArrowRight') {
+ event.preventDefault();
+ moveInFrame(1);
+ }
+ }}
+ >
+ <div className="pointer-events-none absolute inset-0 flex items-center justify-center gap-[2px]">
+ <div className="h-3 w-px rounded-full bg-white/80" />
+ <div className="h-3 w-px rounded-full bg-white/80" />
+ </div>
+ </div>
+ <div
+ aria-label="Trim end"
+ aria-valuemax={durationInFrames - 1}
+ aria-valuemin={currentInFrame + minimumFrameDistance}
+ aria-valuenow={currentOutFrame}
+ className="bg-brand absolute top-0 h-full cursor-ew-resize overflow-hidden rounded-r-md border-l border-blue-800"
+ role="slider"
+ style={{
+ left: endHandleLeft,
+ width: HANDLE_WIDTH,
+ }}
+ tabIndex={0}
+ onContextMenu={() => {
+ setDragging(null);
+ }}
+ onPointerDown={(event) => {
+ if (event.button !== 0) {
+ setDragging(null);
+ return;
+ }
+
+ const {current} = wrapperRef;
+ if (!current) {
+ return;
+ }
+
+ event.stopPropagation();
+ setDragPointerOffset(event.clientX, 'out', current);
+ setDragging('out');
+ }}
+ onKeyDown={(event) => {
+ if (event.key === 'ArrowLeft') {
+ event.preventDefault();
+ moveOutFrame(-1);
+ }
+
+ if (event.key === 'ArrowRight') {
+ event.preventDefault();
+ moveOutFrame(1);
+ }
+ }}
+ >
+ <div className="pointer-events-none absolute inset-0 flex items-center justify-center gap-[2px]">
+ <div className="h-3 w-px rounded-full bg-white/80" />
+ <div className="h-3 w-px rounded-full bg-white/80" />
+ </div>
+ </div>
+ </div>
+ <div className="mt-1 flex items-start justify-between font-brand text-xs tabular-nums text-zinc-700">
+ <div className="flex flex-col items-start gap-1">
+ <span className="min-w-[4.75rem] text-left">{startTimestamp}</span>
+ <div className="flex items-center gap-1">
+ <FrameStepButton
+ aria-label="Move trim start back by 1 frame"
+ disabled={currentInFrame === 0}
+ icon="minus"
+ onClick={() => moveInFrame(-1)}
+ />
+ <FrameStepButton
+ aria-label="Move trim start forward by 1 frame"
+ disabled={
+ currentInFrame >= currentOutFrame - minimumFrameDistance
+ }
+ icon="plus"
+ onClick={() => moveInFrame(1)}
+ />
+ </div>
+ </div>
+ <div className="flex flex-col items-end gap-1">
+ <span className="min-w-[4.75rem] text-right">{endTimestamp}</span>
+ <div className="flex items-center gap-1">
+ <FrameStepButton
+ aria-label="Move trim end back by 1 frame"
+ disabled={
+ currentOutFrame <= currentInFrame + minimumFrameDistance
+ }
+ icon="minus"
+ onClick={() => moveOutFrame(-1)}
+ />
+ <FrameStepButton
+ aria-label="Move trim end forward by 1 frame"
+ disabled={currentOutFrame === durationInFrames - 1}
+ icon="plus"
+ onClick={() => moveOutFrame(1)}
+ />
+ </div>
+ </div>
+ </div>
+ </div>
+ );
+};
diff --git a/packages/convert/app/components/ui/label.tsx b/packages/convert/app/components/ui/label.tsx
index 3261b66a80..4c032301f0 100644
--- a/packages/convert/app/components/ui/label.tsx
+++ b/packages/convert/app/components/ui/label.tsx
@@ -4,7 +4,7 @@ import * as React from 'react';
import {cn} from '~/lib/utils';
const labelVariants = cva(
- 'ont-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70',
+ 'text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70',
);
const Label = React.forwardRef<
diff --git a/packages/convert/app/lib/default-ui.ts b/packages/convert/app/lib/default-ui.ts
index 8f8c67440a..1901c60240 100644
--- a/packages/convert/app/lib/default-ui.ts
+++ b/packages/convert/app/lib/default-ui.ts
@@ -57,6 +57,14 @@ export const defaultRotateOrMirorState = (
return 'crop';
}
+ if (action.type === 'generic-trim') {
+ return null;
+ }
+
+ if (action.type === 'trim-format') {
+ return null;
+ }
+
if (action.type === 'timing-editor') {
return null;
}
@@ -119,6 +127,14 @@ export const isConvertEnabledByDefault = (action: RouteAction) => {
return true;
}
+ if (action.type === 'generic-trim') {
+ return true;
+ }
+
+ if (action.type === 'trim-format') {
+ return true;
+ }
+
if (action.type === 'timing-editor') {
return true;
}
@@ -134,6 +150,7 @@ export type ConvertSections =
| 'mirror'
| 'resize'
| 'crop'
+ | 'trim'
| 'resample';
export const isVideoOnlySection = (section: ConvertSections): boolean => {
@@ -141,7 +158,8 @@ export const isVideoOnlySection = (section: ConvertSections): boolean => {
section === 'rotate' ||
section === 'mirror' ||
section === 'resize' ||
- section === 'crop'
+ section === 'crop' ||
+ section === 'trim'
) {
return true;
}
@@ -162,8 +180,21 @@ export const getOrderOfSections = (
resize: 1,
rotate: 2,
mirror: 3,
- convert: 4,
- resample: 5,
+ trim: 4,
+ convert: 5,
+ resample: 6,
+ };
+ }
+
+ if (action.type === 'generic-trim' || action.type === 'trim-format') {
+ return {
+ trim: 0,
+ crop: 1,
+ resize: 2,
+ rotate: 3,
+ mirror: 4,
+ convert: 5,
+ resample: 6,
};
}
@@ -173,8 +204,9 @@ export const getOrderOfSections = (
resize: 1,
crop: 2,
mirror: 3,
- convert: 4,
- resample: 5,
+ trim: 4,
+ convert: 5,
+ resample: 6,
};
}
@@ -185,7 +217,8 @@ export const getOrderOfSections = (
resize: 2,
rotate: 3,
mirror: 4,
- resample: 5,
+ trim: 5,
+ resample: 6,
};
}
@@ -196,7 +229,8 @@ export const getOrderOfSections = (
crop: 2,
rotate: 3,
mirror: 4,
- resample: 5,
+ trim: 5,
+ resample: 6,
};
}
@@ -206,8 +240,9 @@ export const getOrderOfSections = (
resize: 1,
crop: 2,
rotate: 3,
- convert: 4,
- resample: 5,
+ trim: 4,
+ convert: 5,
+ resample: 6,
};
}
@@ -223,8 +258,9 @@ export const getOrderOfSections = (
rotate: 1,
crop: 2,
mirror: 3,
- convert: 4,
- resample: 5,
+ trim: 4,
+ convert: 5,
+ resample: 6,
};
}
diff --git a/packages/convert/app/lib/is-submit-enabled.ts b/packages/convert/app/lib/is-submit-enabled.ts
index c42883578c..8df3f2b8e4 100644
--- a/packages/convert/app/lib/is-submit-enabled.ts
+++ b/packages/convert/app/lib/is-submit-enabled.ts
@@ -9,18 +9,21 @@ export const isSubmitDisabled = ({
videoConfigIndexSelection,
enableConvert,
enableRotateOrMirror,
+ enableTrim,
}: {
supportedConfigs: SupportedConfigs | null;
audioConfigIndexSelection: Record<number, string>;
videoConfigIndexSelection: Record<number, string>;
enableConvert: boolean;
enableRotateOrMirror: RotateOrMirrorOrCropState;
+ enableTrim: boolean;
}) => {
if (!supportedConfigs) {
return true;
}
- const allActionsDisabled = !enableConvert && enableRotateOrMirror === null;
+ const allActionsDisabled =
+ !enableConvert && enableRotateOrMirror === null && !enableTrim;
if (allActionsDisabled) {
return true;
@@ -42,5 +45,5 @@ export const isSubmitDisabled = ({
enableConvert,
});
- return !(isRotatingOrMirroring || isConverting);
+ return !(isRotatingOrMirroring || isConverting || enableTrim);
};
diff --git a/packages/convert/app/routes/trim.$format.tsx b/packages/convert/app/routes/trim.$format.tsx
new file mode 100644
index 0000000000..964ac53db8
--- /dev/null
+++ b/packages/convert/app/routes/trim.$format.tsx
@@ -0,0 +1,19 @@
+import {useParams} from '@remix-run/react';
+import {useMemo} from 'react';
+import {Main} from '~/components/Main';
+import type {InputContainer, RouteAction} from '~/seo';
+
+const Index = () => {
+ const format = useParams().format as InputContainer;
+
+ const routeAction: RouteAction = useMemo(() => {
+ return {
+ type: 'trim-format',
+ format,
+ };
+ }, [format]);
+
+ return <Main routeAction={routeAction} />;
+};
+
+export default Index;
diff --git a/packages/convert/app/routes/trim._index.tsx b/packages/convert/app/routes/trim._index.tsx
new file mode 100644
index 0000000000..05cb62a377
--- /dev/null
+++ b/packages/convert/app/routes/trim._index.tsx
@@ -0,0 +1,12 @@
+import {Main} from '~/components/Main';
+import type {RouteAction} from '~/seo';
+
+const action: RouteAction = {
+ type: 'generic-trim',
+};
+
+const Index = () => {
+ return <Main routeAction={action} />;
+};
+
+export default Index;
diff --git a/packages/convert/app/seo.ts b/packages/convert/app/seo.ts
index 0c3226a355..b0006c898b 100644
--- a/packages/convert/app/seo.ts
+++ b/packages/convert/app/seo.ts
@@ -60,6 +60,13 @@ export type RouteAction =
type: 'crop-format';
format: InputContainer;
}
+ | {
+ type: 'generic-trim';
+ }
+ | {
+ type: 'trim-format';
+ format: InputContainer;
+ }
| {
type: 'generic-resize';
}
@@ -137,6 +144,14 @@ export const getHeaderTitle = (routeAction: RouteAction) => {
return `Fast ${renderHumanReadableContainer(routeAction.format)} cropping in the browser`;
}
+ if (routeAction.type === 'generic-trim') {
+ return 'Fast video trimming in the browser';
+ }
+
+ if (routeAction.type === 'trim-format') {
+ return `Fast ${renderHumanReadableContainer(routeAction.format)} trimming in the browser`;
+ }
+
throw new Error(`Invalid route action ${routeAction satisfies never}`);
};
@@ -197,6 +212,14 @@ export const getPageTitle = (routeAction: RouteAction) => {
return `Online ${renderHumanReadableContainer(routeAction.format)} Cropper - Remotion Convert`;
}
+ if (routeAction.type === 'generic-trim') {
+ return 'Online Video Trimmer - Remotion Convert';
+ }
+
+ if (routeAction.type === 'trim-format') {
+ return `Online ${renderHumanReadableContainer(routeAction.format)} Trimmer - Remotion Convert`;
+ }
+
throw new Error(`Invalid route action ${routeAction satisfies never}`);
};
@@ -263,6 +286,14 @@ export const getDescription = (routeAction: RouteAction) => {
return `The fastest online ${renderHumanReadableContainer(routeAction.format)} cropper, powered by WebCodecs. No upload required, no watermarks, no limits.`;
}
+ if (routeAction.type === 'generic-trim') {
+ return `The fastest online video trimmer, powered by WebCodecs. No upload required, no watermarks, no limits.`;
+ }
+
+ if (routeAction.type === 'trim-format') {
+ return `The fastest online ${renderHumanReadableContainer(routeAction.format)} trimmer, powered by WebCodecs. No upload required, no watermarks, no limits.`;
+ }
+
throw new Error(`Invalid route action ${routeAction satisfies never}`);
};
@@ -323,5 +354,13 @@ export const makeSlug = (routeAction: RouteAction) => {
return `/crop/${routeAction.format}`;
}
+ if (routeAction.type === 'generic-trim') {
+ return '/trim';
+ }
+
+ if (routeAction.type === 'trim-format') {
+ return `/trim/${routeAction.format}`;
+ }
+
throw new Error(`Invalid route action ${routeAction satisfies never}`);
};
diff --git a/packages/convert/package.json b/packages/convert/package.json
index 99b6728825..f6325a621c 100644
--- a/packages/convert/package.json
+++ b/packages/convert/package.json
@@ -36,6 +36,7 @@
"@remotion/paths": "workspace:*",
"@remotion/player": "workspace:*",
"@remotion/shapes": "workspace:*",
+ "@remotion/timeline-utils": "workspace:*",
"@remotion/whisper-web": "workspace:*",
"@vercel/remix": "2.16.7",
"@vidstack/react": "1.12.13",
diff --git a/packages/convert/test/default-ui.test.ts b/packages/convert/test/default-ui.test.ts
index 523febd418..7d53ea6b7c 100644
--- a/packages/convert/test/default-ui.test.ts
+++ b/packages/convert/test/default-ui.test.ts
@@ -5,6 +5,10 @@ test('treats crop as a video-only operation section', () => {
expect(isVideoOnlySection('crop')).toBe(true);
});
+test('treats trim as a video-only operation section', () => {
+ expect(isVideoOnlySection('trim')).toBe(true);
+});
+
test('treats rotate, mirror, and resize as video-only operation sections', () => {
expect(isVideoOnlySection('rotate')).toBe(true);
expect(isVideoOnlySection('mirror')).toBe(true);
diff --git a/packages/docs/copy-convert.ts b/packages/docs/copy-convert.ts
index 636ba7b019..78d2c23975 100644
--- a/packages/docs/copy-convert.ts
+++ b/packages/docs/copy-convert.ts
@@ -63,6 +63,11 @@ for (const inputs of seo.inputContainers) {
format: inputs,
});
+ extraPages.push({
+ type: 'trim-format',
+ format: inputs,
+ });
+
extraPages.push({
type: 'resize-format',
format: inputs,
@@ -110,6 +115,10 @@ extraPages.push({
type: 'generic-crop',
});
+extraPages.push({
+ type: 'generic-trim',
+});
+
extraPages.push({
type: 'generic-probe',
});
diff --git a/packages/timeline-utils/src/index.ts b/packages/timeline-utils/src/index.ts
index f6f8ba50f0..bc6c3dad38 100644
--- a/packages/timeline-utils/src/index.ts
+++ b/packages/timeline-utils/src/index.ts
@@ -40,4 +40,6 @@ export {
getDurationOfOneFrame,
WEBCODECS_TIMESCALE,
} from './render-frame-strip';
+export {renderFrameStripToCanvas} from './render-frame-strip-to-canvas';
+export type {RenderFrameStripToCanvasOptions} from './render-frame-strip-to-canvas';
export {resizeVideoFrame} from './resize-video-frame';
diff --git a/packages/timeline-utils/src/render-frame-strip-to-canvas.ts b/packages/timeline-utils/src/render-frame-strip-to-canvas.ts
new file mode 100644
index 0000000000..e3ffb1e171
--- /dev/null
+++ b/packages/timeline-utils/src/render-frame-strip-to-canvas.ts
@@ -0,0 +1,182 @@
+import {extractFrames} from './extract-frames';
+import {
+ addFrameToCache,
+ aspectRatioCache,
+ getAspectRatioFromCache,
+ makeFrameDatabaseKey,
+} from './frame-database';
+import {
+ ensureSlots,
+ fillFrameWhereItFits,
+ fillWithCachedFrames,
+ WEBCODECS_TIMESCALE,
+} from './render-frame-strip';
+import {resizeVideoFrame} from './resize-video-frame';
+
+type Canvas = HTMLCanvasElement | OffscreenCanvas;
+type Context = CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D;
+
+export type RenderFrameStripToCanvasOptions = {
+ readonly canvas: Canvas;
+ readonly src: string;
+ readonly fromSeconds: number;
+ readonly toSeconds: number;
+ readonly width: number;
+ readonly frameHeight: number;
+ readonly devicePixelRatio: number;
+ readonly signal?: AbortSignal;
+};
+
+const getContext = (canvas: Canvas): Context => {
+ const ctx = canvas.getContext('2d');
+ if (!ctx) {
+ throw new Error('Could not get 2d context');
+ }
+
+ return ctx;
+};
+
+export const renderFrameStripToCanvas = async ({
+ canvas,
+ src,
+ fromSeconds,
+ toSeconds,
+ width,
+ frameHeight,
+ devicePixelRatio,
+ signal,
+}: RenderFrameStripToCanvasOptions): Promise<void> => {
+ const naturalWidth = Math.max(1, Math.ceil(width));
+ const naturalHeight = Math.max(1, Math.ceil(frameHeight));
+ const segmentDuration = toSeconds - fromSeconds;
+
+ canvas.width = naturalWidth;
+ canvas.height = naturalHeight;
+
+ if (segmentDuration <= 0 || signal?.aborted) {
+ return;
+ }
+
+ const ctx = getContext(canvas);
+ ctx.clearRect(0, 0, naturalWidth, naturalHeight);
+
+ const filledSlots = new Map<number, number | undefined>();
+ let aspectRatio = getAspectRatioFromCache(src);
+
+ if (aspectRatio !== null) {
+ ensureSlots({
+ filledSlots,
+ naturalWidth,
+ fromSeconds,
+ toSeconds,
+ aspectRatio,
+ frameHeight,
+ });
+
+ fillWithCachedFrames({
+ ctx,
+ naturalWidth,
+ filledSlots,
+ src,
+ segmentDuration,
+ fromSeconds,
+ devicePixelRatio,
+ frameHeight,
+ });
+
+ const hasUnfilledSlots = Array.from(filledSlots.values()).some(
+ (value) => value === undefined,
+ );
+ if (!hasUnfilledSlots) {
+ return;
+ }
+ }
+
+ await extractFrames({
+ src,
+ signal,
+ timestampsInSeconds: ({track}) => {
+ aspectRatio = track.width / track.height;
+ aspectRatioCache.set(src, aspectRatio);
+
+ ensureSlots({
+ filledSlots,
+ naturalWidth,
+ fromSeconds,
+ toSeconds,
+ aspectRatio,
+ frameHeight,
+ });
+
+ return Array.from(filledSlots.keys()).map(
+ (timestamp) => timestamp / WEBCODECS_TIMESCALE,
+ );
+ },
+ onVideoSample: (sample) => {
+ let frame: VideoFrame | undefined;
+ try {
+ frame = sample.toVideoFrame();
+ const scale = (frameHeight / frame.displayHeight) * devicePixelRatio;
+ const transformed = resizeVideoFrame({frame, scale});
+
+ if (transformed !== frame) {
+ frame.close();
+ }
+
+ frame = undefined;
+
+ addFrameToCache(
+ makeFrameDatabaseKey(src, transformed.timestamp),
+ transformed,
+ );
+
+ if (aspectRatio === null) {
+ throw new Error('Aspect ratio is not set');
+ }
+
+ ensureSlots({
+ filledSlots,
+ naturalWidth,
+ fromSeconds,
+ toSeconds,
+ aspectRatio,
+ frameHeight,
+ });
+
+ fillFrameWhereItFits({
+ ctx,
+ filledSlots,
+ visualizationWidth: naturalWidth,
+ frame: transformed,
+ segmentDuration,
+ fromSeconds,
+ devicePixelRatio,
+ frameHeight,
+ });
+ } catch (e) {
+ if (frame) {
+ frame.close();
+ }
+
+ throw e;
+ } finally {
+ sample.close();
+ }
+ },
+ });
+
+ if (signal?.aborted) {
+ return;
+ }
+
+ fillWithCachedFrames({
+ ctx,
+ naturalWidth,
+ filledSlots,
+ src,
+ segmentDuration,
+ fromSeconds,
+ devicePixelRatio,
+ frameHeight,
+ });
+};