Skip to content

Open source CapCut alternative.

TypeScript

feat(site): multi-language subtitle tracks [rebuild]

David Leaf0c8a189a4b
diff --git a/site/src/cut/components/OverlayLayer.tsx b/site/src/cut/components/OverlayLayer.tsx
index 2ab5faaf..20e385aa 100644
--- a/site/src/cut/components/OverlayLayer.tsx
+++ b/site/src/cut/components/OverlayLayer.tsx
@@ -3,7 +3,16 @@
import { useCallback, useEffect, useRef, useState, type CSSProperties } from "react";
import { startDrag } from "@/cut/lib/drag";
import { useEditor } from "@/cut/lib/store";
-import { captionStyle, cueAt, cueOverlay, cueWordWindows, karaokeLook } from "@/cut/lib/subtitles";
+import {
+ captionStyle,
+ cueAt,
+ cueOverlay,
+ cueWordWindows,
+ karaokeLook,
+ laneCues,
+ subtitleLaneCount,
+ trackPos,
+} from "@/cut/lib/subtitles";
import {
LINE_HEIGHT,
PLATE_PAD_X,
@@ -30,9 +39,9 @@ interface Guides {
h: number[]; // horizontal lines (y)
}
-/** The subtitle caption's key in the shared snap-box registry. Overlay ids are
- * uids, so this can't collide. */
-const SUBTITLE_BOX_ID = "subtitle-caption";
+/** A subtitle track's key in the shared snap-box registry. Overlay ids are
+ * uids, so these can't collide. */
+const subtitleBoxId = (lane: number) => `subtitle-caption-${lane}`;
export function OverlayLayer({ stageWidth }: { stageWidth: number }) {
const overlays = useEditor((s) => s.overlays);
@@ -129,7 +138,7 @@ export function OverlayLayer({ stageWidth }: { stageWidth: number }) {
return (
<div ref={rootRef} className="pointer-events-none absolute inset-0">
- <SubtitleCaption
+ <SubtitleCaptions
stageWidth={stageWidth}
stageHeight={stageHeight}
registerBox={registerBox}
@@ -175,18 +184,38 @@ export function OverlayLayer({ stageWidth }: { stageWidth: number }) {
);
}
-/** The active subtitle cue, rendered exactly like the export burn-in.
- * Nothing renders when subtitles are hidden or there is no cue (no speech).
- * Dragging the caption moves every cue — the position is one project-wide
- * anchor, not per-cue — and rides the same smart snapping and guide lines as
- * titles. */
+/** Every subtitle track's active cue, one caption per language. */
+function SubtitleCaptions(props: {
+ stageWidth: number;
+ stageHeight: number;
+ registerBox: (id: string, el: HTMLElement | null) => void;
+ snap: (id: string, x: number, y: number, ev: PointerEvent) => { x: number; y: number };
+ onSnapEnd: () => void;
+}) {
+ const subtitles = useEditor((s) => s.subtitles);
+ if (!subtitles.showOnVideo) return null;
+ return (
+ <>
+ {Array.from({ length: subtitleLaneCount(subtitles) }, (_, lane) => (
+ <SubtitleCaption key={lane} lane={lane} {...props} />
+ ))}
+ </>
+ );
+}
+
+/** One track's active cue, rendered exactly like the export burn-in.
+ * Nothing renders when there is no cue at the playhead (no speech). Dragging
+ * the caption moves the whole track — the position is one per-track anchor,
+ * not per-cue — and rides the same smart snapping and guide lines as titles. */
function SubtitleCaption({
+ lane,
stageWidth,
stageHeight,
registerBox,
snap,
onSnapEnd,
}: {
+ lane: number;
stageWidth: number;
stageHeight: number;
registerBox: (id: string, el: HTMLElement | null) => void;
@@ -200,14 +229,14 @@ function SubtitleCaption({
const aspect = useEditor((s) => s.aspect);
const t = !playing && skimTime !== null ? skimTime : currentTime;
- if (!subtitles.showOnVideo) return null;
- const cue = cueAt(subtitles.cues, t);
+ const cues = laneCues(subtitles, lane);
+ const cue = cueAt(cues, t);
if (!cue || !cue.text.trim()) return null;
- // Captions ride the same style/opener logic as the export burn-in, so the
- // preview and the rendered file match exactly.
+ // Captions ride the same style/opener/anchor logic as the export burn-in,
+ // so the preview and the rendered file match exactly.
const style = captionStyle(subtitles.style);
- const ov = cueOverlay(cue, style, cue.id === subtitles.cues[0]?.id, subtitles);
+ const ov = cueOverlay(cue, style, cue.id === cues[0]?.id, trackPos(subtitles, style, lane));
// Karaoke: the word under the playhead lights up as it is spoken.
const wordIndex = subtitles.wordHighlight
? cueWordWindows(cue).findIndex((w) => t >= w.start && t < w.end)
@@ -236,7 +265,7 @@ function SubtitleCaption({
const scale = stageWidth / FRAME[aspect].w;
return (
<div
- ref={(el) => registerBox(SUBTITLE_BOX_ID, el)}
+ ref={(el) => registerBox(subtitleBoxId(lane), el)}
className="sub-caption pointer-events-auto absolute -translate-x-1/2 -translate-y-1/2 cursor-grab text-center whitespace-pre-wrap active:cursor-grabbing"
onPointerDown={(e) => {
const s = useEditor.getState();
@@ -244,8 +273,8 @@ function SubtitleCaption({
const { x: x0, y: y0 } = ov;
startDrag(e, {
onMove: (dx, dy, ev) => {
- const p = snap(SUBTITLE_BOX_ID, x0 + dx / stageWidth, y0 + dy / stageHeight, ev);
- useEditor.getState().setSubtitlesView({
+ const p = snap(subtitleBoxId(lane), x0 + dx / stageWidth, y0 + dy / stageHeight, ev);
+ useEditor.getState().setSubtitleTrackMeta(lane, {
x: Math.min(0.98, Math.max(0.02, p.x)),
y: Math.min(0.98, Math.max(0.02, p.y)),
});
diff --git a/site/src/cut/components/SubtitlesPanel.tsx b/site/src/cut/components/SubtitlesPanel.tsx
index 9655ea01..2830cb54 100644
--- a/site/src/cut/components/SubtitlesPanel.tsx
+++ b/site/src/cut/components/SubtitlesPanel.tsx
@@ -1,14 +1,27 @@
"use client";
import React, { memo, useEffect, useRef, useState } from "react";
-import { AlertCircle, Captions, ChevronDown, Loader2, RefreshCw } from "lucide-react";
+import { AlertCircle, Captions, ChevronDown, Languages, Loader2, Plus, RefreshCw, Trash2 } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Switch } from "@/components/ui/switch";
import { GenerateSubtitlesAudio } from "@/cut/components/VoicePicker";
-import { CAPTION_STYLES, captionStyle, fmtCueTime, karaokeLook } from "@/cut/lib/subtitles";
+import {
+ CAPTION_STYLES,
+ captionStyle,
+ fmtCueTime,
+ karaokeLook,
+ laneCues,
+ subtitleLaneCount,
+} from "@/cut/lib/subtitles";
import { TIMELINE_H_MIN, useEditor } from "@/cut/lib/store";
import { PLATE_PAD_X, PLATE_PAD_Y, PLATE_RADIUS, plateFill } from "@/cut/lib/textRender";
-import { fontStack, type SubtitleCue, type WordAccentMode } from "@/cut/lib/types";
+import {
+ MAX_SUBTITLE_LANES,
+ fontStack,
+ type SubtitleCue,
+ type SubtitlesBlock,
+ type WordAccentMode,
+} from "@/cut/lib/types";
import { cn } from "@/lib/utils";
const LOCALES = [
@@ -28,23 +41,45 @@ const LOCALES = [
/** Give the cue track room when it appears. */
const TIMELINE_H_WITH_SUBS = Math.max(TIMELINE_H_MIN, 276);
+/** A track's short pill label: its language code (EN, KO, …). */
+function laneLabel(subs: SubtitlesBlock, lane: number): string {
+ const locale =
+ subs.tracks?.[lane]?.locale ?? (lane === 0 ? subs.locale : undefined) ?? "en-US";
+ return locale.split("-")[0].toUpperCase();
+}
+
+/** A track's language name from the locale picker list, else its short code. */
+function laneLanguage(subs: SubtitlesBlock, lane: number): string {
+ const locale =
+ subs.tracks?.[lane]?.locale ?? (lane === 0 ? subs.locale : undefined) ?? "en-US";
+ return LOCALES.find(([id]) => id === locale)?.[1] ?? laneLabel(subs, lane);
+}
+
export function SubtitlesPanel() {
const subtitles = useEditor((s) => s.subtitles);
+ const lane = useEditor((s) => s.subtitleLane);
const status = useEditor((s) => s.subtitleStatus);
const error = useEditor((s) => s.subtitleError);
- const hasCues = subtitles.cues.length > 0;
+ const laneCount = subtitleLaneCount(subtitles);
+ const activeCues = laneCues(subtitles, lane);
+ const hasCues = activeCues.length > 0;
const [tab, setTab] = useState<"content" | "styles" | "options">("content");
const growTimeline = () => {
const cur = useEditor.getState();
- if (cur.subtitles.cues.length > 0 && cur.timelineH < TIMELINE_H_WITH_SUBS)
- cur.setTimelineH(TIMELINE_H_WITH_SUBS);
+ // Multiple tracks stack rows, so give the timeline room per track.
+ const want = TIMELINE_H_WITH_SUBS + (subtitleLaneCount(cur.subtitles) - 1) * 22;
+ if (cur.subtitles.cues.length > 0 && cur.timelineH < want) cur.setTimelineH(want);
};
const generate = () => {
void useEditor.getState().generateSubtitles().then(growTimeline);
};
+ const translate = (fromLane: number) => {
+ void useEditor.getState().translateSubtitleTrack(fromLane).then(growTimeline);
+ };
+
return (
<>
<div className="flex h-12 shrink-0 items-center justify-between pr-2.5 pl-4">
@@ -77,8 +112,52 @@ export function SubtitlesPanel() {
)}
</div>
+ {(laneCount > 1 || subtitles.cues.length > 0) && (
+ <div className="sub-tracks flex shrink-0 items-center gap-1 px-3.5 pb-2">
+ {Array.from({ length: laneCount }, (_, i) => (
+ <button
+ key={i}
+ className={cn(
+ "sub-track-pill rounded-full border px-2.5 py-1 text-[11px] font-semibold tracking-wide transition-colors",
+ i === lane
+ ? "border-transparent bg-neutral-900 text-white"
+ : "border-input text-muted-foreground hover:text-foreground"
+ )}
+ aria-pressed={i === lane}
+ title={`Subtitle track ${i + 1}`}
+ onClick={() => useEditor.getState().setSubtitleLane(i)}
+ >
+ {laneLabel(subtitles, i)}
+ </button>
+ ))}
+ {laneCount < MAX_SUBTITLE_LANES && (
+ <button
+ className="sub-track-add grid size-6 place-items-center rounded-full border border-dashed border-input text-muted-foreground transition-colors hover:text-foreground"
+ title="Add a subtitle track (another language)"
+ aria-label="Add a subtitle track"
+ onClick={() => useEditor.getState().addSubtitleTrack()}
+ >
+ <Plus className="size-3.5" />
+ </button>
+ )}
+ {laneCount > 1 && (
+ <button
+ className="sub-track-remove ml-auto grid size-6 place-items-center rounded-md text-muted-foreground transition-colors hover:text-red-600"
+ title="Remove this subtitle track and its captions (undoable)"
+ aria-label="Remove this subtitle track"
+ onClick={() => {
+ const s = useEditor.getState();
+ s.removeSubtitleTrack(s.subtitleLane);
+ }}
+ >
+ <Trash2 className="size-3.5" />
+ </button>
+ )}
+ </div>
+ )}
+
{!hasCues ? (
- <EmptyState status={status} error={error} onGenerate={generate} />
+ <EmptyState status={status} error={error} onGenerate={generate} onTranslate={translate} />
) : tab === "content" ? (
<>
<div className="shrink-0 px-1.5">
@@ -98,7 +177,7 @@ export function SubtitlesPanel() {
Regenerate
</Button>
</div>
- <Transcript cues={subtitles.cues} />
+ <Transcript cues={activeCues} />
{status === "error" && error && (
<p className="sub-error shrink-0 border-t border-border px-4 py-2.5 text-[11px] leading-relaxed text-red-600">
{error}
@@ -128,7 +207,10 @@ const ACCENT_MODES: { id: WordAccentMode; label: string }[] = [
* subtitle-voiceover generator. */
function OptionsTab() {
const subtitles = useEditor((s) => s.subtitles);
- const moved = subtitles.x !== undefined || subtitles.y !== undefined;
+ const moved =
+ subtitles.x !== undefined ||
+ subtitles.y !== undefined ||
+ !!subtitles.tracks?.some((t) => t.x !== undefined || t.y !== undefined);
// Effective word treatment: the caption style's defaults with the user's
// overrides on top, so the controls always show what's on the video.
const look = karaokeLook(captionStyle(subtitles.style), subtitles);
@@ -226,7 +308,13 @@ function OptionsTab() {
size="sm"
className="sub-position-reset"
disabled={!moved}
- onClick={() => useEditor.getState().setSubtitlesView({ x: undefined, y: undefined })}
+ onClick={() => {
+ const s = useEditor.getState();
+ s.setSubtitlesView({ x: undefined, y: undefined });
+ s.subtitles.tracks?.forEach((_, i) =>
+ s.setSubtitleTrackMeta(i, { x: undefined, y: undefined })
+ );
+ }}
>
Reset
</Button>
@@ -290,18 +378,30 @@ function EmptyState({
status,
error,
onGenerate,
+ onTranslate,
}: {
status: string;
error: string | null;
onGenerate: () => void;
+ onTranslate: (fromLane: number) => void;
}) {
- const locale = useEditor((s) => s.subtitles.locale ?? "en-US");
+ const subtitles = useEditor((s) => s.subtitles);
+ const lane = useEditor((s) => s.subtitleLane);
+ const locale =
+ subtitles.tracks?.[lane]?.locale ?? (lane === 0 ? subtitles.locale : undefined) ?? "en-US";
+ // Other tracks that already have captions — each can seed this one by translation.
+ const sources = Array.from({ length: subtitleLaneCount(subtitles) }, (_, i) => i).filter(
+ (i) => i !== lane && laneCues(subtitles, i).length > 0
+ );
+ const [translating, setTranslating] = useState(false);
if (status === "running") {
return (
<div className="sub-generating flex flex-col items-center gap-3 px-6 pt-10 text-center">
<Loader2 className="size-5 animate-spin text-muted-foreground" />
- <p className="text-[13px] font-medium">Transcribing on this Mac…</p>
+ <p className="text-[13px] font-medium">
+ {translating ? "Translating your captions…" : "Transcribing on this Mac…"}
+ </p>
<p className="text-[11.5px] leading-relaxed text-muted-foreground">
Runs in the background — keep editing. Captions appear here when
it finishes.
@@ -328,7 +428,10 @@ function EmptyState({
<select
className="sub-locale w-full appearance-none rounded-lg border border-input bg-transparent py-2 pr-9 pl-2.5 text-[12.5px] outline-none focus:border-ring"
value={locale}
- onChange={(e) => useEditor.getState().setSubtitlesView({ locale: e.target.value })}
+ onChange={(e) => {
+ const s = useEditor.getState();
+ s.setSubtitleTrackMeta(s.subtitleLane, { locale: e.target.value });
+ }}
>
{LOCALES.map(([id, label]) => (
<option key={id} value={id}>
@@ -340,12 +443,32 @@ function EmptyState({
</div>
<Button
className="sub-generate w-full"
- onClick={onGenerate}
+ onClick={() => {
+ setTranslating(false);
+ onGenerate();
+ }}
title="Transcribe your audio into plain captions, word for word"
>
<Captions data-icon="inline-start" />
{status === "empty" || status === "error" ? "Try again" : "Generate subtitles"}
</Button>
+ {sources.map((i) => (
+ <Button
+ key={i}
+ variant="outline"
+ className="sub-translate w-full"
+ title={`Write this track by translating the ${laneLanguage(subtitles, i)} captions into ${
+ LOCALES.find(([id]) => id === locale)?.[1] ?? locale
+ }`}
+ onClick={() => {
+ setTranslating(true);
+ onTranslate(i);
+ }}
+ >
+ <Languages data-icon="inline-start" />
+ Translate from {laneLanguage(subtitles, i)}
+ </Button>
+ ))}
</div>
);
}
diff --git a/site/src/cut/components/Timeline.tsx b/site/src/cut/components/Timeline.tsx
index a1d9831c..8968f75c 100644
--- a/site/src/cut/components/Timeline.tsx
+++ b/site/src/cut/components/Timeline.tsx
@@ -19,13 +19,14 @@ import {
hasAssetDrag,
hasLibraryDrag,
} from "@/cut/lib/assetDrag";
-import { draggingRef, hasRefDrag, refFromAsset, startPointerRefDrag, type AssetRef } from "@/cut/lib/assetRef";
+import { draggingRef, hasRefDrag, type AssetRef } from "@/cut/lib/assetRef";
import { importLibraryAsset, saveTemplate } from "@/cut/lib/library";
import { isDragActive, startDrag, subscribeDragActive } from "@/cut/lib/drag";
import { CLIP_GAP, startLaneMove, startLaneTrim, type LaneDrag } from "@/cut/lib/laneTracks";
import { ensurePeaks, importImage, importStockVideo } from "@/cut/lib/media";
import { clipLen, clipSpeed, getClipSpans, projectDuration, TIMELINE_H_MAX, useEditor } from "@/cut/lib/store";
import type { VideoTrackPlacement } from "@/cut/lib/store";
+import { subtitleLaneCount } from "@/cut/lib/subtitles";
import { formatTime, formatTimecode } from "@/cut/lib/time";
import { IMAGE_CLIP_SECONDS, TRANSITION_STYLE_LABELS } from "@/cut/lib/types";
import type { AudioClip, ClipSpan, MediaAsset, OverlayClip, SubtitleCue, TextOverlay, TransitionStyle } from "@/cut/lib/types";
@@ -986,7 +987,7 @@ export function Timeline() {
{subtitles.showOnTimeline && subtitles.cues.length > 0 && (
<div
className="tl-sub-track relative mt-1.5"
- style={{ height: SUB_H }}
+ style={{ height: subtitleLaneCount(subtitles) * SUB_H }}
onPointerDown={deselectIfSelf}
>
{laneDrag?.kind === "cue" && (
@@ -1003,6 +1004,8 @@ export function Timeline() {
key={c.id}
cue={c}
pps={pps}
+ top={(c.lane ?? 0) * SUB_H}
+ baseRow={c.lane ?? 0}
selected={selKeys.has(`cue:${c.id}`)}
drag={laneDrag?.kind === "cue" && laneDrag.id === c.id ? laneDrag : null}
parting={laneDrag?.kind === "cue" && laneDrag.id !== c.id}
@@ -1234,37 +1237,31 @@ function Playhead({
function ClipView({
span,
- index,
prevOverlap,
pps,
selected,
drag,
- insertAtIndex,
- insertLen,
- scrollRef,
+ parting,
onDrag,
- onDrop,
+ onSnap,
resolveTarget,
onCrossMove,
onCrossDrop,
onDragActive,
}: {
span: ClipSpan;
- index: number;
/** Cross-dissolve overlap of the previous clip into this one, timeline
* seconds — the room the incoming transition block claims on this clip's
* left. This clip's own `span.transitionOut` claims the right. */
prevOverlap: number;
pps: number;
selected: boolean;
- drag: ClipDrag | null;
- /** While a media asset is dragged in, clips at/after this index part to
- * open a slot of `insertLen` seconds. Null when no asset drag is active. */
- insertAtIndex: number | null;
- insertLen: number;
- scrollRef: React.RefObject<HTMLDivElement | null>;
- onDrag: (id: string, dx: number, dy: number) => void;
- onDrop: (id: string, dx: number | null) => void;
+ /** This clip's live drag when it is the one being carried (ghost mode). */
+ drag: LaneDrag | null;
+ /** Another base clip is dragging: animate this one's parting shifts. */
+ parting: boolean;
+ onDrag: (d: LaneDrag | null) => void;
+ onSnap: (x: number | null) => void;
/** Which drop the given screen point is over (track / base / insert gap). */
resolveTarget: (clientX: number, clientY: number) => TrackTarget;
/** Preview a cross-track drop (null clears it). */
@@ -1274,53 +1271,25 @@ function ClipView({
/** Toggle the between-track insertion zones while this clip is dragging. */
onDragActive: (active: boolean) => void;
}) {
- // Left-trim keeps the box and its frames pinned: the handle sweeps through
- // the clip and the leading area dims as "hidden"; release collapses it.
- const [trim, setTrim] = useState<{ side: "l"; in0: number } | { side: "r" } | null>(null);
const { clip, asset } = span;
const speed = clipSpeed(clip);
// A cross-dissolve overlaps two clips; inset each box by half the overlap so
// the pair meets at the overlap midpoint with the same CLIP_GAP gutter as a
- // hard cut (the dissolve badge floats in that gap). An active trim drops the
- // insets so the handle sweeps the clip's true extent; the filmstrip start
- // backs up by exactly the pixels the box gains, so the frames stay pinned
- // through the reveal.
- const leftXf = trim ? 0 : prevOverlap / 2;
- const rightXf = trim ? 0 : span.transitionOut / 2;
+ // hard cut (the dissolve badge floats in that gap).
+ const leftXf = prevOverlap / 2;
+ const rightXf = span.transitionOut / 2;
const visStart = span.start + leftXf;
const visLen = Math.max(0, span.len - leftXf - rightXf);
const w = visLen * pps;
- const left = visStart * pps;
- const trimL = trim?.side === "l" ? trim : null;
- const stripIn = trimL ? Math.min(clip.in, trimL.in0) : clip.in;
- // Source seconds → timeline px goes through the clip's speed.
- const hidPx = trimL ? Math.max(0, ((clip.in - trimL.in0) / speed) * pps) : 0;
- const boxW = trimL ? ((clip.out - stripIn) / speed) * pps : w;
// Frames start where the box does: skip the source seconds the left dissolve
// consumed so the filmstrip stays aligned under the inset edge.
- const filmIn = stripIn + leftXf * speed;
- const isDragged = drag?.id === clip.id;
- // Neighbors part to make room for the open slot.
- const reorderShift =
- !drag || isDragged
- ? 0
- : drag.from < index && index <= drag.to
- ? -drag.len
- : drag.to <= index && index < drag.from
- ? drag.len
- : 0;
- // Clips at/after the media-drop point slide right to open the insertion slot.
- const insertShift = insertAtIndex !== null && index >= insertAtIndex ? insertLen : 0;
- const shiftSec = reorderShift + insertShift;
- const parting = drag !== null || insertAtIndex !== null;
-
- // During a left-trim the strip is computed from the drag-start in-point so
- // every frame stays pinned in place while the hidden region sweeps over it.
+ const filmIn = clip.in + leftXf * speed;
+
const filmstrip = useMemo(() => {
if (!asset.thumbs?.length || !asset.thumbStep) return [];
const aspect = (asset.width ?? 16) / Math.max(1, asset.height ?? 9);
const imgW = Math.max(26, Math.round((VIDEO_H - 4) * aspect));
- const count = Math.min(120, Math.ceil(boxW / imgW));
+ const count = Math.min(120, Math.ceil(w / imgW));
return Array.from({ length: count }, (_, k) => {
const timeAt = filmIn + ((k * imgW + imgW / 2) / pps) * speed;
const idx = Math.min(
@@ -1329,239 +1298,131 @@ function ClipView({
);
return { src: asset.thumbs![idx], left: k * imgW, width: imgW };
});
- }, [asset, filmIn, boxW, pps, speed]);
-
- const onBody = (e: React.PointerEvent) => {
- if (e.metaKey || e.shiftKey) {
- useEditor.getState().toggleSelect({ kind: "clip", id: clip.id });
- return;
- }
- const s = useEditor.getState();
- s.select({ kind: "clip", id: clip.id });
- // Clicking anywhere on the timeline moves the playhead — clips included.
- const rect = e.currentTarget.getBoundingClientRect();
- s.seek(visStart + (e.clientX - rect.left) / pps);
- const el = scrollRef.current;
- const sc0 = el?.scrollLeft ?? 0;
- let effDx = 0;
- let live = false;
- let target: TrackTarget = { kind: "base" };
- let dropStart = span.start;
- // Dragging a clip out of the timeline can also hand its asset to a
- // reference drop zone (AI chat, the image/video creators).
- const refDrag = startPointerRefDrag(refFromAsset(asset));
- startDrag(e, {
- onMove: (dx, dy, ev) => {
- if (!live && Math.abs(dx) < 4 && Math.abs(dy) < 4) return;
- if (!live) onDragActive(true);
- live = true;
- refDrag.move(ev);
- if (el) {
- const r = el.getBoundingClientRect();
- if (ev.clientX > r.right - 36) el.scrollLeft += 14;
- else if (ev.clientX < r.left + 36) el.scrollLeft -= 14;
- }
- effDx = dx + ((el?.scrollLeft ?? sc0) - sc0);
- dropStart = Math.max(0, span.start + effDx / pps);
- // On the base row it's a reorder; over an upper track or a gap it lifts.
- target = resolveTarget(ev.clientX, ev.clientY);
- if (target.kind === "base") {
- onCrossMove(null);
- onDrag(clip.id, effDx, Math.max(-26, Math.min(14, dy)));
- } else {
- onCrossMove(target, dropStart, span.len);
- }
- },
- onUp: () => {
- onDragActive(false);
- if (live && refDrag.drop()) {
- // A zone took the ref; cancel the timeline move.
- onCrossMove(null);
- return onDrop(clip.id, null);
- }
- if (!live) return onDrop(clip.id, null);
- if (target.kind === "base") onDrop(clip.id, effDx);
- else onCrossDrop(clip.id, target, dropStart);
- },
- });
- };
-
- // Shift later titles/captions by however much this clip's footprint changed.
- const rippleTrim = (len0: number) => {
- const c = useEditor.getState().clips.find((x) => x.id === clip.id);
- if (c) useEditor.getState().rippleShift(span.start + len0, clipLen(c) - len0);
- };
-
- const onTrimLeft = (e: React.PointerEvent) => {
- const s = useEditor.getState();
- s.select({ kind: "clip", id: clip.id });
- s.pushHistory();
- const in0 = clip.in;
- const len0 = span.len;
- setTrim({ side: "l", in0 });
- startDrag(e, {
- onMove: (dx) => {
- const nin = Math.min(clip.out - 0.15, Math.max(0, in0 + (dx / pps) * speed));
- s.updateClipTransient(clip.id, { in: nin });
- },
- onUp: () => {
- setTrim(null);
- rippleTrim(len0);
- },
- });
- };
+ }, [asset, filmIn, w, pps, speed]);
- const onTrimRight = (e: React.PointerEvent) => {
- const s = useEditor.getState();
- s.select({ kind: "clip", id: clip.id });
- s.pushHistory();
- setTrim({ side: "r" });
- const out0 = clip.out;
- const len0 = span.len;
- startDrag(e, {
- onMove: (dx) => {
- // A still has no source length, so its clip can stretch to any duration.
- const maxOut = asset.type === "image" ? Infinity : asset.duration;
- const nout = Math.max(clip.in + 0.15, Math.min(maxOut, out0 + (dx / pps) * speed));
- s.updateClipTransient(clip.id, { out: nout });
- },
- onUp: () => {
- setTrim(null);
- rippleTrim(len0);
- },
- });
+ // The move gesture is the shared lane behavior (parting, snapping); its
+ // verticality is the video placement system — upper tracks and insert
+ // gaps — resolved by DOM hit-testing.
+ const ui = {
+ pps,
+ rowH: VIDEO_H,
+ laneCount: 0,
+ baseRow: 0,
+ onDrag,
+ onSnap,
+ vertical: {
+ resolve: (ev: PointerEvent) => resolveTarget(ev.clientX, ev.clientY),
+ isHome: (t: TrackTarget) => samePlacement(t, { kind: "base" }),
+ preview: (t: TrackTarget | null, start: number, len: number) =>
+ t ? onCrossMove(t, start, len) : onCrossMove(null),
+ commit: (id: string, t: TrackTarget, start: number) => onCrossDrop(id, t, start),
+ setActive: onDragActive,
+ },
};
return (
- <>
- <div
- className={cn(
- "tl-clip group absolute top-0.5 cursor-grab overflow-hidden rounded-lg bg-neutral-200 shadow-[inset_0_0_0_1px_rgba(0,0,0,0.12)]",
- selected && SELECTED_SHADOW,
- clip.hidden && "opacity-40 grayscale",
- isDragged
- ? "tl-clip-ghost pointer-events-none z-7 cursor-grabbing opacity-80 shadow-2xl"
- : parting && "transition-transform duration-150 ease-out"
- )}
- style={{
- left,
- width: Math.max(10, boxW - CLIP_GAP),
- height: VIDEO_H - 4,
- transform: isDragged
- ? `translate(${drag!.dx}px, ${drag!.dy}px)`
- : shiftSec !== 0
- ? `translateX(${shiftSec * pps}px)`
- : undefined,
- }}
- onPointerDown={onBody}
- >
- <div className="tl-filmstrip pointer-events-none absolute inset-0">
- {filmstrip.map((f, k) => (
- // eslint-disable-next-line @next/next/no-img-element
- <img
- key={k}
- src={f.src}
- alt=""
- draggable={false}
- className="absolute top-0 h-full object-cover"
- style={{ left: f.left, width: f.width }}
- />
- ))}
- </div>
- {selected && (
- // A blue wash over the whole clip so a multi-selection reads at a
- // glance, not just from the thin border.
- <div className="pointer-events-none absolute inset-0 z-[1] bg-[#0a84ff]/25" />
- )}
- {hidPx > 0 && (
- <div
- className="tl-trim-hidden pointer-events-none absolute inset-y-0 left-0 z-2 border-r border-white/70 bg-black/55"
- style={{ width: hidPx }}
- />
- )}
- {(isDragged || trim !== null) && (
- <span
- className="tl-dur-chip pointer-events-none absolute top-1 z-2 rounded-[5px] bg-black/65 px-1.5 py-px font-mono text-[10px] tabular-nums text-white"
- style={{ left: hidPx + 4 }}
- >
- {(Math.round(span.len * 10) / 10).toFixed(1)}s
- </span>
- )}
- {asset.type === "video" && (
- <MuteChip
- muted={clip.muted}
- className="bottom-1 left-1"
- onToggle={() => useEditor.getState().updateClip(clip.id, { muted: !clip.muted })}
+ <div
+ className={cn(
+ "tl-clip group absolute top-0.5 cursor-grab overflow-hidden rounded-lg bg-neutral-200 shadow-[inset_0_0_0_1px_rgba(0,0,0,0.12)]",
+ selected && SELECTED_SHADOW,
+ clip.hidden && "opacity-40 grayscale",
+ drag
+ ? "tl-clip-ghost pointer-events-none cursor-grabbing opacity-80 shadow-2xl"
+ : parting && "transition-[left] duration-150 ease-out"
+ )}
+ style={{
+ // The ghost keeps the box's dissolve insets, offset to follow the pointer.
+ left: drag ? drag.ghostX + leftXf * pps : visStart * pps,
+ width: Math.max(10, w - CLIP_GAP),
+ height: VIDEO_H - 4,
+ // Inline so it beats SELECTED_SHADOW's z-10 class on the same element.
+ zIndex: drag ? 20 : undefined,
+ }}
+ onPointerDown={(e) => startLaneMove(e, "clip", clip.id, ui)}
+ >
+ <div className="tl-filmstrip pointer-events-none absolute inset-0">
+ {filmstrip.map((f, k) => (
+ // eslint-disable-next-line @next/next/no-img-element
+ <img
+ key={k}
+ src={f.src}
+ alt=""
+ draggable={false}
+ className="absolute top-0 h-full object-cover"
+ style={{ left: f.left, width: f.width }}
/>
- )}
- {(clip.speed ?? 1) !== 1 && (
- <span
- className="tl-speed-chip absolute right-[30px] bottom-1 z-2 rounded-[5px] bg-black/70 px-1 py-px font-mono text-[9.5px] tabular-nums text-white"
- title={`${clip.speed}× speed`}
- >
- {+(clip.speed ?? 1).toFixed(2)}×
- </span>
- )}
- <HideChip
- hidden={!!clip.hidden}
- className="bottom-1 right-2"
- onToggle={() => useEditor.getState().updateClip(clip.id, { hidden: !clip.hidden })}
- />
- {asset.type === "video" && (
- <DropdownMenu>
- <DropdownMenuTrigger
- render={
- <button
- aria-label="Clip options"
- className="tl-clip-menu absolute top-1 right-2 z-4 grid size-[18px] place-items-center rounded-[5px] bg-black/55 text-white opacity-0 transition-opacity group-hover:opacity-100 hover:bg-black/75"
- onPointerDown={(e) => e.stopPropagation()}
- />
- }
- >
- <EllipsisVertical className="size-3" />
- </DropdownMenuTrigger>
- <DropdownMenuContent align="start" className="w-44">
- <DropdownMenuItem
- disabled={clip.muted}
- onClick={() => {
- const s = useEditor.getState();
- s.select({ kind: "clip", id: clip.id });
- s.detachAudio();
- void ensurePeaks(asset);
- }}
- >
- <AudioLines /> Detach audio
- </DropdownMenuItem>
- </DropdownMenuContent>
- </DropdownMenu>
- )}
- <span
- className={cn(trimHandle, "tl-trim-l", trim?.side === "l" && "z-3 after:opacity-100")}
- style={{ left: hidPx }}
- onPointerDown={onTrimLeft}
+ ))}
+ </div>
+ {selected && (
+ // A blue wash over the whole clip so a multi-selection reads at a
+ // glance, not just from the thin border.
+ <div className="pointer-events-none absolute inset-0 z-[1] bg-[#0a84ff]/25" />
+ )}
+ {drag && (
+ <span className="tl-dur-chip pointer-events-none absolute top-1 left-1 z-2 rounded-[5px] bg-black/65 px-1.5 py-px font-mono text-[10px] tabular-nums text-white">
+ {(Math.round(span.len * 10) / 10).toFixed(1)}s
+ </span>
+ )}
+ {asset.type === "video" && (
+ <MuteChip
+ muted={clip.muted}
+ className="bottom-1 left-1"
+ onToggle={() => useEditor.getState().updateClip(clip.id, { muted: !clip.muted })}
/>
+ )}
+ {(clip.speed ?? 1) !== 1 && (
<span
- className={cn(trimHandle, "tl-trim-r right-0", trim?.side === "r" && "after:opacity-100")}
- onPointerDown={onTrimRight}
- />
- </div>
- {trim !== null && (
- <div
- className="tl-trim-tip pointer-events-none absolute z-9 -translate-x-1/2 rounded-md bg-foreground px-1.5 py-0.5 font-mono text-[10px] tabular-nums text-background shadow-md"
- style={{
- left: trim.side === "l" ? left + hidPx : left + Math.max(10, w - CLIP_GAP),
- top: -24,
- }}
+ className="tl-speed-chip absolute right-[30px] bottom-1 z-2 rounded-[5px] bg-black/70 px-1 py-px font-mono text-[9.5px] tabular-nums text-white"
+ title={`${clip.speed}× speed`}
>
- {formatTimecode(trim.side === "l" ? clip.in : clip.out)}
- </div>
+ {+(clip.speed ?? 1).toFixed(2)}×
+ </span>
+ )}
+ <HideChip
+ hidden={!!clip.hidden}
+ className="bottom-1 right-2"
+ onToggle={() => useEditor.getState().updateClip(clip.id, { hidden: !clip.hidden })}
+ />
+ {asset.type === "video" && (
+ <DropdownMenu>
+ <DropdownMenuTrigger
+ render={
+ <button
+ aria-label="Clip options"
+ className="tl-clip-menu absolute top-1 right-2 z-4 grid size-[18px] place-items-center rounded-[5px] bg-black/55 text-white opacity-0 transition-opacity group-hover:opacity-100 hover:bg-black/75"
+ onPointerDown={(e) => e.stopPropagation()}
+ />
+ }
+ >
+ <EllipsisVertical className="size-3" />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="start" className="w-44">
+ <DropdownMenuItem
+ disabled={clip.muted}
+ onClick={() => {
+ const s = useEditor.getState();
+ s.select({ kind: "clip", id: clip.id });
+ s.detachAudio();
+ void ensurePeaks(asset);
+ }}
+ >
+ <AudioLines /> Detach audio
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
)}
- </>
+ <span
+ className={cn(trimHandle, "tl-trim-l left-0")}
+ onPointerDown={(e) => startLaneTrim(e, "clip", clip.id, "l", ui)}
+ />
+ <span
+ className={cn(trimHandle, "tl-trim-r right-0")}
+ onPointerDown={(e) => startLaneTrim(e, "clip", clip.id, "r", ui)}
+ />
+ </div>
);
}
-/** Hover chip that toggles a clip out of the played/exported output ("disable").
- * Stays visible while the clip is hidden so re-enabling is one click. */
function HideChip({
hidden,
onToggle,
@@ -1950,6 +1811,8 @@ function TextBar({
function SubBar({
cue,
pps,
+ top,
+ baseRow,
selected,
drag,
parting,
@@ -1958,6 +1821,9 @@ function SubBar({
}: {
cue: SubtitleCue;
pps: number;
+ /** Rendered row top in px — one row per subtitle track (language). */
+ top: number;
+ baseRow: number;
selected: boolean;
/** This bar's live drag when it is the one being carried (ghost mode). */
drag: LaneDrag | null;
@@ -1967,12 +1833,12 @@ function SubBar({
onSnap: (x: number | null) => void;
}) {
const w = Math.max(8, (cue.end - cue.start) * pps);
- const ui = { pps, rowH: SUB_H, laneCount: 0, baseRow: 0, onDrag, onSnap };
+ const ui = { pps, rowH: SUB_H, laneCount: 0, baseRow, onDrag, onSnap };
return (
<div
className={cn(
- "tl-sub-bar group absolute top-px flex cursor-grab items-center overflow-hidden rounded-[5px] bg-gradient-to-b from-amber-300 to-amber-400 shadow-[inset_0_0_0_1px_rgba(0,0,0,0.12)]",
+ "tl-sub-bar group absolute flex cursor-grab items-center overflow-hidden rounded-[5px] bg-gradient-to-b from-amber-300 to-amber-400 shadow-[inset_0_0_0_1px_rgba(0,0,0,0.12)]",
selected && SELECTED_SHADOW,
drag
? "tl-sub-ghost pointer-events-none cursor-grabbing opacity-80 shadow-2xl"
@@ -1980,6 +1846,7 @@ function SubBar({
)}
style={{
left: drag ? drag.ghostX : cue.start * pps,
+ top: top + 1,
width: Math.max(8, w - CLIP_GAP),
height: SUB_H - 4,
// Inline so it beats SELECTED_SHADOW's z-10 class on the same element.
diff --git a/site/src/cut/lib/exportClient.ts b/site/src/cut/lib/exportClient.ts
index 02cdb9b9..307b9c3e 100644
--- a/site/src/cut/lib/exportClient.ts
+++ b/site/src/cut/lib/exportClient.ts
@@ -1,8 +1,8 @@
"use client";
import { apiFetch, apiJson, apiUrl } from "./api";
-import { clipSpeed, getClipSpans, projectDuration } from "./store";
-import { captionStyle, cueOverlay, cueWordWindows } from "./subtitles";
+import { clipSpeed, getClipSpans, projectDuration, spanSequence } from "./store";
+import { captionStyle, cueOverlay, cueWordWindows, laneCues, subtitleLaneCount, trackPos } from "./subtitles";
import { renderOverlayPng } from "./textRender";
import { FRAME } from "./types";
import type {
@@ -134,7 +134,7 @@ async function buildExportForm(
const form = new FormData();
const assetById = new Map(doc.assets.map((a) => [a.id, a]));
- const clips = spans.map((sp) => ({
+ const clipEntries = spans.map((sp) => ({
file: sp.asset.fileName,
in: sp.clip.in,
out: sp.clip.out,
@@ -166,8 +166,8 @@ async function buildExportForm(
const style = sp.clip.transitionStyle ?? "crossfade";
const d = sp.clip.transition ?? 0;
if (d <= 0) return;
- const a = clips[i];
- const b = clips[i + 1];
+ const a = clipEntries[i];
+ const b = clipEntries[i + 1];
if (style === "crosszoom" && sp.transitionOut > 0) {
a.tailZoom = sp.transitionOut;
b.headZoom = sp.transitionOut;
@@ -182,6 +182,36 @@ async function buildExportForm(
}
});
+ // The server's video graph is a sequential fold, so gaps between the
+ // free-placed clips ship as explicit spacer segments: no file, hidden and
+ // muted, which the server renders as black + silence for the gap's length.
+ const clips = spanSequence(spans).flatMap(({ gapBefore }, i) => [
+ ...(gapBefore > 0
+ ? [
+ {
+ file: "",
+ in: 0,
+ out: gapBefore,
+ muted: true,
+ volume: 0,
+ fit: "fit" as const,
+ panX: 0,
+ panY: 0,
+ frame: undefined,
+ speed: 1,
+ transition: 0,
+ hidden: true,
+ image: false,
+ headFade: 0,
+ tailFade: 0,
+ headZoom: 0,
+ tailZoom: 0,
+ },
+ ]
+ : []),
+ clipEntries[i],
+ ]);
+
// Upper video tracks composited over the base; hidden ones are dropped.
const overlayVideos = doc.overlayClips
.filter((c) => !c.hidden && assetById.has(c.assetId) && c.start < duration)
@@ -224,31 +254,42 @@ async function buildExportForm(
overlays.push({ file: key, start: o.start, end: Math.min(o.end, duration) });
}
- // Subtitle stills travel in their own spec lane: the server plays them as
- // one concat-demuxer slideshow (with a transparent filler frame for gaps),
- // so karaoke word windows don't each become an ffmpeg input.
- const captions: { file: string; start: number; end: number }[] = [];
+ // Subtitle stills travel in their own spec lane: the server plays each
+ // subtitle track as one concat-demuxer slideshow (with a transparent filler
+ // frame for gaps), so karaoke word windows don't each become an ffmpeg
+ // input. Tracks overlap each other in time, so every track (language) gets
+ // its own slideshow, marked by `lane`.
+ const captions: { file: string; start: number; end: number; lane?: number }[] = [];
if (doc.subtitles.showOnVideo) {
const capStyle = captionStyle(doc.subtitles.style);
- for (let i = 0; i < doc.subtitles.cues.length; i++) {
- const cue = doc.subtitles.cues[i];
- if (cue.start >= duration || !cue.text.trim()) continue;
- // Karaoke burns one frame per word window (the spoken word accented);
- // otherwise the whole cue is a single still.
- const windows = doc.subtitles.wordHighlight
- ? cueWordWindows(cue)
- : [{ start: cue.start, end: cue.end }];
- for (let wi = 0; wi < windows.length; wi++) {
- const win = windows[wi];
- if (win.start >= duration) break;
- const png = await renderOverlayPng(
- cueOverlay(cue, capStyle, i === 0, doc.subtitles, doc.subtitles.wordHighlight ? wi : undefined),
- settings.width,
- settings.height
- );
- const key = windows.length > 1 ? `sub_${i}_${wi}.png` : `sub_${i}.png`;
- form.append(key, png, key);
- captions.push({ file: key, start: win.start, end: Math.min(win.end, duration) });
+ for (let lane = 0; lane < subtitleLaneCount(doc.subtitles); lane++) {
+ const cues = laneCues(doc.subtitles, lane);
+ const pos = trackPos(doc.subtitles, capStyle, lane);
+ for (let i = 0; i < cues.length; i++) {
+ const cue = cues[i];
+ if (cue.start >= duration || !cue.text.trim()) continue;
+ // Karaoke burns one frame per word window (the spoken word accented);
+ // otherwise the whole cue is a single still.
+ const windows = doc.subtitles.wordHighlight
+ ? cueWordWindows(cue)
+ : [{ start: cue.start, end: cue.end }];
+ for (let wi = 0; wi < windows.length; wi++) {
+ const win = windows[wi];
+ if (win.start >= duration) break;
+ const png = await renderOverlayPng(
+ cueOverlay(cue, capStyle, i === 0, pos, doc.subtitles.wordHighlight ? wi : undefined),
+ settings.width,
+ settings.height
+ );
+ const key = windows.length > 1 ? `sub_${lane}_${i}_${wi}.png` : `sub_${lane}_${i}.png`;
+ form.append(key, png, key);
+ captions.push({
+ file: key,
+ start: win.start,
+ end: Math.min(win.end, duration),
+ ...(lane > 0 ? { lane } : {}),
+ });
+ }
}
}
if (captions.length > 0) {
diff --git a/site/src/cut/lib/laneTracks.ts b/site/src/cut/lib/laneTracks.ts
index df235ae2..71da8f92 100644
--- a/site/src/cut/lib/laneTracks.ts
+++ b/site/src/cut/lib/laneTracks.ts
@@ -181,9 +181,11 @@ const overlayClipAdapter: LaneAdapter<OverlayClip> = {
const cueAdapter: LaneAdapter<SubtitleCue> = {
minLen: 0.15,
+ // One row per language track, but no vertical retracking: a cue belongs to
+ // its language, and tracks are managed in the panel (capped at three).
multiLane: false,
raws: (s) => s.subtitles.cues,
- view: (c) => ({ id: c.id, start: c.start, len: c.end - c.start, lane: 0 }),
+ view: (c) => ({ id: c.id, start: c.start, len: c.end - c.start, lane: c.lane ?? 0 }),
apply: (patches) => useEditor.getState().updateCuesTransient(patches),
// Retiming detaches a cue from its word timings; an unmoved patch restores
// the originals, so parted neighbors that flow back keep theirs.
diff --git a/site/src/cut/lib/store.ts b/site/src/cut/lib/store.ts
index 9cd1f460..7b496ac3 100644
--- a/site/src/cut/lib/store.ts
+++ b/site/src/cut/lib/store.ts
@@ -13,6 +13,7 @@ import type {
StoredAsset,
SubtitleCue,
SubtitlesBlock,
+ SubtitleTrackMeta,
TemplateAudio,
TemplateLayer,
TemplateMedia,
@@ -22,7 +23,7 @@ import type {
VideoClip,
} from "./types";
import { apiFetch, apiJson } from "./api";
-import { emptySubtitles, IMAGE_CLIP_SECONDS, isCrossStyle, mediaUrl, SPEED_MAX, SPEED_MIN, TRANSITION_MAX } from "./types";
+import { emptySubtitles, IMAGE_CLIP_SECONDS, isCrossStyle, MAX_SUBTITLE_LANES, mediaUrl, SPEED_MAX, SPEED_MIN, TRANSITION_MAX } from "./types";
import { readTextStyle } from "./textStyle";
import { loadUiState, saveUiState } from "./uiState";
import { captureTimelineFrames } from "./visualFrames";
@@ -197,7 +198,21 @@ export interface EditorState {
/** Transcribe (if needed) then rewrite the cues into social captions in the
* given style, one-to-one so cue timings are preserved. */
generateCaptions: (style: "clean" | "hook" | "punchy") => Promise<void>;
+ /** Fill the active track by translating another track's cues into the active
+ * track's language. Timings copy over; word timings don't survive
+ * translation, so the new cues carry none. */
+ translateSubtitleTrack: (fromLane: number) => Promise<void>;
setSubtitlesView: (patch: Partial<Pick<SubtitlesBlock, "showOnVideo" | "showOnTimeline" | "locale" | "style" | "x" | "y" | "wordHighlight" | "accentMode" | "accentColor">>) => void;
+ /** The subtitle track (row) the panel edits and generation writes to. */
+ subtitleLane: number;
+ setSubtitleLane: (lane: number) => void;
+ /** Add a subtitle track — one language each, capped at MAX_SUBTITLE_LANES —
+ * and make it the active one. */
+ addSubtitleTrack: (locale?: string) => void;
+ /** Remove a subtitle track: drops its cues and shifts higher tracks down. */
+ removeSubtitleTrack: (lane: number) => void;
+ /** Patch one track's settings (locale, dragged caption anchor). */
+ setSubtitleTrackMeta: (lane: number, patch: Partial<SubtitleTrackMeta>) => void;
/** Commit a cue's edited text (empty text deletes the cue). */
setCueText: (id: string, text: string) => void;
/** Split a cue at a character offset — at real word timings when known. */
@@ -369,6 +384,7 @@ export const useEditor = create<EditorState>((set, get) => {
publish: { caption: "", tags: "", soundTitle: "", handle: "" },
notes: { text: "", publishedAt: "", links: [] },
subtitles: emptySubtitles(),
+ subtitleLane: 0,
subtitleStatus: "idle",
subtitleError: null,
exportOpen: false,
@@ -397,6 +413,7 @@ export const useEditor = create<EditorState>((set, get) => {
currentTime: 0,
playing: false,
subtitles: emptySubtitles(),
+ subtitleLane: 0,
subtitleStatus: "idle",
subtitleError: null,
exportOpen: false,
@@ -832,9 +849,8 @@ export const useEditor = create<EditorState>((set, get) => {
? s.clips.find((c) => c.id === source.id)
: s.overlayClips.find((c) => c.id === source.id);
if (!src) return;
- // Overlay source already snapshotted history on drag-start (it live-moved);
- // a base source hasn't been mutated yet, so snapshot now.
- if (source.kind === "base") push();
+ // No checkpoint here: the lane coordinator's drag gesture already pushed
+ // one at pointer-down, so the whole move is a single undo step.
const v = {
assetId: src.assetId,
in: src.in,
@@ -1282,9 +1298,11 @@ export const useEditor = create<EditorState>((set, get) => {
}
const duration = totalDuration(s.clips);
const assetById = new Map(s.assets.map((a) => [a.id, a]));
+ // Generation targets the active subtitle track, with its own language.
+ const lane = s.subtitleLane;
const spec = {
duration,
- locale: s.subtitles.locale ?? "en-US",
+ locale: s.subtitles.tracks?.[lane]?.locale ?? s.subtitles.locale ?? "en-US",
// The transcribe mix is a sequential fold, so gaps between the
// free-placed clips ship as explicit silent spacers (empty file).
clips: spanSequence(spans).flatMap(({ gapBefore, span: sp }) => [
@@ -1317,17 +1335,30 @@ export const useEditor = create<EditorState>((set, get) => {
try {
const cues = await runTranscription(projectId, spec);
if (cues === null) return; // switched projects mid-run
+ // Only the active track's cues are replaced; other languages stay.
+ const tagged = cues.map((c) => ({ ...c, ...(lane > 0 ? { lane } : {}) }));
if (cues.length === 0) {
- // No speech in the audio — leave the video untouched.
+ // No speech in the audio — leave the other tracks untouched.
set((cur) => ({
- subtitles: { ...cur.subtitles, cues: [], generatedAt: Date.now() },
+ subtitles: {
+ ...cur.subtitles,
+ cues: cur.subtitles.cues.filter((c) => (c.lane ?? 0) !== lane),
+ generatedAt: Date.now(),
+ },
subtitleStatus: "empty",
}));
return;
}
push();
set((cur) => ({
- subtitles: { ...cur.subtitles, cues, generatedAt: Date.now() },
+ subtitles: {
+ ...cur.subtitles,
+ cues: [
+ ...cur.subtitles.cues.filter((c) => (c.lane ?? 0) !== lane),
+ ...tagged,
+ ].sort((a, b) => a.start - b.start),
+ generatedAt: Date.now(),
+ },
subtitleStatus: "ready",
}));
} catch (err) {
@@ -1348,11 +1379,12 @@ export const useEditor = create<EditorState>((set, get) => {
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.");
+ const lane = s.subtitleLane;
// 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",
+ locale: s.subtitles.tracks?.[lane]?.locale ?? s.subtitles.locale ?? "en-US",
clips: [
{
file: sp.asset.fileName,
@@ -1371,17 +1403,20 @@ export const useEditor = create<EditorState>((set, get) => {
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.
+ // on the active track that overlapped the clip; the rest of the
+ // timeline — and every other track — 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 })),
+ ...(lane > 0 ? { lane } : {}),
}));
if (placed.length > 0) push();
set((cur) => {
const kept = cur.subtitles.cues.filter(
- (c) => !(c.end > sp.start && c.start < sp.start + sp.len)
+ (c) =>
+ (c.lane ?? 0) !== lane || !(c.end > sp.start && c.start < sp.start + sp.len)
);
const merged = [...kept, ...placed].sort((a, b) => a.start - b.start);
return {
@@ -1408,6 +1443,7 @@ export const useEditor = create<EditorState>((set, get) => {
return;
}
const duration = totalDuration(s.clips);
+ const lane = s.subtitleLane;
set({ subtitleStatus: "running", subtitleError: null });
try {
const frames = await captureTimelineFrames(spans);
@@ -1415,7 +1451,11 @@ export const useEditor = create<EditorState>((set, get) => {
const res = await apiFetch("/api/cut/ai/visual-subtitles", {
method: "POST",
headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ frames, duration, locale: s.subtitles.locale ?? "en-US" }),
+ body: JSON.stringify({
+ frames,
+ duration,
+ locale: s.subtitles.tracks?.[lane]?.locale ?? s.subtitles.locale ?? "en-US",
+ }),
});
const body = await apiJson<{
cues?: { start: number; end: number; text: string }[];
@@ -1429,10 +1469,18 @@ export const useEditor = create<EditorState>((set, get) => {
start: c.start,
end: c.end,
text: c.text,
+ ...(lane > 0 ? { lane } : {}),
}));
push();
set((cur) => ({
- subtitles: { ...cur.subtitles, cues, generatedAt: Date.now() },
+ subtitles: {
+ ...cur.subtitles,
+ cues: [
+ ...cur.subtitles.cues.filter((c) => (c.lane ?? 0) !== lane),
+ ...cues,
+ ].sort((a, b) => a.start - b.start),
+ generatedAt: Date.now(),
+ },
subtitleStatus: cues.length > 0 ? "ready" : "empty",
}));
} catch (err) {
@@ -1447,10 +1495,12 @@ export const useEditor = create<EditorState>((set, get) => {
generateCaptions: async (style) => {
const s = get();
if (!s.projectId || s.subtitleStatus === "running") return;
- // Need cues first — transcribe if the cut hasn't been captioned yet.
- if (s.subtitles.cues.length === 0) {
+ const lane = s.subtitleLane;
+ const laneOf = (c: SubtitleCue) => c.lane ?? 0;
+ // Need cues first — transcribe if the active track hasn't been captioned.
+ if (!s.subtitles.cues.some((c) => laneOf(c) === lane)) {
await s.generateSubtitles();
- if (get().subtitles.cues.length === 0) return; // no speech, or an error
+ if (!get().subtitles.cues.some((c) => laneOf(c) === lane)) return; // no speech, or an error
}
const projectId = get().projectId;
// Apply the look right away for instant feedback, then rewrite the text.
@@ -1459,7 +1509,8 @@ export const useEditor = create<EditorState>((set, get) => {
subtitleStatus: "running",
subtitleError: null,
}));
- const cues = get().subtitles.cues;
+ // Rewrite only the active track — other languages keep their text.
+ const cues = get().subtitles.cues.filter((c) => laneOf(c) === lane);
try {
const res = await apiFetch("/api/cut/ai/captions", {
method: "POST",
@@ -1503,9 +1554,149 @@ export const useEditor = create<EditorState>((set, get) => {
}
},
+ translateSubtitleTrack: async (fromLane) => {
+ const s = get();
+ const lane = s.subtitleLane;
+ if (!s.projectId || s.subtitleStatus === "running" || fromLane === lane) return;
+ const laneOf = (c: SubtitleCue) => c.lane ?? 0;
+ const source = s.subtitles.cues.filter((c) => laneOf(c) === fromLane);
+ if (source.length === 0) return;
+ const locale =
+ s.subtitles.tracks?.[lane]?.locale ??
+ (lane === 0 ? s.subtitles.locale : undefined) ??
+ "en-US";
+ const projectId = s.projectId;
+ set({ subtitleStatus: "running", subtitleError: null });
+ try {
+ const res = await apiFetch("/api/cut/ai/captions", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ translateTo: locale,
+ cues: source.map((c) => ({ start: c.start, end: c.end, text: c.text })),
+ }),
+ });
+ const body = await apiJson<{ texts?: string[]; error?: string }>(res);
+ if (get().projectId !== projectId) return;
+ if (!res.ok || !Array.isArray(body.texts) || body.texts.length !== source.length) {
+ throw new Error(body.error || "Could not translate the captions.");
+ }
+ push();
+ const texts = body.texts;
+ set((cur) => ({
+ subtitles: {
+ ...cur.subtitles,
+ cues: [
+ ...cur.subtitles.cues.filter((c) => laneOf(c) !== lane),
+ ...source.map((c, i) => ({
+ id: uid(),
+ start: c.start,
+ end: c.end,
+ text: texts[i],
+ ...(lane > 0 ? { lane } : {}),
+ })),
+ ].sort((a, b) => a.start - b.start),
+ generatedAt: Date.now(),
+ },
+ subtitleStatus: "ready",
+ }));
+ } catch (err) {
+ if (get().projectId !== projectId) return;
+ set({
+ subtitleStatus: "error",
+ subtitleError: err instanceof Error ? err.message : String(err),
+ });
+ }
+ },
+
setSubtitlesView: (patch) =>
set((s) => ({ subtitles: { ...s.subtitles, ...patch } })),
+ setSubtitleLane: (lane) => {
+ const count = Math.max(
+ 1,
+ get().subtitles.tracks?.length ?? 0,
+ ...get().subtitles.cues.map((c) => (c.lane ?? 0) + 1)
+ );
+ set({ subtitleLane: Math.max(0, Math.min(count - 1, lane)) });
+ },
+
+ addSubtitleTrack: (locale) => {
+ const s = get();
+ const count = Math.max(
+ 1,
+ s.subtitles.tracks?.length ?? 0,
+ ...s.subtitles.cues.map((c) => (c.lane ?? 0) + 1)
+ );
+ if (count >= MAX_SUBTITLE_LANES) return;
+ push();
+ // Materialize metas up to the new track so indices stay aligned.
+ const tracks: SubtitleTrackMeta[] = Array.from(
+ { length: count + 1 },
+ (_, i) => s.subtitles.tracks?.[i] ?? {}
+ );
+ tracks[count] = { ...(locale ? { locale } : {}) };
+ set((cur) => ({
+ subtitles: { ...cur.subtitles, tracks },
+ subtitleLane: count,
+ }));
+ },
+
+ removeSubtitleTrack: (lane) => {
+ const s = get();
+ const count = Math.max(
+ 1,
+ s.subtitles.tracks?.length ?? 0,
+ ...s.subtitles.cues.map((c) => (c.lane ?? 0) + 1)
+ );
+ if (count <= 1) return;
+ push();
+ const gone = new Set(
+ s.subtitles.cues.filter((c) => (c.lane ?? 0) === lane).map((c) => c.id)
+ );
+ const keep = (sel: Selection) => !!sel && !(sel.kind === "cue" && gone.has(sel.id));
+ set((cur) => {
+ const tracks = Array.from(
+ { length: count },
+ (_, i) => cur.subtitles.tracks?.[i] ?? {}
+ ).filter((_, i) => i !== lane);
+ const multiSelection = cur.multiSelection.filter(keep);
+ return {
+ subtitles: {
+ ...cur.subtitles,
+ tracks,
+ cues: cur.subtitles.cues
+ .filter((c) => (c.lane ?? 0) !== lane)
+ .map((c) => {
+ const l = c.lane ?? 0;
+ return l > lane ? { ...c, lane: l - 1 > 0 ? l - 1 : undefined } : c;
+ }),
+ },
+ subtitleLane: Math.max(0, Math.min(count - 2, cur.subtitleLane)),
+ multiSelection,
+ selection: keep(cur.selection)
+ ? cur.selection
+ : multiSelection[multiSelection.length - 1] ?? null,
+ };
+ });
+ },
+
+ setSubtitleTrackMeta: (lane, patch) =>
+ set((s) => {
+ const count = Math.max(
+ 1,
+ s.subtitles.tracks?.length ?? 0,
+ ...s.subtitles.cues.map((c) => (c.lane ?? 0) + 1),
+ lane + 1
+ );
+ const tracks: SubtitleTrackMeta[] = Array.from(
+ { length: count },
+ (_, i) => s.subtitles.tracks?.[i] ?? {}
+ );
+ tracks[lane] = { ...tracks[lane], ...patch };
+ return { subtitles: { ...s.subtitles, tracks } };
+ }),
+
setCueText: (id, text) => {
const trimmed = text.replace(/\s+/g, " ").trim();
const cue = get().subtitles.cues.find((c) => c.id === id);
@@ -1584,12 +1775,17 @@ export const useEditor = create<EditorState>((set, get) => {
},
mergeCueIntoPrev: (id) => {
- const cues = get().subtitles.cues;
+ const all = get().subtitles.cues;
+ const cue = all.find((c) => c.id === id);
+ if (!cue) return;
+ // "Previous" means the previous cue on the same subtitle track.
+ const cues = all
+ .filter((c) => (c.lane ?? 0) === (cue.lane ?? 0))
+ .sort((a, b) => a.start - b.start);
const i = cues.findIndex((c) => c.id === id);
if (i <= 0) return;
push();
const prev = cues[i - 1];
- const cue = cues[i];
const merged: SubtitleCue = {
...prev,
end: Math.max(prev.end, cue.end),
diff --git a/site/src/cut/lib/subtitles.ts b/site/src/cut/lib/subtitles.ts
index 92045c76..d128464c 100644
--- a/site/src/cut/lib/subtitles.ts
+++ b/site/src/cut/lib/subtitles.ts
@@ -1,8 +1,46 @@
import { formatTime } from "./time";
-import type { CaptionStyleId, FontId, SubtitleCue, TextOverlay, WordAccentMode } from "./types";
+import type {
+ CaptionStyleId,
+ FontId,
+ SubtitleCue,
+ SubtitlesBlock,
+ TextOverlay,
+ WordAccentMode,
+} from "./types";
export type { CaptionStyleId } from "./types";
+/** How many subtitle tracks (languages) the block carries: its track metas,
+ * or any higher lane a cue still sits on; at least one. */
+export function subtitleLaneCount(subs: SubtitlesBlock): number {
+ let n = Math.max(1, subs.tracks?.length ?? 0);
+ for (const c of subs.cues) n = Math.max(n, (c.lane ?? 0) + 1);
+ return n;
+}
+
+/** One track's cues, in start order. */
+export function laneCues(subs: SubtitlesBlock, lane: number): SubtitleCue[] {
+ return subs.cues.filter((c) => (c.lane ?? 0) === lane);
+}
+
+/** A track's effective caption anchor plus the block's karaoke overrides —
+ * the `pos` argument `cueOverlay` takes. The track's own dragged spot wins,
+ * then the block-level legacy spot (first track only), then the style's
+ * default stacked upward per track so simultaneous languages never overlap. */
+export function trackPos(
+ subs: SubtitlesBlock,
+ style: CaptionStyle,
+ lane: number
+): { x: number; y: number; accentMode?: WordAccentMode; accentColor?: string } {
+ const meta = subs.tracks?.[lane];
+ return {
+ x: meta?.x ?? (lane === 0 ? subs.x : undefined) ?? style.x,
+ y: meta?.y ?? (lane === 0 ? subs.y : undefined) ?? Math.max(0.08, style.y - lane * 0.1),
+ accentMode: subs.accentMode,
+ accentColor: subs.accentColor,
+ };
+}
+
/** Caption look shared by the preview layer and the export burn-in —
* TikTok-style bold white on a translucent plate, low center. */
export const SUB_STYLE = {
diff --git a/site/src/cut/lib/types.ts b/site/src/cut/lib/types.ts
index ba4baec0..fbb5cd87 100644
--- a/site/src/cut/lib/types.ts
+++ b/site/src/cut/lib/types.ts
@@ -348,6 +348,26 @@ export interface SubtitleCue {
* (text swapped in place); adding/removing a word drops them and splitting
* falls back to proportional timing. */
words?: { t0: number; t1: number; w: string }[];
+ /** Which subtitle track (row) this belongs to, 0-based — one language per
+ * track (e.g. English on 0, Korean on 1), up to MAX_SUBTITLE_LANES. Absent
+ * = the first track. Tracks are managed in the panel, so lanes never
+ * renumber under a cue. */
+ lane?: number;
+}
+
+/** The most subtitle tracks (languages) a project can carry. */
+export const MAX_SUBTITLE_LANES = 3;
+
+/** Per-track subtitle settings; `SubtitlesBlock.tracks` indexes these by cue
+ * lane. Everything else about captions (style, karaoke, visibility) stays
+ * block-level and applies to every track. */
+export interface SubtitleTrackMeta {
+ /** Speech-recognition and display language for this track. */
+ locale?: string;
+ /** Caption anchor as frame fractions; absent = the style's spot, stacked
+ * upward per track so simultaneous languages never sit on each other. */
+ x?: number;
+ y?: number;
}
/** Caption look preset ids; the presets themselves live in lib/subtitles.ts. */
@@ -365,16 +385,20 @@ export type CaptionStyleId =
export interface SubtitlesBlock {
cues: SubtitleCue[];
+ /** Per-track settings, indexed by cue lane (absent entries = defaults).
+ * The number of tracks is max(tracks.length, highest cue lane + 1, 1). */
+ tracks?: SubtitleTrackMeta[];
/** Render captions on the preview and burn them into exports. */
showOnVideo: boolean;
- /** Show the cue track on the timeline. */
+ /** Show the cue track(s) on the timeline. */
showOnTimeline: boolean;
+ /** Legacy single-track language; per-track locales live in `tracks`. */
locale?: string;
generatedAt?: number;
/** Caption look preset; absent = the plain "clean" subtitle style. */
style?: CaptionStyleId;
- /** Caption anchor as frame fractions, applied to every cue. Absent = the
- * style preset's spot (low center). Dragging the caption in the preview sets it. */
+ /** Legacy caption anchor for the first track; dragging now writes the
+ * per-track anchor in `tracks`. Read as the lane-0 fallback. */
x?: number;
y?: number;
/** Karaoke mode: each word lights up as it is spoken, in the preview and
diff --git a/site/src/cut/lib/voiceover.ts b/site/src/cut/lib/voiceover.ts
index 4a05eb98..12ff8508 100644
--- a/site/src/cut/lib/voiceover.ts
+++ b/site/src/cut/lib/voiceover.ts
@@ -11,12 +11,15 @@ interface ReadoutCue {
start: number;
}
-/** The cues to voice, in timeline order: all subtitle cues, or just `cueIds`. */
+/** The cues to voice, in timeline order: the active subtitle track's cues
+ * (reading every language at once would talk over itself), or just `cueIds`. */
function readoutCues(cueIds?: string[]): ReadoutCue[] {
const wanted = cueIds && new Set(cueIds);
- return useEditor
- .getState()
- .subtitles.cues.filter((c) => c.text.trim() && (!wanted || wanted.has(c.id)))
+ const s = useEditor.getState();
+ return s.subtitles.cues
+ .filter((c) =>
+ c.text.trim() && (wanted ? wanted.has(c.id) : (c.lane ?? 0) === s.subtitleLane)
+ )
.map((c) => ({ id: c.id, text: c.text, start: c.start }));
}
diff --git a/site/src/cut/server/ai/captions.ts b/site/src/cut/server/ai/captions.ts
index fd70b22f..e1287b16 100644
--- a/site/src/cut/server/ai/captions.ts
+++ b/site/src/cut/server/ai/captions.ts
@@ -49,6 +49,36 @@ ${numbered}`;
return arr.map((s, i) => (s && s.trim() ? s.trim() : originals[i]));
}
+/** Translate cues one-to-one into the target locale's language, timings
+ * untouched. Unlike the style rewrite, a failed translation throws — falling
+ * back to the source language would silently fill the track with wrong text. */
+export async function translateCaptions(cues: CaptionInput[], locale: string): Promise<string[]> {
+ const numbered = cues.map((c, i) => `${i + 1}. ${c.text}`).join("\n");
+ let language = locale;
+ try {
+ language = new Intl.DisplayNames(["en"], { type: "language" }).of(locale) ?? locale;
+ } catch {
+ /* unknown locale tag — the raw tag still reads fine in the prompt */
+ }
+ const prompt = `You translate subtitle lines for a short-form social video.
+
+Translate EACH numbered line below into ${language}. Rules:
+- Return EXACTLY ${cues.length} lines — one translation per input line, in the same order.
+- Translate naturally, preserving the meaning and tone — not word-for-word.
+- Mirror the original's brevity: each caption must stay short enough to fit in a vertical video frame.
+- Keep emoji, proper names, and numbers as they are.
+
+Return ONLY a JSON array of ${cues.length} strings. No commentary, no code fence.
+
+Lines:
+${numbered}`;
+
+ const text = await Promise.race([runOnce(prompt), timeout(90_000)]);
+ const arr = parseStringArray(text);
+ if (!arr || arr.length !== cues.length) throw new Error("The translation came back malformed.");
+ return arr.map((s, i) => (s && s.trim() ? s.trim() : cues[i].text));
+}
+
function timeout(ms: number): Promise<never> {
return new Promise((_resolve, reject) => {
setTimeout(() => reject(new Error("timeout")), ms).unref();
diff --git a/site/src/cut/server/http/ai.ts b/site/src/cut/server/http/ai.ts
index 4fc1af43..39bf8d88 100644
--- a/site/src/cut/server/http/ai.ts
+++ b/site/src/cut/server/http/ai.ts
@@ -11,7 +11,7 @@ import {
unregisterSession,
type UIChunkWriter,
} from "../ai/bridge";
-import { rewriteCaptions } from "../ai/captions";
+import { rewriteCaptions, translateCaptions } from "../ai/captions";
import { writeVisualCues, type VisualFrame } from "../ai/visualSubtitles";
import { AI_SKILL_INDEX, AI_SKILLS, AI_TOOLS, systemPrompt } from "../ai/catalog";
@@ -284,18 +284,24 @@ const mcpText = (value: unknown) => ({
/** The AI assistant: chat streaming, provider probing, and the MCP bridge. */
export const aiApi = {
- /** Rewrite subtitle cues into punchy social captions (one-to-one, timings
- * preserved). Falls back to the originals on any failure. */
+ /** Rewrite subtitle cues into punchy social captions, or — when translateTo
+ * carries a locale — translate them into that language. One-to-one either
+ * way, timings preserved. The style rewrite falls back to the originals on
+ * failure; a failed translation errors instead. */
async captions(req: Request) {
try {
- const { cues, style } = (await req.json()) as {
+ const { cues, style, translateTo } = (await req.json()) as {
cues?: { start: number; end: number; text: string }[];
style?: string;
+ translateTo?: string;
};
if (!Array.isArray(cues) || cues.length === 0) {
return Response.json({ error: "No cues to rewrite." }, { status: 400 });
}
- const texts = await rewriteCaptions(cues, typeof style === "string" ? style : "clean");
+ const texts =
+ typeof translateTo === "string" && translateTo
+ ? await translateCaptions(cues, translateTo)
+ : await rewriteCaptions(cues, typeof style === "string" ? style : "clean");
return Response.json({ texts });
} catch (e) {
return Response.json(
diff --git a/site/src/cut/server/jobs.ts b/site/src/cut/server/jobs.ts
index 47445781..56fba251 100644
--- a/site/src/cut/server/jobs.ts
+++ b/site/src/cut/server/jobs.ts
@@ -81,10 +81,12 @@ export interface ExportSpec {
duck?: number;
}[];
overlays: { file: string; start: number; end: number }[];
- /** Burned-in subtitle stills, non-overlapping and chronological. Kept apart
- * from `overlays` (titles may overlap each other): these render as one
- * concat-demuxer slideshow, so karaoke word windows don't multiply inputs. */
- captions?: { file: string; start: number; end: number }[];
+ /** Burned-in subtitle stills. Kept apart from `overlays` (titles may
+ * overlap each other): each subtitle track (`lane`, absent = 0) is
+ * non-overlapping and chronological within itself and renders as one
+ * concat-demuxer slideshow, so karaoke word windows don't multiply inputs.
+ * Tracks overlap each other in time (one language each). */
+ captions?: { file: string; start: number; end: number; lane?: number }[];
}
export interface Job {
@@ -361,14 +363,17 @@ async function runExport(job: Job, spec: ExportSpec) {
// One ffmpeg input per distinct media file (from the project folder),
// plus one per uploaded overlay PNG.
// Still images are excluded here: a plain `-i file` decodes one frame, so
- // each image clip/overlay gets its own looped input below instead.
+ // each image clip/overlay gets its own looped input below instead. Gap
+ // spacers (empty file) reference no media at all — they render as black.
const mediaFiles = [
...new Set(
[
...spec.clips.filter((c) => !c.image),
...spec.audio,
...overlayVideos.filter((o) => !o.image),
- ].map((c) => c.file)
+ ]
+ .map((c) => c.file)
+ .filter(Boolean)
),
];
const audioPresence = new Map<string, boolean>();
@@ -410,7 +415,7 @@ async function runExport(job: Job, spec: ExportSpec) {
const imageClipInput = new Map<number, number>();
for (let j = 0; j < spec.clips.length; j++) {
const c = spec.clips[j];
- if (!c.image) continue;
+ if (!c.image || !c.file) continue;
const dur = Math.max(0.1, (c.out - c.in) / clipRate(c));
imageClipInput.set(j, nInputs++);
inputs.push("-loop", "1", "-t", num(dur), "-framerate", String(fps), "-i", await resolveMedia(spec, c.file));
@@ -424,18 +429,24 @@ async function runExport(job: Job, spec: ExportSpec) {
inputs.push("-loop", "1", "-t", num(olen), "-framerate", String(fps), "-i", await resolveMedia(spec, oc.file));
}
- // One concat-demuxer input for all subtitle stills: cues never overlap, so
- // they play as a slideshow with transparent filler ("sub_blank.png", uploaded
- // with the stills) covering the gaps.
- let captionsIdx: number | null = null;
- const captions = (spec.captions ?? [])
- .filter((c) => c.end > c.start)
- .sort((a, b) => a.start - b.start);
- if (captions.length > 0) {
+ // One concat-demuxer input per subtitle track: within a track cues never
+ // overlap, so each plays as a slideshow with transparent filler
+ // ("sub_blank.png", uploaded with the stills) covering the gaps. Tracks
+ // (languages) overlap each other, so each gets its own input.
+ const captionLanes = new Map<number, NonNullable<ExportSpec["captions"]>>();
+ for (const c of spec.captions ?? []) {
+ if (c.end <= c.start) continue;
+ const lane = c.lane ?? 0;
+ if (!captionLanes.has(lane)) captionLanes.set(lane, []);
+ captionLanes.get(lane)!.push(c);
+ }
+ const captionInputs: number[] = [];
+ for (const [lane, entries] of [...captionLanes.entries()].sort((a, b) => a[0] - b[0])) {
+ entries.sort((a, b) => a.start - b.start);
const blank = path.join(job.tmpDir, "sub_blank.png");
const lines = ["ffconcat version 1.0"];
let cursor = 0;
- for (const c of captions) {
+ for (const c of entries) {
const from = Math.max(c.start, cursor);
if (c.end - from < 1e-3) continue;
if (from - cursor > 1e-3) lines.push(`file '${blank}'`, `duration ${num(from - cursor)}`);
@@ -448,9 +459,9 @@ async function runExport(job: Job, spec: ExportSpec) {
if (spec.duration - cursor > 1e-3) {
lines.push(`file '${blank}'`, `duration ${num(spec.duration - cursor)}`);
}
- const list = path.join(job.tmpDir, "captions.ffconcat");
+ const list = path.join(job.tmpDir, `captions_${lane}.ffconcat`);
await writeFile(list, lines.join("\n") + "\n");
- captionsIdx = nInputs++;
+ captionInputs.push(nInputs++);
inputs.push("-f", "concat", "-safe", "0", "-i", list);
}
@@ -685,14 +696,14 @@ async function runExport(job: Job, spec: ExportSpec) {
vLabel = next;
});
- // Subtitle stills ride one concat-demuxer slideshow (transparent filler in
- // the gaps), so a karaoke cut with hundreds of word windows still costs a
- // single ffmpeg input instead of one per still.
- if (captionsIdx !== null) {
- filters.push(`[${captionsIdx}:v]fps=${fps},format=yuva420p,setsar=1[caps]`);
- filters.push(`[${vLabel}][caps]overlay=0:0:eof_action=pass[vcaps]`);
- vLabel = "vcaps";
- }
+ // Subtitle stills ride one concat-demuxer slideshow per track (transparent
+ // filler in the gaps), so a karaoke cut with hundreds of word windows still
+ // costs one ffmpeg input per language instead of one per still.
+ captionInputs.forEach((idx, k) => {
+ filters.push(`[${idx}:v]fps=${fps},format=yuva420p,setsar=1[caps${k}]`);
+ filters.push(`[${vLabel}][caps${k}]overlay=0:0:eof_action=pass[vcaps${k}]`);
+ vLabel = `vcaps${k}`;
+ });
// Voiceover ducking: while a ducking clip plays, every other sound drops to
// its gain. The windows are timeline seconds, so the volume automation must
diff --git a/site/src/cut/server/transcribe.ts b/site/src/cut/server/transcribe.ts
index ed5ef591..2623e771 100644
--- a/site/src/cut/server/transcribe.ts
+++ b/site/src/cut/server/transcribe.ts
@@ -187,8 +187,9 @@ async function runTranscribe(job: TranscribeJob, spec: TranscribeSpec) {
try {
// Render the cut's audible mix (clip audio + soundtrack, in timeline
// time) to a 16 kHz mono wav — the same graph the export uses, minus
- // video, so cue times line up with the timeline exactly.
- const files = [...new Set([...spec.clips, ...spec.audio].map((c) => c.file))];
+ // video, so cue times line up with the timeline exactly. Gap spacers
+ // (empty file) reference no media — they mix in as silence.
+ const files = [...new Set([...spec.clips, ...spec.audio].map((c) => c.file).filter(Boolean))];
const inputs: string[] = [];
const inputIndex = new Map<string, number>();
const audible = new Map<string, boolean>();