Skip to content

Open source CapCut alternative.

TypeScript

feat(site): emphasize caption words, place each cue [rebuild]

David Lee2c7d811000d
diff --git a/site/src/clients/chatgpt/server/guidance.ts b/site/src/clients/chatgpt/server/guidance.ts
index 224831d3..588116a2 100644
--- a/site/src/clients/chatgpt/server/guidance.ts
+++ b/site/src/clients/chatgpt/server/guidance.ts
@@ -53,14 +53,14 @@ For one exact instance among similar subjects, ask the user to use Custom, Brush
"graphics": `# Titles, graphics and motion
Use add_title or add_text_sequence for words, add_shape for geometry, add_sticker for an imported image, and add_effect for a treatment over a time range. Read describe_commands for the current supported styles and parameters. set_background sets the project's background color. Use ids and fonts reported by inspect_project.
update_overlay changes text, position, size, color and other element fields, and accepts ids for changes shared by several elements. Layout coordinates are frame fractions. Keep text inside the project's reported safe zones and check legibility with capture_frame.
-set_overlay_keyframes and set_clip_keyframes animate poses at exact times. set_overlay_animation supplies entrances, exits, loops and word motion. set_mask clips a layer to a shape and can animate the reveal. Read text-videos for timed text and text-creativity for design choices.
+set_overlay_keyframes and set_clip_keyframes animate poses at exact times. set_group_camera moves one camera over a group of elements, and blur and motion blur soften what the camera is not on. set_overlay_animation supplies entrances, exits, loops, word motion, a typing caret and a one-shot press at a chosen moment. set_mask clips a layer to a shape and can animate the reveal. Read text-videos for timed text and text-creativity for design choices.
Build composite effects as layers: add_overlay_video for copies of footage, masks for visible regions, shapes for bands, and text for labels. Match source trims so copied footage stays synchronized. Work out geometry and timing, build one representative piece, capture_frame to check it, then repeat and check the whole composition. create_sticker generates a new sticker and spends credits when the user requests it.`,
"audio-and-subtitles": `# Audio and subtitles
Listen to the relevant source with listen_audio. Use detect_silence for pauses, detect_beats for music timing, and measure_level for level matching. Its volumeToMatch result can drive set_clip_volume or update_audio; use a fraction for a music bed beneath speech. Read watching-and-cutting for coverage and source-time rules.
-update_audio edits soundtrack timing, source trim, volume, fades and ducking. A clip's duck lowers other audio while it plays. set_clip_sound applies EQ, compression and limiting to one clip; add_effect treats a time range of the mix. describe_commands supplies the supported presets and settings.
+update_audio edits soundtrack timing, source trim, volume, fades and ducking. A clip's duck lowers other audio while it plays. set_clip_sound applies EQ, compression and limiting to one clip; add_effect treats a time range of the mix. sync_audio lines a separately recorded audio file up with a video's own sound and binds it, so every clip of the video plays the recording; it refuses when no alignment is clear. set_split_edit starts a clip's sound before its picture or carries it past the cut, for J- and L-cuts. describe_commands supplies the supported presets and settings.
When captions are requested, subtitles_generate transcribes the cut; sync_lyrics aligns supplied words with the audio. subtitles_from_visuals writes descriptions of silent footage when the user wants them. captions_generate rewrites existing captions. These model-backed operations use the account's applicable allowance or credits.
-Use update_cue, delete_cue and merge_cue for corrections. subtitles_add_track, subtitles_remove_track and subtitles_translate_track manage languages. set_caption_look controls appearance and words per cue; subtitles_set_view controls visibility. Current choices come from describe_commands, and text-videos covers timed text layouts. align_to_audio measures timing against the mix.
+Use update_cue, delete_cue and merge_cue for corrections. subtitles_add_track, subtitles_remove_track and subtitles_translate_track manage languages. set_caption_look controls appearance and words per cue; subtitles_set_view controls visibility. set_caption_emphasis sets one or two key words apart in a caption every few lines, and update_cue x/y gives one caption its own spot. Current choices come from describe_commands, and text-videos covers timed text layouts. align_to_audio measures timing against the mix.
For requested audio generation, list_voices supplies voice ids, voiceover_generate speaks a script, read_subtitles_aloud voices timed cues, and generate_music makes music. Generation spends credits. Read the result for asset ids and placement, then inspect and listen to verify it. These commands are available through edit_project while the editor card is open.`,
"ai-generation": `# Finding and creating media
diff --git a/site/src/cut/components/Inspector.tsx b/site/src/cut/components/Inspector.tsx
index 37655cda..71a6e339 100644
--- a/site/src/cut/components/Inspector.tsx
+++ b/site/src/cut/components/Inspector.tsx
@@ -116,6 +116,8 @@ import {
import { patchLibrary, refetchLibrary, useLibrary } from "@/cut/lib/queries";
import { TEXT_SIZES, writeTextStyle } from "@/cut/lib/textStyle";
import { formatTime } from "@/cut/lib/time";
+import { captionStyle, cueAnchor, trackPos } from "@/cut/lib/subtitles";
+import { cueEmphasis } from "@/cut/lib/captionEmphasis";
import {
fontStack,
frameOf,
@@ -144,6 +146,7 @@ import {
type Selection,
type ShapeOverlay,
type StickerOverlay,
+ type SubtitleCue,
type TextOverlay,
type VideoClip,
ANIM_DEFAULT_SECONDS,
@@ -163,13 +166,16 @@ import { ScrollArea } from "@/components/ui/scroll-area";
import { Field, ResetButton, Row, Section, SegGroup, SegToggle, Tip, useSliderCheckpoint, Value } from "@/cut/components/panelBits";
import { ColorPanel } from "@/cut/components/ColorPanel";
import { GroupPanel } from "@/cut/components/GroupPanel";
+import { ElementMotionRows } from "@/cut/components/MotionControls";
import { RemovalPanel } from "@/cut/components/RemovalPanel";
+import { CameraCardSection } from "@/cut/components/CameraCardSection";
import { useMatteBakes } from "@/cut/lib/removal/bakeJobs";
/**
- * Whether the selection has a panel to show. Nothing selected, a subtitle cue
- * or a transition bar (the Transitions tab is its panel) leaves the panel out
- * and the preview takes the space.
+ * Whether the selection has a panel to show. Nothing selected or a transition
+ * bar (the Transitions tab is its panel) leaves the panel out and the preview
+ * takes the space. A subtitle cue opens its own small panel: its spot and its
+ * emphasized words.
*/
export function useHasInspector() {
return useEditor((s) => {
@@ -177,7 +183,11 @@ export function useHasInspector() {
// Two or more items open the group panel over what they share, whatever
// was clicked last; one item opens its own panel.
if (s.multiSelection.filter((m) => m && m.kind !== "cue" && m.kind !== "transition").length >= 2) return true;
- return s.selection.kind !== "cue" && s.selection.kind !== "transition";
+ if (s.selection.kind === "cue") {
+ const id = s.selection.id;
+ return s.subtitles.cues.some((c) => c.id === id);
+ }
+ return s.selection.kind !== "transition";
});
}
@@ -199,6 +209,9 @@ export function Inspector() {
const overlay = useEditor((s) =>
selection?.kind === "overlay" ? s.overlays.find((o) => o.id === selection.id) : undefined
);
+ const cue = useEditor((s) =>
+ selection?.kind === "cue" ? s.subtitles.cues.find((c) => c.id === selection.id) : undefined
+ );
// The layer floats over the editor: the preview runs the full width of the
// row and passes under it. The button that brings a folded timeline back
@@ -219,6 +232,7 @@ export function Inspector() {
clip={group ? undefined : clip}
audio={group ? undefined : audio}
overlay={group ? undefined : overlay}
+ cue={group ? undefined : cue}
group={group ?? undefined}
/>
) : (
@@ -286,18 +300,20 @@ function InspectorColumn({
clip,
audio,
overlay,
+ cue,
group,
}: {
clip?: VideoClip;
audio?: AudioClip;
overlay?: Overlay;
+ cue?: SubtitleCue;
group?: NonNullable<Selection>[];
}) {
const open = useEditor((s) => s.inspectorOpen);
const setOpen = useEditor((s) => s.setInspectorOpen);
// The open tab and the Home scroller's place hold per item for the
// session, so coming back to an item lands on its panel as it was left.
- const itemId = clip?.id ?? audio?.id ?? overlay?.id ?? (group ? `group:${group.map((g) => g.id).join()}` : PANEL_GLOBAL);
+ const itemId = clip?.id ?? audio?.id ?? overlay?.id ?? cue?.id ?? (group ? `group:${group.map((g) => g.id).join()}` : PANEL_GLOBAL);
const [view, setView] = usePanelState<string>(itemId, "tab", "main");
const homeScroll = useRememberedScroll(itemId, "main");
const pick = useCallback(
@@ -372,6 +388,8 @@ function InspectorColumn({
) : (
<StickerPanel overlay={overlay} />
)
+ ) : cue ? (
+ <CuePanel cue={cue} />
) : null}
</ScrollArea>
)}
@@ -1588,6 +1606,7 @@ function ClipPanel({ clip }: { clip: VideoClip }) {
</Row>
);
})}
+ </>)}
<Row label="Rotation">
<ValueSlider
label="Rotation"
@@ -3116,6 +3135,61 @@ function PositionRow({
);
}
+/** One caption's own settings: where it sits, and which of its words are set
+ * apart in the track's emphasis style (the Subtitles panel styles it). */
+function CuePanel({ cue }: { cue: SubtitleCue }) {
+ const subtitles = useEditor((s) => s.subtitles);
+ const posCk = useSliderCheckpoint();
+ const style = captionStyle(subtitles.style);
+ const track = trackPos(subtitles, style, cue.lane ?? 0);
+ const own = cue.x !== undefined && cue.y !== undefined;
+ const pose = cueAnchor(cue, track, style);
+ const setPos = (axis: "x" | "y", pct: number) => {
+ const v = Math.min(0.98, Math.max(0.02, pct / 100));
+ useEditor.getState().setCuePosition(cue.id, { ...pose, [axis]: v });
+ };
+ const words = cue.text.split(/\s+/).filter(Boolean);
+ const marked = new Set(cueEmphasis(cue));
+ return (
+ <div className="flex flex-col gap-1 px-3.5 pt-2 pb-4">
+ <Section
+ title="Own position"
+ info="A caption sits where its track does. With its own position it moves alone, here or by Option-dragging it in the preview."
+ enabled={own}
+ onEnabledChange={(on) => {
+ useEditor.getState().pushHistory();
+ useEditor.getState().setCuePosition(cue.id, on ? cueAnchor({}, track, style) : null);
+ }}
+ >
+ <PositionRow pose={pose} min={2} max={98} ck={posCk} onSet={setPos} />
+ </Section>
+ <Section
+ title="Emphasis"
+ info="Set words apart in the track's emphasis style, which the Subtitles panel's Options tab sets."
+ >
+ <div className="cue-emphasis flex flex-wrap gap-1 pb-1.5">
+ {words.map((w, i) => (
+ <button
+ key={i}
+ type="button"
+ aria-pressed={marked.has(i)}
+ className={cn(
+ "rounded-md px-1.5 py-0.5 text-[12px] transition-colors",
+ marked.has(i)
+ ? "bg-[#FFE94A]/80 font-semibold text-[#111114] italic"
+ : "bg-secondary/60 text-foreground hover:bg-secondary"
+ )}
+ onClick={() => useEditor.getState().setCueEmphasis([{ id: cue.id, indices: [i] }])}
+ >
+ {w}
+ </button>
+ ))}
+ </div>
+ </Section>
+ </div>
+ );
+}
+
function TransformRows({ overlay: o }: { overlay: Overlay }) {
const rotationCk = useSliderCheckpoint();
const opacityCk = useSliderCheckpoint();
@@ -3264,7 +3338,7 @@ function KeyframeControls({ overlay: o }: { overlay: Overlay }) {
* key list it is handed. The pose track and the mask track both mount it;
* the mask track's diamond wears the timeline's amber so the two tracks
* read apart everywhere. */
-function KeyRow({
+export function KeyRow({
element,
now,
keys,
diff --git a/site/src/cut/components/OverlayLayer.tsx b/site/src/cut/components/OverlayLayer.tsx
index 6a201179..f49c302c 100644
--- a/site/src/cut/components/OverlayLayer.tsx
+++ b/site/src/cut/components/OverlayLayer.tsx
@@ -434,8 +434,9 @@ function SubtitleCaptions(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. */
+ * the caption moves the whole track's anchor; an Option-drag moves only the
+ * caption on screen, and a caption that has its own spot moves alone on any
+ * drag. Both ride the same smart snapping and guide lines as titles. */
function SubtitleCaption({
lane,
stageWidth,
@@ -500,13 +501,16 @@ function SubtitleCaption({
}
s.pushHistory();
const { x: x0, y: y0 } = ov;
+ const alone = e.altKey || (cue.x !== undefined && cue.y !== undefined);
startDrag(e, {
onMove: (dx, dy, ev) => {
const p = snap(subtitleBoxId(lane), x0 + dx / stageWidth, y0 + dy / stageHeight, ev);
- useEditor.getState().setSubtitleTrackMeta(lane, {
+ const at = {
x: Math.min(0.98, Math.max(0.02, p.x)),
y: Math.min(0.98, Math.max(0.02, p.y)),
- });
+ };
+ if (alone) useEditor.getState().setCuePosition(cue.id, at);
+ else useEditor.getState().setSubtitleTrackMeta(lane, at);
},
onUp: onSnapEnd,
});
diff --git a/site/src/cut/components/SubtitlesPanel.tools.ts b/site/src/cut/components/SubtitlesPanel.tools.ts
index e58e586c..4b14ff73 100644
--- a/site/src/cut/components/SubtitlesPanel.tools.ts
+++ b/site/src/cut/components/SubtitlesPanel.tools.ts
@@ -12,7 +12,12 @@ import {
MAX_WORDS_PER_CUE,
MIN_WORDS_PER_CUE,
} from "@/cut/lib/cueChunk";
-import { CAPTION_STYLES } from "@/cut/lib/subtitles";
+import {
+ CAPTION_EMPHASIS_DEFAULT,
+ CAPTION_STYLES,
+ EMPHASIS_SCALE_MAX,
+ EMPHASIS_SCALE_MIN,
+} from "@/cut/lib/subtitles";
import {
WORD_EFFECT_MENU,
WORD_POP_SCALE,
@@ -115,6 +120,41 @@ export const SUBTITLES_TOOLS = [
x: num("Caption center x 0..1"),
y: num("Caption center y 0..1"),
background: bool("With `look`, also set the project background (default: whatever the look does — the designed looks paint it, plain and over-footage leave it alone)"),
+ emphasis_font: str(
+ `Font id the emphasized words are set in (set_caption_emphasis marks them; default ${CAPTION_EMPHASIS_DEFAULT.font})`
+ ),
+ emphasis_color: str(`Emphasized word color as hex (default ${CAPTION_EMPHASIS_DEFAULT.color})`),
+ emphasis_italic: bool(`Emphasized words in italic (default ${CAPTION_EMPHASIS_DEFAULT.italic})`),
+ emphasis_weight: {
+ type: "number",
+ enum: [400, 700],
+ description: `Emphasized word weight, 400 regular or 700 bold (default ${CAPTION_EMPHASIS_DEFAULT.weight})`,
+ },
+ emphasis_scale: num(
+ `Emphasized word size over the caption's own, ${EMPHASIS_SCALE_MIN}..${EMPHASIS_SCALE_MAX} (default ${CAPTION_EMPHASIS_DEFAULT.scale})`
+ ),
+ }),
+ },
+ {
+ name: "set_caption_emphasis",
+ description:
+ `Set chosen caption words apart in the track's emphasis style (set_caption_look emphasis_* fields; default a bold italic ${CAPTION_EMPHASIS_DEFAULT.font} serif in ${CAPTION_EMPHASIS_DEFAULT.color} at the caption's size) while the rest of the line stays as it is — the social-caption highlight on a product name, a number, the keyword of the call to action. Any word effect still plays on top. Each mark names a cue id and its words, either by 0-based index into the cue's text split on spaces or by the exact word as it appears in that cue (a word that appears twice marks both). Emphasis stays with its word through a words_per_cue re-cut, align_to_audio, retiming and edits that keep the word. editor_state lists each cue's emphasized words. Cadence: one or two meaningful words in a caption, then two or three plain captions before the next; never two emphasized captions in a row, and never a function word (the, and, to, of, is). One call marks the whole track; \`clear_all\` first wipes what is there.`,
+ inputSchema: obj({
+ marks: {
+ type: "array",
+ description: "Words to set on or off, any number of cues in one call (one undo step)",
+ items: obj(
+ {
+ cue_id: str("Cue id"),
+ indices: { type: "array", items: { type: "number" }, description: "0-based word indices in the cue's text" },
+ words: { type: "array", items: { type: "string" }, description: "Words exactly as they appear in the cue" },
+ on: bool("true sets the words apart (default), false returns them to the plain style"),
+ },
+ ["cue_id"]
+ ),
+ },
+ clear_all: bool("Remove every emphasized word before applying `marks` (on `track` when given, else every track)"),
+ track: num("With clear_all: the subtitle track to clear, 0-based"),
}),
},
{
@@ -145,8 +185,18 @@ export const SUBTITLES_TOOLS = [
},
{
name: "update_cue",
- description: "Edit a subtitle cue's text or retime it (start/end seconds).",
- inputSchema: obj({ id: str("Cue id"), ids: ids("id"), text: str("New text"), start: num("Start s"), end: num("End s") }),
+ description:
+ "Edit a subtitle cue's text, retime it (start/end seconds), or give it its own spot. A caption sits where its track does unless it has its own x/y: use it when one caption has to move for the picture under it — centered in the gap of a split layout, a lower third over a full-frame face, the top when the visual's content sits low — and follow_track to hand it back.",
+ inputSchema: obj({
+ id: str("Cue id"),
+ ids: ids("id"),
+ text: str("New text"),
+ start: num("Start s"),
+ end: num("End s"),
+ x: num("This caption's own center x 0..1 (its track's otherwise)"),
+ y: num("This caption's own center y 0..1 (its track's otherwise)"),
+ follow_track: bool("Drop this caption's own x/y so it sits where its track does"),
+ }),
},
{
name: "delete_cue",
diff --git a/site/src/cut/components/SubtitlesPanel.tsx b/site/src/cut/components/SubtitlesPanel.tsx
index 6f5ab588..8d352a25 100644
--- a/site/src/cut/components/SubtitlesPanel.tsx
+++ b/site/src/cut/components/SubtitlesPanel.tsx
@@ -11,13 +11,18 @@ import { ValueSlider } from "@/cut/components/ValueSlider";
import { GenerateSubtitlesAudio } from "@/cut/components/VoicePicker";
import {
CAPTION_STYLES,
+ captionEmphasis,
captionWords,
captionStyle,
+ EMPHASIS_SCALE_MAX,
+ EMPHASIS_SCALE_MIN,
fmtCueTime,
laneCues,
subtitleLaneCount,
trackLocale,
} from "@/cut/lib/subtitles";
+import { cueEmphasis, emphasisRuns, wordIndicesIn } from "@/cut/lib/captionEmphasis";
+import { DropdownMenu, DropdownMenuContent, DropdownMenuItem } from "@/components/ui/dropdown-menu";
import {
cueWordCount,
MAX_WORDS_PER_CUE,
@@ -358,6 +363,7 @@ function OptionsTab() {
</div>
</div>
)}
+ <EmphasisRows />
<div className="flex min-h-8 items-center justify-between text-xs font-medium">
Position
<Button
@@ -383,6 +389,87 @@ function OptionsTab() {
);
}
+/** The emphasis style: how the words set apart in the transcript look on the
+ * video. The words themselves are picked in the Content tab. */
+function EmphasisRows() {
+ const subtitles = useEditor((s) => s.subtitles);
+ const em = captionEmphasis(subtitles);
+ const set = (patch: Parameters<ReturnType<typeof useEditor.getState>["setSubtitlesView"]>[0]) =>
+ useEditor.getState().setSubtitlesView(patch);
+ return (
+ <div className="sub-emphasis mt-1 flex flex-col gap-2.5 border-t border-border pt-3">
+ <div className="flex min-h-8 items-center justify-between text-xs font-medium">
+ Emphasis font
+ <FontPicker
+ className="sub-emphasis-font w-28"
+ value={em.font}
+ onChange={(v) => {
+ useEditor.getState().pushHistory();
+ set({ emphasisFont: v as FontId });
+ }}
+ />
+ </div>
+ <div className="flex min-h-8 items-center justify-between text-xs font-medium">
+ Emphasis color
+ <div className="sub-emphasis-color flex items-center">
+ <ColorField
+ value={em.color}
+ label="Emphasis color"
+ onBegin={() => useEditor.getState().pushHistory()}
+ onLive={(c) => set({ emphasisColor: c })}
+ onCommit={(c) => set({ emphasisColor: c })}
+ />
+ </div>
+ </div>
+ <label className="flex min-h-8 items-center justify-between text-xs font-medium">
+ Italic
+ <Switch
+ className="sub-emphasis-italic"
+ checked={em.italic}
+ onCheckedChange={(v) => {
+ useEditor.getState().pushHistory();
+ set({ emphasisItalic: v });
+ }}
+ />
+ </label>
+ <label className="flex min-h-8 items-center justify-between text-xs font-medium">
+ Bold
+ <Switch
+ className="sub-emphasis-weight"
+ checked={em.weight === 700}
+ onCheckedChange={(v) => {
+ useEditor.getState().pushHistory();
+ set({ emphasisWeight: v ? 700 : 400 });
+ }}
+ />
+ </label>
+ <div className="flex min-h-8 items-center justify-between text-xs font-medium">
+ Emphasis size
+ <div className="sub-emphasis-scale flex items-center gap-2">
+ <ValueSlider
+ label="Emphasis size"
+ sliderClassName="data-horizontal:w-24"
+ valueClassName="w-9 text-muted-foreground"
+ value={em.scale}
+ min={EMPHASIS_SCALE_MIN}
+ max={EMPHASIS_SCALE_MAX}
+ step={0.02}
+ snap={[1]}
+ format={(v) => `${v.toFixed(2)}×`}
+ parse={parseSpeedInput}
+ onDraft={(v) => set({ emphasisScale: v })}
+ onCommit={(v) => set({ emphasisScale: v })}
+ />
+ </div>
+ </div>
+ <p className="-mt-1 text-[11px] leading-relaxed text-muted-foreground">
+ Right-click a word in the transcript, or put the cursor on it and press ⌘B, to set it
+ apart in this style.
+ </p>
+ </div>
+ );
+}
+
/** How many words a caption holds at a time. Committing re-cuts every track
* on its own words and measures the new captions against the cut's mix, which
* takes a moment on a long project — the slider shows the drag, the track is
@@ -616,16 +703,61 @@ function caretOffset(el: HTMLElement): number {
const CueSpan = memo(function CueSpan({ cue, gap }: { cue: SubtitleCue; gap: number }) {
const active = usePreviewSelector((t) => t >= cue.start && t < cue.end);
+ const readOnly = useEditor((s) => s.readOnly);
const ref = useRef<HTMLSpanElement>(null);
const [focused, setFocused] = useState(false);
+ const [menu, setMenu] = useState<{
+ x: number;
+ y: number;
+ from: number;
+ to: number;
+ label: string;
+ on: boolean;
+ } | null>(null);
+ const marked = cueEmphasis(cue);
+ const markKey = marked.join(",");
// The span is uncontrolled while focused (so the caret survives typing);
- // outside edits (undo, regenerate) sync the DOM here.
+ // outside edits (undo, regenerate, emphasis) sync the DOM here.
useEffect(() => {
const el = ref.current;
- if (el && document.activeElement !== el && el.textContent !== cue.text)
- el.textContent = cue.text;
- }, [cue.text]);
+ if (el && document.activeElement !== el) paintCue(el, cue.text, markKey ? markKey.split(",").map(Number) : []);
+ }, [cue.text, markKey]);
+
+ /** The words a character range of the caption touches, and whether they
+ * would all be emphasized by the toggle. Typing not yet committed is
+ * committed first, so the words are the ones on screen. */
+ const wordsAt = (from: number, to: number) => {
+ const el = ref.current;
+ if (!el) return null;
+ const typed = el.textContent ?? "";
+ const indices = wordIndicesIn(typed, from, to);
+ if (indices.length === 0) return null;
+ const words = typed.split(/\s+/).filter(Boolean);
+ const set = new Set(marked);
+ return {
+ typed,
+ indices,
+ on: !indices.every((i) => set.has(i)),
+ label: indices.map((i) => words[i]).join(" "),
+ };
+ };
+
+ const toggle = (from: number, to: number) => {
+ const el = ref.current;
+ const hit = wordsAt(from, to);
+ if (!el || !hit) return;
+ const st = useEditor.getState();
+ st.setCueText(cue.id, hit.typed);
+ st.setCueEmphasis([{ id: cue.id, indices: hit.indices, on: hit.on }]);
+ const live = useEditor.getState().subtitles.cues.find((c) => c.id === cue.id);
+ // While the caption is being edited the effect above leaves it alone, so
+ // the marks are painted here and the selection put back where it was.
+ if (live && document.activeElement === el) {
+ paintCue(el, hit.typed, cueEmphasis(live));
+ selectIn(el, from, to);
+ }
+ };
// Follow along during playback.
useEffect(() => {
@@ -694,6 +826,28 @@ const CueSpan = memo(function CueSpan({ cue, gap }: { cue: SubtitleCue; gap: num
}
}}
/>{" "}
+ {menu && (
+ <DropdownMenu open onOpenChange={(o) => !o && setMenu(null)}>
+ <DropdownMenuContent
+ className="w-56"
+ sideOffset={0}
+ anchor={{ getBoundingClientRect: () => new DOMRect(menu.x, menu.y, 0, 0) }}
+ finalFocus={false}
+ >
+ <DropdownMenuItem
+ className="sub-emphasis-toggle"
+ onClick={() => {
+ toggle(menu.from, menu.to);
+ setMenu(null);
+ }}
+ >
+ <span className="truncate">
+ {menu.on ? `Emphasize “${menu.label}”` : `Remove emphasis from “${menu.label}”`}
+ </span>
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ )}
</span>
);
});
diff --git a/site/src/cut/components/inspectorToolFields.test.ts b/site/src/cut/components/inspectorToolFields.test.ts
index c689d79d..24f45401 100644
--- a/site/src/cut/components/inspectorToolFields.test.ts
+++ b/site/src/cut/components/inspectorToolFields.test.ts
@@ -50,6 +50,8 @@ const ITEM_TOOLS = new Set([
"set_clip_muted",
"set_clip_hidden",
"rename_item",
+ "set_group_camera",
+ "update_cue",
]);
/** The panels that render an item's settings. */
@@ -124,6 +126,8 @@ const PANEL_NAME: Record<string, string> = {
preset_id: "clip-grade-category-saved",
// The source-colour select.
profile: "clip-source-color",
+ // A caption's own spot is the cue panel's Own position switch.
+ follow_track: "setCuePosition",
};
/** The basic and detail grade sliders draw from the registries the tool's
diff --git a/site/src/cut/lib/aiContext.ts b/site/src/cut/lib/aiContext.ts
index febb9568..e7b33f2a 100644
--- a/site/src/cut/lib/aiContext.ts
+++ b/site/src/cut/lib/aiContext.ts
@@ -6,16 +6,19 @@ import { GUIDE_PRESETS, guideFits, guideGeometry, safeAreaOf, sanitizeGuideLines
import { hasOverlayAnim, retimeOf, speedCurveOf, WHEEL_LABELS, WHEEL_ZONES, type ClipSound, type OutputSpace, type SpeedNode } from "@donkeycut/effects-kit";
import { chatOwner } from "./chatAssets";
import { useGenerate } from "./generate";
-import { useMatteBakes } from "./removal/bakeJobs";
+import { matteBakesAvailable, useMatteBakes } from "./removal/bakeJobs";
+import { cardMatteKey, resolveCardShape } from "./cameraCard";
import { deriveTransitionFields, getClipSpans, normalizeDocState, overlayLayers, projectDuration, resolveTransitions, totalDuration, useEditor } from "./store";
import type { VideoProject } from "./genvideo/types";
import { playheadAt, skimAt } from "./playhead";
import { cueWordCount } from "./cueChunk";
import { laneCues, subtitleLaneCount } from "./subtitles";
+import { cueEmphasis } from "./captionEmphasis";
import { watchSweepActive } from "./watch/sweep";
import { libraryFontId, listLibraryFonts, listLutChoices } from "./linkedLibrary";
import { savedGradesKnown } from "./gradePresets";
import { sourceProfileOf } from "./baseFrame";
+import { groupCameras } from "./groupCamera";
import {
clipZoom,
frameOf,
@@ -30,6 +33,7 @@ import {
overlayName,
type Overlay,
type ProjectDoc,
+ type SubtitleCue,
type SubtitlesBlock,
type TimelineTransition,
type VideoClip,
@@ -52,7 +56,7 @@ function transitionToNext(sp: ClipSpan, index: number, spans: ClipSpan[]) {
* refs plus a compact summary of the manual grade (nonzero sliders verbatim;
* curves as presence flags; the wheels by their tool names; the touched hue
* bands by name). */
-function clipEffects(clip: VideoClip, live: boolean) {
+function clipEffects(clip: VideoClip, live: boolean, frame?: CardFrame) {
const grade = clip.grade;
const sliders: Record<string, number> = {};
for (const [k, v] of Object.entries(grade ?? {})) {
@@ -204,7 +208,7 @@ export function buildAiContext(opts?: { fullCues?: boolean; chatId?: string | nu
if (kind === "cue") {
const c = s.subtitles.cues.find((x) => x.id === id);
return c
- ? { kind, id, text: c.text, start: r(c.start), end: r(c.end), track: c.lane ?? 0 }
+ ? { kind, id, text: c.text, start: r(c.start), end: r(c.end), track: c.lane ?? 0, ...cueExtras(c) }
: { kind, id };
}
// The selection's kind stays "overlay" (what select/delete take); the
@@ -575,7 +579,7 @@ function describeState(
...(sp.clip.kf?.length
? { keyframes: sp.clip.kf.map((k) => ({ ...k, t: r(k.t), x: r(k.x), y: r(k.y) })) }
: {}),
- ...clipEffects(sp.clip, live),
+ ...clipEffects(sp.clip, live, { aspect: s.aspect, assetById }),
})),
// Video layers composited over track 0 in track order (the topmost
// full-frame clip covers the rest). Each track carries its own
@@ -590,7 +594,7 @@ function describeState(
const t = transitionToNext(sp, i, trackSpans);
return t ? { transitionToNext: t } : {};
})(),
- ...clipEffects(sp.clip, live),
+ ...clipEffects(sp.clip, live, { aspect: s.aspect, assetById }),
}));
}),
// Every transition bar in the doc. A bar is its own object on the
@@ -652,6 +656,13 @@ function describeState(
...(s.subtitles.wordHighlight ? { wordHighlight: true } : {}),
...(s.subtitles.accentMode ? { accentMode: s.subtitles.accentMode } : {}),
...(s.subtitles.accentColor ? { accentColor: s.subtitles.accentColor } : {}),
+ // The emphasis style, where it departs from the default
+ // (set_caption_look emphasis_*); the words wearing it ride on each cue.
+ ...(s.subtitles.emphasisFont ? { emphasisFont: s.subtitles.emphasisFont } : {}),
+ ...(s.subtitles.emphasisColor ? { emphasisColor: s.subtitles.emphasisColor } : {}),
+ ...(s.subtitles.emphasisItalic !== undefined ? { emphasisItalic: s.subtitles.emphasisItalic } : {}),
+ ...(s.subtitles.emphasisWeight !== undefined ? { emphasisWeight: s.subtitles.emphasisWeight } : {}),
+ ...(s.subtitles.emphasisScale !== undefined ? { emphasisScale: s.subtitles.emphasisScale } : {}),
status: s.subtitleStatus,
// A window of cues by default; when truncated the model calls get_state
// for the whole transcript (e.g. "clean up all the captions").
@@ -662,12 +673,25 @@ function describeState(
end: r(c.end),
text: c.text,
...(subtitleTracks > 1 ? { track: c.lane ?? 0 } : {}),
+ ...cueExtras(c),
})),
cuesTruncated: s.subtitles.cues.length > cueCap,
},
};
}
+/** What a cue carries beyond its words and times: its emphasized words as
+ * [index, word] pairs (set_caption_emphasis), and its own x/y when it sits
+ * apart from its track (update_cue). Absent when it has neither. */
+function cueExtras(c: SubtitleCue) {
+ const marked = cueEmphasis(c);
+ const words = marked.length > 0 ? c.text.split(/\s+/).filter(Boolean) : [];
+ return {
+ ...(marked.length > 0 ? { emphasis: marked.map((i) => [i, words[i]] as const) } : {}),
+ ...(c.x !== undefined && c.y !== undefined ? { x: r(c.x), y: r(c.y) } : {}),
+ };
+}
+
/** A clip's rate as the model reads it: one number, or the average plus the
* curve's nodes as [sourceSeconds, rate] when the rate changes through the
* footage. */
diff --git a/site/src/cut/lib/aiTools.ts b/site/src/cut/lib/aiTools.ts
index 9af7363d..10b6e1fe 100644
--- a/site/src/cut/lib/aiTools.ts
+++ b/site/src/cut/lib/aiTools.ts
@@ -185,12 +185,16 @@ import { loadLibraryLut, lutIdOf, lutLabel } from "./linkedLibrary";
import { sampleClipBaseFrameData, sourceProfileOf, toBaseRendering } from "./baseFrame";
import { applyOverlayPatchSettled, assetClipUses, clipLen, track0Clips, laneGapAt, getClipSpans, overlayLaneOrder, overlayLayers, parkedTransitions, projectDuration, resolveTransitions, totalDuration, useEditor } from "./store";
import { playheadAt } from "./playhead";
-import { renderProjectFrame, renderProjectFrames } from "./exportRender";
+import { mixSpecFor, renderProjectFrame, renderProjectFrames } from "./exportRender";
+import { renderMix } from "./audioMix";
+import { measureLoudnessSliced, roundedLoudness, type LoudnessMeasure } from "./loudness";
import { framesAt, readMediaFileSize } from "./mediaRead";
import { renderStageFrame, storeStageStill } from "./stageFrame";
import { createRasterCanvas, decodeRasterImageUrl, rasterCanvasToDataUrl } from "./raster";
-import { buildAiContext, describeDoc, hiddenFromChat, placedAssetIds } from "./aiContext";
-import { CAPTION_STYLES, laneCues, subtitleLaneCount } from "./subtitles";
+import { buildAiContext, describeCameraCard, describeDoc, hiddenFromChat, placedAssetIds } from "./aiContext";
+import { CARD_SIDES, newCard, normalizeCard, type CardSide } from "./cameraCard";
+import { CAPTION_STYLES, captionEmphasis, captionStyle, cueAnchor, EMPHASIS_SCALE_MAX, EMPHASIS_SCALE_MIN, laneCues, subtitleLaneCount, trackPos } from "./subtitles";
+import { cueEmphasis, emphasisIndicesOf } from "./captionEmphasis";
import { findHighlights } from "./highlights";
import { fuseTimeline, renderFusedTimeline, speechOnsets, speechOver } from "./watch/fuse";
import {
@@ -2491,6 +2495,20 @@ const toolRuns: Record<BrowserToolName, ToolRun> = {
}
if (isNum(input.y)) patch.y = clamp(input.y, 0.02, 0.98);
if (isNum(input.x)) patch.x = clamp(input.x, 0.02, 0.98);
+ if (typeof input.emphasis_font === "string") {
+ if (!allFonts().some((f) => f.id === input.emphasis_font))
+ throw new ToolError(`Unknown font id "${input.emphasis_font}".`);
+ patch.emphasisFont = input.emphasis_font;
+ }
+ if (typeof input.emphasis_color === "string") patch.emphasisColor = input.emphasis_color;
+ if (typeof input.emphasis_italic === "boolean") patch.emphasisItalic = input.emphasis_italic;
+ if (input.emphasis_weight !== undefined) {
+ if (input.emphasis_weight !== 400 && input.emphasis_weight !== 700)
+ throw new ToolError("emphasis_weight is 400 or 700.");
+ patch.emphasisWeight = input.emphasis_weight;
+ }
+ if (isNum(input.emphasis_scale))
+ patch.emphasisScale = clamp(input.emphasis_scale, EMPHASIS_SCALE_MIN, EMPHASIS_SCALE_MAX);
const per = isNum(input.words_per_cue)
? clamp(Math.round(input.words_per_cue), MIN_WORDS_PER_CUE, MAX_WORDS_PER_CUE)
: null;
@@ -2513,6 +2531,57 @@ const toolRuns: Record<BrowserToolName, ToolRun> = {
accentMode: cur.accentMode,
accentScale: cur.accentScale,
accentDim: cur.accentDim,
+ emphasis: captionEmphasis(cur),
+ };
+ },
+
+ set_caption_emphasis: (s, input) => {
+ const marks = Array.isArray(input.marks) ? (input.marks as Record<string, unknown>[]) : [];
+ if (marks.length === 0 && input.clear_all !== true)
+ throw new ToolError("Pass marks (cue_id with indices or words), or clear_all.");
+ // Every mark is resolved against its cue before anything is written, so
+ // one bad id or word leaves the track as it was.
+ const edits: { id: string; indices: number[]; on?: boolean }[] = [];
+ for (const m of marks) {
+ const cue = requireItem(s.subtitles.cues, m.cue_id, "subtitle cue");
+ const count = cue.text.split(/\s+/).filter(Boolean).length;
+ const indices: number[] = [];
+ if (Array.isArray(m.indices)) {
+ for (const i of m.indices) {
+ if (!isNum(i) || !Number.isInteger(i) || i < 0 || i >= count)
+ throw new ToolError(`Cue ${cue.id} has words 0..${count - 1}; index ${String(i)} is not one of them.`);
+ indices.push(i);
+ }
+ }
+ if (Array.isArray(m.words)) {
+ const found = emphasisIndicesOf(cue, m.words.map(String));
+ if (found.missing.length > 0)
+ throw new ToolError(
+ `Cue ${cue.id} reads "${cue.text}" and has no word ${found.missing.map((w) => `"${w}"`).join(", ")}.`
+ );
+ indices.push(...found.indices);
+ }
+ if (indices.length === 0) throw new ToolError(`Name the words of cue ${cue.id} by indices or words.`);
+ edits.push({ id: cue.id, indices, on: m.on !== false });
+ }
+ const clear =
+ input.clear_all === true
+ ? isNum(input.track)
+ ? { lane: Math.round(input.track) }
+ : {}
+ : undefined;
+ s.setCueEmphasis(edits, clear);
+ const cur = useEditor.getState().subtitles;
+ const touched = new Set(edits.map((e) => e.id));
+ return {
+ cues: cur.cues
+ .filter((c) => touched.has(c.id))
+ .map((c) => {
+ const words = c.text.split(/\s+/).filter(Boolean);
+ return { id: c.id, text: c.text, emphasis: cueEmphasis(c).map((i) => words[i]) };
+ }),
+ emphasizedCues: cur.cues.filter((c) => cueEmphasis(c).length > 0).length,
+ ...(cur.showOnVideo ? {} : { note: "Captions are hidden on the video; subtitles_set_view shows them." }),
};
},
@@ -4527,6 +4596,9 @@ const toolRuns: Record<BrowserToolName, ToolRun> = {
update_cue: (s, input) => {
const cue = requireItem(s.subtitles.cues, input.id, "subtitle cue");
+ const clearPos = input.follow_track === true || input.x === null || input.y === null;
+ if (clearPos && (isNum(input.x) || isNum(input.y)))
+ throw new ToolError("Pass x/y for the caption's own spot, or follow_track to drop it — not both.");
if (typeof input.text === "string") s.setCueText(cue.id, input.text);
if (isNum(input.start) || isNum(input.end)) {
const start = isNum(input.start) ? Math.max(0, input.start) : cue.start;
@@ -4534,8 +4606,38 @@ const toolRuns: Record<BrowserToolName, ToolRun> = {
if (end - start < 0.15) throw new ToolError("Cue must stay at least 0.15s long.");
s.setCueTiming(cue.id, start, end);
}
+ if (clearPos || isNum(input.x) || isNum(input.y)) {
+ const st = useEditor.getState();
+ const live = st.subtitles.cues.find((c) => c.id === cue.id);
+ if (live) {
+ // One side given keeps the other where the caption already sits.
+ const at = cueAnchor(
+ live,
+ trackPos(st.subtitles, captionStyle(st.subtitles.style), live.lane ?? 0),
+ captionStyle(st.subtitles.style)
+ );
+ st.pushHistory();
+ st.setCuePosition(
+ cue.id,
+ clearPos
+ ? null
+ : {
+ x: clamp(isNum(input.x) ? input.x : at.x, 0.02, 0.98),
+ y: clamp(isNum(input.y) ? input.y : at.y, 0.02, 0.98),
+ }
+ );
+ }
+ }
const next = useEditor.getState().subtitles.cues.find((c) => c.id === cue.id);
- return next ? { id: next.id, start: next.start, end: next.end, text: next.text } : { deleted: cue.id };
+ return next
+ ? {
+ id: next.id,
+ start: next.start,
+ end: next.end,
+ text: next.text,
+ ...(next.x !== undefined && next.y !== undefined ? { x: round2(next.x), y: round2(next.y) } : {}),
+ }
+ : { deleted: cue.id };
},
delete_cue: (s, input) => {
diff --git a/site/src/cut/lib/captionEmphasis.test.ts b/site/src/cut/lib/captionEmphasis.test.ts
new file mode 100644
index 00000000..f71869e8
--- /dev/null
+++ b/site/src/cut/lib/captionEmphasis.test.ts
@@ -0,0 +1,285 @@
+import { beforeEach, describe, expect, test } from "bun:test";
+import { runAiTool } from "./aiTools";
+import {
+ cueEmphasis,
+ emphasisIndicesOf,
+ emphasisRuns,
+ remapEmphasis,
+ toggleEmphasis,
+ wordIndicesIn,
+} from "./captionEmphasis";
+import { chunkLaneCues } from "./cueChunk";
+import { partialWrites } from "./cueSync";
+import { ITEM_KINDS } from "./itemKinds";
+import { useEditor } from "./store";
+import {
+ CAPTION_EMPHASIS_DEFAULT,
+ CAPTION_STYLES,
+ cueAnchor,
+ cueOverlay,
+ trackPos,
+} from "./subtitles";
+import { emptySubtitles, type SubtitleCue, type SubtitlesBlock } from "./types";
+
+/**
+ * Emphasized caption words and a caption's own spot.
+ *
+ * Emphasis is word indices on the cue, so the thing to hold is that every path
+ * that rewrites a cue's words moves the indices with the words: a re-cut, a
+ * split, a merge, a hand-edit, a realign. A caption's own spot wins over its
+ * track's in every place that draws it.
+ */
+
+const STYLE = CAPTION_STYLES.clean;
+
+/** Measured words at 0.5s apiece from `start`. */
+function timed(id: string, text: string, start: number, emphasis?: number[]): SubtitleCue {
+ const words = text.split(" ").map((w, i) => ({ w, t0: start + i * 0.5, t1: start + i * 0.5 + 0.45 }));
+ return {
+ id,
+ start,
+ end: start + words.length * 0.5,
+ text,
+ words,
+ ...(emphasis ? { emphasis } : {}),
+ };
+}
+
+const emphasized = (c: SubtitleCue) => {
+ const words = c.text.split(/\s+/).filter(Boolean);
+ return cueEmphasis(c).map((i) => words[i]);
+};
+
+describe("emphasis rides its words", () => {
+ test("a re-cut moves each emphasized word into the caption it lands in", () => {
+ const cue = timed("c1", "we shipped Figma plugins in six days flat", 0, [2, 5]);
+ const out = chunkLaneCues([cue], 3);
+ expect(out.map((c) => c.text)).toEqual(["we shipped Figma", "plugins in six", "days flat"]);
+ expect(out.map(emphasized)).toEqual([["Figma"], ["six"], []]);
+ // And back: re-cut to one long caption, the words find their places again.
+ const back = chunkLaneCues(out, 12);
+ expect(back).toHaveLength(1);
+ expect(emphasized(back[0])).toEqual(["Figma", "six"]);
+ });
+
+ test("captions with no measured words keep their emphasis through a re-cut", () => {
+ const cue: SubtitleCue = { id: "t1", start: 0, end: 4, text: "Try the free plan today", emphasis: [2] };
+ const out = chunkLaneCues([cue], 2);
+ expect(out.every((c) => !c.words)).toBe(true);
+ expect(out.flatMap(emphasized)).toEqual(["free"]);
+ });
+
+ test("a re-cut caption sits where the cue it opens on sat", () => {
+ const a = { ...timed("a", "one two three four", 0), x: 0.5, y: 0.2 };
+ const b = timed("b", "five six", 2.05);
+ const out = chunkLaneCues([a, b], 2);
+ expect(out[0]).toMatchObject({ x: 0.5, y: 0.2 });
+ expect(out[out.length - 1].x).toBeUndefined();
+ });
+
+ test("realigning keeps emphasis: only the times move", () => {
+ const cue = timed("c1", "buy it now", 1, [2]);
+ const [moved] = partialWrites([{ ...cue, start: 1.2, end: 2.6 }], [cue], () => true);
+ expect(moved.start).toBe(1.2);
+ expect(moved.emphasis).toEqual([2]);
+ });
+
+ test("a rewrite keeps the emphasis on every word still there", () => {
+ expect(remapEmphasis("we shipped Figma plugins", "we shipped the Figma, plugin", [2])).toEqual([3]);
+ expect(remapEmphasis("save 50 percent today", "save fifty percent today", [1])).toEqual([]);
+ expect(remapEmphasis("one two three", "ONE two three", [0, 2])).toEqual([0, 2]);
+ });
+
+ test("indices past the text are never drawn", () => {
+ expect(cueEmphasis({ text: "two words", emphasis: [1, 5, 1, -1] })).toEqual([1]);
+ });
+
+ test("a timeline split hands each half the emphasis of its own words", () => {
+ const cue = timed("c1", "one two three four", 0, [1, 3]);
+ const [left, right] = ITEM_KINDS.cue.split!(cue, 1.0);
+ expect(left.text).toBe("one two");
+ expect(emphasized(left)).toEqual(["two"]);
+ expect(emphasized(right)).toEqual(["four"]);
+ });
+});
+
+describe("picking words", () => {
+ test("by the cue's own words, case and punctuation aside", () => {
+ const cue = { text: "Download Notion, it's free!" };
+ expect(emphasisIndicesOf(cue, ["notion", "FREE"])).toEqual({ indices: [1, 3], missing: [] });
+ expect(emphasisIndicesOf(cue, ["Figma"]).missing).toEqual(["Figma"]);
+ });
+
+ test("a caret names the word it is in, a selection every word it touches", () => {
+ const text = "one two three";
+ expect(wordIndicesIn(text, 5, 5)).toEqual([1]);
+ expect(wordIndicesIn(text, 3, 3)).toEqual([0]);
+ expect(wordIndicesIn(text, 8, 8)).toEqual([2]);
+ expect(wordIndicesIn(text, 2, 6)).toEqual([0, 1]);
+ });
+
+ test("the editor's runs are the text exactly", () => {
+ const runs = emphasisRuns("a big win", [1, 2]);
+ expect(runs.map((r) => r.text).join("")).toBe("a big win");
+ expect(runs.filter((r) => r.em).map((r) => r.text)).toEqual(["big", "win"]);
+ });
+
+ test("toggling flips each word and drops the field when empty", () => {
+ const cue: SubtitleCue = { id: "c", start: 0, end: 1, text: "a b c" };
+ const on = toggleEmphasis(cue, [0, 2]);
+ expect(on.emphasis).toEqual([0, 2]);
+ const off = toggleEmphasis(on, [0, 2]);
+ expect("emphasis" in off).toBe(false);
+ });
+});
+
+describe("drawing", () => {
+ const subs = (patch: Partial<SubtitlesBlock> = {}) =>
+ ({ ...emptySubtitles(), ...patch }) as SubtitlesBlock;
+
+ test("with no word effect, emphasized words wear the emphasis face and the rest stay plain", () => {
+ const cue = timed("c1", "get Donkey free", 0, [1]);
+ const ov = cueOverlay(cue, STYLE, false, trackPos(subs(), STYLE, 0), undefined, 1080);
+ const draws = ov.wordDraw!;
+ expect(draws).toHaveLength(3);
+ expect(draws[0]).toMatchObject({ color: STYLE.color, scale: 1 });
+ expect(draws[0].font).toBeUndefined();
+ expect(draws[1]).toMatchObject({
+ color: CAPTION_EMPHASIS_DEFAULT.color,
+ font: CAPTION_EMPHASIS_DEFAULT.font,
+ italic: true,
+ weight: 700,
+ });
+ });
+
+ test("a cue with nothing emphasized draws as plain text", () => {
+ const ov = cueOverlay(timed("c1", "plain words", 0), STYLE, false, trackPos(subs(), STYLE, 0), undefined, 1080);
+ expect(ov.wordDraw).toBeUndefined();
+ });
+
+ test("the track's emphasis style dresses the words, scale on top of the effect's", () => {
+ const cue = timed("c1", "one two", 0, [0]);
+ const pos = trackPos(
+ subs({ emphasisColor: "#00FF00", emphasisFont: "serif", emphasisItalic: false, emphasisScale: 1.25 }),
+ STYLE,
+ 0
+ );
+ const draws = cueOverlay(cue, STYLE, false, pos, undefined, 1080).wordDraw!;
+ expect(draws[0]).toMatchObject({ color: "#00FF00", font: "serif", italic: false, scale: 1.25, layoutScale: 1.25 });
+ });
+
+ test("a word effect still plays on an emphasized word, starting from its color", () => {
+ // Color effect, the first word's moment: it runs to the accent; the second
+ // word waits at the emphasis color in the emphasis face.
+ const style = { ...STYLE, accentMode: "color", accent: "#FF0000" };
+ const cue = timed("c1", "one two", 0, [1]);
+ const pos = trackPos(subs(), style, 0);
+ const first = cueOverlay(cue, style, false, pos, 0.1, 1080).wordDraw!;
+ expect(first[1]).toMatchObject({ color: CAPTION_EMPHASIS_DEFAULT.color, font: CAPTION_EMPHASIS_DEFAULT.font });
+ const second = cueOverlay(cue, style, false, pos, 0.9, 1080).wordDraw!;
+ expect(second[1].color.toLowerCase()).toBe("#ff0000");
+ expect(second[1].font).toBe(CAPTION_EMPHASIS_DEFAULT.font);
+ });
+
+ test("the resting picture is held between frames", () => {
+ const cue = timed("c1", "hold this", 0, [0]);
+ const pos = trackPos(subs(), STYLE, 0);
+ const a = cueOverlay(cue, STYLE, false, pos, undefined, 1080).wordDraw;
+ const b = cueOverlay(cue, STYLE, false, trackPos(subs(), STYLE, 0), undefined, 1080).wordDraw;
+ expect(a).toBe(b);
+ });
+});
+
+describe("a caption's own spot", () => {
+ const block = { ...emptySubtitles(), tracks: [{ x: 0.5, y: 0.7 }] } as SubtitlesBlock;
+ const track = trackPos(block, STYLE, 0);
+
+ test("wins over its track's, and the track's fills in without one", () => {
+ expect(cueAnchor({ x: 0.3, y: 0.2 }, track, STYLE)).toEqual({ x: 0.3, y: 0.2 });
+ expect(cueAnchor({}, track, STYLE)).toEqual({ x: 0.5, y: 0.7 });
+ expect(cueAnchor({}, undefined, STYLE)).toEqual({ x: STYLE.x, y: STYLE.y });
+ });
+
+ test("every burn-in reads it through cueOverlay", () => {
+ const ov = cueOverlay({ ...timed("c", "hi there", 0), x: 0.4, y: 0.15 }, STYLE, false, track, undefined, 1080);
+ expect({ x: ov.x, y: ov.y }).toEqual({ x: 0.4, y: 0.15 });
+ const follows = cueOverlay(timed("d", "hi there", 0), STYLE, false, track, undefined, 1080);
+ expect({ x: follows.x, y: follows.y }).toEqual({ x: 0.5, y: 0.7 });
+ });
+});
+
+describe("the editor and the tools", () => {
+ beforeEach(() => {
+ useEditor.setState({
+ clips: [],
+ overlays: [],
+ transitions: [],
+ audioClips: [],
+ subtitles: {
+ ...emptySubtitles(),
+ cues: [
+ timed("c1", "we shipped Figma plugins", 0),
+ timed("c2", "in six days", 2.1),
+ { id: "c3", start: 4, end: 6, text: "try it free today" },
+ ],
+ },
+ });
+ });
+ const cue = (id: string) => useEditor.getState().subtitles.cues.find((c) => c.id === id)!;
+
+ test("set_caption_emphasis marks by index and by word across cues in one undo step", async () => {
+ await runAiTool("set_caption_emphasis", {
+ marks: [
+ { cue_id: "c1", words: ["Figma"] },
+ { cue_id: "c3", indices: [2] },
+ ],
+ });
+ expect(emphasized(cue("c1"))).toEqual(["Figma"]);
+ expect(emphasized(cue("c3"))).toEqual(["free"]);
+ useEditor.getState().undo();
+ expect(cue("c1").emphasis).toBeUndefined();
+ expect(cue("c3").emphasis).toBeUndefined();
+ });
+
+ test("a word the cue does not have is refused and nothing is written", async () => {
+ await expect(
+ runAiTool("set_caption_emphasis", {
+ marks: [
+ { cue_id: "c1", words: ["Figma"] },
+ { cue_id: "c2", words: ["weeks"] },
+ ],
+ })
+ ).rejects.toThrow(/no word "weeks"/);
+ expect(cue("c1").emphasis).toBeUndefined();
+ });
+
+ test("clear_all wipes before marking", async () => {
+ useEditor.getState().setCueEmphasis([{ id: "c1", indices: [2] }]);
+ await runAiTool("set_caption_emphasis", { clear_all: true, marks: [{ cue_id: "c2", words: ["six"] }] });
+ expect(cue("c1").emphasis).toBeUndefined();
+ expect(emphasized(cue("c2"))).toEqual(["six"]);
+ });
+
+ test("hand-edits, splits and merges keep emphasis on its words", () => {
+ const s = () => useEditor.getState();
+ s().setCueEmphasis([{ id: "c1", indices: [2] }]);
+ s().setCueText("c1", "we finally shipped Figma plugins");
+ expect(emphasized(cue("c1"))).toEqual(["Figma"]);
+ s().splitCue("c1", "we finally shipped".length);
+ const halves = s().subtitles.cues.filter((c) => c.text.includes("Figma"));
+ expect(halves.map(emphasized)).toEqual([["Figma"]]);
+ s().setCueEmphasis([{ id: "c2", indices: [1] }]);
+ s().mergeCueIntoPrev("c2");
+ const merged = s().subtitles.cues.find((c) => c.text.endsWith("six days"))!;
+ expect(emphasized(merged)).toEqual(["Figma", "six"]);
+ });
+
+ test("update_cue gives a caption its own spot and follow_track hands it back", async () => {
+ await runAiTool("update_cue", { id: "c2", y: 0.2 });
+ expect(cue("c2").y).toBe(0.2);
+ expect(cue("c2").x).toBe(STYLE.x);
+ await runAiTool("update_cue", { id: "c2", follow_track: true });
+ expect(cue("c2").x).toBeUndefined();
+ expect(cue("c2").y).toBeUndefined();
+ });
+});
diff --git a/site/src/cut/lib/captionEmphasis.ts b/site/src/cut/lib/captionEmphasis.ts
new file mode 100644
index 00000000..f004f083
--- /dev/null
+++ b/site/src/cut/lib/captionEmphasis.ts
@@ -0,0 +1,188 @@
+/**
+ * Which words of a caption are emphasized, and how that survives edits.
+ *
+ * A cue keeps its emphasis as indices into its display words — the text split
+ * on whitespace, the same indexing the word timings and the word effects use.
+ * A timing change never moves a word, so retiming and alignment carry the
+ * indices untouched. A change to the words themselves is where an index could
+ * end up on the wrong word, so every path that rewrites a cue's text runs it
+ * through one of the functions here: a split takes a slice, a merge appends,
+ * and a rewrite lines the old words up against the new ones and keeps the
+ * emphasis on every word that is still there.
+ *
+ * The indices live on the cue and the word timings stay optional, so a caption
+ * with no measured words (a rewrite, a translation, a hand-typed line) can
+ * still have a word set apart.
+ */
+
+import { displayWords } from "@donkeycut/effects-kit";
+import type { SubtitleCue } from "./types";
+
+/** A cue's emphasized word indices, ascending, each one a word the text still
+ * has. */
+export function cueEmphasis(cue: Pick<SubtitleCue, "text" | "emphasis">): number[] {
+ const marked = cue.emphasis;
+ if (!marked?.length) return [];
+ const n = displayWords(cue.text).length;
+ const out: number[] = [];
+ for (const i of [...marked].sort((a, b) => a - b)) {
+ if (Number.isInteger(i) && i >= 0 && i < n && out[out.length - 1] !== i) out.push(i);
+ }
+ return out;
+}
+
+/** The field as a cue stores it: absent when nothing is marked. */
+export function emphasisField(marked: readonly number[]): { emphasis?: number[] } {
+ return marked.length > 0 ? { emphasis: [...marked] } : {};
+}
+
+/** The cue with `indices` set on or off; `on` absent flips each one. */
+export function toggleEmphasis(
+ cue: SubtitleCue,
+ indices: readonly number[],
+ on?: boolean
+): SubtitleCue {
+ const marked = new Set(cueEmphasis(cue));
+ for (const i of indices) {
+ const want = on ?? !marked.has(i);
+ if (want) marked.add(i);
+ else marked.delete(i);
+ }
+ return withEmphasis(cue, cueEmphasis({ text: cue.text, emphasis: [...marked] }));
+}
+
+/** The cue carrying exactly `marked`. */
+export function withEmphasis(cue: SubtitleCue, marked: readonly number[]): SubtitleCue {
+ const out: SubtitleCue = { ...cue };
+ delete out.emphasis;
+ return { ...out, ...emphasisField(marked) };
+}
+
+/** The emphasis of words [from, to) of a cue, re-indexed from 0 — one half of
+ * a split. */
+export function sliceEmphasis(marked: readonly number[], from: number, to: number): number[] {
+ return marked.filter((i) => i >= from && i < to).map((i) => i - from);
+}
+
+/** Two cues' emphasis joined, the second's words following the first's
+ * `count` — a merge. */
+export function joinEmphasis(
+ first: readonly number[],
+ count: number,
+ second: readonly number[]
+): number[] {
+ return [...first, ...second.map((i) => i + count)];
+}
+
+/** A word reduced to what identifies it across a rewrite: case and the
+ * punctuation hugging it are dropped, so "Figma," still lines up with
+ * "figma". */
+const tokenKey = (w: string) => w.toLowerCase().replace(/^[^\p{L}\p{N}]+|[^\p{L}\p{N}]+$/gu, "");
+
+/**
+ * The emphasis carried from `before` to `after`: the two word lists are lined
+ * up by their longest common run of words, and each emphasized word that is
+ * still there keeps its emphasis at its new index. A word that was replaced or
+ * removed loses it; a word that was added has none.
+ */
+export function remapEmphasis(
+ before: string,
+ after: string,
+ marked: readonly number[]
+): number[] {
+ if (marked.length === 0) return [];
+ const a = displayWords(before).map(tokenKey);
+ const b = displayWords(after).map(tokenKey);
+ // Longest common subsequence over the words: lcs[i][j] is the match length
+ // of a[i..] against b[j..]. Captions are a dozen words, so the table is tiny.
+ const lcs: number[][] = Array.from({ length: a.length + 1 }, () =>
+ new Array<number>(b.length + 1).fill(0)
+ );
+ for (let i = a.length - 1; i >= 0; i--) {
+ for (let j = b.length - 1; j >= 0; j--) {
+ lcs[i][j] = a[i] === b[j] ? lcs[i + 1][j + 1] + 1 : Math.max(lcs[i + 1][j], lcs[i][j + 1]);
+ }
+ }
+ const want = new Set(marked);
+ const out: number[] = [];
+ let i = 0;
+ let j = 0;
+ while (i < a.length && j < b.length) {
+ if (a[i] === b[j]) {
+ if (want.has(i)) out.push(j);
+ i++;
+ j++;
+ } else if (lcs[i + 1][j] >= lcs[i][j + 1]) i++;
+ else j++;
+ }
+ return out;
+}
+
+/** The word indices `words` names inside a cue, matched against that cue's
+ * own display words exactly as stored (case and hugging punctuation aside).
+ * A word that appears more than once matches every occurrence. Unknown words
+ * come back in `missing`. */
+export function emphasisIndicesOf(
+ cue: Pick<SubtitleCue, "text">,
+ words: readonly string[]
+): { indices: number[]; missing: string[] } {
+ const tokens = displayWords(cue.text).map(tokenKey);
+ const indices: number[] = [];
+ const missing: string[] = [];
+ for (const w of words) {
+ const key = tokenKey(w);
+ let hit = false;
+ tokens.forEach((t, i) => {
+ if (key && t === key) {
+ indices.push(i);
+ hit = true;
+ }
+ });
+ if (!hit) missing.push(w);
+ }
+ return { indices, missing };
+}
+
+/** Where each display word of `text` starts and ends, in characters. */
+function wordSpans(text: string): { start: number; end: number }[] {
+ const out: { start: number; end: number }[] = [];
+ for (const m of text.matchAll(/\S+/g)) out.push({ start: m.index, end: m.index + m[0].length });
+ return out;
+}
+
+/** The display words a character range of `text` touches — a selection in
+ * the transcript editor. A collapsed range names the word the caret is in or
+ * against, and the next word when it sits in the space between two. */
+export function wordIndicesIn(text: string, from: number, to: number): number[] {
+ const spans = wordSpans(text);
+ const a = Math.min(from, to);
+ const b = Math.max(from, to);
+ if (a === b) {
+ const hit = spans.findIndex((s) => a >= s.start && a <= s.end);
+ if (hit >= 0) return [hit];
+ const next = spans.findIndex((s) => s.start > a);
+ return next >= 0 ? [next] : spans.length > 0 ? [spans.length - 1] : [];
+ }
+ return spans.flatMap((s, i) => (s.start < b && s.end > a ? [i] : []));
+}
+
+/** The caption's text cut into runs for drawing it with its emphasized words
+ * marked: whitespace and plain words in plain runs, each emphasized word in a
+ * run of its own. Joined back together the runs are the text exactly. */
+export function emphasisRuns(
+ text: string,
+ marked: readonly number[]
+): { text: string; em: boolean }[] {
+ if (marked.length === 0) return [{ text, em: false }];
+ const want = new Set(marked);
+ const out: { text: string; em: boolean }[] = [];
+ let at = 0;
+ wordSpans(text).forEach((s, i) => {
+ if (!want.has(i)) return;
+ if (s.start > at) out.push({ text: text.slice(at, s.start), em: false });
+ out.push({ text: text.slice(s.start, s.end), em: true });
+ at = s.end;
+ });
+ if (at < text.length) out.push({ text: text.slice(at), em: false });
+ return out;
+}
diff --git a/site/src/cut/lib/cueChunk.ts b/site/src/cut/lib/cueChunk.ts
index 11a1aeaf..50145d52 100644
--- a/site/src/cut/lib/cueChunk.ts
+++ b/site/src/cut/lib/cueChunk.ts
@@ -19,6 +19,7 @@
* own breaks, so they are split when they run long and never glued together.
*/
+import { cueEmphasis } from "./captionEmphasis";
import type { SubtitleCue } from "./types";
/** Words a caption holds when the project hasn't said otherwise. */
@@ -97,12 +98,13 @@ function streamOf(cues: readonly SubtitleCue[]): StreamWord[] {
// is the honest reading then.
const timed = cue.words && cue.words.length === tokens.length ? cue.words : null;
const spread = timed ? null : spreadWordsEvenly(cue.text, cue.start, cue.end);
+ const marked = new Set(cueEmphasis(cue));
tokens.forEach((w, i) => {
const src = timed ? timed[i] : spread![i];
const t0 = Math.max(src.t0, floor);
const t1 = Math.max(src.t1, t0);
floor = t1;
- out.push({ w, t0, t1, measured: !!timed, from, id: cue.id });
+ out.push({ w, t0, t1, measured: !!timed, from, id: cue.id, em: marked.has(i) });
});
});
return out;
@@ -156,11 +158,18 @@ export function chunkLaneCues(cues: readonly SubtitleCue[], per: number): Subtit
const id = used.has(first.id) ? uid() : first.id;
used.add(id);
const measured = g.every((w) => w.measured);
+ const emphasis = g.flatMap((w, j) => (w.em ? [j] : []));
+ // A caption sits where the cue it opens on sat, the same cue whose id it
+ // takes.
+ const opener = ordered[first.from];
return {
id,
start: round(start),
end: round(end),
text: g.map((w) => w.w).join(" "),
+ ...(emphasis.length > 0 ? { emphasis } : {}),
+ ...(opener?.x !== undefined ? { x: opener.x } : {}),
+ ...(opener?.y !== undefined ? { y: opener.y } : {}),
...(measured
? {
words: g.map((w) => ({
diff --git a/site/src/cut/lib/googleFonts.ts b/site/src/cut/lib/googleFonts.ts
index 6134562a..df045a91 100644
--- a/site/src/cut/lib/googleFonts.ts
+++ b/site/src/cut/lib/googleFonts.ts
@@ -22,6 +22,9 @@ import "@fontsource/space-grotesk/400.css";
import "@fontsource/space-grotesk/700.css";
import "@fontsource/playfair-display/400.css";
import "@fontsource/playfair-display/700.css";
+// The italics are the caption emphasis default's face (subtitles.ts).
+import "@fontsource/playfair-display/400-italic.css";
+import "@fontsource/playfair-display/700-italic.css";
import "@fontsource/caveat/400.css";
import "@fontsource/caveat/700.css";
import "@fontsource/bebas-neue/400.css";
diff --git a/site/src/cut/lib/itemKinds.ts b/site/src/cut/lib/itemKinds.ts
index b7661794..dc668044 100644
--- a/site/src/cut/lib/itemKinds.ts
+++ b/site/src/cut/lib/itemKinds.ts
@@ -13,7 +13,8 @@
// compile until it has an entry, and `itemKinds.test.ts` walks the table so
// every entry proves it copies and pastes.
-import { retimeOf } from "@donkeycut/effects-kit";
+import { retimeOf, shiftCamera } from "@donkeycut/effects-kit";
+import { cueEmphasis, sliceEmphasis, withEmphasis } from "./captionEmphasis";
import {
fontAssetId,
isStickerOverlay,
@@ -184,9 +185,15 @@ export const ITEM_KINDS: { [K in ItemKind]: ItemKindDef<K> } = {
const left = c.words?.filter((w) => w.t0 < at);
const right = c.words?.filter((w) => w.t0 >= at);
const offset = Math.round(c.text.length * ((at - c.start) / (c.end - c.start)));
+ const leftText = left?.length ? left.map((w) => w.w).join(" ") : c.text.slice(0, offset).trim() || c.text;
+ const rightText = right?.length ? right.map((w) => w.w).join(" ") : c.text.slice(offset).trim() || c.text;
+ // Each half keeps the emphasis of the words it took, a word cut in two
+ // on both sides.
+ const marked = cueEmphasis(c);
+ const count = (t: string) => t.split(/\s+/).filter(Boolean).length;
return [
- { ...c, end: at, text: left?.length ? left.map((w) => w.w).join(" ") : c.text.slice(0, offset).trim() || c.text, words: left?.length ? left : undefined },
- { ...c, start: at, text: right?.length ? right.map((w) => w.w).join(" ") : c.text.slice(offset).trim() || c.text, words: right?.length ? right : undefined },
+ withEmphasis({ ...c, end: at, text: leftText, words: left?.length ? left : undefined }, sliceEmphasis(marked, 0, count(leftText))),
+ withEmphasis({ ...c, start: at, text: rightText, words: right?.length ? right : undefined }, sliceEmphasis(marked, Math.max(0, count(c.text) - count(rightText)), Infinity)),
];
},
clone: deep,
diff --git a/site/src/cut/lib/previewSelection.ts b/site/src/cut/lib/previewSelection.ts
index 7ec6cb0c..09d0e943 100644
--- a/site/src/cut/lib/previewSelection.ts
+++ b/site/src/cut/lib/previewSelection.ts
@@ -58,11 +58,18 @@ export function previewSelectionSnapshot(s: EditorState, t: number): Position[]
});
}
const lanes = new Set<number>();
+ const style = captionStyle(s.subtitles.style);
for (const cue of s.subtitles.cues) {
const lane = cue.lane ?? 0;
- if (!selected.has(`cue:${cue.id}`) || lanes.has(lane) || laneHidden(s.subtitles, lane)) continue;
+ if (!selected.has(`cue:${cue.id}`) || laneHidden(s.subtitles, lane)) continue;
+ if (cue.x !== undefined && cue.y !== undefined) {
+ const p = cueAnchor(cue, undefined, style);
+ positions.push({ kind: "cue", id: cue.id, lane, x: p.x, y: p.y, rotation: 0, own: true });
+ continue;
+ }
+ if (lanes.has(lane)) continue;
lanes.add(lane);
- const p = trackPos(s.subtitles, captionStyle(s.subtitles.style), lane);
+ const p = trackPos(s.subtitles, style, lane);
positions.push({ kind: "cue", id: cue.id, lane, x: p.x!, y: p.y!, rotation: 0 });
}
return positions;
@@ -100,9 +107,12 @@ function writePoses(
poses: { p: Position; x: number; y: number; rotation?: number; scale?: number; own?: OverlayPatch & Partial<FrameRect> }[],
) {
const patches: DocPatches = { clips: [], overlays: [] };
- for (const { p, x, y, rotation, scale, own } of poses) {
+ for (const seen of poses) {
+ const { p, scale, own } = seen;
+ const { x, y, rotation } = toWorld(p, seen.x, seen.y, seen.rotation);
if (p.kind === "cue") {
- s.setSubtitleTrackMeta(p.lane!, { x, y });
+ if (p.own) s.setCuePosition(p.id, { x, y });
+ else s.setSubtitleTrackMeta(p.lane!, { x, y });
continue;
}
if (p.key) {
@@ -177,6 +187,6 @@ export function rotatePreviewSelection(s: EditorState, positions: Position[], ce
if (p.kind === "cue") return { p, x: cx, y: cy };
if (p.key) return { p, x: cx, y: cy, rotation };
if (p.kind === "clip") return { p, x: cx - p.frame!.w / 2, y: cy - p.frame!.h / 2, rotation };
- return { p, x: clampOverlayPos(cx), y: clampOverlayPos(cy), rotation };
+ return { p, x: p.cam ? cx : clampOverlayPos(cx), y: p.cam ? cy : clampOverlayPos(cy), rotation };
}));
}
diff --git a/site/src/cut/lib/store.ts b/site/src/cut/lib/store.ts
index bf090f40..2a6c2181 100644
--- a/site/src/cut/lib/store.ts
+++ b/site/src/cut/lib/store.ts
@@ -44,6 +44,7 @@ import type {
Selection,
ShapeKind,
ShareFeatures,
+ SoundFrom,
StoredAsset,
SubtitleCue,
SubtitlesBlock,
@@ -88,9 +89,12 @@ import { useGenNotify } from "./genNotify";
import { clampPlayhead, playheadAt, previewAt, setPlayhead, setSkim } from "./playhead";
import { engineTranscribeSamples, withEngineStt } from "./localStt";
import { laneCues, subtitleLaneCount, trackLocale } from "./subtitles";
+import { cueEmphasis, emphasisField, joinEmphasis, remapEmphasis, sliceEmphasis, toggleEmphasis, withEmphasis } from "./captionEmphasis";
import { clipboardItemAssetIds, clipboardItemFor, listedAssetIds, type TimelineClipboardItem } from "./itemKinds";
import { ANIM_STYLE_IDS, animStyleOfTransition, assetIsSilent, clipPoseAt, DEFAULT_BACKGROUND, emptySubtitles, frameOf, IMAGE_CLIP_SECONDS, isAudioTransition, fontAssetId, isEffectOverlay, isStickerOverlay, MAX_SUBTITLE_LANES, mediaUrl, migrateBehindSubject, migrateLegacyTransitions, normalizeAspect, overlayAnimStyle, projectBackground, SPEED_FLOOR, SPEED_MIN, stampOverlayKinds, stripDefaultOverlayKinds, isTimelineId, sanitizeTimelines, timelineAspect, TRANSITION_MAX, TRANSITION_STYLE_IDS, transitionBarAt, transitionBarStart, transitionStyleOfAnim, type TransitionBoundaryKind } from "./types";
import { liftMoveTracks } from "./textMotion";
+import { soundRoom, soundSourceOf, soundWindow, SPLIT_EDIT_MAX_S } from "./soundSource";
+import { cutSound } from "./soundSettings";
import { readTextStyle } from "./textStyle";
import { loadUiState, saveUiState, type ProjectUiState } from "./uiState";
import { captureTimelineFrames } from "./visualFrames";
@@ -873,6 +877,17 @@ export interface EditorState {
setSubtitleTrackMeta: (lane: number, patch: Partial<SubtitleTrackMeta>) => void;
/** Commit a cue's edited text (empty text deletes the cue). */
setCueText: (id: string, text: string) => void;
+ /** Set caption words on or off in the track's emphasis style, by cue id and
+ * display-word index; `on` absent flips each word. `clear` first removes
+ * every emphasized word (on `clear.lane` when given). One undo step. */
+ setCueEmphasis: (
+ edits: { id: string; indices: number[]; on?: boolean }[],
+ clear?: { lane?: number }
+ ) => void;
+ /** Give one caption its own anchor (frame fractions), or hand it back to
+ * its track's with null. Not an undo step on its own: a drag checkpoints
+ * once and writes many. */
+ setCuePosition: (id: string, pos: { x: number; y: number } | null) => void;
/** Split a cue at a character offset — at real word timings when known. */
splitCue: (id: string, charOffset: number) => void;
mergeCueIntoPrev: (id: string) => void;
@@ -4214,7 +4229,16 @@ export const useEditor = create<EditorState>((baseSet, get, api) => {
if (s.readOnly || !selectedGroupIds(s, s.multiSelection).size) return;
push();
const ungrouped = setTimelineGroup(s, s.multiSelection, undefined);
- set({ ...ungrouped, subtitles: { ...s.subtitles, cues: ungrouped.subtitles.cues } });
+ // An element out of its group leaves the group's camera behind.
+ const overlays = ungrouped.overlays.map((o) => (o.groupId ? o : withoutCamera(o)));
+ set({ ...ungrouped, overlays, subtitles: { ...s.subtitles, cues: ungrouped.subtitles.cues } });
+ },
+
+ setGroupCamera: (groupId, cam, opts) => {
+ const s = get();
+ if (s.readOnly || !s.overlays.some((o) => o.groupId === groupId)) return;
+ if (!opts?.transient) push();
+ set({ overlays: withGroupCamera(s.overlays, groupId, cam) });
},
toggleSelect: (sel) => set((s) => {
@@ -4529,7 +4553,12 @@ export const useEditor = create<EditorState>((baseSet, get, api) => {
// but the cue's own start/end are untouched.
const written = cur.subtitles.cues.map((c) => {
const t = byId.get(c.id);
- return t && t !== c.text ? { ...c, text: t, words: undefined } : c;
+ return t && t !== c.text
+ ? withEmphasis(
+ { ...c, text: t, words: undefined },
+ remapEmphasis(c.text, t, cueEmphasis(c))
+ )
+ : c;
});
// A rewritten line still reads at the project's word count: one
// that came back long is cut, one that came back short is left as
@@ -4815,16 +4844,58 @@ export const useEditor = create<EditorState>((baseSet, get, api) => {
cue.words && cue.words.length === parts.length
? parts.map((w, i) => ({ ...cue.words![i], w }))
: undefined;
+ // Emphasis stays on every word the edit kept, wherever it now sits.
+ const emphasis = remapEmphasis(cue.text, trimmed, cueEmphasis(cue));
set((s) => ({
subtitles: {
...s.subtitles,
cues: trimmed
- ? s.subtitles.cues.map((c) => (c.id === id ? { ...c, text: trimmed, words } : c))
+ ? s.subtitles.cues.map((c) =>
+ c.id === id ? withEmphasis({ ...c, text: trimmed, words }, emphasis) : c
+ )
: s.subtitles.cues.filter((c) => c.id !== id),
},
}));
},
+ setCueEmphasis: (edits, clear) => {
+ const by = new Map<string, { indices: number[]; on?: boolean }[]>();
+ for (const e of edits) {
+ const list = by.get(e.id);
+ if (list) list.push(e);
+ else by.set(e.id, [e]);
+ }
+ const cleared = (c: SubtitleCue) =>
+ !!clear && !!c.emphasis?.length && (clear.lane === undefined || (c.lane ?? 0) === clear.lane);
+ if (!get().subtitles.cues.some((c) => by.has(c.id) || cleared(c))) return;
+ push();
+ set((s) => ({
+ subtitles: {
+ ...s.subtitles,
+ cues: s.subtitles.cues.map((c) =>
+ (by.get(c.id) ?? []).reduce(
+ (cur, e) => toggleEmphasis(cur, e.indices, e.on),
+ cleared(c) ? withEmphasis(c, []) : c
+ )
+ ),
+ },
+ }));
+ },
+
+ setCuePosition: (id, pos) =>
+ set((s) => ({
+ subtitles: {
+ ...s.subtitles,
+ cues: s.subtitles.cues.map((c) => {
+ if (c.id !== id) return c;
+ const next: SubtitleCue = { ...c };
+ delete next.x;
+ delete next.y;
+ return pos ? { ...next, x: pos.x, y: pos.y } : next;
+ }),
+ },
+ })),
+
splitCue: (id, charOffset) => {
const s = get();
const cue = s.subtitles.cues.find((c) => c.id === id);
@@ -4836,6 +4907,7 @@ export const useEditor = create<EditorState>((baseSet, get, api) => {
let rightStart: number;
let leftWords: SubtitleCue["words"];
let rightWords: SubtitleCue["words"];
+ const marked = cueEmphasis(cue);
if (cue.words && cue.words.length > 1) {
// Word timings are intact: split on the word under the caret so both
// halves keep real timestamps.
@@ -4858,18 +4930,28 @@ export const useEditor = create<EditorState>((baseSet, get, api) => {
leftEnd = rightStart = Math.round(t * 100) / 100;
}
push();
- const left: SubtitleCue = {
- ...cue,
- end: leftEnd,
- text: leftWords ? leftWords.map((w) => w.w).join(" ") : before,
- words: leftWords,
- };
+ const leftText = leftWords ? leftWords.map((w) => w.w).join(" ") : before;
+ const rightText = rightWords ? rightWords.map((w) => w.w).join(" ") : after;
+ // Each half keeps the emphasis of the words it took. A caret inside a
+ // word leaves a piece of it on both sides, and both pieces keep it.
+ const count = (t: string) => t.split(/\s+/).filter(Boolean).length;
+ const left: SubtitleCue = withEmphasis(
+ { ...cue, end: leftEnd, text: leftText, words: leftWords },
+ sliceEmphasis(marked, 0, count(leftText))
+ );
+ // The second half keeps the track and the spot the caption sat on.
const right: SubtitleCue = {
id: uid(),
start: rightStart,
end: cue.end,
- text: rightWords ? rightWords.map((w) => w.w).join(" ") : after,
+ text: rightText,
words: rightWords,
+ ...emphasisField(
+ sliceEmphasis(marked, count(cue.text) - count(rightText), Infinity)
+ ),
+ ...(cue.lane ? { lane: cue.lane } : {}),
+ ...(cue.x !== undefined ? { x: cue.x } : {}),
+ ...(cue.y !== undefined ? { y: cue.y } : {}),
};
set((cur) => ({
subtitles: {
@@ -4891,12 +4973,19 @@ export const useEditor = create<EditorState>((baseSet, get, api) => {
if (i <= 0) return;
push();
const prev = cues[i - 1];
- const merged: SubtitleCue = {
- ...prev,
- end: Math.max(prev.end, cue.end),
- text: `${prev.text} ${cue.text}`.replace(/\s+/g, " ").trim(),
- words: prev.words && cue.words ? [...prev.words, ...cue.words] : undefined,
- };
+ const merged: SubtitleCue = withEmphasis(
+ {
+ ...prev,
+ end: Math.max(prev.end, cue.end),
+ text: `${prev.text} ${cue.text}`.replace(/\s+/g, " ").trim(),
+ words: prev.words && cue.words ? [...prev.words, ...cue.words] : undefined,
+ },
+ joinEmphasis(
+ cueEmphasis(prev),
+ prev.text.split(/\s+/).filter(Boolean).length,
+ cueEmphasis(cue)
+ )
+ );
set((s) => ({
subtitles: {
...s.subtitles,
@@ -6339,6 +6428,7 @@ export function assetIdsInUse(s: {
overlays: Overlay[];
transitions?: TimelineTransition[];
subtitles?: { font?: string; cues?: SubtitleCue[] } | null;
+ assets?: readonly StoredAsset[];
}): Set<string> {
// Every item kind says where its asset ids sit; the caption track's font
// is the one project-level reference beside them.
diff --git a/site/src/cut/lib/subtitles.ts b/site/src/cut/lib/subtitles.ts
index 1c07711a..17427d31 100644
--- a/site/src/cut/lib/subtitles.ts
+++ b/site/src/cut/lib/subtitles.ts
@@ -59,9 +59,19 @@ export interface CaptionWordOverrides {
accentDim?: number;
}
+/** The block-level emphasis style: how a caption's emphasized words are set
+ * apart. Absent fields = CAPTION_EMPHASIS_DEFAULT's. */
+export interface CaptionEmphasisOverrides {
+ emphasisFont?: FontId;
+ emphasisColor?: string;
+ emphasisItalic?: boolean;
+ emphasisWeight?: 400 | 700;
+ emphasisScale?: number;
+}
+
/** A track's effective caption anchor plus the block's look overrides — what
* `cueOverlay` reads to place and dress one cue. */
-export interface CaptionPos extends CaptionWordOverrides {
+export interface CaptionPos extends CaptionWordOverrides, CaptionEmphasisOverrides {
x: number;
y: number;
size?: number;
@@ -86,6 +96,46 @@ export function trackPos(
accentColor: subs.accentColor,
accentScale: subs.accentScale,
accentDim: subs.accentDim,
+ emphasisFont: subs.emphasisFont,
+ emphasisColor: subs.emphasisColor,
+ emphasisItalic: subs.emphasisItalic,
+ emphasisWeight: subs.emphasisWeight,
+ emphasisScale: subs.emphasisScale,
+ };
+}
+
+/** Where one caption sits: its own anchor where it has one, else its track's
+ * (see `trackPos`). Preview, drag and every burn-in read this. */
+export function cueAnchor(
+ cue: Pick<SubtitleCue, "x" | "y">,
+ track: { x?: number; y?: number } | undefined,
+ style: CaptionStyle
+): { x: number; y: number } {
+ return { x: cue.x ?? track?.x ?? style.x, y: cue.y ?? track?.y ?? style.y };
+}
+
+/** How emphasized caption words look when the track names nothing: a bold
+ * italic serif in yellow, at the caption's own size. */
+export const CAPTION_EMPHASIS_DEFAULT: Readonly<Required<WordFace>> = {
+ font: "playfair",
+ color: "#FFFF00",
+ italic: true,
+ weight: 700,
+ scale: 1,
+};
+
+/** The bounds an emphasis scale is held to. */
+export const EMPHASIS_SCALE_MIN = 0.8;
+export const EMPHASIS_SCALE_MAX = 1.6;
+
+/** A track's emphasis style with its defaults filled in. */
+export function captionEmphasis(subs?: CaptionEmphasisOverrides): Required<WordFace> {
+ return {
+ font: subs?.emphasisFont ?? CAPTION_EMPHASIS_DEFAULT.font,
+ color: subs?.emphasisColor ?? CAPTION_EMPHASIS_DEFAULT.color,
+ italic: subs?.emphasisItalic ?? CAPTION_EMPHASIS_DEFAULT.italic,
+ weight: subs?.emphasisWeight ?? CAPTION_EMPHASIS_DEFAULT.weight,
+ scale: subs?.emphasisScale ?? CAPTION_EMPHASIS_DEFAULT.scale,
};
}
@@ -367,7 +417,7 @@ export function cueOverlay(
const size = Math.round(
(pos?.size ?? style.size) * (isOpener && style.openerScale ? style.openerScale : 1)
);
- const x = pos?.x ?? style.x;
+ const { x, y } = cueAnchor(cue, pos, style);
const text = wrapCaptionForSize(
cue.text,
size,
@@ -382,7 +432,7 @@ export function cueOverlay(
start: cue.start,
end: cue.end,
x,
- y: pos?.y ?? style.y,
+ y,
size,
font: pos?.font ?? style.font,
weight: style.weight,
diff --git a/site/src/cut/lib/types.ts b/site/src/cut/lib/types.ts
index 0509d3f1..1970cc57 100644
--- a/site/src/cut/lib/types.ts
+++ b/site/src/cut/lib/types.ts
@@ -1209,6 +1209,11 @@ export const CAPTION_LOOK_KEYS = [
"accentColor",
"accentScale",
"accentDim",
+ "emphasisFont",
+ "emphasisColor",
+ "emphasisItalic",
+ "emphasisWeight",
+ "emphasisScale",
] as const;
export type CaptionLook = Partial<Pick<SubtitlesBlock, (typeof CAPTION_LOOK_KEYS)[number]>>;
@@ -1443,6 +1448,16 @@ 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 }[];
+ /** The words set apart in the track's emphasis style, as indices into the
+ * caption's display words (its text split on whitespace — the indexing
+ * `words` and the word effects use). Indices ride with their words: a
+ * re-cut, a split, a merge or a hand-edit that keeps a word keeps its
+ * emphasis, and timing changes never touch it. Absent = none. */
+ emphasis?: number[];
+ /** This caption's own anchor as frame fractions, over its track's. Absent
+ * = the track's. */
+ x?: number;
+ y?: number;
/** 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
@@ -1519,6 +1534,14 @@ export interface SubtitlesBlock {
accentScale?: number;
/** The opacity a word wears off its moment; absent = the effect's own. */
accentDim?: number;
+ /** How an emphasized word (`SubtitleCue.emphasis`) is set apart; each
+ * absent field = CAPTION_EMPHASIS_DEFAULT's (lib/subtitles.ts). */
+ emphasisFont?: FontId;
+ emphasisColor?: string;
+ emphasisItalic?: boolean;
+ emphasisWeight?: 400 | 700;
+ /** Size multiplier over the caption's own size. */
+ emphasisScale?: number;
}
export const emptySubtitles = (): SubtitlesBlock => ({
diff --git a/site/src/cut/server/ai/catalog.ts b/site/src/cut/server/ai/catalog.ts
index 477a86f9..a483caf0 100644
--- a/site/src/cut/server/ai/catalog.ts
+++ b/site/src/cut/server/ai/catalog.ts
@@ -253,7 +253,7 @@ Times are in seconds on the shared timeline. The playhead is currentTime; a skim
- set_speed sets a clip's playback rate; it changes the clip's timeline length and pushes overlapping neighbors on its own row. set_speed with \`reverse: true\` plays the clip backward (a rewind, a drop that rises, a pour that un-pours); it changes nothing about length or the curve. set_speed_curve makes the rate change through the footage — nodes of {at: source seconds, speed} or a named preset ramp — for speed ramps, whips, holds, and hits on the beat: detect_beats first, then place nodes at the beats it returns (same unit, no arithmetic). set_speed on a curved clip makes it uniform again. Either tool takes \`smooth: true\` — smooth slow motion — which synthesizes the frames between source frames wherever the clip's rate is under 1× (the export estimates the motion between them) and leaves the rest of the clip alone; editor_state shows it as \`smooth\`. Ordinary footage slowed below about 0.5× wants it on.
- set_transition joins a clip into the next one (0–2s, ${TRANSITION_STYLE_IDS.length} styles); set_animation animates one clip's own entrance/exit — read the transitions-and-fades skill before styling cuts. A transition is a bar on its own row at an absolute time, so an edit can leave one lining up with nothing: every timeline mutation reports those as \`parkedTransitions\`, and clearing them (remove_transition) is part of finishing the edit. Grading a clip's picture is the color tools (set_color_preset, set_color_grade, set_color_curves, set_color_wheels, set_color_hsl, set_color_lut, copy_color_grade — read the color-grading skill); a stylized post treatment (grain, VHS, halation…) is add_effect, dropped over the stretch of timeline it covers — as is a treatment on the sound (echo, reverb, telephone…).
- Cutting a clip's background away — the AI person matte, ink around the silhouette, a fill behind the subject — is the cutout suite (set_removal, set_removal_stroke, set_removal_background); read the background-removal skill.
-- A sweep is find, then apply. select_items judges every item on a row against a description at once and hands back the ids that match ("the clips with no one talking", "the titles that are all caps"); set_clip_muted, set_clip_hidden, set_clip_volume, set_color_preset, set_color_grade, set_color_curves, set_color_wheels, set_color_hsl, set_color_lut, apply_saved_grade, set_speed, set_framing, set_transition, delete_item, update_cue, delete_cue, update_audio and update_overlay then take \`ids\` in place of their one-item argument (the color tools take \`all_clips\` for the whole timeline) and land the change on all of them in one call, as one undo step. Reading the state and deciding item by item is the slow way to do the same thing. select_items reads what the timeline already says about each item, so anything that depends on the footage or the audio is measured first (watch_video, detect_silence, measure_level) and named in the description.
+- A sweep is find, then apply. select_items judges every item on a row against a description at once and hands back the ids that match ("the clips with no one talking", "the titles that are all caps"); set_clip_muted, set_clip_hidden, set_clip_volume, set_color_preset, set_color_grade, set_color_curves, set_color_wheels, set_color_hsl, set_color_lut, apply_saved_grade, set_speed, set_framing, set_camera_card, set_transition, delete_item, update_cue, delete_cue, update_audio and update_overlay then take \`ids\` in place of their one-item argument (the color tools take \`all_clips\` for the whole timeline) and land the change on all of them in one call, as one undo step. Reading the state and deciding item by item is the slow way to do the same thing. select_items reads what the timeline already says about each item, so anything that depends on the footage or the audio is measured first (watch_video, detect_silence, measure_level) and named in the description.
- split_at cuts selected video, audio, elements and captions at the requested time. Transitions stay whole. With no selection, it cuts the track-0 clip at that time.
- The Media and Library panels take the same gestures: ⌘/⇧-click a tile, or sweep a rubber-band over the grid, and dragging any picked tile onto the timeline lays the whole set down one after another from the drop point.
- The user can multi-select (⌘/⇧-click, or sweep a rubber-band over empty track space) across every kind at once — clips, audio, elements, cues and transitions. Deleting or copying acts on the whole selection, and dragging any member moves the set as one: every item shifts by the same time, relative spacing kept, while unselected items slide out of the way and flow back. A selection of one kind on the multi-row tracks (audio, titles) also retracks together on a vertical drag, one row past the end opening a new track. A hover chip on each video clip toggles its own audio.
@@ -523,7 +523,9 @@ Subtitle tracks: a project carries up to 3, one language each (editor_state subt
How the captions read: one caption holds ${DEFAULT_WORDS_PER_CUE} words at a time by default, ${MIN_WORDS_PER_CUE}–${MAX_WORDS_PER_CUE} through set_caption_look words_per_cue (the current number is editor_state subtitles.wordsPerCue, and the Subtitles panel's Options tab offers the same slider). It answers "show fewer words at once", "one word at a time", "these captions are a wall of text". Every track is re-cut on its own measured words — the wording survives verbatim — and the re-cut track is then measured against the mix, so the new lines land on the speech. Lines somebody authored (a translation, lyrics, narration written to picture) are split when they run long and never glued to the line beside them, and a caption always breaks at a pause or the end of a sentence however few words it holds.
Generating: subtitles_generate transcribes the cut's audio on-device (Apple speech, macOS 26) onto the target track; cues are cut to the project's words-per-caption. subtitles_from_visuals is the fallback for a cut with NO speech — it watches sampled frames (via the user's Claude login) and writes timed narration captions of what's on screen. So: speech present → subtitles_generate; silent/music-only footage the user wants captioned → subtitles_from_visuals. Never fabricate a spoken transcript.
captions_generate rewrites a track's cues into punchy social captions (emoji, curiosity-hook opener) in a style (clean/hook/punchy), keeping timings — use it when the ask is social/TikTok captions rather than a plain transcript.
-Editing: update_cue (text or retime), delete_cue, merge_cue (joins into the previous cue on the same track). In the panel, Return splits a caption at the cursor onto real word timings; hand-edited text drops its word timings.
+Editing: update_cue (text, retime, or the caption's own x/y), delete_cue, merge_cue (joins into the previous cue on the same track). In the panel, Return splits a caption at the cursor onto real word timings; hand-edited text drops its word timings.
+Placement per caption: a track has one spot, and update_cue x/y gives a single caption its own (editor_state shows it on the cue) — a talking-head video moves its captions with the layout: centered in the gap of a split layout, a lower third over the full-frame face, the top when the visual under it is busy low. follow_track hands it back. In the preview, Option-drag moves only the caption on screen.
+Emphasis: set_caption_emphasis sets chosen words apart in the track's emphasis style (default a bold italic ${CAPTION_EMPHASIS_DEFAULT.font} in ${CAPTION_EMPHASIS_DEFAULT.color}; set_caption_look emphasis_font/emphasis_color/emphasis_italic/emphasis_weight/emphasis_scale restyle it), the rest of the line unchanged and any word effect still playing over it. Pick one or two words that carry the line — a product name, a number, the call-to-action keyword — in roughly every third caption; never two emphasized captions in a row, never a function word. editor_state cues list their emphasized words as [index, word].
subtitles_set_view: showOnVideo (preview + export burn-in), showOnTimeline (amber cue rows).
Caption look: set_caption_look carries the whole look — the visual presets (${Object.keys(CAPTION_STYLES).join(", ")}), size, font, and the word effect with its color, swell and fade settings; the Subtitles panel offers the same, and each track's caption drags to a new spot in the preview. The word effects play the caption as it is said:\n${wordEffectCatalog()}\ncaptions_generate's clean/hook/punchy choice shapes the caption text it writes; the visual preset is separate.`,