Record your screen, ship a demo. Free and open-source, GPU-accelerated, no watermarks, no subscriptions. Windows, macOS, Linux. Actively maintained.
TypeScript cross-platformelectronffmpegopen-sourceproduct-demorustscreen-capturescreen-recorderscreen-recordingscreen-studioscreencastspeech-to-texttypescriptvideo-editingvideo-editorwaylandwgpuwhisper
fix(captions): group translated captions into phrases, over the shared colour field
Etienne Lescotbe84d655eb0b
diff --git a/src/components/ai-edition/CaptionLayer.tsx b/src/components/ai-edition/CaptionLayer.tsxindex e74c8ad4f..db2914cf6 100644--- a/src/components/ai-edition/CaptionLayer.tsx+++ b/src/components/ai-edition/CaptionLayer.tsx@@ -11,6 +11,7 @@// preview shows is what the export writes.import { useMemo } from "react";+import { annotationFontSizePx } from "@/lib/ai-edition/annotationScale";import {type CaptionCue,type CaptionSettings,@@ -70,7 +71,11 @@ export function CaptionLayer({style={{color: settings.color,backgroundColor: background,- fontSize: `${settings.fontSize}px`,+ // Same rule as annotations (annotationScale.ts): the authored number is+ // pixels at a 1080-high frame, scaled by the box actually being drawn+ // into — so the preview is a scale model of the render instead of+ // showing one size on screen and another in the file.+ fontSize: `${annotationFontSizePx(settings.fontSize, containerHeight)}px`,fontFamily: settings.fontFamily,fontWeight: settings.fontWeight,textAlign: settings.textAlign,diff --git a/src/components/ai-edition/CaptionsPane.tsx b/src/components/ai-edition/CaptionsPane.tsxindex 5074d4cd1..91661bdc4 100644--- a/src/components/ai-edition/CaptionsPane.tsx+++ b/src/components/ai-edition/CaptionsPane.tsx@@ -13,11 +13,13 @@ import { Captions as CaptionsIcon, Languages, Loader2, Trash2 } from "lucide-reaimport { useMemo, useState } from "react";import { useScopedT } from "@/contexts/I18nContext";import type { CaptionTextAlign, CaptionVerticalPosition } from "@/lib/ai-edition/captions";-import { untranslatedSegments } from "@/lib/ai-edition/captions";+import { untranslatedUnits } from "@/lib/ai-edition/captions";import { useProjectStore } from "@/lib/ai-edition/store/projectStore";import { useCaptions } from "@/lib/ai-edition/store/useCaptions";import { nativeBridgeClient } from "@/native";+import { ColorField } from "./ColorField";import styles from "./NewEditorShell.module.css";+import { SliderCell, Toggle } from "./RightPanes";/** The families `src/index.css` already loads for on-canvas text — anything else* would render in the preview but fall back to a default in the export canvas. */@@ -41,16 +43,6 @@ const CAPTION_FONTS = ["IBM Plex Mono",] as const;-const TEXT_COLORS = ["#ffffff", "#f8fafc", "#fde047", "#34d399", "#60a5fa", "#0f172a"] as const;-const BACKGROUND_COLORS = [- "#000000",- "#16171d",- "#1e293b",- "#334155",- "#10b981",- "#ffffff",-] as const;-/** Offered as translation targets. Codes double as the storage key. */const TRANSLATION_LANGUAGES: ReadonlyArray<{ code: string; label: string }> = [{ code: "en", label: "English" },@@ -116,14 +108,16 @@ export function CaptionsPane({ onTranscribe, isTranscribing }: CaptionsPanePropssetTranslating(true);setTranslateError(null);try {- // Only the assets actually on the timeline, and only the segments that- // aren't translated yet — a re-run after adding footage costs just the new- // material instead of the whole video.+ // Only the assets actually on the timeline, and only the units that aren't+ // translated yet — a re-run after adding footage costs just the new+ // material instead of the whole video. Units, not segments: a Whisper+ // transcript is one segment per word, and translating single words gives+ // nonsense in any language that reorders or agrees differently.const assetIds = new Set(doc.timeline.clips.map((c) => c.assetId));let translatedAny = false;for (const transcript of doc.transcripts) {if (!assetIds.has(transcript.assetId)) continue;- const pending = untranslatedSegments(transcript, translations, target);+ const pending = untranslatedUnits(transcript, translations, target);if (pending.length === 0) {translatedAny = true;continue;@@ -177,13 +171,10 @@ export function CaptionsPane({ onTranscribe, isTranscribing }: CaptionsPaneProps<div className={styles.paneBody} style={{ padding: 0 }}><div className={styles.paneRow}><span className="label">{t("captions.show")}</span>- <button- type="button"- className={`${styles.toggle} ${settings.enabled ? styles.isOn : ""}`}- aria-pressed={settings.enabled}- aria-label={t("captions.show")}+ <Toggle+ checked={settings.enabled}disabled={disabled || !hasTranscript}- onClick={() => void set({ enabled: !settings.enabled })}+ onChange={(next) => void set({ enabled: next })}/></div>@@ -358,73 +349,70 @@ export function CaptionsPane({ onTranscribe, isTranscribing }: CaptionsPaneProps</div><div className={styles.paneRow}><span className="label">{t("captions.bold")}</span>- <button- type="button"- className={`${styles.toggle} ${settings.fontWeight === "bold" ? styles.isOn : ""}`}- aria-pressed={settings.fontWeight === "bold"}- aria-label={t("captions.bold")}+ <Toggle+ checked={settings.fontWeight === "bold"}disabled={disabled}- onClick={() =>- void set({ fontWeight: settings.fontWeight === "bold" ? "normal" : "bold" })- }+ onChange={(next) => void set({ fontWeight: next ? "bold" : "normal" })}/></div><div className={styles.sliderGrid}><SliderCelllabel={t("captions.fontSize")}value={settings.fontSize}- min={10}- max={90}+ min={16}+ max={140}suffix="px"disabled={disabled}onChange={(v) => setLive({ fontSize: v })}onCommit={() => void commit()}/></div>- <div className={styles.sectionLabel}>{t("captions.textColor")}</div>- <SwatchRow- colors={TEXT_COLORS}- value={settings.color}- disabled={disabled}- onPick={(color) => void set({ color })}- label={t("captions.textColor")}- />+ <div className={styles.paneRow}>+ <span className="label">{t("captions.textColor")}</span>+ <ColorField+ label={t("captions.textColor")}+ value={settings.color}+ disabled={disabled}+ onChange={(color) => setLive({ color })}+ onCommit={() => void commit()}+ />+ </div>{/* ── Background ─────────────────────────────────────────── */}<div className={styles.sectionLabel}>{t("captions.background")}</div>+ {/* Colour + switch on one row, exactly like the annotation pane's text+ background: the swatch keeps showing the remembered colour while the+ plate is off, because that is what turning it back on will draw. */}<div className={styles.paneRow}>- <span className="label">{t("captions.showBackground")}</span>- <button- type="button"- className={`${styles.toggle} ${settings.backgroundEnabled ? styles.isOn : ""}`}- aria-pressed={settings.backgroundEnabled}- aria-label={t("captions.showBackground")}- disabled={disabled}- onClick={() => void set({ backgroundEnabled: !settings.backgroundEnabled })}- />+ <span className="label">{t("captions.background")}</span>+ <div style={{ display: "flex", alignItems: "center", gap: 8 }}>+ <ColorField+ label={t("captions.backgroundColor")}+ value={settings.backgroundColor}+ disabled={disabled}+ onChange={(backgroundColor) => setLive({ backgroundColor })}+ onCommit={() => void commit()}+ />+ <Toggle+ checked={settings.backgroundEnabled}+ disabled={disabled}+ onChange={(next) => void set({ backgroundEnabled: next })}+ />+ </div></div>{settings.backgroundEnabled ? (- <>- <SwatchRow- colors={BACKGROUND_COLORS}- value={settings.backgroundColor}+ <div className={styles.sliderGrid}>+ <SliderCell+ label={t("captions.backgroundOpacity")}+ value={Math.round(settings.backgroundOpacity * 100)}+ min={0}+ max={100}+ suffix="%"disabled={disabled}- onPick={(backgroundColor) => void set({ backgroundColor })}- label={t("captions.backgroundColor")}+ onChange={(v) => setLive({ backgroundOpacity: v / 100 })}+ onCommit={() => void commit()}/>- <div className={styles.sliderGrid}>- <SliderCell- label={t("captions.backgroundOpacity")}- value={Math.round(settings.backgroundOpacity * 100)}- min={0}- max={100}- suffix="%"- disabled={disabled}- onChange={(v) => setLive({ backgroundOpacity: v / 100 })}- onCommit={() => void commit()}- />- </div>- </>+ </div>) : null}{/* ── Placement ──────────────────────────────────────────── */}@@ -522,70 +510,15 @@ const selectStyle: React.CSSProperties = {maxWidth: 160,};-function SwatchRow({- colors,- value,- disabled,- onPick,- label,-}: {- colors: readonly string[];- value: string;- disabled?: boolean;- onPick: (color: string) => void;- label: string;-}) {- return (- <div- style={{- margin: "0 var(--sp-4) 12px",- display: "flex",- alignItems: "center",- gap: 8,- flexWrap: "wrap",- }}- >- {colors.map((color) => (- <button- type="button"- key={color}- title={color}- aria-label={`${label} ${color}`}- aria-pressed={value.toLowerCase() === color.toLowerCase()}- disabled={disabled}- onClick={() => onPick(color)}- style={{- width: 24,- height: 24,- borderRadius: "50%",- background: color,- border:- value.toLowerCase() === color.toLowerCase()- ? "2px solid var(--accent)"- : "1px solid var(--border-hi)",- cursor: disabled ? "not-allowed" : "pointer",- }}- />- ))}- <input- type="color"- value={value.startsWith("#") ? value : "#ffffff"}- disabled={disabled}- aria-label={label}- onChange={(e) => onPick(e.target.value)}- style={{- width: 34,- height: 26,- padding: 0,- border: "1px solid var(--border)",- borderRadius: 6,- background: "var(--surface)",- }}- />- </div>- );-}-+/**+ * One "label + swatch" row that opens the app's standard `ColorPicker` (wheel /+ * palette / hex) in a popover.+ *+ * The pane used to carry its own hard-coded caption swatches. That was a third+ * private palette in the app, and it meant the caption colours behaved unlike+ * every other colour surface — so it's gone: this defers to the shared+ * `COLOR_PALETTE` and the shared picker instead.+ */function Segmented<T extends string>({value,options,@@ -614,49 +547,3 @@ function Segmented<T extends string>({</div>);}--function SliderCell({- label,- value,- min,- max,- step = 1,- suffix = "",- disabled,- onChange,- onCommit,-}: {- label: string;- value: number;- min: number;- max: number;- step?: number;- suffix?: string;- disabled?: boolean;- onChange: (next: number) => void;- onCommit: () => void;-}) {- return (- <div className={styles.sliderCell}>- <div className="head">- <span className="label">{label}</span>- <span className="val">- {Math.round(value)}- {suffix}- </span>- </div>- <input- type="range"- min={min}- max={max}- step={step}- value={value}- disabled={disabled}- onChange={(e) => onChange(Number(e.target.value))}- onMouseUp={onCommit}- onTouchEnd={onCommit}- onKeyUp={onCommit}- />- </div>- );-}diff --git a/src/lib/ai-edition/captions/captions.test.ts b/src/lib/ai-edition/captions/captions.test.tsindex 88ee9a354..2b6f37530 100644--- a/src/lib/ai-edition/captions/captions.test.ts+++ b/src/lib/ai-edition/captions/captions.test.ts@@ -9,11 +9,12 @@ import {patchCaptionSettings,} from "./settings";import {+ captionTranslationUnits,getCaptionTranslations,putCaptionTranslation,removeCaptionTranslation,translationCoverage,- untranslatedSegments,+ untranslatedUnits,} from "./translations";function transcript(): AxcutTranscript {@@ -194,13 +195,13 @@ describe("deriveCaptionCues", () => {expect(deriveCaptionCues(cut, ON, {})).toEqual([]);});- it("shows the translation for a translated segment and the original for the rest", () => {+ it("shows the translation for a translated unit and the original for the rest", () => {const translations = {fr: {language: "fr",label: "Français",updatedAt: "2026-01-01T00:00:00.000Z",- byAsset: { "asset-1": { seg_1: "bonjour mon ami" } },+ byAsset: { "asset-1": { "u:seg_1": "bonjour mon ami" } },},};const cues = deriveCaptionCues(doc(), { ...ON, language: "fr" }, translations);@@ -210,13 +211,13 @@ describe("deriveCaptionCues", () => {expect(text).toContain("goodbye");});- it("keeps the translated line inside its own segment's span", () => {+ it("keeps the translated line inside its own unit's span", () => {const translations = {fr: {language: "fr",label: "Français",updatedAt: "",- byAsset: { "asset-1": { seg_1: "bonjour", seg_2: "au revoir" } },+ byAsset: { "asset-1": { "u:seg_1": "bonjour", "u:seg_2": "au revoir" } },},};const cues = deriveCaptionCues(doc(), { ...ON, language: "fr" }, translations);@@ -295,15 +296,15 @@ describe("caption translations", () => {});});- it("reports only the segments still missing a translation", () => {+ it("reports only the units still missing a translation", () => {const d = putCaptionTranslation(doc(), {language: "fr",label: "Français",assetId: "asset-1",- segments: { seg_1: "bonjour" },+ segments: { "u:seg_1": "bonjour" },});- const pending = untranslatedSegments(transcript(), getCaptionTranslations(d), "fr");- expect(pending.map((s) => s.id)).toEqual(["seg_2"]);+ const pending = untranslatedUnits(transcript(), getCaptionTranslations(d), "fr");+ expect(pending.map((u) => u.id)).toEqual(["u:seg_2"]);expect(translationCoverage(transcript(), getCaptionTranslations(d), "fr")).toEqual({translated: 1,total: 2,@@ -328,3 +329,117 @@ describe("caption translations", () => {expect(after.transcripts).toEqual(doc().transcripts);});});++// The bug this suite exists for: a Whisper transcript stores ONE SEGMENT PER+// WORD (see document/transcribe.ts). Translating and laying out per segment+// therefore translated word by word and put one word on screen at a time.+function wordPerSegmentTranscript(): AxcutTranscript {+ const tokens = ["Bienvenue", "dans", "OpenScreen", "le", "logiciel", "de", "capture"];+ const segments: AxcutTranscript["segments"] = [];+ const words: AxcutTranscript["words"] = [];+ let t = 0;+ tokens.forEach((text, i) => {+ const id = `seg_${i + 1}`;+ const wordId = `w_${i + 1}`;+ words.push({ id: wordId, segmentId: id, startSec: t, endSec: t + 0.4, text });+ segments.push({+ id,+ kind: "speech",+ startSec: t,+ endSec: t + 0.4,+ text,+ wordIds: [wordId],+ });+ t += 0.45;+ });+ return { assetId: "asset-1", language: "fr", segments, words };+}++function wordPerSegmentDoc(): AxcutDocument {+ return doc({ transcripts: [wordPerSegmentTranscript()] } as Partial<AxcutDocument>);+}++describe("captionTranslationUnits", () => {+ it("joins a word-per-segment transcript into phrase-sized units", () => {+ const units = captionTranslationUnits(wordPerSegmentTranscript());+ expect(units).toHaveLength(1);+ expect(units[0].text).toBe("Bienvenue dans OpenScreen le logiciel de capture");+ expect(units[0].segmentIds).toHaveLength(7);+ });++ it("starts a new unit after a real pause", () => {+ const t = wordPerSegmentTranscript();+ // Push the last two words out past the pause threshold.+ t.segments[5].startSec += 2;+ t.segments[5].endSec += 2;+ t.segments[6].startSec += 2;+ t.segments[6].endSec += 2;+ expect(captionTranslationUnits(t)).toHaveLength(2);+ });++ it("keys units so they cannot be confused with a bare segment id", () => {+ const units = captionTranslationUnits(wordPerSegmentTranscript());+ expect(units[0].id).toBe("u:seg_1");+ expect(units[0].id).not.toBe(units[0].segmentIds[0]);+ });+});++describe("translated caption layout", () => {+ const withTranslation = (text: string) => ({+ fr2: {+ language: "fr2",+ label: "Test",+ updatedAt: "",+ byAsset: { "asset-1": { "u:seg_1": text } },+ },+ });++ it("groups translated words into lines instead of one word per line", () => {+ const translations = withTranslation("Welcome to OpenScreen the screen capture app");+ const cues = deriveCaptionCues(+ wordPerSegmentDoc(),+ { ...ON, language: "fr2", minWordsPerLine: 2, maxWordsPerLine: 4 },+ translations,+ );++ expect(cues.length).toBeGreaterThan(0);+ for (const cue of cues) {+ expect(cue.text.split(" ").length).toBeGreaterThan(1);+ expect(cue.text.split(" ").length).toBeLessThanOrEqual(4);+ }+ expect(cues.map((c) => c.text).join(" ")).toBe("Welcome to OpenScreen the screen capture app");+ });++ it("lays the original out the same way, so switching language only swaps text", () => {+ const settings = { ...ON, minWordsPerLine: 2, maxWordsPerLine: 4 };+ const original = deriveCaptionCues(wordPerSegmentDoc(), settings, {});+ for (const cue of original) {+ expect(cue.text.split(" ").length).toBeGreaterThan(1);+ }+ const translated = deriveCaptionCues(+ wordPerSegmentDoc(),+ { ...settings, language: "fr2" },+ withTranslation("Welcome to OpenScreen the screen capture app"),+ );+ // Same word count in, same number of lines out.+ expect(translated).toHaveLength(original.length);+ });++ it("keeps translated cues inside the unit's own span", () => {+ const cues = deriveCaptionCues(+ wordPerSegmentDoc(),+ { ...ON, language: "fr2" },+ withTranslation("Welcome to OpenScreen the screen capture app"),+ );+ const unit = captionTranslationUnits(wordPerSegmentTranscript())[0];+ expect(cues[0].startMs).toBeGreaterThanOrEqual(Math.round(unit.startSec * 1000));+ expect(cues.at(-1)?.endMs).toBeLessThanOrEqual(Math.round(unit.endSec * 1000) + 1);+ });++ it("falls back to the original words for a unit with no translation", () => {+ const cues = deriveCaptionCues(wordPerSegmentDoc(), { ...ON, language: "nope" }, {});+ expect(cues.map((c) => c.text).join(" ")).toBe(+ "Bienvenue dans OpenScreen le logiciel de capture",+ );+ });+});diff --git a/src/lib/ai-edition/captions/cues.ts b/src/lib/ai-edition/captions/cues.tsindex d3ba7401b..d69515499 100644--- a/src/lib/ai-edition/captions/cues.ts+++ b/src/lib/ai-edition/captions/cues.ts@@ -24,7 +24,7 @@ import {import type { CaptionSegment } from "@/lib/captioning/transcribe";import type { AxcutClip, AxcutDocument, AxcutTranscript } from "../schema";import { type CaptionSettings, captionBackgroundCss, captionBandRect } from "./settings";-import type { CaptionTranslations } from "./translations";+import { type CaptionTranslations, captionTranslationUnits } from "./translations";/** One on-screen caption line, in whichever time base the producer documented. */export interface CaptionCue {@@ -57,17 +57,34 @@ function segmentWordsAsCaptionSegments(.map((w) => ({ startSec: w.startSec, endSec: w.endSec, text: w.text }));}+/**+ * Spread a piece of text across a span as one entry per word, timed by character+ * weight. This is how translated text gets timings: a translation has its own+ * word count and word order, so the source's per-word timestamps cannot carry+ * over — but the span it was spoken in can, and does.+ */+function textAsPseudoWords(startSec: number, endSec: number, text: string): CaptionSegment[] {+ const trimmed = text.trim();+ if (!trimmed) return [];+ return splitMergedCaptionsByWordBounds([{ startSec, endSec, text: trimmed }], 1, 1);+}+/*** One asset's caption lines in SOURCE seconds.*- * Original language: grouped straight from the word timestamps, so a line- * starts and ends on real speech.+ * Both languages go through the SAME final step — a stream of timed single words+ * fed to `groupTimedCaptionWordsIntoLines`. That is the whole point: line layout+ * (words per line, breaking on real pauses) must not depend on which language is+ * showing. Only where the words come from differs:+ *+ * - original: the transcript's own word timestamps.+ * - translated: each translation unit's text spread across the unit's span,+ * falling back to the original words for units not translated+ * yet, so a partial translation still plays.*- * Translated language: the translated text replaces the segment's text and is- * spread across *the segment's own span* by character weight — a translation- * has a different word count and word order, so per-word timings cannot carry- * over, but the segment boundary can and does. Segments with no translation yet- * fall back to their original words, so a partial translation still plays.+ * Grouping into units before translating also matters upstream: a Whisper+ * transcript stores one segment per word, so translating per segment would have+ * translated word by word.*/export function captionLinesForAsset(transcript: AxcutTranscript,@@ -84,52 +101,42 @@ export function captionLinesForAsset(const polish = (lines: CaptionSegment[]) =>finalizeCaptionSegmentsForPlayback(dedupeAdjacentCaptionRepeats(lines));- if (settings.language === null) {- const words = toCaptionSegments(transcript);- if (words.length > 0) {- return polish(groupTimedCaptionWordsIntoLines(words, minWords, maxWords));- }- // A transcript with segments but no words (hand-authored / imported) still- // deserves captions — split each segment span proportionally instead.- return polish(- splitMergedCaptionsByWordBounds(- transcript.segments- .filter((s) => s.text.trim())- .map((s) => ({ startSec: s.startSec, endSec: s.endSec, text: s.text })),- minWords,- maxWords,- ),- );- }+ const stream =+ settings.language === null+ ? originalWordStream(transcript)+ : translatedWordStream(transcript, translations, settings.language);++ if (stream.length === 0) return [];+ return polish(groupTimedCaptionWordsIntoLines(stream, minWords, maxWords));+}++function originalWordStream(transcript: AxcutTranscript): CaptionSegment[] {+ const words = toCaptionSegments(transcript);+ if (words.length > 0) return words;+ // A transcript with segments but no words (hand-authored / imported) still+ // deserves captions — spread each segment's own text across its span.+ return transcript.segments.flatMap((s) => textAsPseudoWords(s.startSec, s.endSec, s.text));+}- const translated = translations[settings.language]?.byAsset[transcript.assetId] ?? {};- const out: CaptionSegment[] = [];- for (const segment of transcript.segments) {- const replacement = translated[segment.id];+function translatedWordStream(+ transcript: AxcutTranscript,+ translations: CaptionTranslations,+ language: string,+): CaptionSegment[] {+ const translated = translations[language]?.byAsset[transcript.assetId] ?? {};+ return captionTranslationUnits(transcript).flatMap((unit) => {+ const replacement = translated[unit.id];if (typeof replacement === "string" && replacement.trim()) {- out.push(- ...splitMergedCaptionsByWordBounds(- [{ startSec: segment.startSec, endSec: segment.endSec, text: replacement.trim() }],- minWords,- maxWords,- ),- );- continue;- }- const words = segmentWordsAsCaptionSegments(transcript, segment.id);- if (words.length > 0) {- out.push(...groupTimedCaptionWordsIntoLines(words, minWords, maxWords));- } else if (segment.text.trim()) {- out.push(- ...splitMergedCaptionsByWordBounds(- [{ startSec: segment.startSec, endSec: segment.endSec, text: segment.text }],- minWords,- maxWords,- ),- );+ return textAsPseudoWords(unit.startSec, unit.endSec, replacement);}- }- return polish(out);+ // Not translated yet — keep the original words, with their real timings.+ const originals = unit.segmentIds.flatMap((id) =>+ segmentWordsAsCaptionSegments(transcript, id),+ );+ return originals.length > 0+ ? originals+ : textAsPseudoWords(unit.startSec, unit.endSec, unit.text);+ });}/**diff --git a/src/lib/ai-edition/captions/index.ts b/src/lib/ai-edition/captions/index.tsindex ad26aeac0..648602f39 100644--- a/src/lib/ai-edition/captions/index.ts+++ b/src/lib/ai-edition/captions/index.ts@@ -21,11 +21,16 @@ export {getCaptionSettings,patchCaptionSettings,} from "./settings";-export type { CaptionTranslation, CaptionTranslations } from "./translations";+export type {+ CaptionTranslation,+ CaptionTranslations,+ CaptionTranslationUnit,+} from "./translations";export {+ captionTranslationUnits,getCaptionTranslations,putCaptionTranslation,removeCaptionTranslation,translationCoverage,- untranslatedSegments,+ untranslatedUnits,} from "./translations";diff --git a/src/lib/ai-edition/captions/settings.ts b/src/lib/ai-edition/captions/settings.tsindex 08739d3e8..1efe599c2 100644--- a/src/lib/ai-edition/captions/settings.ts+++ b/src/lib/ai-edition/captions/settings.ts@@ -26,8 +26,9 @@ export interface CaptionSettings {* layer (see `translations.ts`) — the transcript is never rewritten.*/language: string | null;- /** Pixels, in preview-space — same convention as `AnnotationTextStyle.fontSize`- * (the exporter rescales it by previewWidth → outputWidth). */+ /** Pixels at a 1080-high frame, the same convention as `AnnotationTextStyle.fontSize`+ * — both the preview overlay and the compositor scale it by the height of the box+ * they draw into (see `annotationScale.ts`), so it is resolution-free. */fontSize: number;fontFamily: string;fontWeight: "normal" | "bold";@@ -53,7 +54,7 @@ export interface CaptionSettings {export const DEFAULT_CAPTION_SETTINGS: CaptionSettings = {enabled: false,language: null,- fontSize: 26,+ fontSize: 48,fontFamily: "Inter",fontWeight: "bold",color: "#ffffff",@@ -131,7 +132,7 @@ export function getCaptionSettings(doc: AxcutDocument | null | undefined): Capti// `null` is a meaningful value here ("show the original"), so an explicit// null must survive; only a missing/garbage entry falls back to the default.language: raw.language === null || typeof raw.language === "string" ? raw.language : d.language,- fontSize: readNumber(raw.fontSize, d.fontSize, 8, 200),+ fontSize: readNumber(raw.fontSize, d.fontSize, 12, 200),fontFamily: readString(raw.fontFamily, d.fontFamily),fontWeight: readEnum(raw.fontWeight, ["normal", "bold"] as const, d.fontWeight),color: readString(raw.color, d.color),diff --git a/src/lib/ai-edition/captions/translations.ts b/src/lib/ai-edition/captions/translations.tsindex e51569ccc..07abd1efb 100644--- a/src/lib/ai-edition/captions/translations.ts+++ b/src/lib/ai-edition/captions/translations.ts@@ -133,19 +133,111 @@ export function removeCaptionTranslation(doc: AxcutDocument, language: string):}/**- * Segments of `transcript` that have no text yet in `language` — the work list- * for a (re)translation run, so an interrupted or extended translation only- * costs the missing pieces.+ * The unit of translation: a run of consecutive transcript segments that reads+ * as one phrase.+ *+ * This exists because a Whisper transcript with word timestamps stores **one+ * segment per word** (see `document/transcribe.ts`). Translating segment by+ * segment would therefore translate word by word — which produces nonsense in+ * any language whose word order or agreement differs from the source, and puts+ * exactly one word on screen at a time. Grouping first is what makes both the+ * translation and its line layout correct.*/-export function untranslatedSegments(+export interface CaptionTranslationUnit {+ /** Storage key. Derived from the first segment's id — stable across renders+ * and across settings changes, since it comes from the transcript alone. */+ id: string;+ segmentIds: string[];+ startSec: number;+ endSec: number;+ text: string;+}++/** A pause this long starts a new phrase even mid-sentence. */+const UNIT_BREAK_GAP_SEC = 0.6;+/** Hard cap so one unbroken monologue still gets translated in digestible parts. */+const UNIT_MAX_WORDS = 40;++/** Sentence-final punctuation, Latin + CJK, allowing trailing quotes/brackets. */+const SENTENCE_END = /[.!?…。!?](["'”’)\]]*)$/;++/**+ * Keys are prefixed so they can never collide with a bare segment id. An earlier+ * revision keyed translations per segment; without the prefix, one of those+ * word-sized translations would silently be read back as a whole phrase's text.+ */+function unitKey(firstSegmentId: string): string {+ return `u:${firstSegmentId}`;+}++/** Group a transcript into translation units, in time order. */+export function captionTranslationUnits(transcript: AxcutTranscript): CaptionTranslationUnit[] {+ const segments = [...transcript.segments]+ .filter((s) => s.text.trim())+ .sort((a, b) => a.startSec - b.startSec || a.endSec - b.endSec);++ const units: CaptionTranslationUnit[] = [];+ let current: CaptionTranslationUnit | null = null;+ let wordCount = 0;++ const flush = () => {+ if (current) units.push(current);+ current = null;+ wordCount = 0;+ };++ for (const segment of segments) {+ const text = segment.text.trim();+ if (!current) {+ current = {+ id: unitKey(segment.id),+ segmentIds: [segment.id],+ startSec: segment.startSec,+ endSec: segment.endSec,+ text,+ };+ wordCount = text.split(/\s+/).length;+ continue;+ }++ if (segment.startSec - current.endSec >= UNIT_BREAK_GAP_SEC) {+ flush();+ current = {+ id: unitKey(segment.id),+ segmentIds: [segment.id],+ startSec: segment.startSec,+ endSec: segment.endSec,+ text,+ };+ wordCount = text.split(/\s+/).length;+ continue;+ }++ current.segmentIds.push(segment.id);+ current.endSec = Math.max(current.endSec, segment.endSec);+ current.text = `${current.text} ${text}`;+ wordCount += text.split(/\s+/).length;++ if (SENTENCE_END.test(current.text) || wordCount >= UNIT_MAX_WORDS) flush();+ }+ flush();++ return units;+}++/**+ * Units of `transcript` that have no text yet in `language` — the work list for+ * a (re)translation run, so an interrupted or extended translation only costs+ * the missing pieces.+ */+export function untranslatedUnits(transcript: AxcutTranscript,translations: CaptionTranslations,language: string,-): AxcutTranscript["segments"] {+): CaptionTranslationUnit[] {const done = translations[language]?.byAsset[transcript.assetId] ?? {};- return transcript.segments.filter((segment) => {- if (!segment.text.trim()) return false;- const existing = done[segment.id];+ return captionTranslationUnits(transcript).filter((unit) => {+ const existing = done[unit.id];return typeof existing !== "string" || existing.trim().length === 0;});}@@ -156,9 +248,9 @@ export function translationCoverage(translations: CaptionTranslations,language: string,): { translated: number; total: number } {- const total = transcript.segments.filter((s) => s.text.trim()).length;+ const total = captionTranslationUnits(transcript).length;return {- translated: total - untranslatedSegments(transcript, translations, language).length,+ translated: total - untranslatedUnits(transcript, translations, language).length,total,};}diff --git a/src/native/sceneDescription.test.ts b/src/native/sceneDescription.test.tsindex f4d79537f..e723e79d2 100644--- a/src/native/sceneDescription.test.ts+++ b/src/native/sceneDescription.test.ts@@ -1420,3 +1420,71 @@ describe("buildSceneDescription.annotations", () => {expect(scene.annotations).toEqual([]);});});++// --- captions --------------------------------------------------------------++describe("buildSceneDescription.captions", () => {+ function docWithCaptions(enabled: boolean) {+ const doc = makeDoc({+ assets: [makeAsset({ id: "a1", originalPath: "/tmp/a1.mp4", durationSec: 30 })],+ clips: [+ makeClip({+ id: "c1",+ assetId: "a1",+ sourceStartSec: 0,+ sourceEndSec: 30,+ timelineStartSec: 0,+ timelineEndSec: 30,+ }),+ ],+ annotations: [],+ });+ return {+ ...doc,+ transcripts: [+ {+ assetId: "a1",+ language: "en",+ segments: [+ {+ id: "seg_1",+ kind: "speech" as const,+ startSec: 1,+ endSec: 3,+ text: "hello there friend",+ wordIds: ["w1", "w2", "w3"],+ },+ ],+ words: [+ { id: "w1", segmentId: "seg_1", startSec: 1, endSec: 1.6, text: "hello" },+ { id: "w2", segmentId: "seg_1", startSec: 1.6, endSec: 2.3, text: "there" },+ { id: "w3", segmentId: "seg_1", startSec: 2.3, endSec: 3, text: "friend" },+ ],+ },+ ],+ legacyEditor: {+ ...((doc.legacyEditor as Record<string, unknown> | null) ?? {}),+ captions: { enabled, fontSize: 48, minWordsPerLine: 2, maxWordsPerLine: 7 },+ },+ } as AxcutDocument;+ }++ it("sends captions to the compositor as text annotations", () => {+ // Without this the caption would show in the DOM overlay and be missing from the+ // composited pixels — the preview/render gap the annotation bridge exists to close.+ const scene = buildSceneDescription(docWithCaptions(true));+ expect(scene.annotations).toHaveLength(1);+ expect(scene.annotations[0]).toMatchObject({ kind: "text" });+ expect(scene.annotations[0].text?.content).toBe("hello there friend");+ });++ it("sends nothing while the caption layer is hidden", () => {+ expect(buildSceneDescription(docWithCaptions(false)).annotations).toHaveLength(0);+ });++ it("carries the caption font size as a fraction, like every annotation", () => {+ const scene = buildSceneDescription(docWithCaptions(true));+ // 48px authored against a 1080-high frame.+ expect(scene.annotations[0].text?.fontSizeRel).toBeCloseTo(48 / 1080, 6);+ });+});diff --git a/src/native/sceneDescription.ts b/src/native/sceneDescription.tsindex 59000e4c7..66b0cad35 100644--- a/src/native/sceneDescription.ts+++ b/src/native/sceneDescription.ts@@ -18,6 +18,12 @@import type { CameraFullscreenRegion, SpeedRegion } from "@/components/video-editor/types";import { DEFAULT_CROP_REGION, ZOOM_DEPTH_SCALES } from "@/components/video-editor/types";import { annotationFontSizeFraction } from "@/lib/ai-edition/annotationScale";+import {+ captionCuesToTextRegions,+ deriveCaptionCues,+ getCaptionSettings,+ getCaptionTranslations,+} from "@/lib/ai-edition/captions";import { createId } from "@/lib/ai-edition/document/ids";import { pickOutputDims } from "@/lib/ai-edition/document/outputFormat";import { resolvePlaybackSegments } from "@/lib/ai-edition/document/timeline";@@ -488,8 +494,22 @@ export function buildSceneDescription();// Same raw→source projection as the zoom regions above, for the same reason: annotations are// authored in RAW document time and the compositor matches each frame's SOURCE time.+ //+ // Captions join the annotations here rather than getting a bridge of their own: they are text+ // over the screen layer with the same geometry and the same time base, so the compositor+ // already knows how to draw them. Skipping this would have left them visible in the DOM+ // overlay and absent from the composited pixels — the exact preview/render gap the annotation+ // work above closed. They are derived on the fly and never stored (see lib/ai-edition/captions).+ const captionSettings = getCaptionSettings(document);+ const captionRegions = captionCuesToTextRegions(+ deriveCaptionCues(document, captionSettings, getCaptionTranslations(document)),+ captionSettings,+ );const projectedAnnotations = projectRegionsToSource(- document.annotations ?? [],+ [+ ...(document.annotations ?? []),+ ...(captionRegions as unknown as NonNullable<AxcutDocument["annotations"]>),+ ],visibleClips,document.timeline.clips,() => createId("ann"),