Skip to content

armgit / fuobe

Public Imported from GitHub
0

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.

Dub studio: prices before each step, review edits saved on leave, readable badge

Claude032b10fa1eb6
diff --git a/src/components/av/frame-sampler.ts b/src/components/av/frame-sampler.ts
index ce4451c8..107bb91c 100644
--- a/src/components/av/frame-sampler.ts
+++ b/src/components/av/frame-sampler.ts
@@ -34,7 +34,36 @@ function once<K extends keyof HTMLMediaElementEventMap>(el: HTMLMediaElement, ev
});
}
-/** Load a video's metadata in a detached element: its duration and size. */
+const known = (d: number) => Number.isFinite(d) && d > 0;
+
+/**
+ * A clip's real length. MediaRecorder WebM (screen and turntable recordings) has no duration in its
+ * header, so the element reports Infinity: seeking far past the end makes the browser scan for the
+ * last frame and report the real length, then the clip is rewound. Null when it never tells.
+ */
+export function realDuration(v: HTMLMediaElement, ms = 8000): Promise<number | null> {
+ if (known(v.duration)) return Promise.resolve(v.duration);
+ return new Promise((resolve) => {
+ const check = () => known(v.duration) && finish(v.duration);
+ const finish = (d: number | null) => {
+ clearTimeout(timer);
+ for (const ev of ["durationchange", "timeupdate", "seeked"] as const) v.removeEventListener(ev, check);
+ try {
+ v.currentTime = 0;
+ } catch {}
+ resolve(d);
+ };
+ const timer = setTimeout(() => finish(null), ms);
+ for (const ev of ["durationchange", "timeupdate", "seeked"] as const) v.addEventListener(ev, check);
+ try {
+ v.currentTime = 1e101;
+ } catch {
+ finish(null);
+ }
+ });
+}
+
+/** Load a video's metadata in a detached element: its duration (found when the header has none) and size. */
export async function openVideo(src: string): Promise<HTMLVideoElement> {
const v = document.createElement("video");
v.muted = true;
@@ -43,6 +72,10 @@ export async function openVideo(src: string): Promise<HTMLVideoElement> {
v.crossOrigin = "anonymous";
v.src = src;
if (v.readyState < 1) await once(v, "loadedmetadata");
+ if (!known(v.duration) && !(await realDuration(v))) {
+ releaseVideo(v);
+ throw new Error("This video doesn't say how long it is — try an MP4, or re-save the recording");
+ }
return v;
}
diff --git a/src/components/av/media-drop.tsx b/src/components/av/media-drop.tsx
index 8b6c8dac..e8e57b5c 100644
--- a/src/components/av/media-drop.tsx
+++ b/src/components/av/media-drop.tsx
@@ -7,6 +7,7 @@ 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";
+import { realDuration } from "./frame-sampler";
/**
* A large drop zone for the one video (or photo) a tool works on: drop, click or pick from the
@@ -93,7 +94,12 @@ export function MediaDrop({
controls
playsInline
preload="metadata"
- onLoadedMetadata={(e) => Number.isFinite(e.currentTarget.duration) && onDuration?.(e.currentTarget.duration)}
+ onLoadedMetadata={(e) => {
+ const el = e.currentTarget;
+ if (Number.isFinite(el.duration) && el.duration > 0) return onDuration?.(el.duration);
+ // A recording with no length in its header (MediaRecorder WebM): find it, else fall back to typed times.
+ void realDuration(el).then((d) => (d ? onDuration?.(d) : onUnreadable?.()));
+ }}
onError={() => !value.uploading && onUnreadable?.()}
className={cn("w-full object-contain", compact ? "max-h-[38vh]" : "max-h-[52vh]")}
/>
diff --git a/src/components/av/step-list.tsx b/src/components/av/step-list.tsx
index 7d8d2443..5c820dca 100644
--- a/src/components/av/step-list.tsx
+++ b/src/components/av/step-list.tsx
@@ -8,6 +8,25 @@ export interface StepRow {
key: string;
label: string;
g?: Generation;
+ /** Several jobs shown as one row (a dub's spoken lines): done when all are, failed when one is. */
+ group?: (Generation | undefined)[];
+}
+
+type Shown = Pick<Generation, "status" | "progress" | "message" | "modelName" | "provider" | "error">;
+
+/** One row's state: the job's own, or a group's roll-up (progress = the share done). */
+function shownState(s: StepRow): { g?: Shown; counted?: string } {
+ if (!s.group) return { g: s.g };
+ const gs = s.group.filter((g): g is Generation => !!g);
+ if (!gs.length) return {};
+ const failed = gs.find((g) => g.status === "failed" || g.status === "canceled");
+ const done = gs.filter((g) => g.status === "succeeded").length;
+ const started = gs.some((g) => g.status === "running" || (g.status === "queued" && !g.message?.startsWith("Waits")));
+ const status = failed ? failed.status : done === gs.length ? "succeeded" : started || done ? "running" : "queued";
+ return {
+ g: { status, progress: done / gs.length, message: null, modelName: gs[0].modelName, provider: gs.every((g) => g.provider === "mock") ? "mock" : gs[0].provider, error: failed?.error ?? null },
+ counted: `${done}/${gs.length}`,
+ };
}
/** One line per pipeline step: waiting, running (with progress), done or failed (with the reason). */
@@ -15,10 +34,10 @@ export function StepList({ steps, className }: { steps: StepRow[]; className?: s
return (
<ol className={cn("space-y-1.5", className)} aria-label="Steps">
{steps.map((s) => {
- const g = s.g;
+ const { g, counted } = shownState(s);
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"));
+ const waiting = status === "queued" && (!g || !!g.message?.startsWith("Waits") || !!counted);
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">
@@ -39,7 +58,7 @@ export function StepList({ steps, className }: { steps: StepRow[]; className?: s
<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"}
+ {status === "succeeded" ? "Done" : status === "failed" ? "Failed" : status === "canceled" ? "Canceled" : waiting ? "Waiting" : counted ?? (pct != null ? `${pct}%` : "Working")}
{g?.provider === "mock" && status === "succeeded" ? " · demo" : ""}
</span>
</div>
diff --git a/src/components/captions/captions-studio.tsx b/src/components/captions/captions-studio.tsx
index 3fbd3fd5..c80038a2 100644
--- a/src/components/captions/captions-studio.tsx
+++ b/src/components/captions/captions-studio.tsx
@@ -8,6 +8,7 @@ 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 { realDuration } from "@/components/av/frame-sampler";
import { SourceLanguageSelect } from "@/components/av/language-picker";
import { MediaDrop } from "@/components/av/media-drop";
import { StepList } from "@/components/av/step-list";
@@ -301,7 +302,11 @@ function Preview({
setT(e.currentTarget.currentTime);
onTime(e.currentTarget.currentTime);
}}
- onLoadedMetadata={(e) => Number.isFinite(e.currentTarget.duration) && onDuration(e.currentTarget.duration)}
+ onLoadedMetadata={(e) => {
+ const el = e.currentTarget;
+ if (Number.isFinite(el.duration) && el.duration > 0) onDuration(el.duration);
+ else void realDuration(el).then((d) => d && onDuration(d));
+ }}
className="max-h-[52vh] w-full object-contain"
/>
{shown && (
diff --git a/src/components/dub/dub-studio.tsx b/src/components/dub/dub-studio.tsx
index 3223d678..74750580 100644
--- a/src/components/dub/dub-studio.tsx
+++ b/src/components/dub/dub-studio.tsx
@@ -17,11 +17,11 @@ 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 { crowdedLines, dubResult, languageStage, ONE_SHOT_MODELS, priceLine, reviewCues, translateKey, type DubPrice, 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";
+import { useDubActions, useDubPrice, useDubSessions, useVoicePrice } 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" },
@@ -30,13 +30,14 @@ const ONE_SHOT: Record<OneShotModel, { name: string; note: string }> = {
};
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.",
+ open: "Open source: MelBand RoFormer splits the voice from the music and Qwen3-ASR times it → your local LLM translates → you review → Chatterbox speaks each line in the cloned voice, at its time → 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 each line at its time and Chatterbox turns it into the speaker's voice → Sync Lipsync 3. The cloud route keeps the voice only (no music stem on this route).",
};
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" },
+ // Solid in both themes: dark text on a translucent yellow over the dark page was unreadable.
+ review: { label: "Ready to review", tone: "bg-highlight 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" },
@@ -71,6 +72,7 @@ function NewDub({ onStarted }: { onStarted: (id: string) => void }) {
const [engine] = useEngine();
const { create } = useDubActions();
const [video, setVideo] = useState<SlotValue | null>(null);
+ const [duration, setDuration] = useState<number | undefined>(undefined);
const [mode, setMode] = useState<"steps" | "oneshot">("steps");
const [model, setModel] = useState<OneShotModel>("heygen-translate");
const [source, setSource] = useState("auto");
@@ -82,14 +84,17 @@ function NewDub({ onStarted }: { onStarted: (id: string) => void }) {
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 body = video && !video.uploading && usable.length ? { engine, mode: oneShot ? ("oneshot" as const) : ("steps" as const), model: oneShot ? model : undefined, video: video.ref, source, targets: usable, duration } : null;
+ const price = useDubPrice(body);
const start = () => {
- if (blocker) return void toast(blocker, { id: "dub-blocker" });
+ if (blocker || !body) 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 },
+ { ...body, title: video!.name?.replace(/\.[a-z0-9]+$/i, "") },
{
onSuccess: (s) => {
toast.success(oneShot ? `Dubbing into ${usable.length} language${usable.length === 1 ? "" : "s"}` : "Transcribing and translating");
setVideo(null);
+ setDuration(undefined);
onStarted(s.id);
},
onError: (e) => toast.error((e as Error).message),
@@ -100,7 +105,18 @@ function NewDub({ onStarted }: { onStarted: (id: string) => void }) {
<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 />
+ <MediaDrop
+ kind="video"
+ value={video}
+ onChange={(v) => {
+ setVideo(v);
+ if (!v) setDuration(undefined);
+ }}
+ onDuration={setDuration}
+ 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." />
@@ -160,10 +176,13 @@ function NewDub({ onStarted }: { onStarted: (id: string) => void }) {
<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 className="flex shrink-0 items-center gap-3 self-end sm:self-auto">
+ <PriceNote price={price.data} loading={price.isFetching && !price.data} error={price.error as Error | null} hint={oneShot ? undefined : "Translating costs little; you'll see the voice's price before it speaks"} />
+ <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>
</div>
{blocker && (
<p id="dub-blocker" className="sr-only">
@@ -175,6 +194,20 @@ function NewDub({ onStarted }: { onStarted: (id: string) => void }) {
);
}
+/** The price of the next step, next to its button: "≈ $8.13 + ElevenLabs v4", "Demo · free", "Free on your GPU". */
+function PriceNote({ price, loading, error, hint }: { price?: DubPrice; loading?: boolean; error?: Error | null; hint?: string }) {
+ if (loading) return <Skeleton className="h-4 w-20" aria-label="Pricing" />;
+ if (error) return <span className="max-w-[16rem] text-right text-[12px] leading-snug text-muted-foreground">{error.message}</span>;
+ if (!price) return null;
+ const extra = price.unpriced.length ? `${price.unpriced.join(" and ")} bill${price.unpriced.length === 1 ? "s" : ""} by the provider's own rate (per character or token).` : undefined;
+ return (
+ <span className="text-right text-[12px] leading-snug" title={[extra, hint].filter(Boolean).join(" ") || undefined}>
+ <span className="font-medium tabular-nums">{priceLine(price)}</span>
+ {price.steps > 1 && <span className="block text-muted-foreground">{price.steps} steps</span>}
+ </span>
+ );
+}
+
function ModeCard({ on, disabled, icon, title, note, onClick }: { on: boolean; disabled?: boolean; icon: React.ReactNode; title: string; note: string; onClick: () => void }) {
return (
<button
@@ -237,17 +270,34 @@ function RecentDubs({ sessions, loading, onOpen }: { sessions?: DubSessionView[]
);
}
+const PREPARE_LABEL: Record<string, string> = { stems: "Voice, background and transcript", voice: "Clean voice", words: "Transcript" };
+
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)] ?? ""] }];
+ // Older open dubs transcribed in a step of their own.
+ const keys = Object.keys(s.prepare ?? {}).filter((k) => !k.startsWith("translate:"));
+ const label = (k: string) => (k === "stems" && keys.includes("words") ? "Voice and background" : (PREPARE_LABEL[k] ?? k));
+ 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] }));
+ const open = s.engine === "open";
+ const label: Record<string, string> = {
+ speech: open ? "Speech in their voice" : "Speech",
+ track: "Placed at each line's time",
+ soundtrack: "Voice track",
+ clone: "Their voice",
+ lips: "Lips re-synced",
+ film: run.lipsync && !open ? "Lips re-synced" : "Dubbed video",
+ };
+ const entries = Object.entries(run.ids);
+ const lines = entries.filter(([k]) => k.startsWith("line:")).map(([, id]) => s.generations[id]);
+ const rows: StepRow[] = [];
+ // One row for the takes: a dub of 30 lines would otherwise list 30 near-identical steps.
+ if (lines.length) rows.push({ key: "lines", label: `${lines.length} line${lines.length === 1 ? "" : "s"} ${open ? "in their voice" : "spoken"}`, group: lines });
+ for (const [k, id] of entries) if (!k.startsWith("line:")) rows.push({ key: k, label: label[k] ?? k, g: s.generations[id] });
+ return rows;
}
function SessionView({ s, onBack }: { s: DubSessionView; onBack: () => void }) {
@@ -273,7 +323,7 @@ function SessionView({ s, onBack }: { s: DubSessionView; onBack: () => void }) {
<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>
+ <AlertDialogDescription>Steps still running are stopped, and the review leaves this list. The videos and audio it already made stay in your Library.</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Keep it</AlertDialogCancel>
@@ -373,7 +423,7 @@ function ResultCard({ s, lang }: { s: DubSessionView; lang: string }) {
>
<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&apos;t mix the original music back in yet.</p>}
+ {s.engine === "cloud" && s.mode === "steps" && <p className="mt-2 text-[12px] text-muted-foreground">Voice only: the cloud route has no music stem to mix back in (the open route and the one-shot models keep it).</p>}
</Panel>
);
}
@@ -389,10 +439,13 @@ function Review({ s, lang, time, onSeek }: { s: DubSessionView; lang: string; ti
const [savedBody, setSavedBody] = useState(() => JSON.stringify(initial));
const cues = editor.cues;
const save = useRef(saveDraft.mutate);
+ const body = JSON.stringify(cues);
+ // What's on screen vs. what the server has, for the flush when this review closes.
+ const pending = useRef({ body, savedBody, id: s.id, lang });
useEffect(() => {
save.current = saveDraft.mutate;
+ pending.current = { body, savedBody, id: s.id, lang };
});
- const body = JSON.stringify(cues);
const dirty = body !== savedBody;
useEffect(() => {
if (body === savedBody) return;
@@ -402,7 +455,25 @@ function Review({ s, lang, time, onSeek }: { s: DubSessionView; lang: string; ti
}, 800);
return () => clearTimeout(t);
}, [body, savedBody, s.id, lang]);
+ // Edits made just before switching language, going back to all dubs or leaving the page are saved right away.
+ useEffect(() => {
+ const flush = (keepalive: boolean) => {
+ const p = pending.current;
+ if (p.body === p.savedBody) return;
+ pending.current = { ...p, savedBody: p.body };
+ if (keepalive) void fetch(`/api/dub/${p.id}`, { method: "PATCH", keepalive: true, headers: { "Content-Type": "application/json" }, body: JSON.stringify({ lang: p.lang, cues: JSON.parse(p.body) }) });
+ else save.current({ id: p.id, lang: p.lang, cues: JSON.parse(p.body) as Cue[] });
+ };
+ const leave = () => flush(true);
+ window.addEventListener("beforeunload", leave);
+ return () => {
+ window.removeEventListener("beforeunload", leave);
+ flush(false);
+ };
+ }, []);
const problems = cueProblems(cues);
+ const crowded = useMemo(() => crowdedLines(cues, s.duration), [cues, s.duration]);
+ const price = useVoicePrice(s.id, lang, lipsync, cues, stage !== "preparing" && !problems.length);
const name = languageByCode(lang)?.name ?? lang;
const start = (c: Cue[]) =>
voice.mutate(
@@ -416,6 +487,18 @@ function Review({ s, lang, time, onSeek }: { s: DubSessionView; lang: string; ti
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." />
+ <p className="mt-3 text-[12px] leading-relaxed text-muted-foreground">
+ Each line is spoken at its start time, so pauses stay where they were; a line that runs past the next one is cut there.
+ {crowded.length > 0 && (
+ <>
+ {" "}
+ <span className="font-medium text-foreground">
+ {crowded.length === 1 ? `Line ${crowded[0] + 1} looks` : `${crowded.length} lines (${crowded.slice(0, 4).map((i) => i + 1).join(", ")}${crowded.length > 4 ? "…" : ""}) look`} long for {crowded.length === 1 ? "its" : "their"} time
+ </span>{" "}
+ — shorten {crowded.length === 1 ? "it" : "them"} or move the next line later.
+ </>
+ )}
+ </p>
</Panel>
<Panel>
<div className="flex flex-col gap-3 sm:flex-row sm:items-center">
@@ -424,19 +507,23 @@ function Review({ s, lang, time, onSeek }: { s: DubSessionView; lang: string; ti
<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>
+ <span className="text-[12px] text-muted-foreground">{s.engine === "open" ? "InfiniteTalk · up to 40 s" : "Sync Lipsync 3 · $8 per minute"}</span>
+ </div>
+ <div className="flex items-center gap-3 self-end sm:self-auto">
+ <PriceNote price={price.data} loading={price.isFetching && !price.data} error={price.error as Error | null} />
+ <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>
- <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.ts
index baf94e4c..63f750a6 100644
--- a/src/components/dub/hooks.ts
+++ b/src/components/dub/hooks.ts
@@ -1,8 +1,9 @@
"use client";
-import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+import { keepPreviousData, useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+import { useEffect, useState } from "react";
import { useGenerationEvents } from "@/lib/api";
-import type { DubSessionView, OneShotModel } from "@/lib/av/dub";
+import type { DubPrice, DubSessionView, OneShotModel } from "@/lib/av/dub";
import type { Cue } from "@/lib/cues";
import type { Engine, Generation } from "@/lib/catalog/types";
@@ -35,6 +36,46 @@ export interface NewDub {
source?: string;
targets: string[];
model?: OneShotModel;
+ /** The video's length as the browser measured it (seconds). */
+ duration?: number;
+}
+
+/** A value that settles `ms` after it last changed (so prices aren't asked for on every keystroke). */
+function useSettled<T>(value: T, ms = 400): T {
+ const [v, setV] = useState(value);
+ useEffect(() => {
+ const t = setTimeout(() => setV(value), ms);
+ return () => clearTimeout(t);
+ }, [value, ms]);
+ return v;
+}
+
+const post = async <T,>(url: string, body: unknown) => json<T>(await fetch(url, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) }));
+
+/** What starting this dub would cost (null body: nothing to price yet). */
+export function useDubPrice(body: NewDub | null) {
+ const key = useSettled(body ? JSON.stringify(body) : null);
+ return useQuery({
+ queryKey: ["dub-price", key],
+ queryFn: () => post<DubPrice>("/api/dub?preview=1", JSON.parse(key!)),
+ enabled: !!key,
+ staleTime: 30_000,
+ retry: false,
+ placeholderData: keepPreviousData,
+ });
+}
+
+/** What voicing one language would cost with these lines. */
+export function useVoicePrice(id: string, lang: string, lipsync: boolean, cues: Cue[], enabled: boolean) {
+ const key = useSettled(enabled ? JSON.stringify({ lang, lipsync, cues }) : null, 800);
+ return useQuery({
+ queryKey: ["dub-voice-price", id, key],
+ queryFn: () => post<DubPrice>(`/api/dub/${id}/voice?preview=1`, JSON.parse(key!)),
+ enabled: !!key,
+ staleTime: 30_000,
+ retry: false,
+ placeholderData: keepPreviousData,
+ });
}
export function useDubActions() {