The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.
TypeScript ai-videocomfyuicreative-toolsgenerative-aiideogramimage-generationimage-to-3dimage-to-videoltx-videominimax-h3nextjsopen-sourceopen-weightsqwen-imagetext-to-imagevideo-generationwan
Translate & dub, Captions and Trim studios; open SFX and Foley defaults
Claude5c48e7843148
diff --git a/src/components/av/cue-editor.tsx b/src/components/av/cue-editor.tsxnew file mode 100644index 00000000..2742c6e4--- /dev/null+++ b/src/components/av/cue-editor.tsx@@ -0,0 +1,202 @@+"use client";++import { Merge, Plus, Redo2, Scissors, Trash2, Undo2 } from "lucide-react";+import { memo, useCallback, useEffect, useReducer, useRef } from "react";+import { Button } from "@/components/ui/button";+import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";+import { cueReducer, formatCueTime, normalizeCues, parseCueTime, type CueAction } from "@/lib/av/cue-edit";+import type { Cue } from "@/lib/cues";+import { cn } from "@/lib/utils";+import { useDraft } from "./use-draft";++interface History {+ past: Cue[][];+ present: Cue[];+ future: Cue[][];+ /** The line being typed into: keystrokes in one line make one undo step. */+ typing: number;+}++type HistoryAction = CueAction | { type: "undo" } | { type: "redo" };++function historyReducer(h: History, a: HistoryAction): History {+ if (a.type === "undo") return h.past.length ? { past: h.past.slice(0, -1), present: h.past.at(-1)!, future: [h.present, ...h.future], typing: -1 } : h;+ if (a.type === "redo") return h.future.length ? { past: [...h.past, h.present], present: h.future[0], future: h.future.slice(1), typing: -1 } : h;+ const next = cueReducer(h.present, a);+ if (next === h.present) return h;+ if (a.type === "text" && h.typing === a.index) return { ...h, present: next, future: [] };+ return { past: [...h.past.slice(-99), h.present], present: next, future: [], typing: a.type === "text" ? a.index : -1 };+}++/** Cue list state with undo / redo. */+export function useCueEditor(initial: Cue[]) {+ const [h, dispatch] = useReducer(historyReducer, initial, (c): History => ({ past: [], present: normalizeCues(c), future: [], typing: -1 }));+ return { cues: h.present, dispatch, canUndo: h.past.length > 0, canRedo: h.future.length > 0 };+}++function RowAction({ label, line, onClick, disabled, children }: { label: string; line: number; onClick: () => void; disabled?: boolean; children: React.ReactNode }) {+ return (+ <Tooltip>+ <TooltipTrigger asChild>+ <button+ type="button"+ disabled={disabled}+ onClick={onClick}+ aria-label={`${label} (line ${line + 1})`}+ className="grid size-7 place-items-center rounded-full text-muted-foreground hover:bg-accent hover:text-foreground disabled:pointer-events-none disabled:opacity-30"+ >+ {children}+ </button>+ </TooltipTrigger>+ <TooltipContent>{label}</TooltipContent>+ </Tooltip>+ );+}++const Row = memo(function Row({+ cue,+ index,+ active,+ last,+ dispatch,+ onSeek,+}: {+ cue: Cue;+ index: number;+ active: boolean;+ last: boolean;+ dispatch: (a: CueAction) => void;+ onSeek?: (t: number) => void;+}) {+ const text = useRef<HTMLTextAreaElement>(null);+ const [start, setStart, resetStart] = useDraft(formatCueTime(cue.start));+ const [end, setEnd, resetEnd] = useDraft(formatCueTime(cue.end));+ const commit = (which: "start" | "end", raw: string) => {+ const t = parseCueTime(raw);+ if (t === null) return which === "start" ? resetStart() : resetEnd();+ dispatch({ type: "time", index, [which]: t });+ };+ const timeInput = (which: "start" | "end", value: string, set: (v: string) => void) => (+ <input+ value={value}+ onChange={(e) => set(e.target.value)}+ onBlur={(e) => commit(which, e.target.value)}+ onKeyDown={(e) => {+ if (e.key === "Enter") e.currentTarget.blur();+ if (e.key === "ArrowUp" || e.key === "ArrowDown") {+ e.preventDefault();+ const step = e.shiftKey ? 1 : 0.1;+ dispatch({ type: "time", index, [which]: (which === "start" ? cue.start : cue.end) + (e.key === "ArrowUp" ? step : -step) });+ }+ }}+ inputMode="decimal"+ aria-label={`${which === "start" ? "Start" : "End"} of line ${index + 1}`}+ className="h-7 w-[4.6rem] rounded-md bg-transparent px-1.5 font-mono text-[12px] tabular-nums outline-none hover:bg-muted focus:bg-muted focus:ring-2 focus:ring-ring/40"+ />+ );+ const splitAtCaret = () => dispatch({ type: "split", index, caret: text.current?.selectionStart ?? undefined });+ return (+ <li data-cue={index} className={cn("group/cue rounded-xl border px-2 py-1.5 transition-colors [content-visibility:auto] [contain-intrinsic-size:auto_76px]", active ? "border-primary bg-brand-faint/50" : "border-transparent hover:border-border")}>+ <div className="flex flex-wrap items-center gap-x-1 gap-y-0.5">+ <button type="button" onClick={() => onSeek?.(cue.start)} className="mr-1 font-mono text-[11px] text-subtle-foreground tabular-nums hover:text-brand-text" aria-label={`Play from line ${index + 1}`}>+ {String(index + 1).padStart(2, "0")}+ </button>+ {timeInput("start", start, setStart)}+ <span className="text-subtle-foreground">→</span>+ {timeInput("end", end, setEnd)}+ <div className="ml-auto flex items-center opacity-100 sm:opacity-0 sm:group-focus-within/cue:opacity-100 sm:group-hover/cue:opacity-100">+ <RowAction label="Split at the cursor" line={index} onClick={splitAtCaret} disabled={!cue.text.trim().includes(" ")}>+ <Scissors className="size-3.5" />+ </RowAction>+ <RowAction label="Merge with the next line" line={index} onClick={() => dispatch({ type: "merge", index })} disabled={last}>+ <Merge className="size-3.5" />+ </RowAction>+ <RowAction label="Add a line after" line={index} onClick={() => dispatch({ type: "insert", index })}>+ <Plus className="size-3.5" />+ </RowAction>+ <RowAction label="Delete line" line={index} onClick={() => dispatch({ type: "remove", index })}>+ <Trash2 className="size-3.5" />+ </RowAction>+ </div>+ </div>+ <textarea+ ref={text}+ value={cue.text}+ onChange={(e) => dispatch({ type: "text", index, text: e.target.value })}+ onFocus={() => onSeek?.(cue.start)}+ onKeyDown={(e) => {+ // Alt+Enter splits the line at the cursor.+ if (e.key === "Enter" && e.altKey) {+ e.preventDefault();+ dispatch({ type: "split", index, caret: e.currentTarget.selectionStart });+ }+ }}+ rows={1}+ aria-label={`Line ${index + 1}`}+ placeholder="Empty line"+ className="field-sizing-content w-full resize-none rounded-md bg-transparent px-1.5 py-1 text-[15px] leading-snug outline-none placeholder:text-subtle-foreground focus:bg-muted/60"+ />+ </li>+ );+});++/** The editable list of timed lines, with undo / redo; the line under `currentTime` is highlighted. */+export function CueEditor({+ editor,+ currentTime,+ onSeek,+ className,+ emptyHint = "No lines yet",+}: {+ editor: ReturnType<typeof useCueEditor>;+ currentTime?: number;+ onSeek?: (t: number) => void;+ className?: string;+ emptyHint?: string;+}) {+ const { cues, dispatch, canUndo, canRedo } = editor;+ const list = useRef<HTMLOListElement>(null);+ const active = currentTime === undefined ? -1 : cues.findIndex((c) => currentTime >= c.start && currentTime < c.end);+ const send = useCallback((a: CueAction) => dispatch(a), [dispatch]);+ // Keep the playing line in view (inside the list only).+ useEffect(() => {+ if (active < 0 || !list.current) return;+ const el = list.current.querySelector<HTMLElement>(`[data-cue="${active}"]`);+ const box = list.current;+ if (!el || box.contains(document.activeElement)) return;+ if (el.offsetTop < box.scrollTop || el.offsetTop + el.offsetHeight > box.scrollTop + box.clientHeight) box.scrollTop = el.offsetTop - 12;+ }, [active]);+ return (+ <div className={cn("flex min-h-0 flex-col", className)}>+ <div className="flex items-center gap-1 pb-2">+ <span className="text-[12px] text-muted-foreground">+ {cues.length} line{cues.length === 1 ? "" : "s"} · Alt+Enter splits+ </span>+ <div className="ml-auto flex items-center">+ <Button variant="ghost" size="icon-sm" className="rounded-full" disabled={!canUndo} onClick={() => dispatch({ type: "undo" })} aria-label="Undo">+ <Undo2 className="size-4" />+ </Button>+ <Button variant="ghost" size="icon-sm" className="rounded-full" disabled={!canRedo} onClick={() => dispatch({ type: "redo" })} aria-label="Redo">+ <Redo2 className="size-4" />+ </Button>+ </div>+ </div>+ {cues.length ? (+ <ol ref={list} className="relative min-h-0 flex-1 space-y-0.5 overflow-y-auto pr-1">+ {cues.map((c, i) => (+ <Row key={i} cue={c} index={i} active={i === active} last={i === cues.length - 1} dispatch={send} onSeek={onSeek} />+ ))}+ </ol>+ ) : (+ <div className="grid flex-1 place-items-center rounded-xl border border-dashed py-10 text-center">+ <div>+ <p className="text-[13px] text-muted-foreground">{emptyHint}</p>+ <Button variant="outline" size="sm" className="mt-3 rounded-full" onClick={() => dispatch({ type: "insert", index: -1 })}>+ <Plus className="size-3.5" /> Add a line+ </Button>+ </div>+ </div>+ )}+ </div>+ );+}diff --git a/src/components/av/frame-sampler.ts b/src/components/av/frame-sampler.tsnew file mode 100644index 00000000..ce4451c8--- /dev/null+++ b/src/components/av/frame-sampler.ts@@ -0,0 +1,102 @@+"use client";++/**+ * Frames of a video, read in the browser: seek a detached <video> to each time and draw it small onto+ * a canvas. Used for trimmer filmstrips, Katana's cut detection and the Virality hook analysis. The+ * video must be same-origin (our /api/files URLs are) or CORS-enabled, or the canvas can't be read.+ */++export interface SampledFrame {+ t: number;+ data: ImageData;+ /** A JPEG data URL, when asked for (filmstrips). */+ url?: string;+}++function once<K extends keyof HTMLMediaElementEventMap>(el: HTMLMediaElement, ev: K, ms = 8000): Promise<void> {+ return new Promise((resolve, reject) => {+ const done = () => {+ clear();+ resolve();+ };+ const fail = () => {+ clear();+ reject(new Error("This video can't be read in the browser — try MP4 (H.264) or WebM"));+ };+ const timer = setTimeout(fail, ms);+ const clear = () => {+ clearTimeout(timer);+ el.removeEventListener(ev, done);+ el.removeEventListener("error", fail);+ };+ el.addEventListener(ev, done, { once: true });+ el.addEventListener("error", fail, { once: true });+ });+}++/** Load a video's metadata in a detached element: its duration and size. */+export async function openVideo(src: string): Promise<HTMLVideoElement> {+ const v = document.createElement("video");+ v.muted = true;+ v.playsInline = true;+ v.preload = "auto";+ v.crossOrigin = "anonymous";+ v.src = src;+ if (v.readyState < 1) await once(v, "loadedmetadata");+ return v;+}++export function releaseVideo(v: HTMLVideoElement) {+ v.removeAttribute("src");+ v.load();+}++/**+ * Sample frames at `times` (seconds), `width` px wide. Stops early when `signal` aborts. Calls+ * `onProgress` with the share done.+ */+export async function sampleFrames(+ src: string | HTMLVideoElement,+ times: number[],+ o: { width?: number; jpeg?: boolean; signal?: AbortSignal; onProgress?: (done: number) => void } = {},+): Promise<SampledFrame[]> {+ const v = typeof src === "string" ? await openVideo(src) : src;+ const width = o.width ?? 64;+ const height = Math.max(1, Math.round((width * (v.videoHeight || 9)) / (v.videoWidth || 16)));+ const canvas = document.createElement("canvas");+ canvas.width = width;+ canvas.height = height;+ const ctx = canvas.getContext("2d", { willReadFrequently: true })!;+ const out: SampledFrame[] = [];+ try {+ for (let i = 0; i < times.length; i++) {+ if (o.signal?.aborted) break;+ const t = Math.min(Math.max(0, times[i]), Math.max(0, (v.duration || 0) - 0.05));+ if (Math.abs(v.currentTime - t) > 0.001 || v.readyState < 2) {+ v.currentTime = t;+ await once(v, "seeked");+ }+ ctx.drawImage(v, 0, 0, width, height);+ out.push({ t, data: ctx.getImageData(0, 0, width, height), ...(o.jpeg && { url: canvas.toDataURL("image/jpeg", 0.7) }) });+ o.onProgress?.((i + 1) / times.length);+ }+ } finally {+ if (typeof src === "string") releaseVideo(v);+ }+ return out;+}++/** Evenly spaced times across a clip (centre of each slice). */+export const spacedTimes = (duration: number, count: number) => Array.from({ length: Math.max(1, count) }, (_, i) => ((i + 0.5) * duration) / Math.max(1, count));++/** Mean absolute luma difference between two same-size frames, 0–1. */+export function frameDiff(a: ImageData, b: ImageData): number {+ const n = Math.min(a.data.length, b.data.length);+ let sum = 0;+ for (let i = 0; i < n; i += 4) {+ const la = a.data[i] * 0.299 + a.data[i + 1] * 0.587 + a.data[i + 2] * 0.114;+ const lb = b.data[i] * 0.299 + b.data[i + 1] * 0.587 + b.data[i + 2] * 0.114;+ sum += Math.abs(la - lb);+ }+ return sum / (n / 4) / 255;+}diff --git a/src/components/av/language-picker.tsx b/src/components/av/language-picker.tsxnew file mode 100644index 00000000..7152a349--- /dev/null+++ b/src/components/av/language-picker.tsx@@ -0,0 +1,104 @@+"use client";++import { Check, Languages, Plus, X } from "lucide-react";+import { useState } from "react";+import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList } from "@/components/ui/command";+import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";+import { DUB_LANGUAGES, type DubLanguage } from "@/lib/av/languages";+import { cn } from "@/lib/utils";++/** The spoken language: detected, or one of the list. */+export function SourceLanguageSelect({ value, onChange, id, languages = DUB_LANGUAGES }: { value: string; onChange: (v: string) => void; id?: string; languages?: DubLanguage[] }) {+ return (+ <Select value={value} onValueChange={onChange}>+ <SelectTrigger id={id} className="h-9 w-full rounded-full sm:w-52" aria-label="Spoken language">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ <SelectItem value="auto">Detect automatically</SelectItem>+ {languages.map((l) => (+ <SelectItem key={l.code} value={l.code}>+ {l.name}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ );+}++/**+ * Languages to translate into: chips you can remove, plus a searchable list. Languages the current+ * route can't speak are listed as unavailable (with the reason) instead of hidden.+ */+export function TargetLanguages({+ value,+ onChange,+ available,+ unavailableHint,+ max = 8,+}: {+ value: string[];+ onChange: (v: string[]) => void;+ available: (l: DubLanguage) => boolean;+ unavailableHint: string;+ max?: number;+}) {+ const [open, setOpen] = useState(false);+ const toggle = (code: string) => onChange(value.includes(code) ? value.filter((c) => c !== code) : value.length >= max ? value : [...value, code]);+ const chosen = value.map((c) => DUB_LANGUAGES.find((l) => l.code === c)).filter((l): l is DubLanguage => !!l);+ return (+ <div className="flex flex-wrap items-center gap-1.5">+ {chosen.map((l) => (+ <span+ key={l.code}+ className={cn(+ "inline-flex h-8 items-center gap-1 rounded-full pr-1 pl-3 text-[13px] font-medium",+ available(l) ? "bg-brand-faint text-brand-text" : "bg-muted text-muted-foreground line-through",+ )}+ title={available(l) ? undefined : unavailableHint}+ >+ {l.name}+ <button type="button" onClick={() => toggle(l.code)} className="grid size-6 place-items-center rounded-full hover:bg-brand-faint-hover" aria-label={`Remove ${l.name}`}>+ <X className="size-3" />+ </button>+ </span>+ ))}+ <Popover open={open} onOpenChange={setOpen}>+ <PopoverTrigger asChild>+ <button+ type="button"+ className="inline-flex h-8 items-center gap-1.5 rounded-full border border-dashed border-border-strong px-3 text-[13px] font-medium text-muted-foreground transition-colors hover:border-primary hover:text-brand-text"+ aria-label="Add a language"+ >+ {chosen.length ? <Plus className="size-3.5" /> : <Languages className="size-3.5" />}+ {chosen.length ? "Add" : "Pick languages"}+ </button>+ </PopoverTrigger>+ <PopoverContent className="w-[min(92vw,300px)] p-0" align="start" collisionPadding={12}>+ <Command>+ <CommandInput placeholder="Search languages…" />+ <CommandList className="max-h-72">+ <CommandEmpty>No language matches.</CommandEmpty>+ <CommandGroup heading={`Up to ${max}`}>+ {DUB_LANGUAGES.map((l) => {+ const on = value.includes(l.code);+ const ok = available(l);+ return (+ <CommandItem key={l.code} value={`${l.name} ${l.code}`} disabled={!ok && !on} onSelect={() => toggle(l.code)} className="justify-between">+ <span className={cn(!ok && "text-subtle-foreground")}>+ {l.name}+ {!ok && <span className="ml-1.5 text-[11px]">· not on this route</span>}+ </span>+ {on && <Check className="size-3.5 text-brand-text" />}+ </CommandItem>+ );+ })}+ </CommandGroup>+ </CommandList>+ </Command>+ </PopoverContent>+ </Popover>+ </div>+ );+}diff --git a/src/components/av/media-drop.tsx b/src/components/av/media-drop.tsxnew file mode 100644index 00000000..b59eb97b--- /dev/null+++ b/src/components/av/media-drop.tsx@@ -0,0 +1,154 @@+"use client";++import { FileVideo, ImagePlus, Library, Loader2, RefreshCw, Upload, X } from "lucide-react";+import { useRef, useState } from "react";+import { toast } from "sonner";+import { Button } from "@/components/ui/button";+import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";+import { ACCEPT, fileToSlot, kindOfFile, LibraryGrid, wrongKindMessage, type SlotValue } from "@/components/studio/media-slot";+import { cn } from "@/lib/utils";++/**+ * A large drop zone for the one video (or photo) a tool works on: drop, click or pick from the+ * library; then a preview with Replace / Remove. Reports the clip's length once the browser knows it.+ */+export function MediaDrop({+ kind,+ value,+ onChange,+ title,+ hint,+ onDuration,+ onUnreadable,+ className,+ compact,+}: {+ kind: "video" | "image";+ value: SlotValue | null;+ onChange: (v: SlotValue | null) => void;+ title: string;+ hint?: string;+ onDuration?: (seconds: number) => void;+ /** The browser can't decode the clip (e.g. H.265): tools fall back to typing times. */+ onUnreadable?: () => void;+ className?: string;+ /** A shorter strip once something is attached (editors keep more room for their work). */+ compact?: boolean;+}) {+ const input = useRef<HTMLInputElement>(null);+ const [over, setOver] = useState(false);+ const [picking, setPicking] = useState(false);+ const take = (f: File | undefined) => {+ if (!f) return;+ if (kindOfFile(f) !== kind) return void toast(wrongKindMessage(kind));+ void fileToSlot(f, onChange, kind);+ };+ const Icon = kind === "video" ? FileVideo : ImagePlus;+ const fileInput = (+ <input+ ref={input}+ type="file"+ accept={ACCEPT[kind]}+ hidden+ onChange={(e) => {+ take(e.target.files?.[0]);+ e.target.value = "";+ }}+ />+ );+ const library = (+ <Popover open={picking} onOpenChange={setPicking}>+ <PopoverTrigger asChild>+ <Button variant="ghost" size="sm" className="rounded-full">+ <Library className="size-3.5" /> From library+ </Button>+ </PopoverTrigger>+ <PopoverContent className="w-[min(92vw,360px)] p-2" collisionPadding={12}>+ <p className="px-1 pb-2 text-[13px] font-medium">From your library</p>+ {picking && (+ <LibraryGrid+ kinds={[kind]}+ onPick={(v) => {+ onChange(v);+ setPicking(false);+ }}+ />+ )}+ </PopoverContent>+ </Popover>+ );++ if (value) {+ return (+ <div className={cn("overflow-hidden rounded-2xl border bg-background shadow-soft", className)}>+ <div className={cn("relative grid place-items-center bg-media", compact ? "max-h-[38vh]" : "max-h-[52vh]")}>+ {kind === "video" ? (+ <video+ key={value.preview}+ src={value.preview}+ controls+ playsInline+ preload="metadata"+ onLoadedMetadata={(e) => Number.isFinite(e.currentTarget.duration) && onDuration?.(e.currentTarget.duration)}+ onError={() => !value.uploading && onUnreadable?.()}+ className={cn("w-full object-contain", compact ? "max-h-[38vh]" : "max-h-[52vh]")}+ />+ ) : (+ // eslint-disable-next-line @next/next/no-img-element+ <img src={value.preview} alt={value.name ?? title} className={cn("w-full object-contain", compact ? "max-h-[38vh]" : "max-h-[52vh]")} />+ )}+ {value.uploading && (+ <div className="absolute inset-0 grid place-items-center bg-background/50" role="status" aria-label="Uploading">+ <span className="inline-flex items-center gap-2 rounded-full bg-background px-3 py-1.5 text-[13px] font-medium shadow-soft">+ <Loader2 className="size-3.5 animate-spin" /> Uploading…+ </span>+ </div>+ )}+ </div>+ <div className="flex min-w-0 items-center gap-1 px-3 py-2">+ <p className="min-w-0 flex-1 truncate text-[13px] text-muted-foreground">{value.name ?? title}</p>+ <Button variant="ghost" size="sm" className="rounded-full" onClick={() => input.current?.click()}>+ <RefreshCw className="size-3.5" /> Replace+ </Button>+ <Button variant="ghost" size="icon-sm" className="rounded-full" aria-label={`Remove ${title.toLowerCase()}`} onClick={() => onChange(null)}>+ <X className="size-4" />+ </Button>+ </div>+ {fileInput}+ </div>+ );+ }++ return (+ <div+ className={cn(+ "relative flex flex-col items-center justify-center gap-3 rounded-2xl border-2 border-dashed border-border-strong bg-background px-4 py-10 text-center transition-colors sm:py-14",+ over && "border-primary bg-brand-faint",+ className,+ )}+ onDragOver={(e) => {+ e.preventDefault();+ setOver(true);+ }}+ onDragLeave={() => setOver(false)}+ onDrop={(e) => {+ e.preventDefault();+ setOver(false);+ take(e.dataTransfer.files?.[0]);+ }}+ >+ <span className="grid size-12 place-items-center rounded-2xl bg-brand-faint text-brand-text">{over ? <Upload className="size-5" /> : <Icon className="size-5" />}</span>+ <div>+ <p className="text-[15px] font-medium">{title}</p>+ {hint && <p className="mt-1 text-[13px] text-muted-foreground">{hint}</p>}+ </div>+ <div className="flex flex-wrap items-center justify-center gap-1.5">+ <Button size="sm" className="rounded-full" onClick={() => input.current?.click()}>+ <Upload className="size-3.5" /> Upload {kind === "video" ? "a video" : "a photo"}+ </Button>+ {library}+ </div>+ {fileInput}+ </div>+ );+}diff --git a/src/components/av/step-list.tsx b/src/components/av/step-list.tsxnew file mode 100644index 00000000..7d8d2443--- /dev/null+++ b/src/components/av/step-list.tsx@@ -0,0 +1,61 @@+"use client";++import { Check, CircleDashed, Loader2, TriangleAlert } from "lucide-react";+import type { Generation } from "@/lib/catalog/types";+import { cn } from "@/lib/utils";++export interface StepRow {+ key: string;+ label: string;+ g?: Generation;+}++/** One line per pipeline step: waiting, running (with progress), done or failed (with the reason). */+export function StepList({ steps, className }: { steps: StepRow[]; className?: string }) {+ return (+ <ol className={cn("space-y-1.5", className)} aria-label="Steps">+ {steps.map((s) => {+ const g = s.g;+ const status = g?.status ?? "queued";+ const pct = g?.progress != null ? Math.round(g.progress * 100) : null;+ const waiting = status === "queued" && (!g || g.message?.startsWith("Waits"));+ return (+ <li key={s.key} className="flex min-w-0 items-start gap-2.5 text-[13px]">+ <span className="mt-0.5 grid size-5 shrink-0 place-items-center">+ {status === "succeeded" ? (+ <span className="grid size-5 place-items-center rounded-full bg-success text-background">+ <Check className="size-3" />+ </span>+ ) : status === "failed" || status === "canceled" ? (+ <TriangleAlert className="size-4 text-destructive" />+ ) : waiting ? (+ <CircleDashed className="size-4 text-subtle-foreground" />+ ) : (+ <Loader2 className="size-4 animate-spin text-brand-text" />+ )}+ </span>+ <div className="min-w-0 flex-1">+ <div className="flex min-w-0 items-baseline gap-2">+ <span className={cn("truncate font-medium", waiting && "text-muted-foreground")}>{s.label}</span>+ {g?.modelName && <span className="hidden truncate text-[12px] text-muted-foreground sm:inline">{g.modelName}</span>}+ <span className="ml-auto shrink-0 font-mono text-[11px] text-muted-foreground">+ {status === "succeeded" ? "Done" : status === "failed" ? "Failed" : status === "canceled" ? "Canceled" : waiting ? "Waiting" : pct != null ? `${pct}%` : "Working"}+ {g?.provider === "mock" && status === "succeeded" ? " · demo" : ""}+ </span>+ </div>+ {(status === "running" || (status === "queued" && !waiting)) && (+ <div className="mt-1 h-1 overflow-hidden rounded-full bg-muted">+ <div className={cn("h-full rounded-full bg-primary transition-[width] duration-500", pct == null && "w-1/3 animate-pulse")} style={pct != null ? { width: `${Math.max(4, pct)}%` } : undefined} />+ </div>+ )}+ {(status === "failed" || status === "canceled") && g?.error && <p className="mt-0.5 text-[12px] leading-snug break-words text-destructive">{g.error}</p>}+ </div>+ </li>+ );+ })}+ </ol>+ );+}++/** Whether any of these generations still renders (poll while true). */+export const anyActive = (gs: (Generation | undefined)[]) => gs.some((g) => g && (g.status === "queued" || g.status === "running"));diff --git a/src/components/av/tool-shell.tsx b/src/components/av/tool-shell.tsxnew file mode 100644index 00000000..84b2530f--- /dev/null+++ b/src/components/av/tool-shell.tsx@@ -0,0 +1,72 @@+"use client";++import { SidebarTrigger } from "@/components/ui/sidebar";+import { EngineSwitch } from "@/components/studio/engine-switch";+import { useEngine } from "@/lib/api";+import { cn } from "@/lib/utils";++/**+ * The frame of a stand-alone audio/video tool (Translate & dub, Captions, Trim, Katana, Image to 3D,+ * Virality): the sticky header with the title, extra controls and the engine switch, an optional row+ * of hub tabs under it, then the page.+ */+export function ToolShell({+ title,+ tabs,+ header,+ engineSwitch = true,+ children,+ wide,+}: {+ title: string;+ tabs?: React.ReactNode;+ header?: React.ReactNode;+ /** Tools that run in the browser only (Virality) have no engine to pick. */+ engineSwitch?: boolean;+ children: React.ReactNode;+ wide?: boolean;+}) {+ const [engine, setEngine] = useEngine();+ return (+ <div className="flex min-h-svh min-w-0 flex-col">+ <div className="sticky top-0 z-20 bg-background/85 backdrop-blur">+ <header className="flex h-14 items-center gap-2 px-3 sm:px-6">+ <SidebarTrigger className="md:hidden" />+ <h1 className="min-w-0 truncate font-heading text-[22px] leading-[1.15]">{title}</h1>+ <div className="ml-auto flex shrink-0 items-center gap-2">+ {header}+ {engineSwitch && <EngineSwitch value={engine} onChange={setEngine} />}+ </div>+ </header>+ {tabs}+ </div>+ <div className={cn("mx-auto w-full min-w-0 flex-1 px-3 pb-16 sm:px-6", wide ? "max-w-[1240px]" : "max-w-[1040px]")}>{children}</div>+ </div>+ );+}++/** The serif hero over an empty tool. */+export function ToolHero({ title, subtitle, children }: { title: string; subtitle?: React.ReactNode; children?: React.ReactNode }) {+ return (+ <div className="flex flex-col items-center pt-[8vh] text-center sm:pt-[10vh]">+ <h2 className="font-heading text-display text-balance">{title}</h2>+ {subtitle && <p className="mt-2 max-w-xl text-[13px] text-pretty text-muted-foreground">{subtitle}</p>}+ {children}+ </div>+ );+}++/** A titled card section (setup steps, review, results). */+export function Panel({ title, aside, children, className }: { title?: React.ReactNode; aside?: React.ReactNode; children: React.ReactNode; className?: string }) {+ return (+ <section className={cn("rounded-2xl border bg-background p-3 shadow-soft sm:p-4", className)}>+ {(title || aside) && (+ <div className="mb-3 flex min-w-0 items-center gap-2">+ {title && <h3 className="min-w-0 truncate text-[13px] font-semibold">{title}</h3>}+ {aside && <div className="ml-auto flex shrink-0 items-center gap-2">{aside}</div>}+ </div>+ )}+ {children}+ </section>+ );+}diff --git a/src/components/av/trim-tool.tsx b/src/components/av/trim-tool.tsxnew file mode 100644index 00000000..632f177a--- /dev/null+++ b/src/components/av/trim-tool.tsx@@ -0,0 +1,205 @@+"use client";++import { Loader2, Pause, Play, Scissors } from "lucide-react";+import { useEffect, useRef, useState } from "react";+import { toast } from "sonner";+import { Button } from "@/components/ui/button";+import { Slider } from "@/components/ui/slider";+import { Feed } from "@/components/studio/feed";+import type { SlotValue } from "@/components/studio/media-slot";+import { useCreateGeneration, useEngine, useGenerations } from "@/lib/api";+import { formatCueTime, parseCueTime } from "@/lib/av/cue-edit";+import { cn } from "@/lib/utils";+import { sampleFrames, spacedTimes } from "./frame-sampler";+import { MediaDrop } from "./media-drop";+import { useDraft } from "./use-draft";+import { Panel, ToolHero, ToolShell } from "./tool-shell";++export const TRIM_FEATURE = "trim";+const MIN_LENGTH = 0.5;++/**+ * Trim (Video tools → Trim): keep the part between two times, with its sound. fal's trim utility on+ * the cloud, ComfyUI's core Trim Video on the open engine (CPU). A minimal in/out picker; Shorts+ * Studio's video trimmer can replace VideoRange when it lands.+ */+export function TrimTool({ tabs }: { tabs?: React.ReactNode }) {+ const [engine] = useEngine();+ const create = useCreateGeneration();+ const results = useGenerations({ features: [TRIM_FEATURE], limit: 24 });+ const [video, setVideo] = useState<SlotValue | null>(null);+ const [duration, setDuration] = useState(0);+ const [unreadable, setUnreadable] = useState(false);+ const [range, setRange] = useState<[number, number]>([0, 0]);+ const trim = () => {+ if (!video || video.uploading) return void toast("Add the video first");+ if (range[1] - range[0] < MIN_LENGTH) return void toast(`Keep at least ${MIN_LENGTH} s`);+ create.mutate(+ {+ feature: TRIM_FEATURE,+ modelId: engine === "open" ? "oss-trim" : "trim-video",+ op: "trim",+ inputs: { video: video.ref },+ params: { startTime: Math.round(range[0] * 100) / 100, endTime: Math.round(range[1] * 100) / 100 },+ },+ { onSuccess: () => toast.success("Trimming"), onError: (e) => toast.error((e as Error).message) },+ );+ };+ return (+ <ToolShell title="Video tools" tabs={tabs}>+ {!video && <ToolHero title="Keep just the part you need" subtitle="Pick where it starts and ends — the sound comes along. Free on your ComfyUI (CPU), fractions of a cent on the cloud." />}+ <div className={cn("mx-auto max-w-[820px] space-y-3", video ? "pt-4" : "mt-8")}>+ <MediaDrop+ kind="video"+ value={video}+ onChange={(v) => {+ setVideo(v);+ setUnreadable(false);+ if (!v) setDuration(0);+ }}+ onDuration={(d) => {+ setDuration(d);+ setRange([0, d]);+ }}+ onUnreadable={() => setUnreadable(true)}+ title="Add a video to trim"+ hint="MP4, MOV or WebM up to 200 MB"+ compact+ />+ {video && !video.uploading && (duration > 0 || unreadable) && (+ <Panel title="Keep">+ {duration > 0 ? <VideoRange src={video.ref} duration={duration} value={range} onChange={setRange} /> : <ManualRange value={range} onChange={setRange} />}+ <div className="mt-4 flex flex-wrap items-center gap-2">+ <p className="flex-1 text-[13px] text-muted-foreground">+ Keeps <span className="font-mono text-foreground">{formatCueTime(Math.max(0, range[1] - range[0]))}</span>+ {duration > 0 && ` of ${formatCueTime(duration)}`}+ </p>+ <Button className="rounded-full" onClick={trim} disabled={create.isPending}>+ {create.isPending ? <Loader2 className="size-4 animate-spin" /> : <Scissors className="size-4" />} Trim+ </Button>+ </div>+ </Panel>+ )}+ </div>+ {(results.data?.length ?? 0) > 0 && (+ <section className="mt-10" aria-labelledby="trimmed">+ <h3 id="trimmed" className="mb-3 font-heading text-[22px]">+ Trimmed clips+ </h3>+ <Feed items={results.data!} />+ </section>+ )}+ </ToolShell>+ );+}++/** Filmstrip + two-handle range + exact times + play the selection. */+export function VideoRange({ src, duration, value, onChange }: { src: string; duration: number; value: [number, number]; onChange: (v: [number, number]) => void }) {+ const [thumbs, setThumbs] = useState<string[]>([]);+ const player = useRef<HTMLVideoElement>(null);+ const [playing, setPlaying] = useState(false);+ useEffect(() => {+ const ctl = new AbortController();+ sampleFrames(src, spacedTimes(duration, 10), { width: 96, jpeg: true, signal: ctl.signal })+ .then((f) => !ctl.signal.aborted && setThumbs(f.map((x) => x.url!)))+ .catch(() => {});+ return () => ctl.abort();+ }, [src, duration]);+ // Playing the selection stops at the out point.+ useEffect(() => {+ const v = player.current;+ if (!v || !playing) return;+ const tick = () => {+ if (v.currentTime >= value[1]) {+ v.pause();+ setPlaying(false);+ }+ };+ v.addEventListener("timeupdate", tick);+ return () => v.removeEventListener("timeupdate", tick);+ }, [playing, value]);+ const play = () => {+ const v = player.current;+ if (!v) return;+ if (playing) {+ v.pause();+ return setPlaying(false);+ }+ v.currentTime = value[0];+ void v.play().then(() => setPlaying(true)).catch(() => toast("This browser can't play the clip — the trim still works"));+ };+ const set = (i: 0 | 1, raw: string) => {+ const t = parseCueTime(raw);+ if (t === null) return;+ const next: [number, number] = i === 0 ? [Math.min(t, value[1] - MIN_LENGTH), value[1]] : [value[0], Math.max(t, value[0] + MIN_LENGTH)];+ onChange([Math.max(0, next[0]), Math.min(duration, next[1])]);+ };+ return (+ <div className="space-y-3">+ <video ref={player} src={src} playsInline preload="metadata" className="hidden" onPause={() => setPlaying(false)} />+ <div className="relative h-12 overflow-hidden rounded-lg bg-muted" aria-hidden>+ <div className="flex h-full">+ {thumbs.map((u, i) => (+ // eslint-disable-next-line @next/next/no-img-element+ <img key={i} src={u} alt="" className="h-full min-w-0 flex-1 object-cover" />+ ))}+ </div>+ <div className="absolute inset-y-0 left-0 bg-background/70" style={{ width: `${(value[0] / duration) * 100}%` }} />+ <div className="absolute inset-y-0 right-0 bg-background/70" style={{ width: `${100 - (value[1] / duration) * 100}%` }} />+ <div className="absolute inset-y-0 rounded-lg border-2 border-primary" style={{ left: `${(value[0] / duration) * 100}%`, right: `${100 - (value[1] / duration) * 100}%` }} />+ </div>+ <Slider+ min={0}+ max={duration}+ step={0.05}+ minStepsBetweenThumbs={Math.round(MIN_LENGTH / 0.05)}+ value={value}+ onValueChange={(v) => onChange([v[0], v[1]])}+ aria-label="Part to keep"+ thumbLabels={["Start", "End"]}+ />+ <div className="flex flex-wrap items-center gap-2">+ <TimeField label="Start" value={value[0]} onCommit={(s) => set(0, s)} />+ <TimeField label="End" value={value[1]} onCommit={(s) => set(1, s)} />+ <Button variant="outline" size="sm" className="ml-auto rounded-full" onClick={play}>+ {playing ? <Pause className="size-3.5" /> : <Play className="size-3.5" />} {playing ? "Pause" : "Play selection"}+ </Button>+ </div>+ </div>+ );+}++/** When the browser can't decode the clip: type the times (the server still trims it). */+function ManualRange({ value, onChange }: { value: [number, number]; onChange: (v: [number, number]) => void }) {+ const set = (i: 0 | 1, raw: string) => {+ const t = parseCueTime(raw);+ if (t === null) return;+ onChange(i === 0 ? [t, Math.max(value[1], t + MIN_LENGTH)] : [value[0], Math.max(t, value[0] + MIN_LENGTH)]);+ };+ return (+ <div className="space-y-2">+ <p className="text-[13px] text-muted-foreground">This browser can't preview the clip, but it can still be trimmed — type the times (e.g. 0:03.5).</p>+ <div className="flex flex-wrap items-center gap-2">+ <TimeField label="Start" value={value[0]} onCommit={(s) => set(0, s)} />+ <TimeField label="End" value={value[1]} onCommit={(s) => set(1, s)} />+ </div>+ </div>+ );+}++function TimeField({ label, value, onCommit }: { label: string; value: number; onCommit: (raw: string) => void }) {+ const [text, setText] = useDraft(formatCueTime(value));+ return (+ <label className="flex items-center gap-1.5 text-[12px] text-muted-foreground">+ {label}+ <input+ value={text}+ onChange={(e) => setText(e.target.value)}+ onBlur={(e) => onCommit(e.target.value)}+ onKeyDown={(e) => e.key === "Enter" && e.currentTarget.blur()}+ inputMode="decimal"+ className="h-8 w-20 rounded-full border bg-background px-2.5 text-center font-mono text-[12px] text-foreground tabular-nums outline-none focus:border-primary focus:ring-2 focus:ring-brand-faint"+ />+ </label>+ );+}diff --git a/src/components/av/use-draft.ts b/src/components/av/use-draft.tsnew file mode 100644index 00000000..bc434b0a--- /dev/null+++ b/src/components/av/use-draft.ts@@ -0,0 +1,19 @@+"use client";++import { useCallback, useState } from "react";++/**+ * Text being typed into a field that also follows a value from outside (a cue's time shown as+ * "1:02.5"): the draft resets whenever the outside value changes, without an effect.+ */+export function useDraft(source: string): [string, (v: string) => void, () => void] {+ const [state, setState] = useState({ source, draft: source });+ let current = state;+ if (state.source !== source) {+ current = { source, draft: source };+ setState(current);+ }+ const set = useCallback((draft: string) => setState((s) => ({ ...s, draft })), []);+ const reset = useCallback(() => setState((s) => ({ ...s, draft: s.source })), []);+ return [current.draft, set, reset];+}diff --git a/src/components/av/use-generation.ts b/src/components/av/use-generation.tsnew file mode 100644index 00000000..37fc8d33--- /dev/null+++ b/src/components/av/use-generation.ts@@ -0,0 +1,44 @@+"use client";++import { useQuery, useQueryClient } from "@tanstack/react-query";+import { useGenerationEvents } from "@/lib/api";+import type { Generation } from "@/lib/catalog/types";++const busy = (g?: Generation | null) => !!g && (g.status === "queued" || g.status === "running");++/** One generation, kept fresh by the shared live stream (and polling while it renders without it). */+export function useGeneration(id: string | null | undefined) {+ const qc = useQueryClient();+ const connected = useGenerationEvents((ev) => {+ if (id && ev.type === "generation" && ev.generation.id === id) qc.setQueryData(["generation", id], ev.generation);+ });+ return useQuery({+ queryKey: ["generation", id],+ enabled: !!id,+ queryFn: async () => {+ const res = await fetch(`/api/generations/${id}`);+ if (!res.ok) throw new Error(res.status === 404 ? "That result is gone" : `Request failed (${res.status})`);+ return (await res.json()) as Generation;+ },+ retry: (n, e) => n < 2 && (e as Error).message !== "That result is gone",+ refetchInterval: (q) => (busy(q.state.data) ? (connected ? 8000 : 1500) : false),+ });+}++/** Several generations by id (Katana steps, 3D results), refreshed the same way. */+export function useGenerationList(ids: string[]) {+ const qc = useQueryClient();+ const key = ids.join(",");+ const connected = useGenerationEvents((ev) => {+ if (ev.type === "generation" && ids.includes(ev.generation.id)) void qc.invalidateQueries({ queryKey: ["generation-list", key] });+ });+ return useQuery({+ queryKey: ["generation-list", key],+ enabled: ids.length > 0,+ queryFn: async () => {+ const all = await Promise.all(ids.map(async (id) => (await fetch(`/api/generations/${id}`)).json().catch(() => null) as Promise<Generation | null>));+ return all.filter((g): g is Generation => !!g && typeof g === "object" && "id" in g);+ },+ refetchInterval: (q) => (q.state.data?.some(busy) ? (connected ? 8000 : 1500) : false),+ });+}diff --git a/src/components/captions/captions-studio.tsx b/src/components/captions/captions-studio.tsxnew file mode 100644index 00000000..3fbd3fd5--- /dev/null+++ b/src/components/captions/captions-studio.tsx@@ -0,0 +1,401 @@+"use client";++import { Captions, Download, FileUp, Flame, Loader2, Sparkles, Wand2 } from "lucide-react";+import { useEffect, useMemo, useRef, useState } from "react";+import { toast } from "sonner";+import { Button } from "@/components/ui/button";+import { Label } from "@/components/ui/label";+import { Feed } from "@/components/studio/feed";+import type { SlotValue } from "@/components/studio/media-slot";+import { CueEditor, useCueEditor } from "@/components/av/cue-editor";+import { SourceLanguageSelect } from "@/components/av/language-picker";+import { MediaDrop } from "@/components/av/media-drop";+import { StepList } from "@/components/av/step-list";+import { Panel, ToolHero, ToolShell } from "@/components/av/tool-shell";+import { useGeneration } from "@/components/av/use-generation";+import { useCreateGeneration, useEngine, useGenerations, useHydrated } from "@/lib/api";+import { cueProblems } from "@/lib/av/cue-edit";+import { burnRequest, burnRouteFor, CAPTION_STYLES, OPEN_FONT_SIZE, previewText, styleById, transcribeRequest, usesCues, type CaptionLook, type CaptionPosition, type CaptionSize } from "@/lib/av/captions";+import { parseCues, toSrt, toVtt, type Cue } from "@/lib/cues";+import { cn } from "@/lib/utils";++const STORE = "fuobe.captions";++interface Saved {+ video: SlotValue;+ cues: Cue[];+ look: CaptionLook;+ transcriptId?: string;+}++function load(): Saved | null {+ try {+ const raw = localStorage.getItem(STORE);+ return raw ? (JSON.parse(raw) as Saved) : null;+ } catch {+ return null;+ }+}++const DEFAULT_LOOK: CaptionLook = { style: "clean", size: "M", position: "bottom" };++function download(name: string, text: string, type: string) {+ const url = URL.createObjectURL(new Blob([text], { type }));+ const a = document.createElement("a");+ a.href = url;+ a.download = name;+ a.click();+ setTimeout(() => URL.revokeObjectURL(url), 1000);+}++/** Captions (Video tools → Captions): transcribe, fix every line, style, burn in — or export .srt / .vtt. */+export function CaptionsStudio({ tabs }: { tabs?: React.ReactNode }) {+ // The last project comes back after a reload (this browser only), once hydrated.+ const hydrated = useHydrated();+ const saved = useMemo(() => (hydrated ? load() : undefined), [hydrated]);+ const [picked, setVideo] = useState<SlotValue | null | undefined>(undefined);+ const video = picked === undefined ? (saved?.video ?? null) : picked;+ const results = useGenerations({ features: ["captions"], kinds: ["video"], limit: 24 });+ return (+ <ToolShell title="Video tools" tabs={tabs}>+ {saved === undefined ? null : video && !video.uploading ? (+ <Editor+ key={video.ref}+ video={video}+ restored={saved?.video.ref === video.ref ? saved : null}+ onReplace={(v) => {+ setVideo(v);+ try {+ localStorage.removeItem(STORE);+ } catch {}+ }}+ />+ ) : (+ <div className="pb-6">+ <ToolHero title="Captions that say exactly what was said" subtitle="Transcribe the speech, fix any line and its timing, pick a style, then burn it in — or export .srt / .vtt." />+ <div className="mx-auto mt-8 max-w-[760px]">+ <MediaDrop kind="video" value={video} onChange={setVideo} title="Add a video to caption" hint="MP4, MOV or WebM up to 200 MB" />+ </div>+ </div>+ )}+ {(results.data?.length ?? 0) > 0 && (+ <section className="mt-10" aria-labelledby="captioned">+ <h3 id="captioned" className="mb-3 font-heading text-[22px]">+ Captioned videos+ </h3>+ <Feed items={results.data!} />+ </section>+ )}+ </ToolShell>+ );+}++function Editor({ video, restored, onReplace }: { video: SlotValue; restored: Saved | null; onReplace: (v: SlotValue | null) => void }) {+ const [engine] = useEngine();+ const create = useCreateGeneration();+ const editor = useCueEditor(restored?.cues ?? []);+ const [look, setLook] = useState<CaptionLook>(restored?.look ?? DEFAULT_LOOK);+ const [transcriptId, setTranscriptId] = useState<string | undefined>(restored?.transcriptId);+ const [source, setSource] = useState("auto");+ const [quick, setQuick] = useState(false);+ const transcript = useGeneration(transcriptId);+ const player = useRef<HTMLVideoElement>(null);+ const [time, setTime] = useState<number | undefined>(undefined);+ const [duration, setDuration] = useState<number | undefined>(undefined);+ const route = burnRouteFor(engine, quick);+ const { cues, dispatch } = editor;+ const loaded = useRef<string | null>(restored?.cues.length ? (restored.transcriptId ?? "restored") : null);++ // The finished transcript fills the editor once (later edits are yours).+ const t = transcript.data;+ useEffect(() => {+ if (!t || t.status !== "succeeded" || loaded.current === t.id) return;+ const out = t.outputs.find((o) => o.kind === "text");+ const list = Array.isArray(out?.meta?.cues) ? (out!.meta!.cues as Cue[]) : out?.text ? parseCues(out.text) : null;+ loaded.current = t.id;+ if (list?.length) {+ dispatch({ type: "reset", cues: list });+ toast.success(`${list.length} lines transcribed`);+ } else toast("No speech found in this clip");+ }, [t, dispatch]);++ // Keep the project in this browser.+ useEffect(() => {+ const id = setTimeout(() => {+ try {+ localStorage.setItem(STORE, JSON.stringify({ video, cues, look, transcriptId } satisfies Saved));+ } catch {}+ }, 400);+ return () => clearTimeout(id);+ }, [video, cues, look, transcriptId]);++ const transcribe = () =>+ create.mutate(transcribeRequest({ engine, video: video.ref, sourceLanguage: source }), {+ onSuccess: (items) => {+ loaded.current = null;+ setTranscriptId(items[0].id);+ },+ onError: (e) => toast.error((e as Error).message),+ });++ const importFile = useRef<HTMLInputElement>(null);+ const problems = cueProblems(cues, duration);+ const burn = () => {+ if (usesCues(route) && problems.length) return void toast(problems[0], { id: "captions-blocker" });+ let req;+ try {+ req = burnRequest({ route, video: video.ref, cues, look, sourceLanguage: source });+ } catch (e) {+ return void toast((e as Error).message);+ }+ create.mutate(req, {+ onSuccess: () => toast.success("Burning captions — it'll show under Captioned videos"),+ onError: (e) => toast.error((e as Error).message),+ });+ };+ const transcribing = t && (t.status === "queued" || t.status === "running");+ const name = (video.name ?? "captions").replace(/\.[a-z0-9]+$/i, "");++ return (+ <div className="grid gap-4 pt-4 lg:grid-cols-[minmax(0,6fr)_minmax(0,5fr)]">+ <div className="min-w-0 space-y-3 lg:sticky lg:top-20 lg:self-start">+ <Preview video={video} cues={cues} look={look} player={player} onTime={setTime} onDuration={setDuration} />+ <div className="flex flex-wrap items-center gap-1.5">+ <p className="min-w-0 flex-1 truncate text-[13px] text-muted-foreground">{video.name}</p>+ <Button variant="ghost" size="sm" className="rounded-full" onClick={() => onReplace(null)}>+ Another video+ </Button>+ </div>+ <StylePanel look={look} onChange={setLook} />+ </div>++ <div className="min-w-0 space-y-3">+ <Panel+ title="Lines"+ aside={+ <>+ <input+ ref={importFile}+ type="file"+ accept=".srt,.vtt,text/vtt,application/x-subrip"+ hidden+ onChange={async (e) => {+ const f = e.target.files?.[0];+ e.target.value = "";+ if (!f) return;+ const list = parseCues(await f.text());+ if (!list?.length) return void toast.error("That file has no timed lines (.srt or .vtt)");+ dispatch({ type: "reset", cues: list });+ toast.success(`${list.length} lines imported`);+ }}+ />+ <Button variant="ghost" size="sm" className="rounded-full" onClick={() => importFile.current?.click()}>+ <FileUp className="size-3.5" /> Import+ </Button>+ </>+ }+ >+ {!cues.length && (+ <div className="mb-3 rounded-xl bg-muted/60 p-3">+ <div className="flex flex-col gap-2 sm:flex-row sm:items-center">+ <Label htmlFor="cap-source" className="text-[13px] sm:w-28">+ Spoken language+ </Label>+ <SourceLanguageSelect id="cap-source" value={source} onChange={setSource} />+ </div>+ <Button className="mt-3 w-full rounded-full sm:w-auto" onClick={transcribe} disabled={create.isPending || !!transcribing}>+ {transcribing ? <Loader2 className="size-4 animate-spin" /> : <Captions className="size-4" />}+ {transcribing ? "Transcribing…" : "Transcribe the speech"}+ </Button>+ <p className="mt-2 text-[12px] text-muted-foreground">{engine === "open" ? "Qwen3-ASR on your ComfyUI (30 languages, detected)." : "ElevenLabs Scribe v2 (word timings, ≈ $0.008 per minute)."}</p>+ {t && <StepList className="mt-3" steps={[{ key: "t", label: "Transcript", g: t }]} />}+ </div>+ )}+ <CueEditor+ editor={editor}+ currentTime={time}+ onSeek={(s) => {+ if (player.current) player.current.currentTime = s;+ }}+ className="max-h-[60vh]"+ emptyHint="Transcribe the clip, import an .srt / .vtt, or write the lines yourself."+ />+ </Panel>++ <Panel title="Burn in">+ {engine === "cloud" && (+ <div role="radiogroup" aria-label="Burner" className="mb-3 grid gap-2 sm:grid-cols-2">+ <RouteCard on={!quick} onClick={() => setQuick(false)} icon={<Flame className="size-4" />} title="Your lines" note="VEED Subtitles burns your edited lines in your style (≈ $0.10 per minute)." />+ <RouteCard on={quick} onClick={() => setQuick(true)} icon={<Wand2 className="size-4" />} title="Quick karaoke" note="Auto Subtitle transcribes again and burns word-by-word captions — your edits aren't used." />+ </div>+ )}+ {engine === "open" && <p className="mb-3 text-[12px] text-muted-foreground">ComfyUI's caption burn-in draws your lines into the frames chunk by chunk and keeps the sound (CPU is fine, no model).</p>}+ <div className="flex flex-wrap items-center gap-2">+ <Button className={cn("rounded-full", usesCues(route) && problems.length > 0 && "bg-muted text-subtle-foreground hover:bg-muted")} onClick={burn} disabled={create.isPending}>+ {create.isPending ? <Loader2 className="size-4 animate-spin" /> : <Sparkles className="size-4" />} Burn captions+ </Button>+ <Button variant="outline" className="rounded-full" disabled={!cues.length} onClick={() => download(`${name}.srt`, toSrt(cues), "application/x-subrip")}>+ <Download className="size-3.5" /> .srt+ </Button>+ <Button variant="outline" className="rounded-full" disabled={!cues.length} onClick={() => download(`${name}.vtt`, toVtt(cues), "text/vtt")}>+ <Download className="size-3.5" /> .vtt+ </Button>+ </div>+ {usesCues(route) && problems.length > 0 && cues.length > 0 && <p className="mt-2 text-[12px] text-muted-foreground">Fix first: {problems.join(" · ")}</p>}+ </Panel>+ </div>+ </div>+ );+}++function RouteCard({ on, onClick, icon, title, note }: { on: boolean; onClick: () => void; icon: React.ReactNode; title: string; note: string }) {+ return (+ <button type="button" role="radio" aria-checked={on} onClick={onClick} className={cn("flex items-start gap-2.5 rounded-xl border p-2.5 text-left transition-colors", on ? "border-primary bg-brand-faint" : "hover:bg-accent")}>+ <span className={cn("mt-0.5 grid size-6 shrink-0 place-items-center rounded-md", on ? "bg-primary text-primary-foreground" : "bg-muted text-muted-foreground")}>{icon}</span>+ <span className="min-w-0">+ <span className="block text-[13px] font-semibold">{title}</span>+ <span className="block text-[12px] leading-snug text-muted-foreground">{note}</span>+ </span>+ </button>+ );+}++/** The video with the active line drawn the way the burner will draw it. */+function Preview({+ video,+ cues,+ look,+ player,+ onTime,+ onDuration,+}: {+ video: SlotValue;+ cues: Cue[];+ look: CaptionLook;+ player: React.RefObject<HTMLVideoElement | null>;+ onTime: (t: number) => void;+ onDuration: (t: number) => void;+}) {+ const [t, setT] = useState(0);+ const [h, setH] = useState(360);+ useEffect(() => {+ const el = player.current;+ if (!el) return;+ const ro = new ResizeObserver(() => setH(el.clientHeight || 360));+ ro.observe(el);+ return () => ro.disconnect();+ }, [player]);+ const style = styleById(look.style);+ const shown = previewText(cues, t, look);+ const color = look.color ?? style.color;+ const words = useMemo(() => shown?.text.split(" ") ?? [], [shown]);+ return (+ <div className="relative overflow-hidden rounded-2xl border bg-media">+ <video+ ref={player}+ src={video.ref}+ controls+ playsInline+ preload="metadata"+ onTimeUpdate={(e) => {+ setT(e.currentTarget.currentTime);+ onTime(e.currentTarget.currentTime);+ }}+ onLoadedMetadata={(e) => Number.isFinite(e.currentTarget.duration) && onDuration(e.currentTarget.duration)}+ className="max-h-[52vh] w-full object-contain"+ />+ {shown && (+ <div+ aria-live="off"+ className={cn("pointer-events-none absolute inset-x-[6%] flex justify-center text-center", look.position === "top" ? "top-[8%]" : look.position === "center" ? "top-1/2 -translate-y-1/2" : "bottom-[14%]")}+ >+ <span+ className={cn("leading-tight", style.box && "rounded-md bg-black/60 px-2 py-0.5")}+ style={{+ fontFamily: `${style.font}, var(--font-sans), sans-serif`,+ fontWeight: style.weight,+ fontSize: Math.max(11, (h * OPEN_FONT_SIZE[look.size]) / 100),+ color,+ textShadow: style.box ? undefined : "0 0 3px #000, 0 0 3px #000, 0 1px 2px #000",+ }}+ >+ {words.map((w, i) => (+ <span key={i} style={shown.highlight === i && style.highlight ? { color: style.highlight } : undefined}>+ {w}+ {i < words.length - 1 ? " " : ""}+ </span>+ ))}+ </span>+ </div>+ )}+ </div>+ );+}++const SIZES: CaptionSize[] = ["S", "M", "L"];+const POSITIONS: { id: CaptionPosition; label: string }[] = [+ { id: "top", label: "Top" },+ { id: "center", label: "Middle" },+ { id: "bottom", label: "Bottom" },+];++function StylePanel({ look, onChange }: { look: CaptionLook; onChange: (l: CaptionLook) => void }) {+ const seg = (on: boolean) => cn("h-7 rounded-full px-3 text-[12px] font-medium transition", on ? "bg-background text-foreground shadow-soft" : "text-muted-foreground hover:text-foreground");+ return (+ <Panel title="Style">+ <div role="radiogroup" aria-label="Caption style" className="grid grid-cols-3 gap-2 sm:grid-cols-6">+ {CAPTION_STYLES.map((s) => (+ <button+ key={s.id}+ type="button"+ role="radio"+ aria-checked={look.style === s.id}+ onClick={() => onChange({ ...look, style: s.id, color: undefined })}+ className={cn("flex flex-col items-center gap-1 rounded-xl border p-2 transition-colors", look.style === s.id ? "border-primary bg-brand-faint" : "hover:bg-accent")}+ >+ <span className={cn("grid h-9 w-full place-items-center rounded-md bg-[oklch(0.3_0.02_260)] text-[13px] leading-none", s.box && "px-1")} style={{ fontWeight: s.weight, fontFamily: `${s.font}, var(--font-sans), sans-serif` }}>+ <span className={cn(s.box && "rounded bg-black/70 px-1 py-0.5")} style={{ color: s.color, textShadow: s.box ? undefined : "0 0 2px #000" }}>+ {s.upper ? "AA" : "Aa"}+ {s.karaoke && <span style={{ color: s.highlight }}>a</span>}+ </span>+ </span>+ <span className="text-[11px] font-medium">{s.name}</span>+ </button>+ ))}+ </div>+ <div className="mt-3 flex flex-wrap items-center gap-x-4 gap-y-2">+ <div className="flex items-center gap-2">+ <span className="text-[12px] text-muted-foreground">Size</span>+ <div role="radiogroup" aria-label="Size" className="inline-flex rounded-full bg-muted p-0.5">+ {SIZES.map((s) => (+ <button key={s} type="button" role="radio" aria-checked={look.size === s} onClick={() => onChange({ ...look, size: s })} className={seg(look.size === s)}>+ {s}+ </button>+ ))}+ </div>+ </div>+ <div className="flex items-center gap-2">+ <span className="text-[12px] text-muted-foreground">Position</span>+ <div role="radiogroup" aria-label="Position" className="inline-flex rounded-full bg-muted p-0.5">+ {POSITIONS.map((p) => (+ <button key={p.id} type="button" role="radio" aria-checked={look.position === p.id} onClick={() => onChange({ ...look, position: p.id })} className={seg(look.position === p.id)}>+ {p.label}+ </button>+ ))}+ </div>+ </div>+ <label className="flex items-center gap-2 text-[12px] text-muted-foreground">+ Colour+ <input+ type="color"+ value={look.color ?? styleById(look.style).color}+ onChange={(e) => onChange({ ...look, color: e.target.value })}+ className="size-7 cursor-pointer rounded-full border bg-transparent p-0.5"+ aria-label="Caption colour"+ />+ </label>+ </div>+ <p className="mt-3 text-[12px] text-muted-foreground">Karaoke styles show a few words at a time on the open engine and highlight the spoken word on the cloud. The open burner places text at the top or the bottom.</p>+ </Panel>+ );+}diff --git a/src/components/dub/dub-studio.tsx b/src/components/dub/dub-studio.tsxnew file mode 100644index 00000000..bc1b0c43--- /dev/null+++ b/src/components/dub/dub-studio.tsx@@ -0,0 +1,442 @@+"use client";++import { ArrowLeft, AudioLines, ChevronRight, Cloud, Cpu, Download, Languages, Loader2, Mic2, Sparkles, Trash2, Wand2 } from "lucide-react";+import { useEffect, useMemo, useRef, useState } from "react";+import { toast } from "sonner";+import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, AlertDialogTrigger } from "@/components/ui/alert-dialog";+import { Button } from "@/components/ui/button";+import { Label } from "@/components/ui/label";+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";+import { Skeleton } from "@/components/ui/skeleton";+import { Switch } from "@/components/ui/switch";+import type { SlotValue } from "@/components/studio/media-slot";+import { CueEditor, useCueEditor } from "@/components/av/cue-editor";+import { SourceLanguageSelect, TargetLanguages } from "@/components/av/language-picker";+import { MediaDrop } from "@/components/av/media-drop";+import { StepList, type StepRow } from "@/components/av/step-list";+import { Panel, ToolHero, ToolShell } from "@/components/av/tool-shell";+import { useEngine } from "@/lib/api";+import { cueProblems } from "@/lib/av/cue-edit";+import { dubResult, languageStage, ONE_SHOT_MODELS, reviewCues, translateKey, type DubSessionView, type DubStage, type OneShotModel } from "@/lib/av/dub";+import { languageByCode, supportsTarget, type DubRoute } from "@/lib/av/languages";+import type { Cue } from "@/lib/cues";+import { cn } from "@/lib/utils";+import { useDubActions, useDubSessions } from "./hooks";++const ONE_SHOT: Record<OneShotModel, { name: string; note: string }> = {+ "heygen-translate": { name: "HeyGen Translate", note: "Lip-synced, 170+ languages and accents · ≈ $0.10 per second" },+ "heygen-translate-fast": { name: "HeyGen Translate Speed", note: "Faster and cheaper, lip-synced · ≈ $0.05 per second" },+ "elevenlabs-dubbing": { name: "ElevenLabs Dubbing", note: "Keeps each speaker's voice, no lip re-sync · ≈ $0.60 per minute" },+};++const ROUTE_LINE = {+ open: "Open source: MelBand RoFormer splits the voice from the music → Qwen3-ASR times it → your local LLM translates → you review → Chatterbox speaks in the cloned voice → InfiniteTalk re-syncs the lips → mixed back over the music.",+ cloud: "Cloud: ElevenLabs isolates the voice → Scribe v2 times it → Claude (or Ollama) translates → you review → ElevenLabs speaks and Chatterbox turns it into the speaker's voice → Sync Lipsync 3. The cloud route keeps the voice only — no cloud model here mixes the music back in.",+};++const STAGE: Record<DubStage, { label: string; tone: string }> = {+ preparing: { label: "Translating", tone: "bg-muted text-muted-foreground" },+ review: { label: "Ready to review", tone: "bg-highlight/30 text-highlight-foreground" },+ voicing: { label: "Voicing", tone: "bg-brand-faint text-brand-text" },+ done: { label: "Done", tone: "bg-success/15 text-foreground" },+ failed: { label: "Failed", tone: "bg-destructive/10 text-destructive" },+};++function StageBadge({ stage }: { stage: DubStage }) {+ const s = STAGE[stage];+ return <span className={cn("inline-flex h-5 shrink-0 items-center rounded-full px-2 text-[11px] font-medium", s.tone)}>{s.label}</span>;+}++/** Translate & dub (Audio → Translate): a new dub, the dubs in progress and, opened, one dub's review. */+export function DubStudio({ tabs }: { tabs?: React.ReactNode }) {+ const sessions = useDubSessions();+ const [openId, setOpenId] = useState<string | null>(null);+ // A dub removed elsewhere (another tab) just closes.+ const open = sessions.data?.find((s) => s.id === openId);+ return (+ <ToolShell title="Audio" tabs={tabs}>+ {open ? (+ <SessionView key={open.id} s={open} onBack={() => setOpenId(null)} />+ ) : (+ <>+ <NewDub onStarted={(id) => setOpenId(id)} />+ <RecentDubs sessions={sessions.data} loading={sessions.isLoading} onOpen={setOpenId} />+ </>+ )}+ </ToolShell>+ );+}++function NewDub({ onStarted }: { onStarted: (id: string) => void }) {+ const [engine] = useEngine();+ const { create } = useDubActions();+ const [video, setVideo] = useState<SlotValue | null>(null);+ const [mode, setMode] = useState<"steps" | "oneshot">("steps");+ const [model, setModel] = useState<OneShotModel>("heygen-translate");+ const [source, setSource] = useState("auto");+ const [targets, setTargets] = useState<string[]>(["es"]);+ const oneShot = mode === "oneshot" && engine === "cloud";+ const route: DubRoute = oneShot ? model : engine === "open" ? "open" : "cloud-steps";+ const usable = targets.filter((c) => {+ const l = languageByCode(c);+ return l && supportsTarget(route, l);+ });+ const blocker = !video ? "Add the video to translate" : video.uploading ? "Uploading…" : !usable.length ? "Pick a language to dub into" : null;+ const start = () => {+ if (blocker) return void toast(blocker, { id: "dub-blocker" });+ create.mutate(+ { engine, mode: oneShot ? "oneshot" : "steps", model: oneShot ? model : undefined, video: video!.ref, title: video!.name?.replace(/\.[a-z0-9]+$/i, ""), source, targets: usable },+ {+ onSuccess: (s) => {+ toast.success(oneShot ? `Dubbing into ${usable.length} language${usable.length === 1 ? "" : "s"}` : "Transcribing and translating");+ setVideo(null);+ onStarted(s.id);+ },+ onError: (e) => toast.error((e as Error).message),+ },+ );+ };+ return (+ <div className="pb-10">+ <ToolHero title="Speak every language" subtitle="Translate the speech, keep the speaker's voice and re-sync the lips. Review every line before it's spoken." />+ <div className="mx-auto mt-8 max-w-[760px] space-y-3">+ <MediaDrop kind="video" value={video} onChange={setVideo} title="Add the video to translate" hint="MP4, MOV or WebM up to 200 MB · one clear speaker works best" compact />+ <Panel title="How">+ <div role="radiogroup" aria-label="How to dub" className="grid gap-2 sm:grid-cols-2">+ <ModeCard on={!oneShot} icon={<Languages className="size-4" />} title="Review the script first" onClick={() => setMode("steps")} note="Transcribe and translate, edit every line, then voice it. Cloud and open source." />+ <ModeCard+ on={oneShot}+ disabled={engine === "open"}+ icon={<Wand2 className="size-4" />}+ title="One shot"+ onClick={() => setMode("oneshot")}+ note={engine === "open" ? "Cloud only — switch the engine to Cloud" : "HeyGen or ElevenLabs dub the whole video in one go."}+ />+ </div>+ {oneShot && (+ <div className="mt-3 flex flex-col gap-1.5 sm:flex-row sm:items-center">+ <Label htmlFor="dub-model" className="text-[13px] sm:w-32">+ Model+ </Label>+ <Select value={model} onValueChange={(v) => setModel(v as OneShotModel)}>+ <SelectTrigger id="dub-model" className="h-9 w-full rounded-full sm:w-64">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {ONE_SHOT_MODELS.map((m) => (+ <SelectItem key={m} value={m}>+ {ONE_SHOT[m].name}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ <p className="text-[12px] text-muted-foreground sm:ml-2">{ONE_SHOT[model].note}</p>+ </div>+ )}+ </Panel>+ <Panel title="Languages">+ <div className="space-y-3">+ <div className="flex flex-col gap-1.5 sm:flex-row sm:items-center">+ <Label htmlFor="dub-source" className="text-[13px] sm:w-32">+ Spoken language+ </Label>+ <SourceLanguageSelect id="dub-source" value={source} onChange={setSource} />+ </div>+ <div className="flex flex-col gap-1.5 sm:flex-row sm:items-start">+ <span className="pt-1.5 text-[13px] font-medium sm:w-32">Translate into</span>+ <div className="min-w-0 flex-1">+ <TargetLanguages+ value={targets}+ onChange={setTargets}+ available={(l) => supportsTarget(route, l)}+ unavailableHint={route === "open" ? "Chatterbox doesn't speak this one yet" : "This model doesn't offer it"}+ />+ {targets.length > usable.length && <p className="mt-1.5 text-[12px] text-muted-foreground">Crossed-out languages aren't available on this route and will be skipped.</p>}+ </div>+ </div>+ </div>+ </Panel>+ <div className="flex flex-col gap-3 pt-1 sm:flex-row sm:items-center">+ <p className="flex-1 text-[12px] leading-relaxed text-muted-foreground">+ {oneShot ? `${ONE_SHOT[model].name} returns the finished video for each language.` : engine === "open" ? ROUTE_LINE.open : ROUTE_LINE.cloud}+ </p>+ <Button size="lg" className={cn("shrink-0 rounded-full", blocker && "bg-muted text-subtle-foreground hover:bg-muted")} onClick={start} disabled={create.isPending} aria-describedby={blocker ? "dub-blocker" : undefined}>+ {create.isPending ? <Loader2 className="size-4 animate-spin" /> : <Sparkles className="size-4" />}+ {oneShot ? "Dub it" : "Translate"}+ </Button>+ </div>+ {blocker && (+ <p id="dub-blocker" className="sr-only">+ {blocker}+ </p>+ )}+ </div>+ </div>+ );+}++function ModeCard({ on, disabled, icon, title, note, onClick }: { on: boolean; disabled?: boolean; icon: React.ReactNode; title: string; note: string; onClick: () => void }) {+ return (+ <button+ type="button"+ role="radio"+ aria-checked={on}+ disabled={disabled}+ onClick={onClick}+ className={cn(+ "flex items-start gap-3 rounded-xl border p-3 text-left transition-colors",+ on ? "border-primary bg-brand-faint" : "hover:bg-accent",+ disabled && "cursor-not-allowed opacity-60 hover:bg-transparent",+ )}+ >+ <span className={cn("mt-0.5 grid size-7 shrink-0 place-items-center rounded-lg", on ? "bg-primary text-primary-foreground" : "bg-muted text-muted-foreground")}>{icon}</span>+ <span className="min-w-0">+ <span className="block text-[13px] font-semibold">{title}</span>+ <span className="mt-0.5 block text-[12px] leading-snug text-muted-foreground">{note}</span>+ </span>+ </button>+ );+}++function RecentDubs({ sessions, loading, onOpen }: { sessions?: DubSessionView[]; loading: boolean; onOpen: (id: string) => void }) {+ if (loading)+ return (+ <div className="mx-auto max-w-[760px] space-y-2">+ <Skeleton className="h-5 w-28" />+ <Skeleton className="h-16 w-full rounded-2xl" />+ <Skeleton className="h-16 w-full rounded-2xl" />+ </div>+ );+ if (!sessions?.length) return null;+ return (+ <section className="mx-auto max-w-[760px]" aria-labelledby="recent-dubs">+ <h3 id="recent-dubs" className="mb-2 font-heading text-[22px]">+ Your dubs+ </h3>+ <ul className="space-y-2">+ {sessions.map((s) => (+ <li key={s.id}>+ <button type="button" onClick={() => onOpen(s.id)} className="flex w-full min-w-0 items-center gap-3 rounded-2xl border bg-background p-3 text-left transition-colors hover:bg-accent">+ <span className="grid size-10 shrink-0 place-items-center rounded-xl bg-brand-faint text-brand-text">{s.engine === "open" ? <Cpu className="size-4" /> : <Cloud className="size-4" />}</span>+ <span className="min-w-0 flex-1">+ <span className="block truncate text-[14px] font-medium">{s.title}</span>+ <span className="mt-1 flex flex-wrap gap-1">+ {s.targets.map((c) => (+ <span key={c} className="inline-flex items-center gap-1 text-[12px] text-muted-foreground">+ {languageByCode(c)?.name ?? c} <StageBadge stage={languageStage(s, c)} />+ </span>+ ))}+ </span>+ </span>+ <ChevronRight className="size-4 shrink-0 text-muted-foreground" />+ </button>+ </li>+ ))}+ </ul>+ </section>+ );+}++function prepareRows(s: DubSessionView, lang: string): StepRow[] {+ const keys = s.engine === "open" ? ["stems", "words"] : ["voice", "words"];+ const label: Record<string, string> = { stems: "Voice and background", voice: "Clean voice", words: "Transcript" };+ return [...keys.map((k) => ({ key: k, label: label[k], g: s.generations[s.prepare?.[k] ?? ""] })), { key: "t", label: `Translate into ${languageByCode(lang)?.name ?? lang}`, g: s.generations[s.prepare?.[translateKey(lang)] ?? ""] }];+}++function voiceRows(s: DubSessionView, lang: string): StepRow[] {+ const run = s.voices?.[lang]?.at(-1);+ if (!run) return [];+ const label: Record<string, string> = { speech: s.engine === "open" ? "Speech in their voice" : "Speech", clone: "Their voice", lips: "Lips re-synced", film: run.lipsync && s.engine === "cloud" ? "Lips re-synced" : "Dubbed video" };+ return Object.entries(run.ids).map(([k, id]) => ({ key: k, label: label[k] ?? k, g: s.generations[id] }));+}++function SessionView({ s, onBack }: { s: DubSessionView; onBack: () => void }) {+ const { remove } = useDubActions();+ const [lang, setLang] = useState(s.targets[0]);+ const video = useRef<HTMLVideoElement>(null);+ const [time, setTime] = useState<number | undefined>(undefined);+ const stage = languageStage(s, lang);+ const result = dubResult(s, lang);+ return (+ <div className="pt-4 pb-10">+ <div className="mb-4 flex min-w-0 items-center gap-2">+ <Button variant="ghost" size="sm" className="-ml-2 rounded-full" onClick={onBack}>+ <ArrowLeft className="size-4" /> All dubs+ </Button>+ <h2 className="min-w-0 flex-1 truncate font-heading text-[22px] leading-tight">{s.title}</h2>+ <AlertDialog>+ <AlertDialogTrigger asChild>+ <Button variant="ghost" size="icon-sm" className="rounded-full" aria-label="Remove this dub">+ <Trash2 className="size-4" />+ </Button>+ </AlertDialogTrigger>+ <AlertDialogContent>+ <AlertDialogHeader>+ <AlertDialogTitle>Remove this dub?</AlertDialogTitle>+ <AlertDialogDescription>The review and its steps leave this list. The videos and audio it made stay in your Library.</AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <AlertDialogCancel>Keep it</AlertDialogCancel>+ <AlertDialogAction+ onClick={() =>+ remove.mutate(s.id, {+ onSuccess: () => {+ toast("Dub removed");+ onBack();+ },+ onError: (e) => toast.error((e as Error).message),+ })+ }+ >+ Remove+ </AlertDialogAction>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>+ </div>++ <div role="tablist" aria-label="Languages" className="scrollbar-none mb-4 flex gap-1.5 overflow-x-auto">+ {s.targets.map((c) => (+ <button+ key={c}+ role="tab"+ aria-selected={c === lang}+ onClick={() => setLang(c)}+ className={cn("inline-flex h-8 shrink-0 items-center gap-2 rounded-full px-3 text-[13px] font-medium transition-colors", c === lang ? "bg-foreground text-background" : "bg-secondary hover:bg-accent")}+ >+ {languageByCode(c)?.name ?? c}+ <span className={cn("size-1.5 rounded-full", { preparing: "bg-subtle-foreground", review: "bg-highlight", voicing: "bg-primary", done: "bg-success", failed: "bg-destructive" }[languageStage(s, c)])} />+ </button>+ ))}+ </div>++ <div className="grid gap-4 lg:grid-cols-[minmax(0,5fr)_minmax(0,6fr)]">+ <div className="space-y-3 lg:sticky lg:top-20 lg:self-start">+ <div className="overflow-hidden rounded-2xl border bg-media">+ <video ref={video} src={s.video} controls playsInline preload="metadata" onTimeUpdate={(e) => setTime(e.currentTarget.currentTime)} className="max-h-[42vh] w-full object-contain" />+ </div>+ <p className="text-[12px] text-muted-foreground">Original · {s.source === "auto" ? "language detected" : (languageByCode(s.source)?.name ?? s.source)}</p>+ {result && <ResultCard s={s} lang={lang} />}+ </div>+ <div className="min-w-0 space-y-3">+ {s.mode === "oneshot" ? (+ <Panel title={`Dub into ${languageByCode(lang)?.name ?? lang}`} aside={<StageBadge stage={stage} />}>+ <StepList steps={[{ key: "dub", label: ONE_SHOT[s.model ?? "heygen-translate"].name, g: s.generations[s.oneshot?.[lang] ?? ""] }]} />+ </Panel>+ ) : (+ <>+ <Panel title="Translation" aside={<StageBadge stage={stage} />}>+ <StepList steps={prepareRows(s, lang)} />+ </Panel>+ {stage === "preparing" ? (+ <Panel>+ <p className="text-[13px] text-muted-foreground">Transcribing and translating. You'll review every line here before anything is spoken.</p>+ </Panel>+ ) : stage === "failed" && !s.voices?.[lang]?.length ? (+ <Panel>+ <p className="text-[13px] text-muted-foreground">A step failed (see above). Start a new dub to try again — check the clip has clear speech.</p>+ </Panel>+ ) : (+ <Review+ key={`${s.id}:${lang}`}+ s={s}+ lang={lang}+ time={time}+ onSeek={(t) => {+ if (video.current) video.current.currentTime = t;+ }}+ />+ )}+ </>+ )}+ </div>+ </div>+ </div>+ );+}++function ResultCard({ s, lang }: { s: DubSessionView; lang: string }) {+ const g = dubResult(s, lang)!;+ const out = g.outputs.find((o) => o.kind === "video");+ if (!out) return null;+ const name = `${s.title} · ${languageByCode(lang)?.name ?? lang}.mp4`;+ return (+ <Panel+ title={`Dubbed · ${languageByCode(lang)?.name ?? lang}`}+ aside={+ <Button asChild variant="outline" size="sm" className="rounded-full">+ <a href={out.url} download={name}>+ <Download className="size-3.5" /> Download+ </a>+ </Button>+ }+ >+ <video src={out.url} controls playsInline preload="metadata" className="max-h-[42vh] w-full rounded-xl bg-media object-contain" />+ {g.provider === "mock" && <p className="mt-2 text-[12px] text-muted-foreground">Demo result — connect a provider (or start ComfyUI) to dub for real.</p>}+ {s.engine === "cloud" && s.mode === "steps" && <p className="mt-2 text-[12px] text-muted-foreground">Voice only: the cloud route can't mix the original music back in yet.</p>}+ </Panel>+ );+}++function Review({ s, lang, time, onSeek }: { s: DubSessionView; lang: string; time?: number; onSeek: (t: number) => void }) {+ const { saveDraft, voice } = useDubActions();+ const initial = useMemo(() => reviewCues(s, lang) ?? [], [s, lang]);+ const editor = useCueEditor(initial);+ const [lipsync, setLipsync] = useState(true);+ const stage = languageStage(s, lang);+ const runs = s.voices?.[lang] ?? [];+ // Autosave the reviewed lines shortly after the last edit (the video's time updates don't restart the wait).+ const [savedBody, setSavedBody] = useState(() => JSON.stringify(initial));+ const cues = editor.cues;+ const save = useRef(saveDraft.mutate);+ useEffect(() => {+ save.current = saveDraft.mutate;+ });+ const body = JSON.stringify(cues);+ const dirty = body !== savedBody;+ useEffect(() => {+ if (body === savedBody) return;+ const t = setTimeout(() => {+ setSavedBody(body);+ save.current({ id: s.id, lang, cues: JSON.parse(body) as Cue[] }, { onError: (e) => toast.error((e as Error).message) });+ }, 800);+ return () => clearTimeout(t);+ }, [body, savedBody, s.id, lang]);+ const problems = cueProblems(cues);+ const name = languageByCode(lang)?.name ?? lang;+ const start = (c: Cue[]) =>+ voice.mutate(+ { id: s.id, lang, cues: c, lipsync },+ { onSuccess: () => toast.success(`Voicing ${name}`), onError: (e) => toast.error((e as Error).message) },+ );+ return (+ <>+ <Panel+ title={`Review · ${name}`}+ aside={<span className="text-[12px] text-muted-foreground">{saveDraft.isPending || dirty ? "Saving…" : "Saved"}</span>}+ >+ <CueEditor editor={editor} currentTime={time} onSeek={onSeek} className="max-h-[56vh]" emptyHint="The translation has no lines." />+ </Panel>+ <Panel>+ <div className="flex flex-col gap-3 sm:flex-row sm:items-center">+ <div className="flex flex-1 items-center gap-2">+ <Switch id={`lips-${lang}`} checked={lipsync} onCheckedChange={setLipsync} />+ <Label htmlFor={`lips-${lang}`} className="text-[13px]">+ Re-sync the lips+ </Label>+ <span className="text-[12px] text-muted-foreground">{s.engine === "open" ? "InfiniteTalk · up to 40 s of speech" : "Sync Lipsync 3"}</span>+ </div>+ <Button+ className={cn("rounded-full", problems.length && "bg-muted text-subtle-foreground hover:bg-muted")}+ disabled={voice.isPending || stage === "voicing"}+ onClick={() => (problems.length ? toast(problems[0], { id: "dub-blocker" }) : start(cues))}+ >+ {voice.isPending || stage === "voicing" ? <Loader2 className="size-4 animate-spin" /> : runs.length ? <Mic2 className="size-4" /> : <AudioLines className="size-4" />}+ {stage === "voicing" ? "Voicing…" : runs.length ? "Voice again" : `Voice it in ${name}`}+ </Button>+ </div>+ {runs.length > 0 && <StepList steps={voiceRows(s, lang)} className="mt-4" />}+ </Panel>+ </>+ );+}diff --git a/src/components/dub/hooks.ts b/src/components/dub/hooks.tsnew file mode 100644index 00000000..baf94e4c--- /dev/null+++ b/src/components/dub/hooks.ts@@ -0,0 +1,72 @@+"use client";++import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";+import { useGenerationEvents } from "@/lib/api";+import type { DubSessionView, OneShotModel } from "@/lib/av/dub";+import type { Cue } from "@/lib/cues";+import type { Engine, Generation } from "@/lib/catalog/types";++async function json<T>(res: Response): Promise<T> {+ const body = (await res.json().catch(() => ({}))) as T & { error?: string };+ if (!res.ok) throw new Error(body.error ?? `Request failed (${res.status})`);+ return body;+}++const active = (gs: Generation[]) => gs.some((g) => g.status === "queued" || g.status === "running");++/** Recent dubs; refreshed when one of their steps changes on the live stream. */+export function useDubSessions() {+ const qc = useQueryClient();+ const connected = useGenerationEvents((ev) => {+ if (ev.type === "generation" && ev.generation.feature === "dub") void qc.invalidateQueries({ queryKey: ["dub"] });+ });+ return useQuery({+ queryKey: ["dub"],+ queryFn: async () => (await json<{ items: DubSessionView[] }>(await fetch("/api/dub"))).items,+ refetchInterval: (q) => (q.state.data?.some((s) => active(Object.values(s.generations))) ? (connected ? 8000 : 2000) : false),+ });+}++export interface NewDub {+ engine: Engine;+ mode: "oneshot" | "steps";+ video: string;+ title?: string;+ source?: string;+ targets: string[];+ model?: OneShotModel;+}++export function useDubActions() {+ const qc = useQueryClient();+ const put = (s: DubSessionView) => qc.setQueryData<DubSessionView[]>(["dub"], (xs) => (xs ? [s, ...xs.filter((x) => x.id !== s.id)] : [s]));+ const create = useMutation({+ mutationFn: async (body: NewDub) => json<DubSessionView>(await fetch("/api/dub", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) })),+ onSuccess: (s) => {+ put(s);+ void qc.invalidateQueries({ queryKey: ["generations"] });+ },+ });+ const saveDraft = useMutation({+ mutationFn: async ({ id, lang, cues }: { id: string; lang: string; cues: Cue[] }) =>+ json<DubSessionView>(await fetch(`/api/dub/${id}`, { method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ lang, cues }) })),+ onSuccess: put,+ });+ const voice = useMutation({+ mutationFn: async ({ id, lang, cues, lipsync }: { id: string; lang: string; cues?: Cue[]; lipsync?: boolean }) =>+ json<DubSessionView>(await fetch(`/api/dub/${id}/voice`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ lang, cues, lipsync }) })),+ onSuccess: (s) => {+ put(s);+ void qc.invalidateQueries({ queryKey: ["generations"] });+ },+ });+ const remove = useMutation({+ mutationFn: async (id: string) => {+ const res = await fetch(`/api/dub/${id}`, { method: "DELETE" });+ if (!res.ok && res.status !== 404) throw new Error("Couldn't remove it");+ return id;+ },+ onSuccess: (id) => qc.setQueryData<DubSessionView[]>(["dub"], (xs) => xs?.filter((x) => x.id !== id)),+ });+ return { create, saveDraft, voice, remove };+}diff --git a/src/components/studio/mode-studio.tsx b/src/components/studio/mode-studio.tsxindex 08c5a96d..523110e1 100644--- a/src/components/studio/mode-studio.tsx+++ b/src/components/studio/mode-studio.tsx@@ -15,7 +15,7 @@ export interface ModeTab {}/** Underline tabs on their own row under the page title; they scroll sideways (with faded edges) on phones. */-function ModeTabs({ tabs, current }: { tabs: ModeTab[]; current: string }) {+export function ModeTabs({ tabs, current }: { tabs: ModeTab[]; current: string }) {const [ref, fade] = useEdgeFade<HTMLDivElement>();const active = useRef<HTMLAnchorElement>(null);// Keep the selected tab in view when the row scrolls (only the row: the page stays put).diff --git a/src/components/studio/mode-switch-studio.tsx b/src/components/studio/mode-switch-studio.tsxindex f65228f6..a2e72a12 100644--- a/src/components/studio/mode-switch-studio.tsx+++ b/src/components/studio/mode-switch-studio.tsx@@ -19,7 +19,10 @@ import {} from "@/lib/studios";import { studioCatalog } from "@/lib/studio-catalog";import { HUB_MODES, modeHref, type HubKind } from "@/lib/hubs";-import { ModeStudio } from "./mode-studio";+import { CaptionsStudio } from "@/components/captions/captions-studio";+import { DubStudio } from "@/components/dub/dub-studio";+import { TrimTool } from "@/components/av/trim-tool";+import { ModeStudio, ModeTabs } from "./mode-studio";import type { StudioConfig } from "./studio-context";const CONFIGS: Record<HubKind, Record<string, StudioConfig>> = {@@ -42,6 +45,12 @@ const CONFIGS: Record<HubKind, Record<string, StudioConfig>> = {},};+/** Modes that are their own tool rather than a composer studio (Translate & dub, Captions, Trim). */+const TOOLS: Partial<Record<HubKind, Record<string, (p: { tabs: React.ReactNode }) => React.ReactNode>>> = {+ audio: { translate: ({ tabs }) => <DubStudio tabs={tabs} /> },+ "video-tools": { captions: ({ tabs }) => <CaptionsStudio tabs={tabs} />, trim: ({ tabs }) => <TrimTool tabs={tabs} /> },+};+const HUB_TITLE: Record<HubKind, string> = { upscale: "Upscale", audio: "Audio", "video-tools": "Video tools" };/**@@ -51,9 +60,11 @@ const HUB_TITLE: Record<HubKind, string> = { upscale: "Upscale", audio: "Audio",*/export function ModeSwitchStudio({ kind, mode }: { kind: HubKind; mode?: string }) {const current = mode ?? HUB_MODES[kind][0].id;+ const tabs = HUB_MODES[kind].map((m) => ({ id: m.id, label: m.label, href: modeHref(kind, m.id) }));+ const Tool = TOOLS[kind]?.[current];+ if (Tool) return <Tool tabs={<ModeTabs tabs={tabs} current={current} />} />;const config = CONFIGS[kind][current];if (!config) notFound();- const tabs = HUB_MODES[kind].map((m) => ({ id: m.id, label: m.label, href: modeHref(kind, m.id) }));return <ModeStudio key={current} tabs={tabs} current={current} config={config} catalog={studioCatalog(config)} />;}diff --git a/src/lib/av/captions.ts b/src/lib/av/captions.tsnew file mode 100644index 00000000..390316fa--- /dev/null+++ b/src/lib/av/captions.ts@@ -0,0 +1,187 @@+import { toSrt, type Cue } from "@/lib/cues";+import type { Engine, GenerationRequest } from "@/lib/catalog/types";++/**+ * Caption styles and how each burner takes them. The edited cue list is burned as-is: on the open+ * engine by ComfyUI's caption burn-in (core TextOverlay, cues in params.extra.cues), on the cloud by+ * VEED Subtitles from SRT text (srt_content skips its own transcription). Auto Subtitle is the+ * "quick" route: it transcribes and burns in one call (word-by-word karaoke), without your edits.+ */+export const CAPTIONS_FEATURE = "captions";++export type CaptionSize = "S" | "M" | "L";+export type CaptionPosition = "top" | "center" | "bottom";++export interface CaptionStyle {+ id: string;+ name: string;+ /** Google font the cloud burners render with (and the preview uses where loaded). */+ font: string;+ weight: 400 | 700 | 900;+ /** Text colour (hex). */+ color: string;+ /** Word-by-word: a few words at a time (open), the spoken word highlighted (cloud dynamic styles / Auto Subtitle). */+ karaoke: boolean;+ /** Highlight colour for karaoke (hex). */+ highlight?: string;+ /** A dark box behind the text instead of an outline. */+ box?: boolean;+ /** VEED's own preset this style starts from. */+ veed: string;+ /** Uppercase text (bold social styles). */+ upper?: boolean;+}++export const CAPTION_STYLES: CaptionStyle[] = [+ { id: "clean", name: "Clean", font: "Inter", weight: 700, color: "#ffffff", karaoke: false, veed: "simple" },+ { id: "bold", name: "Bold pop", font: "Montserrat", weight: 900, color: "#ffd400", karaoke: false, veed: "beans", upper: true },+ { id: "karaoke", name: "Karaoke", font: "Montserrat", weight: 900, color: "#ffffff", karaoke: true, highlight: "#8b5cf6", veed: "glide", upper: true },+ { id: "boxed", name: "Boxed", font: "Inter", weight: 700, color: "#ffffff", karaoke: false, box: true, veed: "backdrop" },+ { id: "subtle", name: "Subtle", font: "Inter", weight: 400, color: "#f5f5f5", karaoke: false, veed: "plain" },+ { id: "neon", name: "Neon", font: "Poppins", weight: 700, color: "#00e5ff", karaoke: true, highlight: "#ffffff", veed: "fusion" },+];++export const styleById = (id: string | undefined) => CAPTION_STYLES.find((s) => s.id === id) ?? CAPTION_STYLES[0];++export interface CaptionLook {+ style: string;+ size: CaptionSize;+ position: CaptionPosition;+ /** Overrides the style's colour. */+ color?: string;+}++/** The open burner's text size: % of the frame height. */+export const OPEN_FONT_SIZE: Record<CaptionSize, number> = { S: 4.5, M: 6, L: 8 };+/** Auto Subtitle's font size (px at its render size). */+const AUTO_FONT_SIZE: Record<CaptionSize, number> = { S: 60, M: 90, L: 120 };++/** Auto Subtitle's colour names: the nearest one to a hex colour. */+const NAMED: [string, [number, number, number]][] = [+ ["white", [255, 255, 255]],+ ["black", [0, 0, 0]],+ ["red", [230, 40, 40]],+ ["green", [40, 200, 80]],+ ["blue", [40, 90, 230]],+ ["yellow", [255, 212, 0]],+ ["orange", [255, 140, 0]],+ ["purple", [139, 92, 246]],+ ["pink", [244, 114, 182]],+ ["brown", [140, 90, 40]],+ ["gray", [128, 128, 128]],+ ["cyan", [0, 229, 255]],+ ["magenta", [230, 0, 230]],+];++export function nearestColorName(hex: string): string {+ const m = /^#?([0-9a-f]{6})$/i.exec(hex.trim());+ if (!m) return "white";+ const n = parseInt(m[1], 16);+ const rgb = [(n >> 16) & 255, (n >> 8) & 255, n & 255];+ let best = NAMED[0];+ let bestD = Infinity;+ for (const c of NAMED) {+ const d = c[1].reduce((acc, v, i) => acc + (v - rgb[i]) ** 2, 0);+ if (d < bestD) {+ bestD = d;+ best = c;+ }+ }+ return best[0];+}++export type BurnRoute = "open" | "veed" | "auto";++export const BURN_MODELS: Record<BurnRoute, string> = { open: "oss-captions-burnin", veed: "veed-subtitles", auto: "auto-subtitle" };++/** Which burner a route uses on an engine ("auto" is cloud only, "open" is the open engine's). */+export const burnRouteFor = (engine: Engine, quick: boolean): BurnRoute => (engine === "open" ? "open" : quick ? "auto" : "veed");++/** Whether a route burns your edited lines (Auto Subtitle transcribes again by itself). */+export const usesCues = (route: BurnRoute) => route !== "auto";++const upper = (cues: Cue[], on?: boolean) => (on ? cues.map((c) => ({ ...c, text: c.text.toUpperCase() })) : cues);++/** The burn job for a style: the model, its settings (params.extra) and the cues it takes. */+export function burnRequest(o: { route: BurnRoute; video: string; cues: Cue[]; look: CaptionLook; sourceLanguage?: string }): GenerationRequest {+ const style = styleById(o.look.style);+ const color = o.look.color ?? style.color;+ const cues = upper(o.cues.filter((c) => c.text.trim()), style.upper);+ const base = { feature: CAPTIONS_FEATURE, modelId: BURN_MODELS[o.route], op: "captions" as const, inputs: { video: o.video } };+ if (o.route === "open") {+ if (!cues.length) throw new Error("There are no lines to burn in");+ return {+ ...base,+ params: {+ extra: {+ cues: cues.map((c) => ({ start: c.start, end: c.end, text: c.text.trim() })),+ fontSize: OPEN_FONT_SIZE[o.look.size],+ fontColor: color,+ // The open burner places text at the top or the bottom.+ captionPosition: o.look.position === "top" ? "top" : "bottom",+ wordsPerCaption: style.karaoke ? 3 : 0,+ },+ },+ };+ }+ if (o.route === "veed") {+ if (!cues.length) throw new Error("There are no lines to burn in");+ return {+ ...base,+ params: {+ extra: {+ preset: style.veed,+ srt_content: toSrt(cues),+ "customization.position": o.look.position,+ "customization.shadow": style.box ? "none" : "mid",+ "customization.text_customizations.baseline.font": style.font,+ "customization.text_customizations.baseline.weight": style.weight,+ "customization.text_customizations.baseline.color": color,+ ...(style.highlight && { "customization.text_customizations.highlighted.color": style.highlight }),+ },+ },+ };+ }+ return {+ ...base,+ params: {+ ...(o.sourceLanguage && o.sourceLanguage !== "auto" && { sourceLanguage: o.sourceLanguage }),+ extra: {+ font_name: style.font,+ font_weight: style.weight >= 900 ? "black" : style.weight >= 700 ? "bold" : "normal",+ font_color: nearestColorName(color),+ highlight_color: nearestColorName(style.highlight ?? color),+ position: o.look.position,+ font_size: AUTO_FONT_SIZE[o.look.size],+ words_per_subtitle: style.karaoke ? 3 : 6,+ background_color: style.box ? "black" : "none",+ ...(style.box && { background_opacity: 0.6 }),+ },+ },+ };+}++/** The transcription job: the engine's transcriber, the spoken language if known. */+export function transcribeRequest(o: { engine: Engine; video: string; modelId?: string; sourceLanguage?: string }): GenerationRequest {+ return {+ feature: CAPTIONS_FEATURE,+ modelId: o.modelId ?? (o.engine === "open" ? "oss-qwen3-asr" : "scribe-v2"),+ op: "transcribe",+ inputs: { video: o.video },+ ...(o.sourceLanguage && o.sourceLanguage !== "auto" && { params: { sourceLanguage: o.sourceLanguage } }),+ };+}++/** The words shown at time `t` (karaoke styles show a few words at a time), for the live preview. */+export function previewText(cues: Cue[], t: number, look: CaptionLook): { text: string; highlight?: number } | null {+ const c = cues.find((x) => t >= x.start && t < x.end);+ if (!c) return null;+ const style = styleById(look.style);+ const text = style.upper ? c.text.toUpperCase() : c.text;+ if (!style.karaoke) return { text };+ const words = text.split(/\s+/).filter(Boolean);+ if (!words.length) return null;+ const i = Math.min(words.length - 1, Math.floor(((t - c.start) / Math.max(0.01, c.end - c.start)) * words.length));+ const group = Math.floor(i / 3) * 3;+ return { text: words.slice(group, group + 3).join(" "), highlight: i - group };+}diff --git a/src/lib/hubs.ts b/src/lib/hubs.tsindex 36e2e1c8..d3da001a 100644--- a/src/lib/hubs.ts+++ b/src/lib/hubs.ts@@ -23,6 +23,8 @@ export const HUB_MODES: Record<HubKind, { id: string; label: string }[]> = {{ id: "matte", label: "Remove background" },{ id: "relight", label: "Relight" },{ id: "depth", label: "Depth map" },+ { id: "captions", label: "Captions" },+ { id: "trim", label: "Trim" },{ id: "join", label: "Join clips" },{ id: "colors", label: "Match colors" },],diff --git a/src/lib/studios.ts b/src/lib/studios.tsindex 70476e68..68759b34 100644--- a/src/lib/studios.ts+++ b/src/lib/studios.ts@@ -192,7 +192,7 @@ export const SFX_STUDIO: StudioConfig = {ops: ["sfx"],feed: { kind: "audio", features: ["audio"] },slots: [],- defaultModels: { cloud: "mirelo-sfx-2", open: "" },+ defaultModels: { cloud: "mirelo-sfx-2", open: "oss-stable-audio-3" },suggestions: ["Thunder rolling over a quiet forest", "Footsteps on gravel, distant birds", "Sci-fi door whooshing open"],};@@ -213,12 +213,13 @@ export const FOLEY_STUDIO: StudioConfig = {feature: "audio",title: "Audio",hero: "Add sound to a video",+ subtitle: "Foley in sync with the picture: Mirelo SFX 2.0 on the cloud, HunyuanVideo-Foley or MMAudio on your ComfyUI.",placeholder: "Optional: describe the sound, e.g. “footsteps on gravel, distant birds”",kind: "video",ops: ["v2a"],feed: { features: ["audio"] },slots: [{ key: "video", label: "Video", accept: "video", required: true }],- defaultModels: { cloud: "mirelo-sfx-2-video", open: "oss-mmaudio" },+ defaultModels: { cloud: "mirelo-sfx-2-video", open: "oss-hunyuan-foley-video" },promptOptional: true,};