Skip to content

Open source CapCut alternative.

TypeScript

feat(site): transcribe just the clip when generating audio for it without cues

David Le8db5dae18924
diff --git a/site/src/cut/components/Inspector.tsx b/site/src/cut/components/Inspector.tsx
index 9919d892..854b2e3e 100644
--- a/site/src/cut/components/Inspector.tsx
+++ b/site/src/cut/components/Inspector.tsx
@@ -1,6 +1,6 @@
"use client";
-import { useEffect, useMemo, useRef, useState } from "react";
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { Bold, Smile } from "lucide-react";
import { Button } from "@/components/ui/button";
import {
@@ -18,7 +18,7 @@ import {
import { Slider } from "@/components/ui/slider";
import { Switch } from "@/components/ui/switch";
import { Textarea } from "@/components/ui/textarea";
-import { getClipSpans, useEditor } from "@/cut/lib/store";
+import { getClipSpans, useEditor, type EditorState } from "@/cut/lib/store";
import { GenerateSubtitlesAudio } from "@/cut/components/VoicePicker";
import { PLATE_COLOR, PLATE_OPACITY, PLATE_RADIUS } from "@/cut/lib/textRender";
import { writeTextStyle } from "@/cut/lib/textStyle";
@@ -258,19 +258,21 @@ function ClipPanel({ clip }: { clip: VideoClip }) {
const [volumeDraft, setVolumeDraft] = useState<number | null>(null);
const volume = volumeDraft ?? clip.volume ?? 1;
// Subtitle cues overlapping this clip's timeline span, for the per-clip
- // readout. Selected as a joined string so the reference stays stable while
- // the playhead ticks through the same store.
- const clipCueIdsKey = useEditor((s) => {
- const sp = getClipSpans(s.clips, s.assets).find((x) => x.clip.id === clip.id);
- if (!sp) return "";
- return s.subtitles.cues
- .filter((c) => c.text.trim() && c.end > sp.start && c.start < sp.start + sp.len)
- .map((c) => c.id)
- .join("\n");
- });
- const clipCueIds = useMemo(
- () => (clipCueIdsKey ? clipCueIdsKey.split("\n") : []),
- [clipCueIdsKey]
+ // readout. A selector rather than a snapshot so the generate button reads
+ // fresh ids after it auto-transcribes the cut.
+ const selectClipCueIds = useCallback(
+ (s: EditorState) => {
+ const sp = getClipSpans(s.clips, s.assets).find((x) => x.clip.id === clip.id);
+ if (!sp) return [];
+ return s.subtitles.cues
+ .filter((c) => c.text.trim() && c.end > sp.start && c.start < sp.start + sp.len)
+ .map((c) => c.id);
+ },
+ [clip.id]
+ );
+ const ensureClipCues = useCallback(
+ () => useEditor.getState().generateClipSubtitles(clip.id),
+ [clip.id]
);
// Generated voiceover clips overlapping this clip's span — the "Generated
// audio" slider drives them all, so clip sound and voiceover balance from one
@@ -474,7 +476,11 @@ function ClipPanel({ clip }: { clip: VideoClip }) {
onPick={(frame, fit) => updateClip(clip.id, { frame, fit })}
/>
<div className="mt-2 flex flex-col gap-1 border-t border-border pt-3">
- <GenerateSubtitlesAudio cueIds={clipCueIds} label="Generate audio for clip" />
+ <GenerateSubtitlesAudio
+ selectCueIds={selectClipCueIds}
+ ensureCues={ensureClipCues}
+ label="Generate audio for clip"
+ />
{genAudioIds.length > 0 && (
<Row label="Volume">
<Slider
diff --git a/site/src/cut/components/VoicePicker.tsx b/site/src/cut/components/VoicePicker.tsx
index f1979029..62816b6a 100644
--- a/site/src/cut/components/VoicePicker.tsx
+++ b/site/src/cut/components/VoicePicker.tsx
@@ -5,7 +5,7 @@ import { Captions, ChevronDown, Languages, Loader2, Pause, Play } from "lucide-r
import { Button } from "@/components/ui/button";
import { SectionTitle } from "@/cut/components/SectionTitle";
import { creditsUrl, signInUrl, useSignedIn } from "@/cut/lib/generate";
-import { useEditor } from "@/cut/lib/store";
+import { useEditor, type EditorState } from "@/cut/lib/store";
import {
NoCreditsError,
resolveLanguage,
@@ -191,16 +191,27 @@ function languageLabel(code: string): string {
return SPEECH_LANGUAGES.find((l) => l.id === code)?.label ?? code;
}
+/** The cue ids the readout covers: `select`'s scope, or every non-empty cue. */
+function scopedCueIds(s: EditorState, select?: (s: EditorState) => string[]): string[] {
+ return select ? select(s) : s.subtitles.cues.filter((c) => c.text.trim()).map((c) => c.id);
+}
+
/**
* Self-contained "voice the subtitles" block: the voice picker plus a generate
- * button and its error line. `cueIds` scopes the readout (e.g. the cues inside
- * one clip); absent = every cue.
+ * button and its error line. `selectCueIds` scopes the readout (e.g. the cues
+ * inside one clip); absent = every cue. When the scope has no cues yet,
+ * Generate transcribes the cut first and then voices the fresh cues.
*/
export function GenerateSubtitlesAudio({
- cueIds,
+ selectCueIds,
+ ensureCues,
label = "Generate audio for subtitles",
}: {
- cueIds?: string[];
+ selectCueIds?: (s: EditorState) => string[];
+ /** Makes cues exist when the scope has none, matched to that scope (e.g.
+ * transcribe just the clip); defaults to transcribing the whole cut. Throws
+ * a user-facing error on failure. */
+ ensureCues?: () => Promise<void>;
label?: string;
}) {
const voice = useSpeakerVoice();
@@ -208,16 +219,35 @@ export function GenerateSubtitlesAudio({
const signedOut = useSignedIn() === false;
const [busy, setBusy] = useState(false);
const [error, setError] = useState<{ text: string; credits?: boolean } | null>(null);
- const wanted = cueIds && new Set(cueIds);
- const cueCount = useEditor(
- (s) => s.subtitles.cues.filter((c) => c.text.trim() && (!wanted || wanted.has(c.id))).length
- );
+ const cueCount = useEditor((s) => scopedCueIds(s, selectCueIds).length);
+ const hasVideo = useEditor((s) => s.clips.length > 0);
const generate = async () => {
setBusy(true);
setError(null);
try {
- await generateSubtitlesReadout(voice, { cueIds, language });
+ if (scopedCueIds(useEditor.getState(), selectCueIds).length === 0) {
+ // Nothing to read yet — transcribe first, then voice the fresh cues.
+ if (ensureCues) {
+ await ensureCues();
+ } else {
+ if (useEditor.getState().subtitleStatus === "running") {
+ throw new Error("Subtitles are still generating — try again in a moment.");
+ }
+ await useEditor.getState().generateSubtitles();
+ const after = useEditor.getState();
+ if (after.subtitleStatus === "error") {
+ throw new Error(after.subtitleError ?? "Transcription failed.");
+ }
+ }
+ if (scopedCueIds(useEditor.getState(), selectCueIds).length === 0) {
+ throw new Error("No speech found to voice.");
+ }
+ }
+ await generateSubtitlesReadout(voice, {
+ cueIds: selectCueIds?.(useEditor.getState()),
+ language,
+ });
} catch (e) {
setError(
e instanceof Error
@@ -236,7 +266,11 @@ export function GenerateSubtitlesAudio({
// Play previews the subtitle readout itself; Generate commits it. The
// preview is cached, so committing afterward reuses the same audio.
sample={{
- run: () => previewSubtitlesReadout(voice, { cueIds, language }),
+ run: () =>
+ previewSubtitlesReadout(voice, {
+ cueIds: selectCueIds?.(useEditor.getState()),
+ language,
+ }),
title: "Play the subtitles",
disabled: cueCount === 0,
}}
@@ -245,8 +279,14 @@ export function GenerateSubtitlesAudio({
<Button
variant="outline"
className="voice-readout w-full"
- disabled={cueCount === 0 || busy || signedOut}
- title={cueCount === 0 ? "Generate subtitles first" : "Voice the subtitle text and drop it on the soundtrack"}
+ disabled={busy || signedOut || (cueCount === 0 && !hasVideo)}
+ title={
+ cueCount === 0
+ ? hasVideo
+ ? "Transcribe the speech, then voice it onto the soundtrack"
+ : "Add a video to the timeline first"
+ : "Voice the subtitle text and drop it on the soundtrack"
+ }
onClick={() => void generate()}
>
{busy ? <Loader2 className="animate-spin" /> : <Captions data-icon="inline-start" />}
diff --git a/site/src/cut/lib/store.ts b/site/src/cut/lib/store.ts
index 9e595d71..91efea49 100644
--- a/site/src/cut/lib/store.ts
+++ b/site/src/cut/lib/store.ts
@@ -75,7 +75,7 @@ export type SubtitleStatus = "idle" | "running" | "ready" | "empty" | "error";
export type SaveState = "saved" | "dirty" | "saving" | "error";
-interface EditorState {
+export interface EditorState {
projectId: string | null;
projectName: string;
loaded: boolean;
@@ -180,6 +180,10 @@ interface EditorState {
setNotes: (patch: Partial<{ text: string; publishedAt: string; links: string[] }>) => void;
/** Kick off (and poll) an on-device transcription of the current cut. */
generateSubtitles: () => Promise<void>;
+ /** Transcribe one clip's own audio (even when muted) and merge its cues into
+ * the subtitles; cues elsewhere on the timeline stay put. Throws a
+ * user-facing error on failure. */
+ generateClipSubtitles: (clipId: string) => Promise<void>;
/** Caption the cut from its picture alone (no audio needed): sample frames
* along the timeline and have the AI write timed narration cues. */
generateVisualSubtitles: () => Promise<void>;
@@ -278,6 +282,29 @@ function nextFreeStart(spans: { start: number; end: number }[], t: number, len:
return at;
}
+/** POST a transcribe spec and poll the job to completion. Returns the cues, or
+ * null when the user switches projects mid-run. Throws user-facing errors. */
+async function runTranscription(projectId: string, spec: object): Promise<SubtitleCue[] | null> {
+ const res = await apiFetch(`/api/cut/projects/${projectId}/transcribe`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(spec),
+ });
+ const body = await apiJson<{ id?: string }>(res);
+ if (!res.ok || !body.id) throw new Error(body.error ?? "Transcription failed to start.");
+ for (;;) {
+ await new Promise((r) => setTimeout(r, 600));
+ if (useEditor.getState().projectId !== projectId) return null;
+ const st = await apiFetch(`/api/cut/projects/${projectId}/transcribe?job=${body.id}`);
+ if (!st.ok) throw new Error("The transcription job was lost — try again.");
+ const status = (await st.json()) as { status: string; error?: string; cues?: SubtitleCue[] };
+ if (status.status === "error") throw new Error(status.error ?? "Transcription failed.");
+ if (status.status === "done") {
+ return useEditor.getState().projectId === projectId ? (status.cues ?? []) : null;
+ }
+ }
+}
+
export const useEditor = create<EditorState>((set, get) => {
const snapshot = (): DocSnapshot => {
const { clips, audioClips, overlayClips, overlays, subtitles } = get();
@@ -1169,43 +1196,21 @@ export const useEditor = create<EditorState>((set, get) => {
};
set({ subtitleStatus: "running", subtitleError: null });
try {
- const res = await apiFetch(`/api/cut/projects/${projectId}/transcribe`, {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify(spec),
- });
- const body = await apiJson<{ id?: string }>(res);
- if (!res.ok || !body.id) throw new Error(body.error ?? "Transcription failed to start.");
- for (;;) {
- await new Promise((r) => setTimeout(r, 600));
- if (get().projectId !== projectId) return; // switched projects mid-run
- const st = await apiFetch(`/api/cut/projects/${projectId}/transcribe?job=${body.id}`);
- if (!st.ok) throw new Error("The transcription job was lost — try again.");
- const status = (await st.json()) as {
- status: string;
- error?: string;
- cues?: SubtitleCue[];
- };
- if (status.status === "error") throw new Error(status.error ?? "Transcription failed.");
- if (status.status === "done") {
- if (get().projectId !== projectId) return;
- const cues = status.cues ?? [];
- if (cues.length === 0) {
- // No speech in the audio — leave the video untouched.
- set((cur) => ({
- subtitles: { ...cur.subtitles, cues: [], generatedAt: Date.now() },
- subtitleStatus: "empty",
- }));
- return;
- }
- push();
- set((cur) => ({
- subtitles: { ...cur.subtitles, cues, generatedAt: Date.now() },
- subtitleStatus: "ready",
- }));
- return;
- }
+ const cues = await runTranscription(projectId, spec);
+ if (cues === null) return; // switched projects mid-run
+ if (cues.length === 0) {
+ // No speech in the audio — leave the video untouched.
+ set((cur) => ({
+ subtitles: { ...cur.subtitles, cues: [], generatedAt: Date.now() },
+ subtitleStatus: "empty",
+ }));
+ return;
}
+ push();
+ set((cur) => ({
+ subtitles: { ...cur.subtitles, cues, generatedAt: Date.now() },
+ subtitleStatus: "ready",
+ }));
} catch (err) {
if (get().projectId !== projectId) return;
set({
@@ -1215,6 +1220,65 @@ export const useEditor = create<EditorState>((set, get) => {
}
},
+ generateClipSubtitles: async (clipId) => {
+ const s = get();
+ if (!s.projectId) throw new Error("Open a project first.");
+ if (s.subtitleStatus === "running") {
+ throw new Error("Subtitles are already generating — try again in a moment.");
+ }
+ const projectId = s.projectId;
+ const sp = getClipSpans(s.clips, s.assets).find((x) => x.clip.id === clipId);
+ if (!sp) throw new Error("The clip is no longer on the timeline.");
+ // The clip's own sound, deliberately unmuted: this transcribes what the
+ // clip says even when its timeline audio is muted.
+ const spec = {
+ duration: sp.len,
+ locale: s.subtitles.locale ?? "en-US",
+ clips: [
+ {
+ file: sp.asset.fileName,
+ in: sp.clip.in,
+ out: sp.clip.out,
+ muted: false,
+ speed: clipSpeed(sp.clip),
+ transition: 0,
+ },
+ ],
+ audio: [],
+ };
+ set({ subtitleStatus: "running", subtitleError: null });
+ try {
+ const cues = await runTranscription(projectId, spec);
+ if (cues === null) return; // switched projects mid-run
+ // The job timed cues against the lone clip, so shift them (and their
+ // word timings) onto the clip's timeline span. New cues replace any
+ // that overlapped the clip; the rest of the timeline keeps its cues.
+ const placed = cues.map((c) => ({
+ ...c,
+ start: c.start + sp.start,
+ end: c.end + sp.start,
+ words: c.words?.map((w) => ({ ...w, t0: w.t0 + sp.start, t1: w.t1 + sp.start })),
+ }));
+ if (placed.length > 0) push();
+ set((cur) => {
+ const kept = cur.subtitles.cues.filter(
+ (c) => !(c.end > sp.start && c.start < sp.start + sp.len)
+ );
+ const merged = [...kept, ...placed].sort((a, b) => a.start - b.start);
+ return {
+ subtitles: { ...cur.subtitles, cues: merged, generatedAt: Date.now() },
+ subtitleStatus: merged.length > 0 ? "ready" : "empty",
+ };
+ });
+ } catch (err) {
+ // The clip panel reports the error; just clear the global busy flag.
+ if (get().projectId === projectId) {
+ set({ subtitleStatus: get().subtitles.cues.length > 0 ? "ready" : "idle" });
+ }
+ throw err;
+ }
+ },
+
generateVisualSubtitles: async () => {
const s = get();
if (!s.projectId || s.subtitleStatus === "running") return;