Skip to content

Create professional demos and 3D mockups in seconds, directly in your browser

feat: implement video clip splitting functionality and enhance export process

CristianOlivera179b39f43d18f
diff --git a/app/[locale]/(editor)/editor/page.tsx b/app/[locale]/(editor)/editor/page.tsx
index 5c783dd..75f595d 100644
--- a/app/[locale]/(editor)/editor/page.tsx
+++ b/app/[locale]/(editor)/editor/page.tsx
@@ -17,7 +17,7 @@ import { useVideoThumbnails, type VideoThumbnail } from "@/hooks/useVideoThumbna
import { useUndoRedo } from "@/hooks/useUndoRedo";
import { clearAllThumbnailCache } from "@/lib/thumbnail-cache";
import { addVideoToLibrary, addVideoToLibraryWithMetadata, getLibraryVideoCount, getLibraryVideo, findExistingVideo } from "@/lib/videos-library";
-import { calculateTotalDuration, findNextClipPosition, getClipAtTime, type VideoTrackClip } from "@/types/video-track.types";
+import { calculateTotalDuration, findNextClipPosition, getClipAtTime, splitClipAtTime, type VideoTrackClip } from "@/types/video-track.types";
import type { ExportQuality, BackgroundTab, VideoCanvasHandle, BackgroundColorConfig, AspectRatio, CropArea, ZoomFragment, AudioTrack, ImageExportFormat } from "@/types";
import type { TrimRange } from "@/types/timeline.types";
import type { MockupConfig, MenuPage } from "@/types/mockup.types";
@@ -1610,29 +1610,30 @@ export default function Editor() {
}
exportVideo({
- quality,
- videoBlob: videoBlob ?? undefined,
- transparentBackground: selectedWallpaper === -1,
- trim: trimRange.end > trimRange.start ? { start: trimRange.start, end: trimRange.end } : undefined,
- muteOriginalAudio,
- videoHasAudioTrack: videoHasAudioTrack,
- audioTracks: audioTracks.map(track => {
- const audio = uploadedAudios.find(a => a.id === track.audioId);
- return {
- audioUrl: audio?.url || '',
- startTime: track.startTime,
- duration: track.duration,
- trimStart: track.trimStart ?? 0,
- volume: track.volume,
- loop: track.loop,
- };
- }),
- masterVolume,
- videoClips: videoClips.length > 0 ? videoClips : undefined,
- videoClipBlobs: videoClips.length > 1 ? videoBlobsRef.current : undefined,
- clipAudioStates: Object.fromEntries(clipAudioStateRef.current),
- }).finally(() => {
- });
+ quality,
+ videoBlob: videoBlob ?? undefined,
+ transparentBackground: selectedWallpaper === -1,
+ trim: trimRange.end > trimRange.start ? { start: trimRange.start, end: trimRange.end } : undefined,
+ muteOriginalAudio,
+ videoHasAudioTrack: videoHasAudioTrack,
+ audioTracks: audioTracks.map(track => {
+ const audio = uploadedAudios.find(a => a.id === track.audioId);
+ return {
+ audioUrl: audio?.url || '',
+ startTime: track.startTime,
+ duration: track.duration,
+ trimStart: track.trimStart ?? 0,
+ volume: track.volume,
+ loop: track.loop,
+ };
+ }),
+ masterVolume,
+ videoClips: videoClips.length > 0 ? videoClips : undefined,
+ videoClipBlobs: videoClips.length > 1 ? videoBlobsRef.current : undefined,
+ clipAudioStates: Object.fromEntries(clipAudioStateRef.current),
+}).finally(() => {
+ isExportingRef.current = false; // ← antes quedaba en true para siempre
+});
};
// Handler para subir video (desde ToolsSidebar)
@@ -1864,6 +1865,37 @@ export default function Editor() {
}
}, [selectedVideoClipId]);
+ const handleSplitVideoClip = useCallback(() => {
+ const clips = videoClipsRef.current;
+ const clipAtPlayhead = getClipAtTime(clips, currentTime);
+ if (!clipAtPlayhead) return;
+
+ const result = splitClipAtTime(clipAtPlayhead, currentTime);
+ if (!result) return;
+
+ const { updatedClip, newClip } = result;
+
+ setVideoClips(prev => {
+ const next = prev.map(c => (c.id === updatedClip.id ? updatedClip : c));
+ next.push(newClip);
+ return next.sort((a, b) => a.startTime - b.startTime);
+ });
+
+ if (activeClipIdRef.current === updatedClip.id) {
+ activeClipIdRef.current = newClip.id;
+ activeClipDataRef.current = newClip;
+ }
+
+ setSelectedVideoClipId(newClip.id);
+ setSelectedZoomFragmentId(null);
+ setSelectedAudioTrackId(null);
+ setSelectedElementId(null);
+ setActiveTool("videos");
+ }, [currentTime]);
+
+ const activeClipForSplit = getClipAtTime(videoClipsRef.current, currentTime);
+ const canSplitClip = !!activeClipForSplit && splitClipAtTime(activeClipForSplit, currentTime) !== null;
+
// Handler to remove video from track when deleted from library (cascade delete)
const handleDeleteVideoFromLibrary = useCallback((libraryVideoId: string) => {
setVideoClips(prev => {
@@ -2523,7 +2555,11 @@ export default function Editor() {
if (clipAtTime.id !== activeClipIdRef.current) {
const url = videoUrlsRef.current.get(clipAtTime.libraryVideoId);
- if (url) {
+ const isSameSource = !!url && videoRef.current.src === url;
+ activeClipIdRef.current = clipAtTime.id;
+ activeClipDataRef.current = clipAtTime;
+
+ if (url && !isSameSource) {
activeClipIdRef.current = clipAtTime.id;
activeClipDataRef.current = clipAtTime;
isSeekingToClipRef.current = true;
@@ -2582,26 +2618,41 @@ export default function Editor() {
setTimelineZoom(zoom);
}, []);
- const handleLoadedMetadata = useCallback(() => {
- if (videoRef.current) {
- videoRef.current.playbackRate = 1.0;
-
- const duration = videoRef.current.duration;
- if (isFinite(duration) && duration > 0) {
- const currentClips = videoClipsRef.current;
- if (currentClips.length <= 1) {
- setVideoDuration(duration);
- setTrimRange(prev => prev.end === 0 ? { start: 0, end: duration } : prev);
- }
- }
+ const handleLoadedMetadata = useCallback(() => {
+ if (videoRef.current) {
+ videoRef.current.playbackRate = 1.0;
- const vw = videoRef.current.videoWidth;
- const vh = videoRef.current.videoHeight;
- if (vw > 0 && vh > 0) {
- setVideoDimensions({ width: vw, height: vh });
- }
+ // Durante la exportación, el pipeline reasigna video.src entre los
+ // blobs de cada clip para renderizar sus frames. Ese reasignado
+ // dispara este mismo evento nativo "loadedmetadata"; sin este guard
+ // redimensionaríamos el canvas de exportación cada vez que carga un
+ // clip con resolución nativa distinta — justo lo que provoca el
+ // error "Video sample size must remain constant" de mediabunny.
+ if (isExportingRef.current) return;
+
+ const duration = videoRef.current.duration;
+ const currentClips = videoClipsRef.current;
+ const isMultiClip = currentClips.length > 1;
+
+ if (isFinite(duration) && duration > 0 && !isMultiClip) {
+ setVideoDuration(duration);
+ setTrimRange(prev => prev.end === 0 ? { start: 0, end: duration } : prev);
}
- }, []);
+
+ const vw = videoRef.current.videoWidth;
+ const vh = videoRef.current.videoHeight;
+ // Mismo razonamiento fuera de la exportación: en un track multi-clip
+ // el <video> compartido cambia de src entre clips a medida que la
+ // reproducción cruza límites de clip. Esos clips pueden tener
+ // resoluciones nativas distintas, así que el canvas/aspect-ratio
+ // debe quedar fijado con lo que se registró al construir el track
+ // (ver handleVideoUpload / handleAddVideoToTrack), no seguir al
+ // clip que esté cargado en ese instante.
+ if (vw > 0 && vh > 0 && !isMultiClip) {
+ setVideoDimensions({ width: vw, height: vh });
+ }
+ }
+}, []);
const skipBackward = useCallback(() => {
if (videoRef.current) {
@@ -2642,10 +2693,14 @@ export default function Editor() {
const clipTime = timelineToClipTime(time, clipAtTime);
const currentUrl = videoRef.current.src;
const targetUrl = videoUrlsRef.current.get(clipAtTime.libraryVideoId);
- const needsClipSwitch = clipAtTime.id !== activeClipIdRef.current
- || (targetUrl && currentUrl !== targetUrl);
+ const isDifferentSource = !!targetUrl && currentUrl !== targetUrl;
+
+ if (clipAtTime.id !== activeClipIdRef.current) {
+ activeClipIdRef.current = clipAtTime.id;
+ activeClipDataRef.current = clipAtTime;
+ }
- if (needsClipSwitch && targetUrl) {
+ if (isDifferentSource && targetUrl) {
const wasPlaying = isPlaying;
if (videoRef.current && !videoRef.current.paused) {
@@ -3219,6 +3274,8 @@ export default function Editor() {
videoMaskConfig={videoMaskConfig}
onVideoMaskConfigChange={setVideoMaskConfig}
videoPreviewImageUrl={getThumbnailForTime(currentDisplayTime)?.dataUrl ?? null}
+ onSplitClip={handleSplitVideoClip}
+ canSplitClip={canSplitClip}
/>
<Suspense fallback={<TimelineSkeleton />}>
diff --git a/app/components/ui/editor/ControlPanel.tsx b/app/components/ui/editor/ControlPanel.tsx
index 6506e1f..bf61343 100644
--- a/app/components/ui/editor/ControlPanel.tsx
+++ b/app/components/ui/editor/ControlPanel.tsx
@@ -244,7 +244,7 @@ export function ControlPanel({
label={t("screenshot.sliders.blur")}
value={backgroundBlur}
min={0}
- max={20}
+ max={30}
onChange={onBackgroundBlurChange}
/>
<SliderControl
@@ -252,7 +252,7 @@ export function ControlPanel({
label={t("screenshot.sliders.padding")}
value={padding}
min={0}
- max={20}
+ max={30}
onChange={onPaddingChange}
/>
<SliderControl
@@ -260,7 +260,7 @@ export function ControlPanel({
label={t("screenshot.sliders.rounded")}
value={roundedCorners}
min={0}
- max={20}
+ max={30}
onChange={onRoundedCornersChange}
/>
<SliderControl
@@ -268,7 +268,7 @@ export function ControlPanel({
label={t("screenshot.sliders.shadows")}
value={shadows}
min={0}
- max={20}
+ max={30}
onChange={onShadowsChange}
/>
</div>
diff --git a/app/components/ui/editor/MockupMenu.tsx b/app/components/ui/editor/MockupMenu.tsx
index d8fa0a4..b4a426f 100644
--- a/app/components/ui/editor/MockupMenu.tsx
+++ b/app/components/ui/editor/MockupMenu.tsx
@@ -332,8 +332,8 @@ export function MockupMenu({
</span>
</div>
</div>
- <div className="flex items-center justify-center px-2 border-l border-white/5 h-full group-hover:text-white transition-colors">
- <Icon icon="uil:sort" aria-hidden="true" />
+ <div className="flex items-center justify-center px-1 border-l border-white/5 h-full group-hover:text-white transition-colors">
+ <Icon icon="uil:sort" aria-hidden="true" width="20" />
</div>
</button>
</PopoverTrigger>
diff --git a/app/components/ui/editor/PlayerControls.tsx b/app/components/ui/editor/PlayerControls.tsx
index c68dce4..4c45ea8 100644
--- a/app/components/ui/editor/PlayerControls.tsx
+++ b/app/components/ui/editor/PlayerControls.tsx
@@ -29,6 +29,8 @@ export function PlayerControls({
videoMaskConfig = { enabled: false },
onVideoMaskConfigChange,
videoPreviewImageUrl,
+ onSplitClip,
+ canSplitClip = false,
}: PlayerControlsProps) {
const t = useTranslations("playerControls");
@@ -86,12 +88,17 @@ export function PlayerControls({
e.preventDefault();
onToggleFullscreen();
break;
+ case "s":
+ case "S":
+ e.preventDefault();
+ if (canSplitClip) onSplitClip?.();
+ break;
}
};
window.addEventListener("keydown", handleKeyDown);
return () => window.removeEventListener("keydown", handleKeyDown);
- }, [onTogglePlayPause, onSkipBackward, onSkipForward, onToggleFullscreen, handleZoomIn, handleZoomOut]);
+ }, [onTogglePlayPause, onSkipBackward, onSkipForward, onToggleFullscreen, handleZoomIn, handleZoomOut, onSplitClip, canSplitClip]);
const fullscreenLabel = isFullscreen ? t("fullscreen.exit") : t("fullscreen.enter");
const playPauseLabel = isPlaying ? t("transport.pause") : t("transport.play");
@@ -170,15 +177,16 @@ export function PlayerControls({
</div>
<div className="h-4 w-px bg-white/10" />
-
- {/* <TooltipAction label="Dividir video">
+ <TooltipAction label={t("split.clip")}>
<button
- className="text-zinc-500 hover:text-white active:scale-95 transition-all p-1 flex items-center justify-center"
- aria-label="Dividir track en la línea de tiempo"
+ onClick={() => onSplitClip?.()}
+ disabled={!canSplitClip}
+ className="text-zinc-500 hover:text-white active:scale-95 transition-all p-1 flex items-center justify-center disabled:opacity-40 disabled:cursor-not-allowed disabled:hover:text-zinc-500 disabled:active:scale-100"
+ aria-label={t("split.clip")}
>
- <Icon icon="lucide:scissors" width="15" aria-hidden="true" />
+ <Icon icon="mingcute:scissors-fill" width="15" aria-hidden="true" />
</button>
- </TooltipAction> */}
+ </TooltipAction>
{/* Select de Mask Image aqui */}
<div className="h-4 w-px bg-white/10" />
diff --git a/app/components/ui/editor/ToolsSidebar.tsx b/app/components/ui/editor/ToolsSidebar.tsx
index 8637046..8f443aa 100644
--- a/app/components/ui/editor/ToolsSidebar.tsx
+++ b/app/components/ui/editor/ToolsSidebar.tsx
@@ -369,14 +369,14 @@ export function ToolsSidebar({
}}
/>
- <SidebarTool
+ {/* <SidebarTool
icon="solar:cursor-bold-duotone"
label={t("tools.cursor")}
isActive={activeTool === "cursor"}
onClick={() => onToolChange("cursor")}
badge={!isCursorEnabled ? t("tools.soon") : undefined}
disabled={!isCursorEnabled}
- />
+ /> */}
</>
)}
<div className="shrink-0 h-12" aria-hidden="true" />
diff --git a/app/components/ui/editor/VideoCanvas.tsx b/app/components/ui/editor/VideoCanvas.tsx
index 7c45aca..50505cf 100644
--- a/app/components/ui/editor/VideoCanvas.tsx
+++ b/app/components/ui/editor/VideoCanvas.tsx
@@ -1012,7 +1012,7 @@ const VideoCanvasInner = forwardRef<VideoCanvasHandle, VideoCanvasProps>(functio
};
// Function to draw a frame on the export canvas
- const drawFrame = async (highQuality: boolean = true) => {
+ const drawFrame = async (highQuality: boolean = true, explicitTimelineTime?: number) => {
const canvas = exportCanvasRef.current;
const canvasCtxOptions: CanvasRenderingContext2DSettings = { alpha: true, colorSpace: 'srgb', desynchronized: false, willReadFrequently: false };
const ctx = canvas?.getContext('2d', canvasCtxOptions);
@@ -1041,7 +1041,9 @@ const VideoCanvasInner = forwardRef<VideoCanvasHandle, VideoCanvasProps>(functio
ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.clearRect(0, 0, canvasWidth, canvasHeight);
- const frameTime = mediaType === "video" && video ? video.currentTime : 0;
+ const frameTime = mediaType === "video"
+ ? (explicitTimelineTime ?? (video ? video.currentTime : 0))
+ : 0;
const zoomState = calculateSmoothZoom(frameTime, zoomFragments);
const zoomCenterX = canvasWidth / 2;
const zoomCenterY = canvasHeight / 2;
@@ -1126,7 +1128,7 @@ const VideoCanvasInner = forwardRef<VideoCanvasHandle, VideoCanvasProps>(functio
// Shadow
if (shadows > 0 && !SELF_SHADOWING_MOCKUPS.includes(mockupId)) {
c.save();
- c.shadowColor = 'rgba(0, 0, 0, 0.5)';
+ c.shadowColor = 'rgba(0, 0, 0, 1)';
c.shadowBlur = scaledShadowBlur;
c.shadowOffsetY = scaledShadowBlur * 0.3;
c.fillStyle = 'black';
diff --git a/hooks/useActiveTool.ts b/hooks/useActiveTool.ts
index 4a16666..7ff163b 100644
--- a/hooks/useActiveTool.ts
+++ b/hooks/useActiveTool.ts
@@ -1,26 +1,6 @@
"use client";
-/**
- * useActiveTool
- *
- * Sincroniza la herramienta activa del editor (sidebar/ControlPanel) con
- * el query param `?m=<tool>` de la URL.
- *
- * /es/editor?mode=video&m=mockup → mockup menu
- * /es/editor?mode=photo&m=elements → elements menu
- *
- * Usa `useSearchParams` de Next.js + `useRouter` para que el state se
- * mantenga sincronizado con la URL en AMBAS direcciones:
- * - Al hacer click en un tool → URL cambia → state se actualiza
- * (porque useSearchParams es reactivo a router.replace)
- * - Al navegar a una URL con `?m=X` (pegar URL, back/forward) → el
- * state lee el valor de la URL en mount/vía re-render.
- *
- * El setter usa `router.replace` en lugar de `window.history.replaceState`
- * para que Next.js se entere del cambio y `useSearchParams` se actualice.
- */
-
-import { useCallback, useEffect } from "react";
+import { useCallback } from "react";
import { usePathname, useRouter, useSearchParams } from "next/navigation";
import type { Tool } from "@/types/editor.types";
@@ -44,22 +24,14 @@ function parseTool(value: string | null): Tool {
return "screenshot";
}
-/**
- * Hook estilo `useState`: retorna [value, setter]. Lee `m` de la URL y
- * actualiza la URL al cambiar.
- */
export function useActiveTool(): [Tool, (next: Tool) => void] {
const router = useRouter();
const pathname = usePathname();
const searchParams = useSearchParams();
- // `useSearchParams` es reactivo a router.replace (no a replaceState).
- // En mount, ya tiene el valor de la URL; no necesita useEffect extra.
const tool = parseTool(searchParams.get("m"));
const setTool = useCallback((next: Tool) => {
- // Construye los nuevos params preservando todos los existentes
- // (mode, preset, etc.) y actualizando solo `m`
const params = new URLSearchParams(searchParams.toString());
params.set("m", next);
router.replace(`${pathname}?${params.toString()}`);
diff --git a/hooks/useVideoExport.ts b/hooks/useVideoExport.ts
index 35623df..a7199b7 100644
--- a/hooks/useVideoExport.ts
+++ b/hooks/useVideoExport.ts
@@ -275,7 +275,8 @@ async function exportWithFFmpegWebM(
for (let i = 0; i < totalFrames; i++) {
if (cancellation.cancelled) throw new Error("Exportación cancelada");
- await canvasHandle.drawFrame();
+ const timelineTime = trimStart + i / fps;
+ await canvasHandle.drawFrame(true, timelineTime);
const nextI = i + 1;
if (nextI < totalFrames) {
@@ -399,8 +400,9 @@ async function exportWithMediabunny(
}
const outputTime = frameIndex / fps;
+ const timelineTime = trimStart + outputTime;
- await canvasHandle.drawFrame();
+ await canvasHandle.drawFrame(true, timelineTime);
await videoSource.add(outputTime, frameDuration);
const nextIndex = frameIndex + 1;
@@ -559,6 +561,9 @@ async function exportWithMediabunnyAndAudio(
await waitForVideoFrame(video);
+ const lockedWidth = canvas.width;
+ const lockedHeight = canvas.height;
+
for (let frameIndex = 0; frameIndex < totalFrames; frameIndex++) {
if (cancellation.cancelled) {
throw new Error("Exportación cancelada");
@@ -592,7 +597,12 @@ async function exportWithMediabunnyAndAudio(
}
}
- await canvasHandle.drawFrame();
+ if (canvas.width !== lockedWidth || canvas.height !== lockedHeight) {
+ canvas.width = lockedWidth;
+ canvas.height = lockedHeight;
+ }
+
+ await canvasHandle.drawFrame(true, timelineTime);
await videoSource.add(outputTime, frameDuration);
if (!hasMultipleClips) {
@@ -761,7 +771,8 @@ async function exportWithMediabunnyAndAudio(
if (hasSourceAudio) {
if (hasMultipleClips && clipAudioFiles.length > 0) {
for (const { clip, filename } of clipAudioFiles) {
- ffmpegArgs.push("-ss", String(clip.trimStart), "-t", String(clip.duration), "-i", filename);
+ const clipTrimmedDuration = clip.trimEnd - clip.trimStart;
+ ffmpegArgs.push("-ss", String(clip.trimStart), "-t", String(clipTrimmedDuration), "-i", filename);
}
} else {
ffmpegArgs.push("-ss", String(trimStart), "-t", String(duration), "-i", "original.mp4");
@@ -936,7 +947,8 @@ async function exportWithFFmpegGif(
for (let i = 0; i < totalFrames; i++) {
if (cancellation.cancelled) throw new Error("Exportación cancelada");
- await canvasHandle.drawFrame();
+ const timelineTime = trimStart + i / fps;
+ await canvasHandle.drawFrame(true, timelineTime);
const nextI = i + 1;
if (nextI < totalFrames) {
diff --git a/messages/en.json b/messages/en.json
index e4227b3..54ca564 100644
--- a/messages/en.json
+++ b/messages/en.json
@@ -1023,6 +1023,9 @@
"in": "Zoom in (↑)",
"label": "Timeline zoom: {level}×"
},
+ "split": {
+ "clip": "Split clip"
+ },
"transport": {
"group": "Transport controls",
"currentTime": "Current time: {time}",
diff --git a/messages/es.json b/messages/es.json
index e6e4877..ed8efd1 100644
--- a/messages/es.json
+++ b/messages/es.json
@@ -1001,6 +1001,9 @@
"in": "Acercar (↑)",
"label": "Zoom: {level}×"
},
+ "split": {
+ "clip": "Dividir"
+ },
"transport": {
"group": "Controles de transporte",
"currentTime": "Tiempo actual: {time}",
diff --git a/messages/ru.json b/messages/ru.json
index ac93fdc..edb66b1 100644
--- a/messages/ru.json
+++ b/messages/ru.json
@@ -991,6 +991,9 @@
"in": "Увеличить (↑)",
"label": "Зум таймлайна: {level}×"
},
+ "split": {
+ "clip": "Разделить клип (S)"
+ },
"transport": {
"group": "Управление воспроизведением",
"currentTime": "Текущее время: {time}",
diff --git a/types/editor.types.ts b/types/editor.types.ts
index 56b5fd6..7c38770 100644
--- a/types/editor.types.ts
+++ b/types/editor.types.ts
@@ -43,7 +43,7 @@ export interface EditorState {
export interface VideoCanvasHandle {
getExportCanvas: () => HTMLCanvasElement | null;
- drawFrame: (highQuality?: boolean) => Promise<void>;
+ drawFrame: (highQuality?: boolean, time?: number) => Promise<void>;
getPreviewContainer: () => HTMLDivElement | null;
clearAllSelection: () => { multiIds: string[]; videoSelected: boolean };
restoreSelectionState: (state: { multiIds: string[]; videoSelected: boolean }) => void;
diff --git a/types/player-control.types.ts b/types/player-control.types.ts
index 0a4ba27..30a70ad 100644
--- a/types/player-control.types.ts
+++ b/types/player-control.types.ts
@@ -20,6 +20,8 @@ export interface PlayerControlsProps {
videoMaskConfig: ImageMaskConfig;
onVideoMaskConfigChange: (config: ImageMaskConfig) => void;
videoPreviewImageUrl?: string | null;
+ onSplitClip?: () => void;
+ canSplitClip?: boolean;
}
export const MIN_ZOOM = 1;
diff --git a/types/video-track.types.ts b/types/video-track.types.ts
index 0c753ec..777cce8 100644
--- a/types/video-track.types.ts
+++ b/types/video-track.types.ts
@@ -10,6 +10,13 @@ export interface VideoTrackClip {
hasCamera?: boolean;
}
+export const MIN_CLIP_DURATION = 0.1;
+
+export interface SplitClipResult {
+ updatedClip: VideoTrackClip;
+ newClip: VideoTrackClip;
+}
+
export function calculateTotalDuration(clips: VideoTrackClip[]): number {
if (clips.length === 0) return 0;
const sorted = [...clips].sort((a, b) => a.startTime - b.startTime);
@@ -53,3 +60,32 @@ export function getActiveClipAtTime(
export function sortClipsByTime(clips: VideoTrackClip[]): VideoTrackClip[] {
return [...clips].sort((a, b) => a.startTime - b.startTime);
}
+
+export function splitClipAtTime(clip: VideoTrackClip, timelineTime: number): SplitClipResult | null {
+ const clipDuration = clip.trimEnd - clip.trimStart;
+ const clipEnd = clip.startTime + clipDuration;
+
+ if (
+ timelineTime <= clip.startTime + MIN_CLIP_DURATION ||
+ timelineTime >= clipEnd - MIN_CLIP_DURATION
+ ) {
+ return null;
+ }
+
+ const splitPointInSource = clip.trimStart + (timelineTime - clip.startTime);
+
+ const updatedClip: VideoTrackClip = {
+ ...clip,
+ trimEnd: splitPointInSource,
+ };
+
+ const newClip: VideoTrackClip = {
+ ...clip,
+ id: crypto.randomUUID(),
+ startTime: timelineTime,
+ trimStart: splitPointInSource,
+ trimEnd: clip.trimEnd,
+ };
+
+ return { updatedClip, newClip };
+}
\ No newline at end of file