import React, { useState, useEffect, useCallback, useRef } from 'react'; import { X, Loader2, Crosshair, RotateCcw, AlertCircle, Play, Pause, Columns2 } from 'lucide-react'; import { getApiUrl } from '../config'; import { apiJson } from '../lib/api'; // Manual reframing: the automatic crop is right most of the time and grossly // wrong occasionally, and until now there was no way to say "frame it here". // // The unit is the scene, because a podcast cuts between a fixed close camera // and a fixed wide one and the right crop differs per camera. Scenes the user // does not touch stay automatic, so fixing one bad shot cannot spoil the good // ones — only adjusted scenes are sent. // // Two things a still frame cannot tell you, and both are handled here: // - WHO is talking. Each scene plays its own range of an uncropped preview, // with sound, and the rectangle stays overlaid while it plays. // - Whether one window is even enough. A scene can be split into two stacked // regions, positioned independently. const fmt = (s) => { const m = Math.floor(s / 60); const r = Math.floor(s % 60); return `${m}:${String(r).padStart(2, '0')}`; }; export default function ReframeEditor({ jobId, clipIndex, clipTitle, onClose, onReframed }) { const [loading, setLoading] = useState(true); const [error, setError] = useState(null); const [data, setData] = useState(null); const [overrides, setOverrides] = useState({}); // idx -> number | {top,bottom} const [playing, setPlaying] = useState(null); // scene index being played const [saving, setSaving] = useState(false); useEffect(() => { let alive = true; (async () => { try { const res = await apiJson(`/api/clip/${jobId}/${clipIndex}/scenes`); if (!alive) return; setData(res); // Start from what is already applied. A re-render rebuilds // from source with only what it receives, so opening blank // would quietly discard every earlier adjustment on the next // save. const salvos = res.saved_overrides || {}; setOverrides(Object.fromEntries( Object.entries(salvos).map(([k, v]) => [Number(k), v]) )); } catch (e) { if (alive) setError(e?.message || 'Could not read the scenes of this clip.'); } finally { if (alive) setLoading(false); } })(); return () => { alive = false; }; }, [jobId, clipIndex]); const half = (data?.crop_width_fraction ?? 0.5) / 2; const clamp = useCallback((v) => Math.min(1 - half, Math.max(half, v)), [half]); // What a scene shows right now: the user's value, else the backend's // suggestion (the biggest face in the shot). const valueOf = useCallback((scene) => ( overrides[scene.index] ?? clamp(scene.suggested_center) ), [overrides, clamp]); const setSingle = useCallback((idx, fraction) => { setOverrides((o) => ({ ...o, [idx]: clamp(fraction) })); }, [clamp]); const setSplitHalf = useCallback((idx, which, fraction) => { setOverrides((o) => { const cur = o[idx]; const base = (cur && typeof cur === 'object') ? cur : { top: { x: clamp(0.3), y: 0.5 }, bottom: { x: clamp(0.7), y: 0.5 } }; const anterior = base[which] || { y: 0.5 }; return { ...o, [idx]: { ...base, [which]: { x: clamp(fraction), y: anterior.y ?? 0.5 }, } }; }); }, [clamp]); const toggleSplit = useCallback((idx, scene) => { setOverrides((o) => { const cur = o[idx]; if (cur && typeof cur === 'object') { // back to a single window, kept where the top half was return { ...o, [idx]: cur.top?.x ?? 0.5 }; } const centre = typeof cur === 'number' ? cur : clamp(scene.suggested_center); // SPLIT halves crop vertically as well, so each carries the face // height the backend measured for this scene. const y = scene.suggested_center_y ?? 0.5; return { ...o, [idx]: { top: { x: clamp(centre - 0.2), y }, bottom: { x: clamp(centre + 0.2), y }, } }; }); }, [clamp]); const resetScene = useCallback((idx) => { setOverrides((o) => { const next = { ...o }; delete next[idx]; return next; }); }, []); const adjusted = Object.keys(overrides).length; const handleSave = async () => { if (!adjusted || saving) return; setSaving(true); setError(null); try { const payload = Object.fromEntries(Object.entries(overrides).map(([k, v]) => [ String(k), typeof v === 'object' ? { top: { x: Number(v.top.x.toFixed(4)), y: Number(v.top.y.toFixed(4)) }, bottom: { x: Number(v.bottom.x.toFixed(4)), y: Number(v.bottom.y.toFixed(4)) } } : Number(v.toFixed(4)), ])); const res = await apiJson('/api/clip/reframe', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ job_id: jobId, clip_index: clipIndex, crop_overrides: payload }), }); if (onReframed) onReframed(clipIndex, res); onClose(); } catch (e) { setError(e?.message || 'The re-render failed.'); } finally { setSaving(false); } }; return (

reframing

{clipTitle &&

{clipTitle}

}

Play a scene to hear who is talking, then drag the rectangle over the person you want. Each scene is one camera. Scenes you leave alone keep the automatic camera.

{loading && (
reading the scenes…
)} {error && (
{error}
)} {data?.scenes?.map((scene) => ( setPlaying((p) => (p === scene.index ? null : scene.index))} onMoveSingle={(f) => setSingle(scene.index, f)} onMoveHalf={(which, f) => setSplitHalf(scene.index, which, f)} onToggleSplit={() => toggleSplit(scene.index, scene)} onReset={() => resetScene(scene.index)} /> ))}
{adjusted === 0 ? 'nothing adjusted yet' : `${adjusted} scene${adjusted > 1 ? 's' : ''} reframed by hand`}
); } // One scene. While it plays, the frame is replaced by the uncropped preview // seeked to this scene, so the rectangle can be judged against moving pictures // and sound rather than a single still. function SceneRow({ scene, value, widthFraction, previewUrl, touched, playing, onPlayToggle, onMoveSingle, onMoveHalf, onToggleSplit, onReset }) { const boxRef = useRef(null); const videoRef = useRef(null); const [dragging, setDragging] = useState(null); // null | 'single' | 'top' | 'bottom' const isSplit = value && typeof value === 'object'; // Play only this scene's slice of the shared preview. useEffect(() => { const v = videoRef.current; if (!v) return; if (!playing) { v.pause(); return; } v.currentTime = scene.start; v.play().catch(() => {}); const stopAtEnd = () => { if (v.currentTime >= scene.end) { v.pause(); } }; v.addEventListener('timeupdate', stopAtEnd); return () => v.removeEventListener('timeupdate', stopAtEnd); }, [playing, scene.start, scene.end]); const fractionFromEvent = useCallback((clientX) => { const el = boxRef.current; if (!el) return 0.5; const rect = el.getBoundingClientRect(); return (clientX - rect.left) / rect.width; }, []); useEffect(() => { if (!dragging) return; const move = (e) => { const x = e.touches ? e.touches[0].clientX : e.clientX; const f = fractionFromEvent(x); if (dragging === 'single') onMoveSingle(f); else onMoveHalf(dragging, f); }; const up = () => setDragging(null); window.addEventListener('mousemove', move); window.addEventListener('mouseup', up); window.addEventListener('touchmove', move); window.addEventListener('touchend', up); return () => { window.removeEventListener('mousemove', move); window.removeEventListener('mouseup', up); window.removeEventListener('touchmove', move); window.removeEventListener('touchend', up); }; }, [dragging, fractionFromEvent, onMoveSingle, onMoveHalf]); const startDrag = (which) => (e) => { e.stopPropagation(); setDragging(which); const x = e.touches ? e.touches[0].clientX : e.clientX; if (which === 'single') onMoveSingle(fractionFromEvent(x)); else onMoveHalf(which, fractionFromEvent(x)); }; const win = (centre, label, which) => { const leftPct = (centre - widthFraction / 2) * 100; return (
{label && ( {label} )}
); }; return (
scene {scene.index + 1} · {fmt(scene.start)}–{fmt(scene.end)}
{touched ? ( ) : ( automatic )}
{playing && previewUrl ? (