import { useState, useRef, useEffect, useMemo } from "react"; import type { FileEntry } from "../types"; import { api } from "../api"; import { fmt, secondsToHms, hmsToSeconds, formatAspectRatio } from "../utils"; interface AdvancedTrimCropSegment { id: string; start: string; end: string; cropEnabled: boolean; cropLeft: number; cropRight: number; cropTop: number; cropBottom: number; } interface AdvancedTrimCropModalProps { file: FileEntry; onClose: () => void; onProcessingStarted: () => void; } type DragType = "move" | "top" | "bottom" | "left" | "right" | "tl" | "tr" | "bl" | "br"; // ── Crop overlay with edge + corner resize handles ──────────────────────────── function CropOverlay({ seg, dragType, startCropDrag, onPointerMove, onPointerUp, }: { seg: AdvancedTrimCropSegment; dragType: DragType | null; startCropDrag: (type: DragType) => (e: React.PointerEvent) => void; onPointerMove: (e: React.PointerEvent) => void; onPointerUp: (e: React.PointerEvent) => void; }) { const handleProps = (type: DragType, cursor: string, className: string) => ({ className: `${className} pointer-events-auto select-none`, style: { cursor }, onPointerDown: startCropDrag(type), onPointerMove, onPointerUp, onPointerCancel: onPointerUp, }); return (
{/* Dim the area outside the crop box using 4 strips */}
{/* Crop box */}
{/* Clear the dim inside the crop box */}
{/* Visible border frame */}
{/* Rule-of-thirds grid lines */}
{/* ── Center drag-to-move zone ── */}
✥ move
{/* ── Edge handles (full-width/height transparent strips + visible pill) ── */} {/* Top */}
{/* Bottom */}
{/* Left */}
{/* Right */}
{/* ── Corner handles ── */} {/* TL */}
{/* TR */}
{/* BL */}
{/* BR */}
); } export function AdvancedTrimCropModal({ file, onClose, onProcessingStarted }: AdvancedTrimCropModalProps) { const [duration, setDuration] = useState(null); const [segments, setSegments] = useState(() => { try { const raw = sessionStorage.getItem(`encodeConfig_${file.id}`); if (raw) { const saved = JSON.parse(raw); if (Array.isArray(saved?.segments) && saved.segments.length > 0) return saved.segments; } } catch {} return []; }); const [activeSegmentId, setActiveSegmentId] = useState(null); const [loading, setLoading] = useState(true); const [busy, setBusy] = useState(false); const [error, setError] = useState(null); const [previewCurrentTime, setPreviewCurrentTime] = useState(0); const [videoDimensions, setVideoDimensions] = useState<{ width: number; height: number } | null>(null); const [seekStep, setSeekStep] = useState(6); const [isVideoPlaying, setIsVideoPlaying] = useState(false); const [pendingClipStart, setPendingClipStart] = useState(null); const [dragAnchor, setDragAnchor] = useState<{ x: number; y: number; left: number; right: number; top: number; bottom: number; type: DragType; } | null>(null); // Encode settings panel state const [showEncodeSettings, setShowEncodeSettings] = useState(false); const [encodeJobStarted, setEncodeJobStarted] = useState(false); const [encodeSettings, setEncodeSettings] = useState(() => { const defaults = { codec: "av1" as "h264" | "h265" | "av1", mode: "crf-1pass" as "crf-1pass" | "vbr", crf: 33, videoBitrateKbps: 2000, audioBitrateKbps: 96, resolution: "original" as string, sameAsOriginalAudio: true, h26xPreset: "medium" as string, av1Preset: 5, aqMode: 1, tiles: "0" as string, }; try { const raw = sessionStorage.getItem(`encodeConfig_${file.id}`); if (raw) { const saved = JSON.parse(raw); if (saved?.encodeSettings) return { ...defaults, ...saved.encodeSettings }; } } catch {} return defaults; }); const videoRef = useRef(null); const videoContainerRef = useRef(null); // Auto-save segments + encode settings to sessionStorage so reopening restores them useEffect(() => { try { sessionStorage.setItem(`encodeConfig_${file.id}`, JSON.stringify({ fileId: file.id, fileName: file.name, segments, encodeSettings, })); } catch {} }, [segments, encodeSettings, file.id, file.name]); // Initialize with file info useEffect(() => { const loadFileInfo = async () => { try { const res = await api.getFileInfo(file.id); if (res.ok && res.info.durationSeconds) { setDuration(res.info.durationSeconds); } } catch (err) { console.error("Failed to load file info:", err); } finally { setLoading(false); } }; loadFileInfo(); }, [file.id, file.name]); // Auto-select first segment when segments change useEffect(() => { if (segments.length > 0 && !activeSegmentId) { setActiveSegmentId(segments[0].id); } }, [segments, activeSegmentId]); const activeSegment = useMemo(() => { return segments.find(seg => seg.id === activeSegmentId) || null; }, [segments, activeSegmentId]); const activeSegmentDuration = useMemo(() => { if (!activeSegment) return null; const startSec = hmsToSeconds(activeSegment.start); const endSec = hmsToSeconds(activeSegment.end); return Math.max(0, endSec - startSec); }, [activeSegment]); const seekVideo = (delta: number) => { const v = videoRef.current; if (!v) return; v.currentTime = Math.max(0, Math.min(isFinite(v.duration) ? v.duration : Infinity, v.currentTime + delta)); }; const togglePlayback = () => { const v = videoRef.current; if (!v) return; if (v.paused) { void v.play(); setIsVideoPlaying(true); } else { v.pause(); setIsVideoPlaying(false); } }; const playActiveSegment = () => { const v = videoRef.current; if (!v || !activeSegment) return; const startSec = hmsToSeconds(activeSegment.start); const endSec = hmsToSeconds(activeSegment.end); v.currentTime = startSec; void v.play(); setIsVideoPlaying(true); const checkEnd = () => { if (v.currentTime >= endSec) { v.pause(); setIsVideoPlaying(false); v.removeEventListener('timeupdate', checkEnd); } }; v.addEventListener('timeupdate', checkEnd); }; const inheritCrop = () => { const ref = activeSegment ?? (segments.length > 0 ? segments[segments.length - 1] : null); return { cropEnabled: true, cropLeft: ref ? ref.cropLeft : 10, cropRight: ref ? ref.cropRight : 10, cropTop: ref ? ref.cropTop : 10, cropBottom: ref ? ref.cropBottom : 10, }; }; const addSegment = () => { if (!duration) return; const lastEnd = segments.length > 0 ? hmsToSeconds(segments[segments.length - 1].end) : 0; const startTime = Math.min(lastEnd, duration); const endTime = Math.min(startTime + 30, duration); const newSegment: AdvancedTrimCropSegment = { id: `seg_${Math.random().toString(16).slice(2)}_${Date.now()}`, start: secondsToHms(startTime), end: secondsToHms(endTime), ...inheritCrop(), }; setSegments(prev => [...prev, newSegment]); setActiveSegmentId(newSegment.id); }; const updateSegment = (id: string, updates: Partial) => { setSegments(prev => prev.map(seg => seg.id === id ? { ...seg, ...updates } : seg)); }; const removeSegment = (id: string) => { setSegments(prev => { const newSegments = prev.filter(seg => seg.id !== id); if (newSegments.length === 0) setActiveSegmentId(null); else if (activeSegmentId === id) setActiveSegmentId(newSegments[0].id); return newSegments; }); }; const moveSegment = (index: number, direction: -1 | 1) => { setSegments(prev => { const newSegments = [...prev]; const newIndex = index + direction; if (newIndex < 0 || newIndex >= newSegments.length) return prev; [newSegments[index], newSegments[newIndex]] = [newSegments[newIndex], newSegments[index]]; return newSegments; }); }; const handleSegmentClick = (segment: AdvancedTrimCropSegment) => { setActiveSegmentId(segment.id); const v = videoRef.current; if (v) { const startSec = hmsToSeconds(segment.start); v.currentTime = startSec; setPreviewCurrentTime(startSec); } }; const captureCurrentTimeAsStart = () => { const currentTime = Math.floor(videoRef.current?.currentTime || 0); setPreviewCurrentTime(currentTime); setPendingClipStart(currentTime); setError(null); }; const captureCurrentTimeAsEnd = () => { const currentTime = Math.floor(videoRef.current?.currentTime || 0); setPreviewCurrentTime(currentTime); if (pendingClipStart == null) { setError("Set clip start first."); return; } if (currentTime <= pendingClipStart) { setError("Clip end must be after clip start."); return; } const newSegment: AdvancedTrimCropSegment = { id: `seg_${Math.random().toString(16).slice(2)}_${Date.now()}`, start: secondsToHms(pendingClipStart), end: secondsToHms(currentTime), ...inheritCrop(), }; setSegments(prev => [...prev, newSegment]); setActiveSegmentId(newSegment.id); setPendingClipStart(null); setError(null); }; const validateSegments = (): string | null => { if (segments.length === 0) return "Please add at least one segment"; for (const segment of segments) { const startSec = hmsToSeconds(segment.start); const endSec = hmsToSeconds(segment.end); if (endSec <= startSec) return "Each segment must have end time after start time"; if (duration && endSec > duration) return "Segment exceeds video duration"; } return null; }; // Opens the in-modal encode settings panel const handleOpenEncodeSettings = () => { const validationError = validateSegments(); if (validationError) { setError(validationError); return; } setError(null); setShowEncodeSettings(true); }; // Submit encode & merge job from within the modal const handleTrimEncodeMerge = async () => { setBusy(true); setError(null); try { const response = await fetch("/api/trim-encode-merge", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ fileId: file.id, segments: segments.map(seg => ({ start: seg.start, end: seg.end, cropEnabled: seg.cropEnabled, cropLeft: seg.cropLeft, cropRight: seg.cropRight, cropTop: seg.cropTop, cropBottom: seg.cropBottom, })), encodeSettings: { codec: encodeSettings.codec, mode: encodeSettings.mode, crf: encodeSettings.crf, videoBitrateKbps: encodeSettings.videoBitrateKbps, audioBitrateKbps: encodeSettings.audioBitrateKbps, resolution: encodeSettings.resolution, sameAsOriginalAudio: encodeSettings.sameAsOriginalAudio, h26xPreset: encodeSettings.h26xPreset, av1Preset: encodeSettings.av1Preset, aqMode: encodeSettings.aqMode, tiles: encodeSettings.tiles, }, }), }); if (!response.ok) { const data = await response.json().catch(() => ({})); throw new Error((data as any).error || "Failed to start job"); } const result = await response.json(); if ((result as any).error) throw new Error((result as any).error); setEncodeJobStarted(true); onProcessingStarted(); } catch (err) { setError(err instanceof Error ? err.message : "Failed to start encode"); setBusy(false); } }; const applyPresetCrop = (preset: "center" | "lt" | "rt" | "up" | "low") => { if (!activeSegment) return; const presets = { center: { cropLeft: 10, cropRight: 10, cropTop: 10, cropBottom: 10 }, lt: { cropLeft: 20, cropRight: 10, cropTop: 10, cropBottom: 5 }, rt: { cropLeft: 10, cropRight: 20, cropTop: 10, cropBottom: 5 }, up: { cropLeft: 10, cropRight: 10, cropTop: 20, cropBottom: 5 }, low: { cropLeft: 10, cropRight: 10, cropTop: 5, cropBottom: 20 }, }; updateSegment(activeSegment.id, { cropEnabled: true, ...presets[preset] }); }; // Factory: start a crop drag of the given type (move / edge / corner) const startCropDrag = (type: DragType) => (event: React.PointerEvent) => { if (!activeSegment || !activeSegment.cropEnabled) return; event.preventDefault(); event.stopPropagation(); event.currentTarget.setPointerCapture(event.pointerId); setDragAnchor({ x: event.clientX, y: event.clientY, left: activeSegment.cropLeft, right: activeSegment.cropRight, top: activeSegment.cropTop, bottom: activeSegment.cropBottom, type, }); }; const handleCropPointerMove = (event: React.PointerEvent) => { if (!dragAnchor || !activeSegment) return; const container = videoContainerRef.current; if (!container) return; const rect = container.getBoundingClientRect(); const dx = ((event.clientX - dragAnchor.x) / rect.width) * 100; const dy = ((event.clientY - dragAnchor.y) / rect.height) * 100; const { type, left: aL, right: aR, top: aT, bottom: aB } = dragAnchor; let nL = aL, nR = aR, nT = aT, nB = aB; if (type === "move") { nL = Math.max(0, Math.min(90 - aR, aL + dx)); nR = Math.max(0, Math.min(90 - aL, aR - dx)); nT = Math.max(0, Math.min(90 - aB, aT + dy)); nB = Math.max(0, Math.min(90 - aT, aB - dy)); } if (type === "top" || type === "tl" || type === "tr") nT = Math.max(0, Math.min(90 - aB - 2, aT + dy)); if (type === "bottom" || type === "bl" || type === "br") nB = Math.max(0, Math.min(90 - aT - 2, aB - dy)); if (type === "left" || type === "tl" || type === "bl") nL = Math.max(0, Math.min(90 - aR - 2, aL + dx)); if (type === "right" || type === "tr" || type === "br") nR = Math.max(0, Math.min(90 - aL - 2, aR - dx)); updateSegment(activeSegment.id, { cropLeft: nL, cropRight: nR, cropTop: nT, cropBottom: nB }); }; const handleCropPointerUp = (event: React.PointerEvent) => { if (dragAnchor) { event.currentTarget.releasePointerCapture(event.pointerId); setDragAnchor(null); } }; const handleProcess = async () => { const validationError = validateSegments(); if (validationError) { setError(validationError); return; } setError(null); setBusy(true); try { const processingData = { fileId: file.id, segments: segments.map((seg, index) => ({ start: seg.start, end: seg.end, cropSettings: seg.cropEnabled ? { enabled: true, left: seg.cropLeft, right: seg.cropRight, top: seg.cropTop, bottom: seg.cropBottom } : null, outputFilename: generateSegmentFilename(file.name, index + 1, seg.start, seg.end), })), }; const response = await fetch("/api/trim-segments", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(processingData), }); if (!response.ok) { const errorData = await response.json().catch(() => ({})); throw new Error((errorData as any).error || "Failed to start processing"); } const result = await response.json(); if ((result as any).error) throw new Error((result as any).error); onProcessingStarted(); onClose(); } catch (err) { setError(err instanceof Error ? err.message : "Processing failed"); setBusy(false); } }; const generateSegmentFilename = (originalName: string, segmentNum: number, start: string, end: string) => { const ext = originalName.match(/(\.[^.]+)$/)?.[1] || ".mp4"; const base = originalName.replace(/(\.[^.]+)$/, ""); return `${base}_seg${segmentNum}_${start.replace(/:/g, "-")}_${end.replace(/:/g, "-")}${ext}`; }; const activeOutputSize = useMemo(() => { if (!activeSegment || !activeSegment.cropEnabled || !videoDimensions) return null; const width = Math.max(1, Math.round(videoDimensions.width * (1 - (activeSegment.cropLeft + activeSegment.cropRight) / 100))); const height = Math.max(1, Math.round(videoDimensions.height * (1 - (activeSegment.cropTop + activeSegment.cropBottom) / 100))); return { width, height }; }, [activeSegment, videoDimensions]); useEffect(() => { const onKeyDown = (e: KeyboardEvent) => { const tag = (e.target as HTMLElement).tagName; if (tag === "INPUT" || tag === "TEXTAREA") return; if (e.key === "ArrowLeft") { e.preventDefault(); seekVideo(-seekStep); } if (e.key === "ArrowRight") { e.preventDefault(); seekVideo(seekStep); } if (e.key === " " && e.target === document.body) { e.preventDefault(); togglePlayback(); } }; window.addEventListener("keydown", onKeyDown); return () => window.removeEventListener("keydown", onKeyDown); }, [seekStep]); if (loading) { return (

Loading video information...

); } // ── Helpers for encode settings panel ────────────────────────────────────── const isAV1 = encodeSettings.codec === "av1"; const isH26x = encodeSettings.codec === "h264" || encodeSettings.codec === "h265"; const isCRF = encodeSettings.mode === "crf-1pass"; const setEnc = (key: K, val: (typeof encodeSettings)[K]) => setEncodeSettings(prev => ({ ...prev, [key]: val })); // ── Encode-settings panel (renders in place of the main body) ───────────── const renderEncodeSettingsPanel = () => { if (encodeJobStarted) { return (
🎬

Encode & Merge started!

{segments.length} segment{segments.length !== 1 ? "s" : ""} queued. You can monitor progress in the Jobs panel.

); } return ( <> {/* Panel header */}

Encode & Merge Settings

{segments.length} segment{segments.length !== 1 ? "s" : ""} · {file.name}

{/* Settings body — scrollable */}
{/* Codec + Mode */}
{/* CRF slider or bitrate input */} {isCRF ? (
{encodeSettings.crf} ({encodeSettings.crf <= 20 ? "high quality" : encodeSettings.crf <= 35 ? "balanced" : "small file"})
setEnc("crf", Number(e.target.value))} className="w-full accent-violet-600" />
0 – lossless {isAV1 ? 63 : 51} – smallest
) : (
setEnc("videoBitrateKbps", Number(e.target.value))} className="w-full rounded-xl border border-slate-200 bg-white px-3 py-2 text-sm text-slate-800 focus:border-violet-400 focus:outline-none focus:ring-2 focus:ring-violet-200" />
)} {/* Resolution + Audio bitrate */}
setEnc("audioBitrateKbps", Number(e.target.value))} className="w-full rounded-xl border border-slate-200 bg-white px-3 py-2 text-sm text-slate-800 focus:border-violet-400 focus:outline-none focus:ring-2 focus:ring-violet-200 disabled:opacity-50 disabled:cursor-not-allowed" />
{/* Same as original audio toggle */} {/* H26x preset */} {isH26x && (
)} {/* AV1 options */} {isAV1 && (

AV1 Options

Preset (speed) {encodeSettings.av1Preset}
setEnc("av1Preset", Number(e.target.value))} className="w-full accent-violet-600" />
0 slowest12 fastest
)} {/* Segment summary */}

Segments to encode:

{segments.map((seg, i) => (
#{i + 1} {seg.start} → {seg.end} {seg.cropEnabled && ( Crop L{seg.cropLeft.toFixed(0)} R{seg.cropRight.toFixed(0)} T{seg.cropTop.toFixed(0)} B{seg.cropBottom.toFixed(0)} )}
))}
{error && (
{error}
)}
{/* Panel footer */}
); }; // ── Main modal ───────────────────────────────────────────────────────────── return (
e.stopPropagation()} > {/* ── Encode-settings panel ─────────────────────── */} {showEncodeSettings ? renderEncodeSettingsPanel() : ( <> {/* Header */}

Trim Segments & Set Crop

Create multiple trimmed clips with saved crop settings for later encoding

{/* Body */}
{/* Left Column */}
{activeSegment && (
Active Segment: {activeSegment.start} → {activeSegment.end} Duration: {activeSegmentDuration !== null ? secondsToHms(activeSegmentDuration) : '--:--:--'}
)}
{pendingClipStart != null && (
📍 Start set: {secondsToHms(pendingClipStart)}
)}
⌨️ Keyboard: ←Seek back →Seek forward SpacePlay/Pause
Video Timeline
{duration && segments.map(segment => { const startSec = hmsToSeconds(segment.start); const endSec = hmsToSeconds(segment.end); return (
handleSegmentClick(segment)} /> ); })} {duration && (
)}
00:00:00 {duration && {secondsToHms(Math.floor(duration))}}
{/* Right Column */}
Segments ({segments.length})
{segments.length === 0 ? (

No segments added yet

Use "Set Start" and "Set End" or click "Add Segment"

) : (
{segments.map((segment, index) => { const segmentDuration = Math.max(0, hmsToSeconds(segment.end) - hmsToSeconds(segment.start)); const isActive = segment.id === activeSegmentId; return (
handleSegmentClick(segment)} className={`rounded-xl border p-3 cursor-pointer transition-colors ${isActive ? "border-violet-300 bg-violet-50" : "border-slate-200 bg-white hover:bg-slate-50"}`} >
#{index + 1} {segment.start} → {segment.end} ({secondsToHms(segmentDuration)})
{segment.cropEnabled ? Crop: L{segment.cropLeft.toFixed(0)}% R{segment.cropRight.toFixed(0)}% T{segment.cropTop.toFixed(0)}% B{segment.cropBottom.toFixed(0)}% : No crop }
); })}
)}
{activeSegment && (
Crop Settings (saved for encoding)
{activeSegment.cropEnabled && (

💡 Crop settings will be applied when encoding

)}
{[ { key: "cropLeft", label: "Left", value: activeSegment.cropLeft }, { key: "cropRight", label: "Right", value: activeSegment.cropRight }, { key: "cropTop", label: "Top", value: activeSegment.cropTop }, { key: "cropBottom", label: "Bottom", value: activeSegment.cropBottom }, ].map(field => (
{field.label}{field.value.toFixed(0)}%
updateSegment(activeSegment.id, { [field.key]: Number(e.target.value) })} className="w-full accent-violet-600 disabled:cursor-not-allowed disabled:opacity-60" />
))}
{(["center","lt","rt","up","low"] as const).map(p => ( ))}
{activeOutputSize && (
Output: {activeOutputSize.width}×{activeOutputSize.height} Aspect: {formatAspectRatio(activeOutputSize.width, activeOutputSize.height)}
)}
)} {error && (
{error}
)}

💡 How it works:

1. Add segments with different time ranges

2. Set crop area for each segment (optional)

3. Trim only – fast stream copy, saves crop settings

4. Encode & Merge – re-encodes with crop, merges into one file

{/* Footer */}
)}
); }