Tele-v / src /components /AdvancedTrimCropModal.tsx
oga3oga's picture
update-from-mohaziz8890Replit
b859647 verified
Raw History Blame Contribute Delete
52.9 kB
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<HTMLDivElement>) => void; onPointerMove: (e: React.PointerEvent<HTMLDivElement>) => void; onPointerUp: (e: React.PointerEvent<HTMLDivElement>) => 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 ( <div className="absolute inset-0 pointer-events-none"> {/* Dim the area outside the crop box using 4 strips */} <div className="absolute inset-0 bg-black/40" /> {/* Crop box */} <div className="absolute z-10" style={{ top: `${seg.cropTop}%`, bottom: `${seg.cropBottom}%`, left: `${seg.cropLeft}%`, right: `${seg.cropRight}%`, }} > {/* Clear the dim inside the crop box */} <div className="absolute inset-0 bg-transparent mix-blend-normal" /> {/* Visible border frame */} <div className="absolute inset-0 rounded-sm border-2 border-white/90 pointer-events-none shadow-[inset_0_0_0_1px_rgba(0,0,0,0.4)]" /> {/* Rule-of-thirds grid lines */} <div className="absolute inset-0 pointer-events-none"> <div className="absolute top-1/3 left-0 right-0 h-px bg-white/25" /> <div className="absolute top-2/3 left-0 right-0 h-px bg-white/25" /> <div className="absolute left-1/3 top-0 bottom-0 w-px bg-white/25" /> <div className="absolute left-2/3 top-0 bottom-0 w-px bg-white/25" /> </div> {/* ── Center drag-to-move zone ── */} <div {...handleProps("move", dragType === "move" ? "grabbing" : "grab", "absolute inset-5 flex items-center justify-center")} > <div className="bg-black/30 rounded-lg px-2.5 py-1 text-[10px] text-white font-semibold backdrop-blur-sm select-none pointer-events-none"> βœ₯ move </div> </div> {/* ── Edge handles (full-width/height transparent strips + visible pill) ── */} {/* Top */} <div {...handleProps("top", "n-resize", "absolute -top-2 left-6 right-6 h-5 flex items-center justify-center")}> <div className="w-10 h-2 rounded-full bg-white shadow-md border border-white/60" /> </div> {/* Bottom */} <div {...handleProps("bottom", "s-resize", "absolute -bottom-2 left-6 right-6 h-5 flex items-center justify-center")}> <div className="w-10 h-2 rounded-full bg-white shadow-md border border-white/60" /> </div> {/* Left */} <div {...handleProps("left", "w-resize", "absolute -left-2 top-6 bottom-6 w-5 flex items-center justify-center")}> <div className="h-10 w-2 rounded-full bg-white shadow-md border border-white/60" /> </div> {/* Right */} <div {...handleProps("right", "e-resize", "absolute -right-2 top-6 bottom-6 w-5 flex items-center justify-center")}> <div className="h-10 w-2 rounded-full bg-white shadow-md border border-white/60" /> </div> {/* ── Corner handles ── */} {/* TL */} <div {...handleProps("tl", "nw-resize", "absolute -top-2 -left-2 w-6 h-6 flex items-end justify-end")}> <div className="w-4 h-4 rounded-sm bg-white border-2 border-slate-400 shadow-lg" /> </div> {/* TR */} <div {...handleProps("tr", "ne-resize", "absolute -top-2 -right-2 w-6 h-6 flex items-end justify-start")}> <div className="w-4 h-4 rounded-sm bg-white border-2 border-slate-400 shadow-lg" /> </div> {/* BL */} <div {...handleProps("bl", "sw-resize", "absolute -bottom-2 -left-2 w-6 h-6 flex items-start justify-end")}> <div className="w-4 h-4 rounded-sm bg-white border-2 border-slate-400 shadow-lg" /> </div> {/* BR */} <div {...handleProps("br", "se-resize", "absolute -bottom-2 -right-2 w-6 h-6 flex items-start justify-start")}> <div className="w-4 h-4 rounded-sm bg-white border-2 border-slate-400 shadow-lg" /> </div> </div> </div> ); } export function AdvancedTrimCropModal({ file, onClose, onProcessingStarted }: AdvancedTrimCropModalProps) { const [duration, setDuration] = useState<number | null>(null); const [segments, setSegments] = useState<AdvancedTrimCropSegment[]>(() => { 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<string | null>(null); const [loading, setLoading] = useState(true); const [busy, setBusy] = useState(false); const [error, setError] = useState<string | null>(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<number | null>(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<HTMLVideoElement>(null); const videoContainerRef = useRef<HTMLDivElement>(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<AdvancedTrimCropSegment>) => { 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<HTMLDivElement>) => { 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<HTMLDivElement>) => { 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<HTMLDivElement>) => { 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 ( <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/40 backdrop-blur-sm"> <div className="bg-white rounded-2xl shadow-2xl w-full max-w-lg p-6 text-center"> <div className="animate-spin h-8 w-8 mx-auto mb-4 text-violet-500" /> <p className="text-sm text-slate-600">Loading video information...</p> </div> </div> ); } // ── 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 = <K extends keyof typeof encodeSettings>(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 ( <div className="flex flex-col items-center justify-center flex-1 gap-5 p-8 text-center"> <div className="flex h-16 w-16 items-center justify-center rounded-full bg-emerald-100 text-4xl">🎬</div> <div> <p className="text-lg font-bold text-slate-900">Encode &amp; Merge started!</p> <p className="mt-1 text-sm text-slate-500"> {segments.length} segment{segments.length !== 1 ? "s" : ""} queued. You can monitor progress in the Jobs panel. </p> </div> <button onClick={onClose} className="rounded-xl bg-violet-600 px-6 py-2.5 text-sm font-bold text-white hover:bg-violet-700" > Close </button> </div> ); } return ( <> {/* Panel header */} <div className="flex-shrink-0 flex items-center gap-3 border-b border-slate-200 px-6 py-4"> <button onClick={() => { setShowEncodeSettings(false); setError(null); }} className="flex items-center gap-1.5 rounded-lg px-2.5 py-1.5 text-xs font-semibold text-slate-500 hover:bg-slate-100 hover:text-slate-700 transition-colors" > ← Back </button> <div className="flex-1"> <h3 className="text-base font-bold text-slate-900">Encode &amp; Merge Settings</h3> <p className="text-[11px] text-slate-400">{segments.length} segment{segments.length !== 1 ? "s" : ""} Β· {file.name}</p> </div> </div> {/* Settings body β€” scrollable */} <div className="flex-1 overflow-y-auto min-h-0 p-5 space-y-4"> {/* Codec + Mode */} <div className="grid grid-cols-2 gap-3"> <div className="space-y-1"> <label className="block text-[11px] font-semibold uppercase tracking-wide text-slate-500">Video Codec</label> <select value={encodeSettings.codec} onChange={e => setEnc("codec", e.target.value as "h264" | "h265" | "av1")} 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" > <option value="av1">AV1 (best compression)</option> <option value="h264">H.264 (fastest)</option> <option value="h265">H.265 / HEVC</option> </select> </div> <div className="space-y-1"> <label className="block text-[11px] font-semibold uppercase tracking-wide text-slate-500">Rate Mode</label> <select value={encodeSettings.mode} onChange={e => setEnc("mode", e.target.value as "crf-1pass" | "vbr")} 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" > <option value="crf-1pass">CRF (quality-based)</option> <option value="vbr">VBR (target bitrate)</option> </select> </div> </div> {/* CRF slider or bitrate input */} {isCRF ? ( <div className="space-y-1.5"> <div className="flex items-center justify-between"> <label className="text-[11px] font-semibold uppercase tracking-wide text-slate-500"> CRF β€” Quality </label> <span className="rounded-full bg-violet-100 px-2 py-0.5 text-xs font-bold text-violet-700"> {encodeSettings.crf} <span className="ml-1 text-[10px] font-normal text-violet-500"> ({encodeSettings.crf <= 20 ? "high quality" : encodeSettings.crf <= 35 ? "balanced" : "small file"}) </span> </span> </div> <input type="range" min={isAV1 ? 0 : 0} max={isAV1 ? 63 : 51} step={1} value={encodeSettings.crf} onChange={e => setEnc("crf", Number(e.target.value))} className="w-full accent-violet-600" /> <div className="flex justify-between text-[10px] text-slate-400"> <span>0 – lossless</span> <span>{isAV1 ? 63 : 51} – smallest</span> </div> </div> ) : ( <div className="space-y-1"> <label className="block text-[11px] font-semibold uppercase tracking-wide text-slate-500"> Video Bitrate (kbps) </label> <input type="number" min={100} max={50000} step={100} value={encodeSettings.videoBitrateKbps} onChange={e => 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" /> </div> )} {/* Resolution + Audio bitrate */} <div className="grid grid-cols-2 gap-3"> <div className="space-y-1"> <label className="block text-[11px] font-semibold uppercase tracking-wide text-slate-500">Resolution</label> <select value={encodeSettings.resolution} onChange={e => setEnc("resolution", 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" > <option value="original">Original</option> <option value="1080p">1080p</option> <option value="720p">720p</option> <option value="480p">480p</option> </select> </div> <div className="space-y-1"> <label className="block text-[11px] font-semibold uppercase tracking-wide text-slate-500"> Audio Bitrate (kbps) </label> <input type="number" min={32} max={320} step={8} disabled={encodeSettings.sameAsOriginalAudio} value={encodeSettings.audioBitrateKbps} onChange={e => 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" /> </div> </div> {/* Same as original audio toggle */} <label className="flex cursor-pointer items-center gap-3 rounded-xl border border-slate-200 bg-slate-50 px-4 py-2.5 hover:bg-slate-100 transition-colors"> <input type="checkbox" checked={encodeSettings.sameAsOriginalAudio} onChange={e => setEnc("sameAsOriginalAudio", e.target.checked)} className="h-4 w-4 rounded border-slate-300 text-violet-600 focus:ring-violet-500" /> <span className="text-sm font-semibold text-slate-700">Copy original audio (no re-encode)</span> </label> {/* H26x preset */} {isH26x && ( <div className="space-y-1"> <label className="block text-[11px] font-semibold uppercase tracking-wide text-slate-500">H26x Preset</label> <select value={encodeSettings.h26xPreset} onChange={e => setEnc("h26xPreset", 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" > {["ultrafast","superfast","veryfast","faster","fast","medium","slow","slower","veryslow"].map(p => ( <option key={p} value={p}>{p}</option> ))} </select> </div> )} {/* AV1 options */} {isAV1 && ( <div className="space-y-3 rounded-xl border border-slate-200 bg-slate-50 p-3"> <p className="text-[11px] font-semibold uppercase tracking-wide text-slate-500">AV1 Options</p> <div className="grid grid-cols-2 gap-3"> <div className="space-y-1"> <div className="flex items-center justify-between text-[11px]"> <span className="font-semibold text-slate-600">Preset (speed)</span> <span className="font-bold text-violet-700">{encodeSettings.av1Preset}</span> </div> <input type="range" min={0} max={12} step={1} value={encodeSettings.av1Preset} onChange={e => setEnc("av1Preset", Number(e.target.value))} className="w-full accent-violet-600" /> <div className="flex justify-between text-[10px] text-slate-400"> <span>0 slowest</span><span>12 fastest</span> </div> </div> <div className="space-y-1"> <label className="block text-[11px] font-semibold text-slate-600">AQ Mode</label> <select value={encodeSettings.aqMode} onChange={e => setEnc("aqMode", Number(e.target.value))} className="w-full rounded-xl border border-slate-200 bg-white px-3 py-2 text-xs text-slate-800 focus:border-violet-400 focus:outline-none" > <option value={0}>0 – Off</option> <option value={1}>1 – Variance</option> <option value={2}>2 – Complexity</option> </select> </div> </div> <div className="space-y-1"> <label className="block text-[11px] font-semibold text-slate-600">Tile Columns Γ— Rows</label> <select value={encodeSettings.tiles} onChange={e => setEnc("tiles", e.target.value)} className="w-full rounded-xl border border-slate-200 bg-white px-3 py-2 text-xs text-slate-800 focus:border-violet-400 focus:outline-none" > <option value="0">0 – off</option> <option value="1x1">1Γ—1</option> <option value="2x2">2Γ—2</option> <option value="4x2">4Γ—2</option> <option value="4x4">4Γ—4</option> </select> </div> </div> )} {/* Segment summary */} <div className="rounded-xl border border-violet-100 bg-violet-50 px-4 py-3 text-xs text-violet-800 space-y-1"> <p className="font-semibold text-violet-900">Segments to encode:</p> {segments.map((seg, i) => ( <div key={seg.id} className="flex items-center gap-2"> <span className="font-mono font-bold">#{i + 1}</span> <span>{seg.start} β†’ {seg.end}</span> {seg.cropEnabled && ( <span className="rounded-full bg-violet-200 px-2 py-0.5 text-[10px] font-semibold text-violet-700"> Crop L{seg.cropLeft.toFixed(0)} R{seg.cropRight.toFixed(0)} T{seg.cropTop.toFixed(0)} B{seg.cropBottom.toFixed(0)} </span> )} </div> ))} </div> {error && ( <div className="rounded-xl bg-red-50 border border-red-100 px-4 py-3 text-xs font-semibold text-red-600"> {error} </div> )} </div> {/* Panel footer */} <div className="flex-shrink-0 border-t border-slate-200 bg-slate-50 px-5 py-4"> <button onClick={handleTrimEncodeMerge} disabled={busy} className="w-full rounded-xl bg-violet-600 py-3 text-sm font-bold text-white transition-colors hover:bg-violet-700 disabled:cursor-not-allowed disabled:opacity-50 flex items-center justify-center gap-2" > {busy ? <><span className="h-4 w-4 animate-spin rounded-full border-2 border-white/30 border-t-white inline-block" /> Starting…</> : "🎬 Start Encode & Merge"} </button> </div> </> ); }; // ── Main modal ───────────────────────────────────────────────────────────── return ( <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/45 p-4 backdrop-blur-sm" onClick={onClose}> <div className="w-full max-w-4xl max-h-[90vh] flex flex-col overflow-hidden rounded-3xl bg-white shadow-2xl" onClick={e => e.stopPropagation()} > {/* ── Encode-settings panel ─────────────────────── */} {showEncodeSettings ? renderEncodeSettingsPanel() : ( <> {/* Header */} <div className="flex-shrink-0 flex items-center justify-between border-b border-slate-200 px-6 py-4"> <div> <h2 className="text-lg font-bold text-slate-900">Trim Segments &amp; Set Crop</h2> <p className="text-xs text-slate-500">Create multiple trimmed clips with saved crop settings for later encoding</p> </div> <button onClick={onClose} className="rounded-lg p-1.5 text-slate-400 hover:bg-slate-100 hover:text-slate-600 transition-colors"> <svg className="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}> <path strokeLinecap="round" strokeLinejoin="round" d="M6 18 18 6M6 6l12 12" /> </svg> </button> </div> {/* Body */} <div className="grid gap-6 p-6 lg:grid-cols-[1.3fr_0.7fr] flex-1 overflow-y-auto min-h-0"> {/* Left Column */} <div className="space-y-4"> <div ref={videoContainerRef} className="relative overflow-hidden rounded-2xl border border-slate-200 bg-slate-950"> <video ref={videoRef} src={`/api/files/${encodeURIComponent(file.id)}/stream`} controls playsInline className="w-full rounded-2xl bg-black" onPlay={() => setIsVideoPlaying(true)} onPause={() => setIsVideoPlaying(false)} onEnded={() => setIsVideoPlaying(false)} onTimeUpdate={() => setPreviewCurrentTime(Math.floor(videoRef.current?.currentTime || 0))} onLoadedMetadata={() => { const video = videoRef.current; if (video) setVideoDimensions({ width: video.videoWidth || 0, height: video.videoHeight || 0 }); }} /> {activeSegment && activeSegment.cropEnabled && videoDimensions && ( <CropOverlay seg={activeSegment} dragType={dragAnchor?.type ?? null} startCropDrag={startCropDrag} onPointerMove={handleCropPointerMove} onPointerUp={handleCropPointerUp} /> )} </div> {activeSegment && ( <div className="rounded-xl border border-violet-200 bg-violet-50 p-3"> <div className="flex items-center justify-between"> <div className="flex items-center gap-3"> <span className="text-xs font-semibold text-violet-700">Active Segment:</span> <span className="text-sm font-bold text-violet-900">{activeSegment.start} β†’ {activeSegment.end}</span> <span className="rounded-full bg-violet-200 px-2 py-0.5 text-[10px] font-semibold text-violet-700"> Duration: {activeSegmentDuration !== null ? secondsToHms(activeSegmentDuration) : '--:--:--'} </span> </div> <button onClick={playActiveSegment} className="rounded-full bg-violet-600 px-3 py-1 text-xs font-semibold text-white hover:bg-violet-700">β–Ά Play Segment</button> </div> </div> )} <div className="flex flex-wrap items-center gap-2"> <button onClick={togglePlayback} className="rounded-full bg-slate-900 px-3 py-1.5 text-sm font-semibold text-white hover:bg-slate-700"> {isVideoPlaying ? "Pause" : "Play"} </button> <button onClick={() => seekVideo(-seekStep)} className="rounded-full bg-slate-100 px-3 py-1.5 text-sm font-semibold text-slate-700 hover:bg-slate-200" title="Left Arrow key"> ← βˆ’{seekStep}s </button> <button onClick={() => seekVideo(seekStep)} className="rounded-full bg-slate-100 px-3 py-1.5 text-sm font-semibold text-slate-700 hover:bg-slate-200" title="Right Arrow key"> +{seekStep}s β†’ </button> <label className="flex items-center gap-1.5 text-xs text-slate-500"> Step: <input type="number" min={1} max={600} value={seekStep} onChange={e => setSeekStep(Math.max(1, parseInt(e.target.value) || 6))} className="w-14 rounded-lg border border-slate-200 bg-white px-2 py-1 text-xs text-center" /> s </label> <button onClick={captureCurrentTimeAsStart} className={`rounded-full px-3 py-1.5 text-sm font-semibold text-white ${pendingClipStart != null ? "bg-amber-500 hover:bg-amber-600" : "bg-violet-600 hover:bg-violet-700"}`} > {pendingClipStart != null ? `Start: ${secondsToHms(pendingClipStart)}` : "Set Start"} </button> <button onClick={captureCurrentTimeAsEnd} className="rounded-full px-3 py-1.5 text-sm font-semibold text-white bg-emerald-600 hover:bg-emerald-700"> Set End </button> </div> {pendingClipStart != null && ( <div className="flex items-center gap-2 rounded-xl border border-amber-200 bg-amber-50 px-3 py-2 text-xs font-semibold text-amber-800"> <span>πŸ“ Start set:</span> <span className="rounded bg-amber-100 px-2 py-0.5 font-mono">{secondsToHms(pendingClipStart)}</span> <button onClick={() => setPendingClipStart(null)} className="ml-auto rounded-full border border-amber-200 px-2 py-0.5 text-amber-600 hover:bg-amber-100">Cancel</button> </div> )} <div className="text-[10px] text-slate-400 flex items-center gap-3"> <span>⌨️ Keyboard:</span> <span className="rounded bg-slate-100 px-1.5 py-0.5">←</span><span>Seek back</span> <span className="rounded bg-slate-100 px-1.5 py-0.5">β†’</span><span>Seek forward</span> <span className="rounded bg-slate-100 px-1.5 py-0.5">Space</span><span>Play/Pause</span> </div> <div className="rounded-2xl border border-slate-200 bg-slate-50 p-3"> <div className="text-xs font-semibold text-slate-700 mb-2">Video Timeline</div> <div className="relative h-8 rounded-full bg-slate-200 overflow-hidden"> {duration && segments.map(segment => { const startSec = hmsToSeconds(segment.start); const endSec = hmsToSeconds(segment.end); return ( <div key={segment.id} className={`absolute h-full cursor-pointer transition-colors ${segment.id === activeSegmentId ? 'bg-violet-500 hover:bg-violet-600' : 'bg-blue-500 hover:bg-blue-600'}`} style={{ left: `${(startSec / duration) * 100}%`, width: `${((endSec - startSec) / duration) * 100}%` }} title={`${segment.start} - ${segment.end}`} onClick={() => handleSegmentClick(segment)} /> ); })} {duration && ( <div className="absolute h-full w-0.5 bg-red-500" style={{ left: `${(previewCurrentTime / duration) * 100}%` }} /> )} </div> <div className="flex justify-between text-[10px] text-slate-500 mt-1"> <span>00:00:00</span> {duration && <span>{secondsToHms(Math.floor(duration))}</span>} </div> </div> </div> {/* Right Column */} <div className="space-y-4"> <div className="space-y-2"> <div className="flex items-center justify-between"> <span className="text-xs font-semibold uppercase text-slate-500">Segments ({segments.length})</span> <button onClick={addSegment} className="rounded-full bg-violet-600 px-3 py-1 text-xs font-semibold text-white hover:bg-violet-700">+ Add Segment</button> </div> {segments.length === 0 ? ( <div className="rounded-xl border border-slate-200 bg-white p-4 text-center"> <p className="text-xs text-slate-400">No segments added yet</p> <p className="text-xs text-slate-300 mt-1">Use "Set Start" and "Set End" or click "Add Segment"</p> </div> ) : ( <div className="space-y-2 max-h-64 overflow-y-auto"> {segments.map((segment, index) => { const segmentDuration = Math.max(0, hmsToSeconds(segment.end) - hmsToSeconds(segment.start)); const isActive = segment.id === activeSegmentId; return ( <div key={segment.id} onClick={() => 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"}`} > <div className="flex items-start justify-between gap-2"> <div className="flex-1 min-w-0"> <div className="flex items-center gap-2"> <span className="rounded-full bg-slate-200 px-1.5 py-0.5 text-[10px] font-bold text-slate-600">#{index + 1}</span> <span className="text-xs font-semibold text-slate-700">{segment.start} β†’ {segment.end}</span> <span className="text-xs text-slate-400">({secondsToHms(segmentDuration)})</span> </div> <div className="flex items-center gap-2 mt-1"> {segment.cropEnabled ? <span className="rounded-full bg-violet-100 px-2 py-0.5 text-[10px] font-semibold text-violet-700">Crop: L{segment.cropLeft.toFixed(0)}% R{segment.cropRight.toFixed(0)}% T{segment.cropTop.toFixed(0)}% B{segment.cropBottom.toFixed(0)}%</span> : <span className="text-[10px] text-slate-400">No crop</span> } </div> </div> <div className="flex items-center gap-1 flex-shrink-0"> <button onClick={e => { e.stopPropagation(); moveSegment(index, -1); }} disabled={index === 0} className="rounded p-1 text-slate-400 hover:text-slate-600 disabled:opacity-30" title="Move up">↑</button> <button onClick={e => { e.stopPropagation(); moveSegment(index, 1); }} disabled={index === segments.length - 1} className="rounded p-1 text-slate-400 hover:text-slate-600 disabled:opacity-30" title="Move down">↓</button> <button onClick={e => { e.stopPropagation(); removeSegment(segment.id); }} className="rounded p-1 text-red-400 hover:text-red-600" title="Remove">βœ•</button> </div> </div> </div> ); })} </div> )} </div> {activeSegment && ( <div className="space-y-3 rounded-2xl border border-slate-200 bg-white p-3"> <div className="flex items-center justify-between"> <span className="text-xs font-semibold text-slate-700">Crop Settings (saved for encoding)</span> <label className="flex items-center gap-2"> <span className="text-xs text-slate-500">Enable</span> <input type="checkbox" checked={activeSegment.cropEnabled} onChange={e => updateSegment(activeSegment.id, { cropEnabled: e.target.checked })} className="h-4 w-4 rounded border-slate-300 text-violet-600 focus:ring-violet-500" /> </label> </div> {activeSegment.cropEnabled && ( <p className="text-[10px] text-violet-600 bg-violet-50 rounded-lg px-2 py-1"> πŸ’‘ Crop settings will be applied when encoding </p> )} <div className="grid grid-cols-2 gap-3"> {[ { 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 => ( <div key={field.key} className="space-y-1.5"> <div className="flex items-center justify-between text-xs font-semibold uppercase tracking-wider text-slate-500"> <span>{field.label}</span><span>{field.value.toFixed(0)}%</span> </div> <input type="range" min={0} max={45} step={1} value={field.value} disabled={!activeSegment.cropEnabled} onChange={e => updateSegment(activeSegment.id, { [field.key]: Number(e.target.value) })} className="w-full accent-violet-600 disabled:cursor-not-allowed disabled:opacity-60" /> </div> ))} </div> <div className="flex flex-wrap gap-2 pt-2"> {(["center","lt","rt","up","low"] as const).map(p => ( <button key={p} onClick={() => applyPresetCrop(p)} className="rounded-full border border-slate-200 bg-slate-50 px-2.5 py-1 text-[11px] font-semibold text-slate-700 hover:bg-slate-100 uppercase"> {p} </button> ))} </div> {activeOutputSize && ( <div className="mt-3 rounded-lg bg-slate-50 p-2 text-xs text-slate-600"> <div className="flex gap-2"> <span className="font-semibold">Output:</span> <span>{activeOutputSize.width}Γ—{activeOutputSize.height}</span> <span>Aspect: {formatAspectRatio(activeOutputSize.width, activeOutputSize.height)}</span> </div> </div> )} </div> )} {error && ( <div className="rounded-lg bg-red-50 p-3 text-xs text-red-600">{error}</div> )} <div className="rounded-lg bg-slate-50 p-3 text-xs text-slate-500"> <p className="font-semibold text-slate-700">πŸ’‘ How it works:</p> <p className="mt-1">1. Add segments with different time ranges</p> <p>2. Set crop area for each segment (optional)</p> <p>3. <strong>Trim only</strong> – fast stream copy, saves crop settings</p> <p>4. <strong>Encode &amp; Merge</strong> – re-encodes with crop, merges into one file</p> </div> </div> </div> {/* Footer */} <div className="border-t border-slate-200 bg-slate-50 flex-shrink-0"> <div className="p-4 space-y-2"> <button onClick={handleOpenEncodeSettings} disabled={busy || segments.length === 0} className="w-full rounded-xl bg-violet-600 py-3 text-sm font-bold text-white transition-colors hover:bg-violet-700 disabled:opacity-50 disabled:cursor-not-allowed" > 🎬 Encode &amp; Merge… (choose settings) </button> <button onClick={handleProcess} disabled={busy || segments.length === 0} className="w-full rounded-xl border border-slate-200 bg-white py-2 text-sm font-semibold text-slate-600 transition-colors hover:bg-slate-50 disabled:opacity-50 disabled:cursor-not-allowed" > {busy ? "Processing…" : "βœ‚οΈ Just Trim (fast copy, saves crop settings separately)"} </button> </div> </div> </> )} </div> </div> ); }
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<HTMLDivElement>) => void;
onPointerMove: (e: React.PointerEvent<HTMLDivElement>) => void;
onPointerUp: (e: React.PointerEvent<HTMLDivElement>) => 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 (
<div className="absolute inset-0 pointer-events-none">
{/* Dim the area outside the crop box using 4 strips */}
<div className="absolute inset-0 bg-black/40" />
{/* Crop box */}
<div
className="absolute z-10"
style={{
top: `${seg.cropTop}%`,
bottom: `${seg.cropBottom}%`,
left: `${seg.cropLeft}%`,
right: `${seg.cropRight}%`,
}}
>
{/* Clear the dim inside the crop box */}
<div className="absolute inset-0 bg-transparent mix-blend-normal" />
{/* Visible border frame */}
<div className="absolute inset-0 rounded-sm border-2 border-white/90 pointer-events-none shadow-[inset_0_0_0_1px_rgba(0,0,0,0.4)]" />
{/* Rule-of-thirds grid lines */}
<div className="absolute inset-0 pointer-events-none">
<div className="absolute top-1/3 left-0 right-0 h-px bg-white/25" />
<div className="absolute top-2/3 left-0 right-0 h-px bg-white/25" />
<div className="absolute left-1/3 top-0 bottom-0 w-px bg-white/25" />
<div className="absolute left-2/3 top-0 bottom-0 w-px bg-white/25" />
</div>
{/* ── Center drag-to-move zone ── */}
<div
{...handleProps("move", dragType === "move" ? "grabbing" : "grab",
"absolute inset-5 flex items-center justify-center")}
>
<div className="bg-black/30 rounded-lg px-2.5 py-1 text-[10px] text-white font-semibold backdrop-blur-sm select-none pointer-events-none">
βœ₯ move
</div>
</div>
{/* ── Edge handles (full-width/height transparent strips + visible pill) ── */}
{/* Top */}
<div {...handleProps("top", "n-resize", "absolute -top-2 left-6 right-6 h-5 flex items-center justify-center")}>
<div className="w-10 h-2 rounded-full bg-white shadow-md border border-white/60" />
</div>
{/* Bottom */}
<div {...handleProps("bottom", "s-resize", "absolute -bottom-2 left-6 right-6 h-5 flex items-center justify-center")}>
<div className="w-10 h-2 rounded-full bg-white shadow-md border border-white/60" />
</div>
{/* Left */}
<div {...handleProps("left", "w-resize", "absolute -left-2 top-6 bottom-6 w-5 flex items-center justify-center")}>