"use client"; import { useCallback, useEffect, useRef, useState } from "react"; import { useTranslations } from "next-intl"; import { Pause, Play, SkipBack, SkipForward, Repeat, Scan, VolumeX, } from "lucide-react"; import { Button } from "@/components/ui/button"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from "@/components/ui/select"; import { Toggle } from "@/components/ui/toggle"; import { Tooltip, TooltipContent, TooltipTrigger, } from "@/components/ui/tooltip"; import { brollAlpha, brollAt, brollOf, clamp, editDuration, footageKey, footageUrl, frameRect, outputSize, outputTime, timecode, type BRollFootage, type EditDocument, type EditorState, } from "@/lib/editor/document"; import { drawEditorFrame, loadEditorFont, type TextDraft, type BRollLayer } from "@/lib/editor/render"; import type { InspectorTab } from "./inspector"; import { cn } from "@/lib/utils"; import { Panel, ToolButton } from "./studio-ui"; import { TextLayers } from "./text-layers"; import { usePreviewResolution } from "./use-preview-resolution"; interface Props { doc: EditDocument; asset: EditorState; endpoint: string; segmentIndex: number; select: (index: number) => void; time: number; onTime: (time: number) => void; seekRequest: { time: number; nonce: number }; textDraft?: TextDraft; tab: InspectorTab; update: (change: (doc: EditDocument) => EditDocument, group?: string) => void; videoRef: React.RefObject; /** Shown under the transport, inside the viewer card (the AI edit field). */ footer?: React.ReactNode; } export function Preview({ doc, asset, endpoint, segmentIndex, select, time, onTime, seekRequest, textDraft, tab, update, videoRef, footer, }: Props) { const t = useTranslations("editor"); const stageRef = useRef(null); const pictureRef = useRef(null); const [previewWidth, setPreviewWidth] = useState(270); const canvasRef = useRef(null), audioRef = useRef<{ context: AudioContext; gain: GainNode } | null>(null); // One hidden, muted player per stock video, kept in step with the clip. const brollPlayers = useRef(new Map()); const footage = [ ...new Map(brollOf(doc).map((b) => [footageKey(b.footage), b.footage])).entries(), ] as [string, BRollFootage][]; const [playing, setPlaying] = useState(false), [loop, setLoop] = useState(true), [guides, setGuides] = useState(false), [rate, setRate] = useState(1), [mediaError, setMediaError] = useState(false), [fontError, setFontError] = useState(false); const drag = useRef<{ x: number; y: number; startX: number; startY: number; } | null>(null); const size = outputSize(doc, asset.width, asset.height); const resolution = usePreviewResolution(pictureRef, size); useEffect(() => { const stage = stageRef.current; if (!stage) return; const observer = new ResizeObserver(([entry]) => setPreviewWidth( Math.min( entry.contentRect.width, (entry.contentRect.height * size.width) / size.height, ), ), ); observer.observe(stage); return () => observer.disconnect(); }, [size.width, size.height]); const play = useCallback(async () => { const video = videoRef.current; if (!video) return; if (!video.paused) { video.pause(); return; } if (!audioRef.current && asset.hasAudio) { const context = new AudioContext(); const gain = context.createGain(); context.createMediaElementSource(video).connect(gain); gain.connect(context.destination); audioRef.current = { context, gain }; } if (audioRef.current) { audioRef.current.gain.gain.value = doc.muted ? 0 : doc.volume; await audioRef.current.context.resume(); } const s = doc.segments[segmentIndex]; if (video.currentTime < s.start || video.currentTime >= s.end - 0.01) video.currentTime = s.start; await video.play().catch(() => setMediaError(true)); }, [asset.hasAudio, doc, segmentIndex, videoRef]); useEffect(() => { void loadEditorFont(doc.captions.font) .then(() => setFontError(false)) .catch(() => setFontError(true)); }, [doc.captions.font]); useEffect(() => { const video = videoRef.current; if (video) { video.muted = doc.muted; video.playbackRate = rate; } if (audioRef.current) audioRef.current.gain.gain.value = doc.muted ? 0 : doc.volume; }, [doc.volume, doc.muted, rate, videoRef]); useEffect(() => { const video = videoRef.current; if (video) { video.currentTime = seekRequest.time; onTime(seekRequest.time); } }, [seekRequest, videoRef, onTime]); useEffect( () => () => { void audioRef.current?.context.close(); }, [], ); useEffect(() => { let frame: number; const draw = () => { const canvas = canvasRef.current, video = videoRef.current; if (canvas && video && video.readyState >= 2) { const segment = doc.segments[segmentIndex] ?? doc.segments[0]; if (!video.paused && video.currentTime >= segment.end - 0.012) { const next = segmentIndex + 1; if (next < doc.segments.length) { video.currentTime = doc.segments[next].start; select(next); } else if (loop) { video.currentTime = doc.segments[0].start; select(0); } else { video.pause(); video.currentTime = segment.end; } } const context = canvas.getContext("2d"); const sourceTime = video.currentTime, active = brollAt(doc, sourceTime), activeKey = active ? footageKey(active.footage) : null; let layer: BRollLayer | null = null; for (const [key, player] of brollPlayers.current) { if (key !== activeKey || !active) { if (!player.paused) player.pause(); continue; } const wanted = active.offset + sourceTime - active.start; // Paused scrubbing seeks precisely; playback only corrects real drift. if (Math.abs(player.currentTime - wanted) > (video.paused ? 0.04 : 0.3)) player.currentTime = wanted; player.playbackRate = video.playbackRate; if (!video.paused && player.paused) void player.play().catch(() => {}); if (video.paused && !player.paused) player.pause(); if (player.readyState >= 2) layer = { width: player.videoWidth, height: player.videoHeight, alpha: brollAlpha(active, sourceTime), draw: (x, y, w, h) => context?.drawImage(player, x, y, w, h), }; } if (context) drawEditorFrame( context, doc, video.videoWidth || asset.width, video.videoHeight || asset.height, outputTime( doc, Math.min(segmentIndex, doc.segments.length - 1), video.currentTime, ), (rect) => context.drawImage(video, rect.x, rect.y, rect.width, rect.height), asset.captionLooks, layer, "none", ); } frame = requestAnimationFrame(draw); }; frame = requestAnimationFrame(draw); return () => cancelAnimationFrame(frame); }, [ asset.captionLooks, asset.height, asset.width, doc, loop, segmentIndex, select, videoRef, ]); const step = (direction: number) => { const video = videoRef.current; if (!video) return; video.pause(); video.currentTime = clamp( video.currentTime + direction / asset.fps, 0, asset.duration, ); onTime(video.currentTime); }; const hint = fontError ? t("preview.fontError") : tab === "framing" ? t("preview.framingHint") : tab === "captions" ? t("preview.captionHint") : null; return (
{t("preview.size", { width: size.width, height: size.height, fps: Math.round(asset.fps), })} {t("preview.safeArea")} {t("preview.safeAreaTip")}
{hint && (

{hint}

)}
{t("preview.loopTip")}
step(-1)} > step(1)}>
{doc.muted && ( )} {timecode( clamp( outputTime( doc, Math.min(segmentIndex, doc.segments.length - 1), time, ), 0, editDuration(doc), ), )} {" "} / {timecode(editDuration(doc))}
{footer}
); }