From 570b8dba50404b166cb172cfb849843034090c4d Mon Sep 17 00:00:00 2001 From: Maulik Date: Mon, 19 Oct 2026 12:01:37 +0530 Subject: [PATCH 01/11] feat: transcript cut planning, filler detection, and timeline track restoration --- apps/desktop-gpui/src/transcription.rs | 61 +- .../src/routes/editor/Timeline/index.tsx | 7 + .../src/routes/editor/TranscriptPage.tsx | 953 +++++++++-- apps/desktop/src/routes/editor/captions.ts | 64 +- .../src/routes/editor/filler-detection.ts | 58 + .../src/routes/editor/timeline-utils.ts | 97 +- .../src/routes/editor/transcript-cuts.test.ts | 1244 ++++++++++++++ .../src/routes/editor/transcript-cuts.ts | 1522 +++++++++++++++++ .../routes/editor/transcript-edits.test.ts | 49 +- .../src/routes/editor/transcript-edits.ts | 118 +- apps/desktop/src/utils/tauri.ts | 63 +- crates/project/src/caption_timing.rs | 111 +- crates/project/src/configuration.rs | 214 +++ crates/project/src/lib.rs | 5 +- crates/verify/tests/captions.rs | 6 + 15 files changed, 4253 insertions(+), 319 deletions(-) create mode 100644 apps/desktop/src/routes/editor/filler-detection.ts create mode 100644 apps/desktop/src/routes/editor/transcript-cuts.test.ts create mode 100644 apps/desktop/src/routes/editor/transcript-cuts.ts diff --git a/apps/desktop-gpui/src/transcription.rs b/apps/desktop-gpui/src/transcription.rs index bc7ad223b00..ca21f2ba0ce 100644 --- a/apps/desktop-gpui/src/transcription.rs +++ b/apps/desktop-gpui/src/transcription.rs @@ -18,7 +18,7 @@ //! bundle's per-segment mic/system audio to 16kHz mono WAV via ffmpeg, then //! run whisper-rs or parakeet-rs with word timestamps and chunk the words //! into caption segments. `apply_caption_result` is -//! `applyCaptionResultToProject` (`captions.ts:469-527`) plus the +//! `applyCaptionResultToProject` (`captions.ts:524-591`) plus the //! `deriveCaptionTrackSegments` projection (`captions.ts:323-366`) that the //! Tauri app runs in TypeScript. @@ -2182,9 +2182,10 @@ pub fn write_caption_edit_to_source( ); } -/// `applyCaptionResultToProject` (`captions.ts:469-527`): set the captions +/// `applyCaptionResultToProject` (`captions.ts:524-591`): set the captions /// block (enabled, preserving existing style settings), mark it source-timed, -/// and re-derive the rendered track through the current edit list. +/// keep the transcript editor's cuts cut, and re-derive the rendered track +/// through the current edit list. pub fn apply_caption_result( project: &mut ProjectConfiguration, segments: Vec, @@ -2225,19 +2226,19 @@ pub fn apply_caption_result( image_segments: Vec::new(), }); } + let captions = project.captions.get_or_insert_with(CaptionsData::default); + captions.segments = segments; + captions.settings = settings; + captions.source_timed = true; + cap_project::reconcile_transcript_cuts(captions); + let timeline = project .timeline .as_mut() .expect("timeline was just created"); timeline.caption_segments = - derive_caption_track_segments(&segments, timeline, recording_durations); - - project.captions = Some(CaptionsData { - segments, - settings, - source_timed: true, - }); + derive_caption_track_segments(&captions.segments, timeline, recording_durations); } /// `getCaptionGenerationErrorMessage` (`captions.ts:634-662`). @@ -2694,6 +2695,7 @@ mod tests { ..CaptionSettings::default() }, source_timed: false, + ..Default::default() }); apply_caption_result( @@ -2716,6 +2718,45 @@ mod tests { assert_eq!(track[0].text, "hello"); } + #[test] + fn apply_caption_result_keeps_transcript_cuts() { + let mut project: ProjectConfiguration = serde_json::from_value(serde_json::json!({ + "timeline": { + "segments": [ + { "recordingSegment": 0, "timescale": 1.0, "start": 0.0, "end": 1.6 }, + { "recordingSegment": 0, "timescale": 1.0, "start": 1.9, "end": 10.0 } + ], + "zoomSegments": [] + }, + "captions": { + "segments": [], + "settings": {}, + "transcriptCuts": [ + { "id": "cut", "kind": "word", "text": "um", "start": 1.6, "end": 1.9 } + ], + "transcriptRemoved": [{ "start": 1.6, "end": 1.9 }] + } + })) + .unwrap(); + + apply_caption_result( + &mut project, + vec![caption( + "segment-0-0", + 1.0, + 2.5, + &[("hello", 1.0, 1.4), ("um", 1.6, 1.9), ("world", 2.0, 2.5)], + )], + &[10.0], + 10.0, + ); + + let captions = project.captions.as_ref().unwrap(); + assert_eq!(captions.segments[0].text, "hello world"); + assert_eq!(captions.transcript_cuts.len(), 1); + assert_eq!(captions.transcript_removed.len(), 1); + } + #[test] fn apply_caption_result_synthesises_a_timeline_when_missing() { let mut project = ProjectConfiguration::default(); diff --git a/apps/desktop/src/routes/editor/Timeline/index.tsx b/apps/desktop/src/routes/editor/Timeline/index.tsx index 8e86f03b0cc..446f3c55e71 100644 --- a/apps/desktop/src/routes/editor/Timeline/index.tsx +++ b/apps/desktop/src/routes/editor/Timeline/index.tsx @@ -62,6 +62,7 @@ import { sortTrackSegments, trackInsertionIndex, } from "../timelineTracks"; +import { hideCaptionSpeech } from "../transcript-cuts"; import { formatTime } from "../utils"; import { type AudioSegmentDragState, AudioTrack } from "./AudioTrack"; import { type CaptionSegmentDragState, CaptionsTrack } from "./CaptionsTrack"; @@ -742,6 +743,12 @@ export function Timeline(props: { setProject( produce((project) => { if (project.captions) { + hideCaptionSpeech( + project.captions, + project.captions.segments.flatMap((segment) => + segment.words?.length ? segment.words : [segment], + ), + ); project.captions.segments = []; project.captions.settings = { ...defaultCaptionSettings, diff --git a/apps/desktop/src/routes/editor/TranscriptPage.tsx b/apps/desktop/src/routes/editor/TranscriptPage.tsx index 41ab6a8b7d9..0d61b5bcf39 100644 --- a/apps/desktop/src/routes/editor/TranscriptPage.tsx +++ b/apps/desktop/src/routes/editor/TranscriptPage.tsx @@ -7,14 +7,17 @@ import { createEffect, createMemo, createSignal, - For, + Index, + Match, on, Show, + Switch, } from "solid-js"; import { produce } from "solid-js/store"; +import { Portal } from "solid-js/web"; import toast from "solid-toast"; import { defaultCaptionSettings } from "~/store/captions"; -import { commands } from "~/utils/tauri"; +import { commands, type TranscriptCut } from "~/utils/tauri"; import { getCaptionTextFromWords, mapEditedTimeToSource, @@ -29,6 +32,23 @@ import { } from "./captions-export"; import { FPS, useEditorContext } from "./context"; import { routeEditorPlaybackIntent } from "./playback-intent-routing"; +import { + AUTO_CLEAN_SILENCE_THRESHOLD, + commitTranscriptCutEdit, + cutClaim, + cutPaddingLimits, + cutPaddingRoom, + fillerTokens, + flattenCaptionWords, + type PaddingRoom, + planAutoClean, + planPauseCut, + planWordCuts, + type SourceRange, + type TranscriptCutEdit, + type TranscriptItem, + transcriptPlanContext, +} from "./transcript-cuts"; import { deleteTranscriptWords, type FlatWord, @@ -43,11 +63,6 @@ function formatTimePrecise(secs: number) { return `${minutes}:${whole.toString().padStart(2, "0")}.${hundredths.toString().padStart(2, "0")}`; } -interface TranscriptSegmentGroup { - segmentIndex: number; - words: FlatWord[]; -} - const TEXT_SIZES = [ { label: "S", value: "text-xs leading-normal" }, { label: "M", value: "text-sm leading-normal" }, @@ -55,6 +70,13 @@ const TEXT_SIZES = [ { label: "XL", value: "text-lg leading-snug" }, ] as const; +const MIN_SILENCE_THRESHOLD = 0.5; +const MAX_SILENCE_THRESHOLD = 5; + +function plural(count: number, word: string) { + return `${count} ${word}${count === 1 ? "" : "s"}`; +} + export function TranscriptPanel() { const { editorState, @@ -74,6 +96,16 @@ export function TranscriptPanel() { const [textSizeIndex, setTextSizeIndex] = makePersisted(createSignal(1), { name: "editorTranscriptTextSize", }); + const [storedSilenceThreshold, setSilenceThreshold] = makePersisted( + createSignal(AUTO_CLEAN_SILENCE_THRESHOLD), + { name: "editorAutoCleanThreshold" }, + ); + const silenceThreshold = () => { + const value = storedSilenceThreshold(); + return Number.isFinite(value) + ? Math.min(MAX_SILENCE_THRESHOLD, Math.max(MIN_SILENCE_THRESHOLD, value)) + : AUTO_CLEAN_SILENCE_THRESHOLD; + }; const [exportingFormat, setExportingFormat] = createSignal(null); @@ -87,38 +119,50 @@ export function TranscriptPanel() { ), ); - const allWords = createMemo((): FlatWord[] => { - const segments = project.captions?.segments ?? []; - const result: FlatWord[] = []; - for (let segIdx = 0; segIdx < segments.length; segIdx++) { - const seg = segments[segIdx]; - const words = seg.words ?? []; - for (let wordIdx = 0; wordIdx < words.length; wordIdx++) { - const w = words[wordIdx]; - result.push({ - text: w.text, - start: w.start, - end: w.end, - segmentIndex: segIdx, - wordIndex: wordIdx, - }); - } - } - return result; - }); + const allWords = createMemo((): FlatWord[] => + flattenCaptionWords(project.captions?.segments ?? []), + ); - const segmentGroups = createMemo((): TranscriptSegmentGroup[] => { - const flatWords = allWords(); - return (project.captions?.segments ?? []).map((_segment, segmentIndex) => ({ - segmentIndex, - words: flatWords.filter((word) => word.segmentIndex === segmentIndex), - })); - }); + const transcript = createMemo(() => + transcriptPlanContext(project, recordingSegments(), allWords()), + ); + + const transcriptItems = () => transcript().items; + + const tokenCount = createMemo( + () => + transcriptItems().filter( + (item) => item.type === "word" || item.type === "cut-word", + ).length, + ); - const updateWordText = (flatIndex: number, rawText: string) => { - const target = allWords()[flatIndex]; - if (!target) return; + const fillers = createMemo(() => fillerTokens(transcriptItems())); + + const fillerCount = () => fillers().size; + + const longPauseCount = createMemo( + () => + transcriptItems().filter( + (item) => + item.type === "pause" && item.end - item.start >= silenceThreshold(), + ).length, + ); + const canAutoClean = () => fillerCount() > 0 || longPauseCount() > 0; + + const autoCleanSummary = () => { + const parts = [ + fillerCount() > 0 ? plural(fillerCount(), "filler word") : null, + longPauseCount() > 0 + ? `${plural(longPauseCount(), "pause")} over ${silenceThreshold().toFixed(1)}s` + : null, + ].filter(Boolean); + return parts.length > 0 + ? `Cuts ${parts.join(" and ")}` + : "Nothing to clean"; + }; + + const updateWordText = (target: FlatWord, rawText: string) => { const tokens = rawText .trim() .split(/\s+/) @@ -127,15 +171,18 @@ export function TranscriptPanel() { setProject( produce((p) => { + if (tokens.length === 0) { + deleteTranscriptWords(p, [target]); + return; + } + const segment = p.captions?.segments?.[target.segmentIndex]; if (!segment?.words) return; const existing = segment.words[target.wordIndex]; if (!existing) return; - if (tokens.length === 0) { - segment.words.splice(target.wordIndex, 1); - } else if (tokens.length === 1) { + if (tokens.length === 1) { existing.text = tokens[0]; } else { const start = existing.start; @@ -149,13 +196,9 @@ export function TranscriptPanel() { segment.words.splice(target.wordIndex, 1, ...replacements); } - if (segment.words.length === 0) { - p.captions?.segments.splice(target.segmentIndex, 1); - } else { - segment.text = getCaptionTextFromWords(segment.words); - segment.start = segment.words[0].start; - segment.end = segment.words[segment.words.length - 1].end; - } + segment.text = getCaptionTextFromWords(segment.words); + segment.start = segment.words[0].start; + segment.end = segment.words[segment.words.length - 1].end; }), ); setEditorState("captions", "isStale", false); @@ -250,12 +293,9 @@ export function TranscriptPanel() { } }; - const activeWordIndex = createMemo(() => { - const words = allWords(); - if (words.length === 0) return -1; - - const sourceTime = mapEditedTimeToSource( - editorState.playbackTime, + const outputToSource = (outputTime: number) => + mapEditedTimeToSource( + outputTime, project.timeline?.segments ?? [], recordingSegments(), project.timeline?.transitions ?? [], @@ -263,7 +303,22 @@ export function TranscriptPanel() { "incoming", project.timeline?.textSegments, ); - if (sourceTime === null) return -1; + + const sourceToOutput = (sourceTime: number) => + mapSourceTimeToEdited( + sourceTime, + project.timeline?.segments ?? [], + recordingSegments(), + project.timeline?.transitions ?? [], + project.timeline?.textSegments, + ); + + const activeWord = createMemo(() => { + const words = allWords(); + if (words.length === 0) return null; + + const sourceTime = outputToSource(editorState.playbackTime); + if (sourceTime === null) return null; let lo = 0; let hi = words.length - 1; @@ -274,22 +329,14 @@ export function TranscriptPanel() { } else if (sourceTime < words[mid].start) { hi = mid - 1; } else { - return mid; + return words[mid]; } } - return -1; + return null; }); - const handleWordClick = async (word: FlatWord) => { + const seekToOutputTime = async (outputTime: number) => { try { - const outputTime = mapSourceTimeToEdited( - word.start, - project.timeline?.segments ?? [], - recordingSegments(), - project.timeline?.transitions ?? [], - project.timeline?.textSegments, - ); - if (outputTime === null) return; const accepted = await routeEditorPlaybackIntent( requestHandoffPlayback, { playing: false, seconds: outputTime }, @@ -319,45 +366,121 @@ export function TranscriptPanel() { } }; - const applyWordDeletions = ( - flatIndices: number[], - mode: "captions" | "video" = "captions", + const seekToItem = (item: TranscriptItem) => { + let outputTime: number | null = null; + if (item.type === "word") { + outputTime = sourceToOutput(item.word.start); + } else if (item.type === "cut-word" || item.type === "cut-pause") { + const claim = cutClaim(item.cut); + outputTime = + (claim && (sourceToOutput(claim.end) ?? sourceToOutput(claim.start))) ?? + null; + } + if (outputTime !== null) void seekToOutputTime(outputTime); + }; + + const keepPlayheadOnContent = (sourceTime: number | null) => { + if (editorState.playing) return; + const total = totalDuration(); + const mapped = sourceTime === null ? null : sourceToOutput(sourceTime); + const target = Math.min( + mapped ?? editorState.playbackTime, + Math.max(total - 0.01, 0), + ); + if (Math.abs(target - editorState.playbackTime) > 1 / FPS) { + void seekToOutputTime(target); + } + }; + + const commitCutEdit = ( + edit: TranscriptCutEdit | null, + action: "cut" | "restore" | "adjust", ) => { - const words = allWords(); - const wordsToDelete = [...new Set(flatIndices)] - .map((idx) => words[idx]) - .filter((word): word is FlatWord => !!word); - const outcome: { result: ReturnType } = { - result: "empty", + if (!edit) return false; + const playheadSource = editorState.playing + ? null + : outputToSource(editorState.playbackTime); + const outcome = { + result: "empty" as ReturnType, }; setProject( produce((p) => { - outcome.result = deleteTranscriptWords( - p, - wordsToDelete, - recordingSegments(), - mode, - ); + outcome.result = commitTranscriptCutEdit(p, edit, recordingSegments()); }), ); + if (outcome.result === "transition") { toast.error( - "Remove the nearby transition before cutting this transcript range.", + action === "restore" + ? "Remove the nearby transition before restoring this transcript range." + : "Remove the nearby transition before cutting this transcript range.", ); - return; + return false; } - if (outcome.result !== "deleted") return; - if ( - mode === "video" || - editorState.timeline.selection?.type === "caption" - ) { + if (outcome.result === "failed") { + toast.error("That cut would remove the whole video."); + return false; + } + if (outcome.result !== "applied") return false; + + batch(() => { + setEditorState("styleEditIndex", null); + setEditorState("timeline", "selection", null); + setEditorState("captions", "isStale", false); + }); + keepPlayheadOnContent(playheadSource); + return true; + }; + + const deleteWordsFromCaptions = (words: FlatWord[]) => { + if (words.length === 0) return; + setProject( + produce((p) => { + deleteTranscriptWords(p, words); + }), + ); + if (editorState.timeline.selection?.type === "caption") { setEditorState("styleEditIndex", null); setEditorState("timeline", "selection", null); } setEditorState("captions", "isStale", false); - if (mode === "video" && editorState.playbackTime > totalDuration()) { - setEditorState("playbackTime", Math.max(totalDuration() - 0.01, 0)); + }; + + const cutTokens = (tokens: number[]) => + commitCutEdit(planWordCuts(transcript(), tokens), "cut"); + + const restoreCuts = (ids: string[]) => + commitCutEdit(ids.length > 0 ? { restore: ids } : null, "restore"); + + const cutPause = (pause: SourceRange) => + commitCutEdit(planPauseCut(transcript(), pause), "cut"); + + const adjustCutPadding = ( + cut: TranscriptCut, + bufferStart: number, + bufferEnd: number, + ) => + commitCutEdit( + { padding: [{ id: cut.id, bufferStart, bufferEnd }] }, + "adjust", + ); + + const autoClean = () => { + const { edit, skipped } = planAutoClean(transcript(), silenceThreshold()); + if (!edit) { + if (skipped > 0) + toast.error( + "Everything Auto Clean found sits next to a clip transition.", + ); + return false; + } + const applied = commitCutEdit(edit, "cut"); + if (applied && skipped > 0) { + toast( + `Left ${plural(skipped, "cut")} next to clip transitions untouched.`, + ); } + return applied; }; const isAtEnd = () => { @@ -424,11 +547,89 @@ export function TranscriptPanel() { handlePlayPause(); }); + const [autoCleanOpen, setAutoCleanOpen] = createSignal(false); + let autoCleanRef: HTMLDivElement | undefined; + + createEventListener(document, "mousedown", (e) => { + if ( + autoCleanOpen() && + autoCleanRef && + !autoCleanRef.contains(e.target as Node) + ) { + setAutoCleanOpen(false); + } + }); + + createEventListener(window, "keydown", (e) => { + if (autoCleanOpen() && e.key === "Escape") setAutoCleanOpen(false); + }); + return (
-
+
Captions -
+
+
+
+ + +
+ +
+
+ Cut pauses longer than + + {silenceThreshold().toFixed(1)}s + +
+ + setSilenceThreshold( + Number.parseFloat(e.currentTarget.value), + ) + } + class="mt-2 w-full h-1 accent-blue-9" + /> +

+ {autoCleanSummary()}. Filler words are cut with the silence + around them. +

+ +
+
+
0 || tokenCount() > 0 + } + tokenCount={tokenCount()} + fillers={fillers()} + activeWord={activeWord()} textSizeClass={ TEXT_SIZES[textSizeIndex()]?.value ?? TEXT_SIZES[1].value } - onWordClick={handleWordClick} - onDeleteWords={applyWordDeletions} - onCutWords={(indices) => applyWordDeletions(indices, "video")} + onSeek={seekToItem} + onDeleteWords={deleteWordsFromCaptions} + onCutTokens={cutTokens} + onRestoreCuts={restoreCuts} + onCutPause={cutPause} + onAdjustCut={adjustCutPadding} + paddingRoom={(cut) => cutPaddingRoom(project.captions, cut)} onEditWord={updateWordText} onAddCaption={addCaptionAtPlayhead} /> @@ -503,9 +712,9 @@ function TranscriptWord(props: { isActive: boolean; isSelected: boolean; isEditing: boolean; + isFiller: boolean; selectedCount: number; textSizeClass: string; - ref: (el: HTMLSpanElement) => void; onClick: (e: MouseEvent) => void; onStartEdit: () => void; onCommitEdit: (text: string) => void; @@ -552,9 +761,10 @@ function TranscriptWord(props: { when={props.isEditing} fallback={ {formatTimePrecise(props.word.start)} + + Filler + + + + + + ); +} + +function PauseBadge(props: { + duration: number; + cut: boolean; + onToggle: () => void; + onAdjust?: (e: MouseEvent) => void; +}) { + return ( + { + if (!props.onAdjust) return; + e.preventDefault(); + props.onAdjust(e); + }} + > + + {props.duration.toFixed(1)}s + + + ); +} + +function CutPaddingPopover(props: { + cut: TranscriptCut; + room: PaddingRoom; + position: { x: number; y: number }; + onClose: () => void; + onChange: (bufferStart: number, bufferEnd: number) => boolean; + onRestore: () => void; +}) { + const [start, setStart] = createSignal(props.cut.bufferStart ?? 0); + const [end, setEnd] = createSignal(props.cut.bufferEnd ?? 0); + const room = createMemo(() => props.room); + const limits = () => + cutPaddingLimits( + { ...props.cut, bufferStart: start(), bufferEnd: end() }, + room(), + ); + let popoverRef: HTMLDivElement | undefined; + + createEffect( + on( + () => [props.cut.bufferStart ?? 0, props.cut.bufferEnd ?? 0] as const, + ([bufferStart, bufferEnd]) => { + setStart(bufferStart); + setEnd(bufferEnd); + }, + { defer: true }, + ), + ); + + createEventListener(document, "mousedown", (e) => { + if (popoverRef && !popoverRef.contains(e.target as Node)) props.onClose(); + }); + + const commit = (bufferStart: number, bufferEnd: number) => { + if (props.onChange(bufferStart, bufferEnd)) return; + setStart(props.cut.bufferStart ?? 0); + setEnd(props.cut.bufferEnd ?? 0); + }; + + const slider = ( + label: string, + value: () => number, + range: () => { min: number; max: number }, + stored: () => number, + set: (value: number) => void, + onCommit: (value: number) => void, + ) => { + const clampPadding = (input: number) => + Math.max(range().min, Number.isFinite(input) ? input : 0); + return ( +
+
+ {label} + + {value() >= 0 ? "+" : ""} + {value().toFixed(2)}s + +
+ + set(clampPadding(Number.parseFloat(e.currentTarget.value))) + } + onChange={(e) => + onCommit(clampPadding(Number.parseFloat(e.currentTarget.value))) + } + class="mt-1 w-full h-1 accent-blue-9" + /> +
+ ); + }; + + return ( +
e.stopPropagation()} + onKeyDown={(e) => { + e.stopPropagation(); + if (e.key === "Escape") props.onClose(); + }} + > +
+ + {props.cut.kind === "pause" ? "Pause cut" : `Cut "${props.cut.text}"`} + + +
+

+ Extend the cut to remove breaths, or shrink it to keep the start or end + of the sound. +

+
+ {slider( + "Before", + start, + () => limits().before, + () => props.cut.bufferStart ?? 0, + setStart, + (value) => commit(value, end()), + )} + {slider( + "After", + end, + () => limits().after, + () => props.cut.bufferEnd ?? 0, + setEnd, + (value) => commit(start(), value), + )} +
+ +
+ ); +} + +function itemOfType( + item: TranscriptItem, + type: T, +) { + return item.type === type + ? (item as Extract) + : undefined; +} + function TranscriptEditor(props: { - segmentGroups: TranscriptSegmentGroup[]; - allWords: FlatWord[]; - activeWordIndex: number; + items: readonly TranscriptItem[]; + hasContent: boolean; + tokenCount: number; + fillers: ReadonlySet; + activeWord: FlatWord | null; textSizeClass: string; - onWordClick: (word: FlatWord) => void; - onDeleteWords: (flatIndices: number[]) => void; - onCutWords: (flatIndices: number[]) => void; - onEditWord: (flatIndex: number, text: string) => void; + onSeek: (item: TranscriptItem) => void; + onDeleteWords: (words: FlatWord[]) => void; + onCutTokens: (tokens: number[]) => boolean; + onRestoreCuts: (ids: string[]) => boolean; + onCutPause: (pause: SourceRange) => boolean; + onAdjustCut: ( + cut: TranscriptCut, + bufferStart: number, + bufferEnd: number, + ) => boolean; + paddingRoom: (cut: TranscriptCut) => PaddingRoom; + onEditWord: (word: FlatWord, text: string) => void; onAddCaption: () => void; }) { const [selectedIndices, setSelectedIndices] = createSignal>( @@ -661,30 +1143,61 @@ function TranscriptEditor(props: { ); const [anchorIndex, setAnchorIndex] = createSignal(-1); const [editingIndex, setEditingIndex] = createSignal(-1); + const [padding, setPadding] = createSignal<{ + id: string; + position: { x: number; y: number }; + } | null>(null); let scrollContainerRef: HTMLDivElement | undefined; - let activeWordRef: HTMLSpanElement | undefined; - const flatIndexMap = createMemo(() => { - const map = new Map(); - for (let i = 0; i < props.allWords.length; i++) { - const w = props.allWords[i]; - map.set(`${w.segmentIndex}:${w.wordIndex}`, i); + const tokenItems = createMemo(() => + props.items.flatMap((item) => + item.type === "word" || item.type === "cut-word" ? [item] : [], + ), + ); + + const paddingCut = createMemo(() => { + const open = padding(); + if (!open) return null; + for (const item of props.items) { + if ( + (item.type === "cut-word" || item.type === "cut-pause") && + item.cut.id === open.id + ) + return item.cut; } - return map; + return null; }); - const flatIndexOf = (word: FlatWord) => - flatIndexMap().get(`${word.segmentIndex}:${word.wordIndex}`) ?? -1; + createEffect(() => { + if (padding() && !paddingCut()) setPadding(null); + }); const selectedCount = () => selectedIndices().size; + const clearSelection = () => { + setSelectedIndices(new Set()); + setAnchorIndex(-1); + }; + + createEffect( + on( + () => props.tokenCount, + () => { + clearSelection(); + setEditingIndex(-1); + }, + { defer: true }, + ), + ); + createEffect( on( - () => props.activeWordIndex, - (idx) => { - if (idx >= 0 && activeWordRef && scrollContainerRef) { + () => props.activeWord, + (word) => { + const el = + scrollContainerRef?.querySelector("[data-active-word]"); + if (word && el && scrollContainerRef) { const container = scrollContainerRef; - const el = activeWordRef; const containerRect = container.getBoundingClientRect(); const elRect = el.getBoundingClientRect(); @@ -702,6 +1215,30 @@ function TranscriptEditor(props: { ), ); + const selectedTokens = () => + [...selectedIndices()] + .sort((a, b) => a - b) + .flatMap((index) => { + const item = tokenItems()[index]; + return item ? [item] : []; + }); + + const removeSelection = (mode: "captions" | "video") => { + const tokens = selectedTokens(); + const live = tokens.flatMap((item) => (item.type === "word" ? [item] : [])); + if (live.length > 0) { + if (mode === "video") props.onCutTokens(live.map((item) => item.token)); + else props.onDeleteWords(live.map((item) => item.word)); + } else { + props.onRestoreCuts( + tokens.flatMap((item) => + item.type === "cut-word" ? [item.cut.id] : [], + ), + ); + } + clearSelection(); + }; + const handleKeyDown = (e: KeyboardEvent) => { if (editingIndex() !== -1) return; const selected = selectedIndices(); @@ -713,35 +1250,32 @@ function TranscriptEditor(props: { if (!fromContainer) scrollContainerRef?.focus({ preventScroll: true }); if (action === "edit") { - const word = props.allWords[[...selected][0]]; - if (word) startEditing(word); + const item = tokenItems()[[...selected][0]]; + if (item?.type === "word") startEditing(item.token); } else if (action === "delete" || action === "cut") { - if (action === "cut") props.onCutWords([...selected]); - else props.onDeleteWords([...selected]); - setSelectedIndices(new Set()); - setAnchorIndex(-1); + removeSelection(action === "cut" ? "video" : "captions"); } else { const target = action === "previous" ? Math.max(Math.min(...selected) - 1, 0) - : Math.min(Math.max(...selected) + 1, props.allWords.length - 1); + : Math.min(Math.max(...selected) + 1, tokenItems().length - 1); setSelectedIndices(new Set([target])); setAnchorIndex(target); - const word = props.allWords[target]; - if (word) props.onWordClick(word); + const item = tokenItems()[target]; + if (item) props.onSeek(item); } }; const handleContainerClick = (e: MouseEvent) => { - if (e.target === scrollContainerRef) { - setSelectedIndices(new Set()); - setAnchorIndex(-1); - } + if (e.target === scrollContainerRef) clearSelection(); }; - const handleWordSelect = (word: FlatWord, e: MouseEvent) => { + const handleTokenSelect = ( + item: TranscriptItem, + idx: number, + e: MouseEvent, + ) => { scrollContainerRef?.focus({ preventScroll: true }); - const idx = flatIndexOf(word); const isCtrlOrCmd = e.ctrlKey || e.metaKey; const isShift = e.shiftKey; @@ -781,21 +1315,29 @@ function TranscriptEditor(props: { setAnchorIndex(idx); } - props.onWordClick(word); + props.onSeek(item); }; - const handleWordRemoval = (word: FlatWord, mode: "captions" | "video") => { - const selected = selectedIndices(); - const indices = selected.size > 1 ? [...selected] : [flatIndexOf(word)]; - if (mode === "video") props.onCutWords(indices); - else props.onDeleteWords(indices); - setSelectedIndices(new Set()); - setAnchorIndex(-1); + const removeToken = (idx: number, mode: "captions" | "video") => { + if (!selectedIndices().has(idx) || selectedIndices().size <= 1) { + setSelectedIndices(new Set([idx])); + } + removeSelection(mode); scrollContainerRef?.focus({ preventScroll: true }); }; - const startEditing = (word: FlatWord) => { - const idx = flatIndexOf(word); + const restoreToken = (idx: number) => { + const tokens = selectedIndices().has(idx) + ? selectedTokens() + : tokenItems().filter((item) => item.token === idx); + props.onRestoreCuts( + tokens.flatMap((item) => (item.type === "cut-word" ? [item.cut.id] : [])), + ); + clearSelection(); + scrollContainerRef?.focus({ preventScroll: true }); + }; + + const startEditing = (idx: number) => { setSelectedIndices(new Set([idx])); setAnchorIndex(idx); setEditingIndex(idx); @@ -804,13 +1346,17 @@ function TranscriptEditor(props: { const commitEditing = (word: FlatWord, text: string) => { if (editingIndex() === -1) return; setEditingIndex(-1); - props.onEditWord(flatIndexOf(word), text); + props.onEditWord(word, text); }; const cancelEditing = () => { setEditingIndex(-1); }; + const openPadding = (cut: TranscriptCut, e: MouseEvent) => { + setPadding({ id: cut.id, position: { x: e.clientX, y: e.clientY } }); + }; + return (
0} + when={props.hasContent} fallback={
@@ -842,40 +1388,99 @@ function TranscriptEditor(props: {
- - {(group) => ( - - {(word) => { - const flatIdx = () => flatIndexOf(word); - const isActive = () => props.activeWordIndex === flatIdx(); - const isSelected = () => selectedIndices().has(flatIdx()); - const isEditing = () => editingIndex() === flatIdx(); - - return ( - + {(item) => ( + + + {(word) => { + const isActive = () => props.activeWord === word().word; + const isSelected = () => + selectedIndices().has(word().token); + const isEditing = () => editingIndex() === word().token; + return ( + + handleTokenSelect(word(), word().token, e) + } + onStartEdit={() => startEditing(word().token)} + onCommitEdit={(text: string) => + commitEditing(word().word, text) + } + onCancelEdit={cancelEditing} + onDelete={() => removeToken(word().token, "captions")} + onCut={() => removeToken(word().token, "video")} + /> + ); + }} + + + {(cut) => ( + { - if (isActive()) activeWordRef = el; - }} - onClick={(e: MouseEvent) => handleWordSelect(word, e)} - onStartEdit={() => startEditing(word)} - onCommitEdit={(text: string) => commitEditing(word, text)} - onCancelEdit={cancelEditing} - onDelete={() => handleWordRemoval(word, "captions")} - onCut={() => handleWordRemoval(word, "video")} + onClick={(e: MouseEvent) => + handleTokenSelect(cut(), cut().token, e) + } + onRestore={() => restoreToken(cut().token)} + onAdjust={(e: MouseEvent) => openPadding(cut().cut, e)} + /> + )} + + + {(pause) => ( + + props.onCutPause({ + start: pause().start, + end: pause().end, + }) + } /> - ); - }} - + )} + + + {(pause) => ( + props.onRestoreCuts([pause().cut.id])} + onAdjust={(e: MouseEvent) => openPadding(pause().cut, e)} + /> + )} + + )} - +
+ + {(cut) => ( + + setPadding(null)} + onChange={(bufferStart, bufferEnd) => + props.onAdjustCut(cut(), bufferStart, bufferEnd) + } + onRestore={() => { + if (props.onRestoreCuts([cut().id])) setPadding(null); + }} + /> + + )} +
); } diff --git a/apps/desktop/src/routes/editor/captions.ts b/apps/desktop/src/routes/editor/captions.ts index d3be3e084fc..e60db82147c 100644 --- a/apps/desktop/src/routes/editor/captions.ts +++ b/apps/desktop/src/routes/editor/captions.ts @@ -10,6 +10,8 @@ import { commands, type SegmentRecordings, type TimelineSegment, + type TranscriptCut, + type TranscriptRange, } from "~/utils/tauri"; import { type ClipTransition, clipTimelineOffsets } from "./clip-transitions"; import type { TextSegment } from "./text"; @@ -466,6 +468,59 @@ export function mapEditedTimeToSource( return fallback; } +// A fresh transcription covers the whole recording again, including words +// whose footage the transcript editor already cut. Those words go back to +// being cut words instead of reappearing as captions for footage that is gone. +function reconcileTranscriptCuts(captions: { + segments: CaptionSegment[]; + transcriptCuts?: TranscriptCut[]; + transcriptRemoved?: TranscriptRange[]; +}) { + const removed = captions.transcriptRemoved ?? []; + if (removed.length === 0) return; + const cuts = captions.transcriptCuts ?? []; + const added: TranscriptCut[] = []; + captions.segments = captions.segments.flatMap((segment) => { + const words = segment.words ?? []; + const kept = words.filter((word) => { + const midpoint = (word.start + word.end) / 2; + if ( + !removed.some((range) => midpoint > range.start && midpoint < range.end) + ) + return true; + const alreadyCut = [...cuts, ...added].some( + (cut) => + cut.kind === "word" && cut.start < word.end && word.start < cut.end, + ); + if (!alreadyCut) { + added.push({ + id: `cut-${Date.now()}-${Math.random().toString(36).slice(2)}`, + kind: "word", + text: word.text, + start: word.start, + end: word.end, + bufferStart: 0, + bufferEnd: 0, + segmentId: segment.id, + }); + } + return false; + }); + if (kept.length === words.length) return [segment]; + if (kept.length === 0) return []; + return [ + { + ...segment, + words: kept, + text: getCaptionTextFromWords(kept), + start: kept[0].start, + end: kept[kept.length - 1].end, + }, + ]; + }); + if (added.length > 0) captions.transcriptCuts = [...cuts, ...added]; +} + export function applyCaptionResultToProject< T extends { captions?: @@ -518,8 +573,15 @@ export function applyCaptionResultToProject< captions.segments = rawSegments; captions.sourceTimed = true; + reconcileTranscriptCuts( + captions as { + segments: CaptionSegment[]; + transcriptCuts?: TranscriptCut[]; + transcriptRemoved?: TranscriptRange[]; + }, + ); timeline.captionSegments = deriveCaptionTrackSegments( - rawSegments, + captions.segments, timeline.segments, recordingSegments, timeline.captionSegments ?? [], diff --git a/apps/desktop/src/routes/editor/filler-detection.ts b/apps/desktop/src/routes/editor/filler-detection.ts new file mode 100644 index 00000000000..adffc446eab --- /dev/null +++ b/apps/desktop/src/routes/editor/filler-detection.ts @@ -0,0 +1,58 @@ +import { MAX_CAPTION_WORD_DURATION } from "./captions"; + +const FILLER_WORDS = new Set([ + "uh", + "um", + "uhm", + "ah", + "er", + "erm", + "hm", + "mhm", +]); + +const ENGLISH_MARKERS = new Set([ + "the", + "and", + "you", + "that", + "it", + "this", + "with", + "what", + "have", + "are", + "think", + "know", + "just", + "yeah", + "yes", + "right", + "really", + "because", + "there", +]); + +export function isFillerWord(text: string): boolean { + const letters = text.toLowerCase().replace(/[^a-z]/g, ""); + return FILLER_WORDS.has(letters.replace(/(.)\1+/g, "$1")); +} + +// "um" is a Portuguese article and a German preposition, and "er" is German +// for "he" and Dutch for "there". Captions don't record their language, so +// the English fillers only count in transcripts that read as English. +export function readsAsEnglish(texts: readonly string[]): boolean { + let markers = 0; + for (const text of texts) { + if (ENGLISH_MARKERS.has(text.toLowerCase().replace(/[^a-z]/g, ""))) + markers++; + } + return markers > 0 && markers >= texts.length * 0.05; +} + +// Transcription engines often stretch a word's end across the silence that +// follows it. Capping a word at the caption track's longest spoken word lets +// that silence count as a pause without ever treating real speech as silence. +export function spokenWordEnd(word: { start: number; end: number }): number { + return Math.min(word.end, word.start + MAX_CAPTION_WORD_DURATION); +} diff --git a/apps/desktop/src/routes/editor/timeline-utils.ts b/apps/desktop/src/routes/editor/timeline-utils.ts index fdd616d13db..f34d115b076 100644 --- a/apps/desktop/src/routes/editor/timeline-utils.ts +++ b/apps/desktop/src/routes/editor/timeline-utils.ts @@ -5,10 +5,14 @@ import { clipTimelineDuration, clipTimelineOffsets, getClipTransition, + rippleTimelineTrack, transitionsAfterClipDelete, transitionsAfterClipSplit, } from "./clip-transitions"; -import { rippleDeleteKeyboardTrack } from "./keyboard-timing"; +import { + rippleDeleteKeyboardTrack, + rippleKeyboardTrack, +} from "./keyboard-timing"; import { CAMERA3D_TRACK_KEYS, type Camera3DTracks, @@ -476,6 +480,97 @@ export function rippleDeleteAllTracks( } } +function rippleInsertMaskTrack( + segments: RippleMaskSegment[], + boundary: number, + shift: number, +) { + for (const segment of segments) { + if (segment.start >= boundary) { + segment.start += shift; + segment.end += shift; + continue; + } + if (segment.end <= boundary) continue; + const local = boundary - segment.start; + segment.end += shift; + if (!segment.keyframes) continue; + const shiftAfter = ( + keyframes: T[] | undefined, + ) => + keyframes?.map((keyframe) => + keyframe.time >= local + ? { ...keyframe, time: keyframe.time + shift } + : keyframe, + ); + segment.keyframes.position = shiftAfter(segment.keyframes.position); + segment.keyframes.size = shiftAfter(segment.keyframes.size); + segment.keyframes.intensity = shiftAfter(segment.keyframes.intensity); + } +} + +function rippleInsertCamera3DTrack( + segments: RippleCamera3DSegment[], + boundary: number, + shift: number, +) { + for (const segment of segments) { + if (segment.start >= boundary) { + segment.start += shift; + segment.end += shift; + continue; + } + if (segment.end <= boundary) continue; + const local = boundary - segment.start; + segment.end += shift; + for (const trackKey of CAMERA3D_TRACK_KEYS) { + const keyframes = segment.tracks[trackKey]; + if (!keyframes?.length) continue; + segment.tracks[trackKey] = keyframes.map((keyframe) => + keyframe.time >= local + ? { ...keyframe, time: keyframe.time + shift } + : keyframe, + ); + } + } +} + +export function rippleInsertAllTracks( + timeline: { + styleSegments?: Array<{ start: number; end: number }> | null; + imageSegments?: Array<{ start: number; end: number }> | null; + zoomSegments?: Array<{ start: number; end: number }> | null; + sceneSegments?: Array<{ start: number; end: number }> | null; + maskSegments?: RippleMaskSegment[] | null; + textSegments?: Array<{ start: number; end: number }> | null; + captionSegments?: Array<{ start: number; end: number }> | null; + keyboardSegments?: KeyboardTrackSegment[] | null; + audioSegments?: Array<{ start: number; end: number }> | null; + camera3dSegments?: RippleCamera3DSegment[] | null; + }, + boundary: number, + shift: number, +) { + if (shift <= 0) return; + for (const track of [ + timeline.styleSegments, + timeline.imageSegments, + timeline.zoomSegments, + timeline.sceneSegments, + timeline.textSegments, + timeline.captionSegments, + timeline.audioSegments, + ]) { + if (track) rippleTimelineTrack(track, boundary, shift); + } + if (timeline.maskSegments) + rippleInsertMaskTrack(timeline.maskSegments, boundary, shift); + if (timeline.keyboardSegments) + rippleKeyboardTrack(timeline.keyboardSegments, boundary, shift); + if (timeline.camera3dSegments) + rippleInsertCamera3DTrack(timeline.camera3dSegments, boundary, shift); +} + export function deleteClipAndRippleAllTracks( timeline: Parameters[0], segmentIndex: number, diff --git a/apps/desktop/src/routes/editor/transcript-cuts.test.ts b/apps/desktop/src/routes/editor/transcript-cuts.test.ts new file mode 100644 index 00000000000..5922b1f46d2 --- /dev/null +++ b/apps/desktop/src/routes/editor/transcript-cuts.test.ts @@ -0,0 +1,1244 @@ +import { describe, expect, it } from "vitest"; +import { defaultCaptionSettings } from "~/store/captions"; +import type { + SegmentRecordings, + TimelineSegment, + TranscriptCut, +} from "~/utils/tauri"; +import { + applyCaptionResultToProject, + deriveCaptionTrackSegments, +} from "./captions"; +import { clipTimelineDuration } from "./clip-transitions"; +import type { EditorProjectConfiguration } from "./context"; +import { + isFillerWord, + readsAsEnglish, + spokenWordEnd, +} from "./filler-detection"; +import { defaultMaskSegment } from "./masks"; +import { defaultTextSegment } from "./text"; +import { + commitTranscriptCutEdit, + cutPaddingLimits, + cutPaddingRoom, + intersectSourceRanges, + mergeSourceRanges, + planAutoClean, + planPauseCut, + planWordCuts, + subtractSourceRanges, + type TranscriptItem, + transcriptPlanContext, +} from "./transcript-cuts"; +import { deleteTranscriptWords } from "./transcript-edits"; + +type Project = Pick; +type Timeline = NonNullable; + +const recordings = (...durations: number[]) => + durations.map((duration) => ({ display: { duration } }) as SegmentRecordings); + +const clip = ( + start: number, + end: number, + extra: Partial = {}, +): TimelineSegment => ({ + start, + end, + timescale: 1, + recordingSegment: 0, + ...extra, +}); + +function project( + words: Array<[string, number, number]>, + segments: TimelineSegment[], + tracks: Partial = {}, +): Project { + return { + captions: { + settings: { ...defaultCaptionSettings }, + sourceTimed: true, + segments: [ + { + id: "caption", + start: words[0][1], + end: words[words.length - 1][2], + text: words.map(([text]) => text).join(" "), + words: words.map(([text, start, end]) => ({ text, start, end })), + }, + ], + }, + timeline: { + segments, + transitions: [], + zoomSegments: [], + captionSegments: [], + keyboardSegments: [], + sceneSegments: [], + maskSegments: [], + textSegments: [], + styleSegments: [], + imageSegments: [], + camera3dSegments: [], + ...tracks, + }, + }; +} + +let nextId = 0; +const createId = () => `test-cut-${nextId++}`; + +function context(p: Project, recs: SegmentRecordings[]) { + return { ...transcriptPlanContext(p, recs), createId }; +} + +function token(items: readonly TranscriptItem[], text: string) { + const item = items.find( + (candidate) => + (candidate.type === "word" && candidate.word.text === text) || + (candidate.type === "cut-word" && candidate.cut.text === text), + ); + if (!item || (item.type !== "word" && item.type !== "cut-word")) + throw new Error(`No transcript token for ${text}`); + return item.token; +} + +function cut(p: Project, recs: SegmentRecordings[], ...texts: string[]) { + const ctx = context(p, recs); + const edit = planWordCuts( + ctx, + texts.map((text) => token(ctx.items, text)), + ); + if (!edit) throw new Error("Nothing to cut"); + return commitTranscriptCutEdit(p, edit, recs); +} + +function cutRecord(p: Project, text: string): TranscriptCut { + const record = p.captions?.transcriptCuts?.find((cut) => cut.text === text); + if (!record) throw new Error(`No cut for ${text}`); + return record; +} + +function liveWords(p: Project) { + return (p.captions?.segments ?? []).flatMap((segment) => + (segment.words ?? []).map((word) => word.text), + ); +} + +function clips(p: Project) { + return (p.timeline?.segments ?? []).map((segment) => [ + Number(segment.start.toFixed(6)), + Number(segment.end.toFixed(6)), + ]); +} + +const helloWorld: Array<[string, number, number]> = [ + ["hello", 1.0, 1.4], + ["um", 1.6, 1.9], + ["world", 2.0, 2.5], + ["again", 4.0, 4.4], +]; + +describe("source range arithmetic", () => { + it("merges, subtracts and intersects ranges", () => { + expect( + mergeSourceRanges([ + { start: 3, end: 4 }, + { start: 1, end: 2 }, + { start: 2, end: 2.5 }, + { start: 5, end: 5.00001 }, + ]), + ).toEqual([ + { start: 1, end: 2.5 }, + { start: 3, end: 4 }, + ]); + expect( + subtractSourceRanges( + [{ start: 0, end: 10 }], + [ + { start: 2, end: 3 }, + { start: 5, end: 6 }, + ], + ), + ).toEqual([ + { start: 0, end: 2 }, + { start: 3, end: 5 }, + { start: 6, end: 10 }, + ]); + expect( + intersectSourceRanges( + [ + { start: 0, end: 2 }, + { start: 4, end: 6 }, + ], + [{ start: 1, end: 5 }], + ), + ).toEqual([ + { start: 1, end: 2 }, + { start: 4, end: 5 }, + ]); + }); +}); + +describe("transcript word cuts", () => { + it("cuts a word out of the video and restores it exactly", () => { + const recs = recordings(10); + const p = project(helloWorld, [clip(0, 10)]); + + expect(cut(p, recs, "um")).toBe("applied"); + expect(clips(p)).toEqual([ + [0, 1.6], + [1.9, 10], + ]); + expect(liveWords(p)).toEqual(["hello", "world", "again"]); + expect(p.captions?.segments[0].text).toBe("hello world again"); + expect(p.captions?.transcriptCuts).toHaveLength(1); + const track = deriveCaptionTrackSegments( + p.captions?.segments ?? [], + p.timeline?.segments ?? [], + recs, + ); + expect( + track.flatMap((segment) => segment.words?.map((w) => w.text)), + ).toEqual(["hello", "world", "again"]); + + expect( + commitTranscriptCutEdit(p, { restore: [cutRecord(p, "um").id] }, recs), + ).toBe("applied"); + expect(clips(p)).toEqual([[0, 10]]); + expect(liveWords(p)).toEqual(["hello", "um", "world", "again"]); + expect(p.captions?.segments[0].text).toBe("hello um world again"); + expect(p.captions?.transcriptCuts).toEqual([]); + expect(p.captions?.transcriptRemoved).toEqual([]); + }); + + it("moves overlay tracks out with the cut and back on restore", () => { + const recs = recordings(10); + const p = project(helloWorld, [clip(0, 10)], { + zoomSegments: [ + { start: 0.5, end: 0.9, amount: 2, mode: "auto" }, + { start: 1.0, end: 3.0, amount: 2, mode: "auto" }, + { start: 5, end: 6, amount: 2, mode: "auto" }, + ], + keyboardSegments: [ + { + id: "keys", + start: 5, + end: 6, + displayText: "ab", + keys: [ + { key: "a", timeOffset: 0 }, + { key: "b", timeOffset: 500 }, + ], + }, + ], + maskSegments: [ + { + ...defaultMaskSegment(1.0, 4.0), + keyframes: { + position: [ + { time: 0.2, x: 0.1, y: 0.1 }, + { time: 2.5, x: 0.9, y: 0.9 }, + ], + size: [], + intensity: [], + }, + }, + ], + }); + const before = structuredClone(p.timeline); + + cut(p, recs, "um"); + expect( + p.timeline?.zoomSegments.map(({ start, end }) => [start, end]), + ).toEqual([ + [0.5, 0.9], + [1.0, expect.closeTo(2.7)], + [expect.closeTo(4.7), expect.closeTo(5.7)], + ]); + expect(p.timeline?.keyboardSegments?.[0].start).toBeCloseTo(4.7); + + commitTranscriptCutEdit(p, { restore: [cutRecord(p, "um").id] }, recs); + expect( + p.timeline?.zoomSegments.map(({ start, end }) => [start, end]), + ).toEqual( + before?.zoomSegments.map(({ start, end }) => [ + expect.closeTo(start), + expect.closeTo(end), + ]), + ); + expect(p.timeline?.keyboardSegments?.[0]).toMatchObject({ + start: expect.closeTo(5), + end: expect.closeTo(6), + keys: [ + { key: "a", timeOffset: expect.closeTo(0) }, + { key: "b", timeOffset: expect.closeTo(500) }, + ], + }); + expect(p.timeline?.maskSegments[0]).toMatchObject({ + start: 1.0, + end: expect.closeTo(4.0), + keyframes: { + position: [ + { time: expect.closeTo(0.2) }, + { time: expect.closeTo(2.5) }, + ], + }, + }); + }); + + it("round-trips overlays around a fullscreen text hold", () => { + const recs = recordings(10); + const hold = { + ...defaultTextSegment(5, 7), + layout: "fullscreen" as const, + }; + const p = project( + [ + ["um", 1.6, 1.9], + ["late", 6.0, 6.3], + ], + [clip(0, 10)], + { + textSegments: [hold], + zoomSegments: [{ start: 8.5, end: 9, amount: 2, mode: "auto" }], + }, + ); + + cut(p, recs, "um"); + cut(p, recs, "late"); + expect(clips(p)).toEqual([ + [0, 1.6], + [1.9, 6.0], + [6.3, 10], + ]); + expect(p.timeline?.textSegments[0]).toMatchObject({ + start: expect.closeTo(4.7), + end: expect.closeTo(6.7), + }); + expect(p.timeline?.zoomSegments[0]).toMatchObject({ + start: expect.closeTo(7.9), + end: expect.closeTo(8.4), + }); + + commitTranscriptCutEdit( + p, + { restore: p.captions?.transcriptCuts?.map((cut) => cut.id) }, + recs, + ); + expect(clips(p)).toEqual([[0, 10]]); + expect(p.timeline?.textSegments[0]).toMatchObject({ + start: expect.closeTo(5), + end: expect.closeTo(7), + }); + expect(p.timeline?.zoomSegments[0]).toMatchObject({ + start: expect.closeTo(8.5), + end: expect.closeTo(9), + }); + }); + + it("cuts the silence between consecutively cut words and restores words one at a time", () => { + const recs = recordings(10); + const p = project(helloWorld, [clip(0, 10)]); + + expect(cut(p, recs, "hello", "um", "world")).toBe("applied"); + expect(clips(p)).toEqual([ + [0, 1.0], + [2.5, 10], + ]); + expect(cutRecord(p, "um").bufferStart).toBeCloseTo(0.2); + expect(cutRecord(p, "world").bufferStart).toBeCloseTo(0.1); + + commitTranscriptCutEdit(p, { restore: [cutRecord(p, "um").id] }, recs); + expect(clips(p)).toEqual([ + [0, 1.0], + [1.4, 1.9], + [2.5, 10], + ]); + expect(liveWords(p)).toEqual(["um", "again"]); + }); + + it("also cuts a detected pause that sits between two cut words", () => { + const recs = recordings(10); + const p = project( + [ + ["a", 0.2, 0.5], + ["b", 1.5, 1.8], + ["c", 3.0, 3.3], + ], + [clip(0, 10)], + ); + + cut(p, recs, "a", "b"); + expect(clips(p)).toEqual([ + [0, 0.2], + [1.8, 10], + ]); + expect(p.captions?.transcriptCuts?.map((cut) => cut.kind).sort()).toEqual([ + "pause", + "word", + "word", + ]); + expect( + context(p, recs).items.map((item) => + item.type === "pause" ? [item.start, item.end] : item.type, + ), + ).toEqual(["cut-word", "cut-pause", "cut-word", [1.8, 3.0], "word"]); + }); + + it("leaves a pause alone when only one of its neighbours is cut now", () => { + const recs = recordings(40); + const p = project( + [ + ["show", 1.0, 1.3], + ["you", 1.4, 1.6], + ["okay", 31.6, 31.9], + ["done", 32.0, 32.3], + ], + [clip(0, 40)], + ); + cut(p, recs, "you"); + cut(p, recs, "okay"); + expect(clips(p)).toEqual([ + [0, 1.4], + [1.6, 31.6], + [31.9, 40], + ]); + expect(p.captions?.transcriptCuts?.map((cut) => cut.kind)).toEqual([ + "word", + "word", + ]); + }); + + it("refuses to cut across a clip transition without touching the project", () => { + const recs = recordings(10); + const p = project( + [ + ["tail", 4.6, 4.9], + ["head", 5.2, 5.5], + ], + [clip(0, 5), clip(5, 10)], + { transitions: [{ segmentIndex: 1, type: "cross-fade", duration: 1 }] }, + ); + const before = structuredClone(p); + + expect(cut(p, recs, "tail")).toBe("transition"); + expect(p).toEqual(before); + }); + + it("refuses to restore into a boundary that gained a transition", () => { + const recs = recordings(10); + const p = project(helloWorld, [clip(0, 10)]); + cut(p, recs, "um"); + p.timeline?.transitions.push({ + segmentIndex: 1, + type: "cross-fade", + duration: 0.5, + }); + const before = structuredClone(p); + + expect( + commitTranscriptCutEdit(p, { restore: [cutRecord(p, "um").id] }, recs), + ).toBe("transition"); + expect(p).toEqual(before); + }); + + it("fails without changes when a cut would empty the timeline", () => { + const recs = recordings(10); + const p = project( + [ + ["only", 1.0, 1.4], + ["words", 1.5, 2.5], + ], + [clip(1.0, 2.5)], + ); + const before = structuredClone(p); + + expect(cut(p, recs, "only", "words")).toBe("failed"); + expect(p).toEqual(before); + }); + + it("cuts a word that ends a clip in a later recording despite float drift", () => { + const recs = recordings(0.17, 1); + const offset = 0.17; + const p = project( + [ + ["first", 0.05, 0.15], + ["last", offset + 0.4, offset + 0.61], + ], + [clip(0, 0.17), clip(0.03, 0.61, { recordingSegment: 1 })], + ); + + expect(cut(p, recs, "last")).toBe("applied"); + expect(clips(p)).toEqual([ + [0, 0.17], + [0.03, 0.4], + ]); + commitTranscriptCutEdit(p, { restore: [cutRecord(p, "last").id] }, recs); + expect(clips(p)).toEqual([ + [0, 0.17], + [0.03, 0.61], + ]); + }); + + it("keeps clip settings by extending instead of merging differing clips", () => { + const recs = recordings(10); + const p = project(helloWorld, [clip(0, 10)]); + cut(p, recs, "um"); + const second = p.timeline?.segments[1]; + if (second) second.volume = 0.5; + + commitTranscriptCutEdit(p, { restore: [cutRecord(p, "um").id] }, recs); + expect(clips(p)).toEqual([ + [0, 1.9], + [1.9, 10], + ]); + expect(p.timeline?.segments[1].volume).toBe(0.5); + }); + + it("follows clip speed when cutting and restoring", () => { + const recs = recordings(10); + const p = project(helloWorld, [clip(0, 10, { timescale: 2 })]); + + cut(p, recs, "um"); + expect(clipTimelineDuration(p.timeline?.segments ?? [], [])).toBeCloseTo( + 4.85, + ); + commitTranscriptCutEdit(p, { restore: [cutRecord(p, "um").id] }, recs); + expect(clipTimelineDuration(p.timeline?.segments ?? [], [])).toBeCloseTo(5); + expect(clips(p)).toEqual([[0, 10]]); + }); + + it("keeps caption-only deletes out of the cut list", () => { + const recs = recordings(10); + const p = project(helloWorld, [clip(0, 10)]); + + expect(cut(p, recs, "um")).toBe("applied"); + expect(cutRecord(p, "um")).toMatchObject({ kind: "word", start: 1.6 }); + expect( + deleteTranscriptWords(p, [ + { text: "world", start: 2.0, end: 2.5, segmentIndex: 0, wordIndex: 1 }, + ]), + ).toBe("deleted"); + expect(p.captions?.transcriptCuts).toHaveLength(1); + expect(p.captions?.transcriptHidden).toEqual([{ start: 2.0, end: 2.5 }]); + }); +}); + +describe("transcript cut padding", () => { + it("grows and shrinks a cut while overlapping cuts keep their footage", () => { + const recs = recordings(10); + const p = project(helloWorld, [clip(0, 10)]); + const pad = (text: string, bufferStart: number, bufferEnd: number) => + commitTranscriptCutEdit( + p, + { padding: [{ id: cutRecord(p, text).id, bufferStart, bufferEnd }] }, + recs, + ); + cut(p, recs, "um"); + + expect(pad("um", 0, 0.05)).toBe("applied"); + expect(clips(p)).toEqual([ + [0, 1.6], + [1.95, 10], + ]); + pad("um", -0.1, 0); + expect(clips(p)).toEqual([ + [0, 1.7], + [1.9, 10], + ]); + pad("um", 0, 0); + + cut(p, recs, "hello"); + expect(cutRecord(p, "hello").bufferEnd).toBeCloseTo(0.2); + expect(clips(p)).toEqual([ + [0, 1.0], + [1.9, 10], + ]); + expect(pad("hello", 0, 0.3)).toBe("applied"); + expect(clips(p)).toEqual([ + [0, 1.0], + [1.9, 10], + ]); + pad("hello", 0, 0); + expect(clips(p)).toEqual([ + [0, 1.0], + [1.4, 1.6], + [1.9, 10], + ]); + }); + + it("keeps at least half the cut when both sides shrink", () => { + expect(cutPaddingLimits({ start: 1.6, end: 1.9 })).toEqual({ + before: { min: -0.15, max: 1 }, + after: { min: -0.15, max: 1 }, + }); + expect( + cutPaddingLimits({ start: 1.6, end: 1.9, bufferStart: -0.15 }).after.min, + ).toBeCloseTo(0); + expect( + cutPaddingLimits({ start: 1, end: 3, bufferEnd: -0.5 }).before.min, + ).toBe(-0.5); + + const recs = recordings(10); + const p = project(helloWorld, [clip(0, 10)]); + cut(p, recs, "um"); + const id = cutRecord(p, "um").id; + commitTranscriptCutEdit( + p, + { padding: [{ id, bufferStart: -0.15, bufferEnd: -0.15 }] }, + recs, + ); + const claim = (p.timeline?.segments ?? []).map((segment) => segment.end); + expect(cutRecord(p, "um").bufferStart).toBeCloseTo(0); + expect(cutRecord(p, "um").bufferEnd).toBeCloseTo(-0.15); + expect(claim[0]).toBeCloseTo(1.6); + }); + + it("stops padding at the neighbouring words", () => { + const recs = recordings(10); + const p = project(helloWorld, [clip(0, 10)]); + cut(p, recs, "um"); + const record = cutRecord(p, "um"); + expect(cutPaddingRoom(p.captions, record)).toEqual({ + before: expect.closeTo(0.2), + after: expect.closeTo(0.1), + }); + + commitTranscriptCutEdit( + p, + { padding: [{ id: record.id, bufferStart: 0, bufferEnd: 0.6 }] }, + recs, + ); + expect(cutRecord(p, "um").bufferEnd).toBeCloseTo(0.1); + expect(clips(p)).toEqual([ + [0, 1.6], + [2.0, 10], + ]); + expect(liveWords(p)).toEqual(["hello", "world", "again"]); + }); +}); + +describe("transcript pauses", () => { + it("lists pauses between words and never restores footage it did not cut", () => { + const recs = recordings(10); + const p = project( + [ + ["first", 3.5, 3.9], + ["next", 4.0, 4.3], + ], + [clip(2, 10)], + ); + const ctx = context(p, recs); + const pause = ctx.items.find((item) => item.type === "pause"); + expect(pause).toEqual({ type: "pause", start: 2, end: 3.5 }); + if (pause?.type !== "pause") return; + + expect(commitTranscriptCutEdit(p, planPauseCut(ctx, pause), recs)).toBe( + "applied", + ); + expect(clips(p)).toEqual([[3.5, 10]]); + const record = p.captions?.transcriptCuts?.[0]; + commitTranscriptCutEdit(p, { restore: [record?.id ?? ""] }, recs); + expect(clips(p)).toEqual([[2, 10]]); + }); + + it("treats a stretched word end as silence without duplicating the caption", () => { + const recs = recordings(10); + const p = project( + [ + ["so", 1.0, 5.0], + ["next", 5.05, 5.4], + ], + [clip(0, 10)], + ); + const ctx = context(p, recs); + const pause = ctx.items.find( + (item) => item.type === "pause" && item.start > 1, + ); + expect(pause).toEqual({ type: "pause", start: 3.5, end: 5.05 }); + if (pause?.type !== "pause") return; + + commitTranscriptCutEdit(p, planPauseCut(ctx, pause), recs); + expect(p.captions?.segments[0].words?.[0]).toMatchObject({ + text: "so", + end: 3.5, + }); + const record = p.captions?.transcriptCuts?.[0]; + commitTranscriptCutEdit( + p, + { padding: [{ id: record?.id ?? "", bufferStart: 0, bufferEnd: -0.3 }] }, + recs, + ); + expect(clips(p)).toEqual([ + [0, 3.5], + [4.75, 10], + ]); + const track = deriveCaptionTrackSegments( + p.captions?.segments ?? [], + p.timeline?.segments ?? [], + recs, + ); + expect( + track.flatMap((segment) => segment.words ?? []).map((word) => word.text), + ).toEqual(["so", "next"]); + }); +}); + +describe("speech kept out of the captions", () => { + it("never offers a caption-only deleted word as a pause", () => { + const recs = recordings(10); + const p = project( + [ + ["So", 0.5, 0.8], + ["um", 1.0, 1.2], + ["important", 1.3, 1.9], + ["stuff", 2.0, 2.4], + ["you", 2.5, 2.7], + ["know", 2.8, 3.0], + ], + [clip(0, 10)], + ); + deleteTranscriptWords(p, [ + { + text: "important", + start: 1.3, + end: 1.9, + segmentIndex: 0, + wordIndex: 2, + }, + ]); + expect( + context(p, recs).items.some( + (item) => item.type === "pause" && item.start < 1.9 && item.end > 1.3, + ), + ).toBe(false); + + const { edit } = planAutoClean(context(p, recs), 1.5); + if (!edit) throw new Error("Nothing planned"); + expect(commitTranscriptCutEdit(p, edit, recs)).toBe("applied"); + expect( + p.timeline?.segments.some( + (segment) => segment.start <= 1.3 + 1e-6 && segment.end >= 1.9 - 1e-6, + ), + ).toBe(true); + expect(liveWords(p)).toEqual(["So", "stuff", "you", "know"]); + }); + + it("treats captions without word timing as speech", () => { + const recs = recordings(10); + const p = project( + [ + ["hello", 1.0, 1.4], + ["again", 4.0, 4.4], + ], + [clip(0, 10)], + ); + p.captions?.segments.push({ + id: "manual", + start: 2.0, + end: 3.6, + text: "Manual caption", + words: [], + }); + expect( + context(p, recs).items.flatMap((item) => + item.type === "pause" ? [[item.start, item.end]] : [], + ), + ).toEqual([ + [0, 1.0], + [1.4, 2.0], + ]); + }); +}); + +describe("auto clean", () => { + it("cuts fillers with their surrounding silence and only long pauses, in one restorable edit", () => { + const recs = recordings(10); + const p = project( + [ + ["So", 0.5, 0.8], + ["um,", 1.0, 1.2], + ["I", 1.3, 1.4], + ["think", 1.5, 1.9], + ["yes", 3.9, 4.2], + ["uhh", 5.0, 5.2], + ["right", 5.6, 6.0], + ], + [clip(0, 10)], + ); + const { edit, skipped } = planAutoClean(context(p, recs), 1.5); + expect(skipped).toBe(0); + if (!edit) throw new Error("Nothing planned"); + + expect(commitTranscriptCutEdit(p, edit, recs)).toBe("applied"); + expect(clips(p)).toEqual([ + [0, 0.8], + [1.3, 1.9], + [3.9, 4.2], + [5.6, 10], + ]); + expect(liveWords(p)).toEqual(["So", "I", "think", "yes", "right"]); + expect(p.captions?.transcriptCuts).toHaveLength(4); + + commitTranscriptCutEdit( + p, + { restore: p.captions?.transcriptCuts?.map((cut) => cut.id) }, + recs, + ); + expect(clips(p)).toEqual([[0, 10]]); + expect(liveWords(p)).toEqual([ + "So", + "um,", + "I", + "think", + "yes", + "uhh", + "right", + ]); + }); + + it("has nothing to do without fillers or long pauses", () => { + const recs = recordings(10); + const p = project(helloWorld.slice(0, 1), [clip(0, 10)]); + expect(planAutoClean(context(p, recs), 1.5)).toEqual({ + edit: null, + skipped: 0, + }); + }); + + it("skips only the cuts that sit next to a clip transition", () => { + const recs = recordings(10); + const p = project( + [ + ["Well", 0.5, 0.8], + ["um", 1.0, 1.2], + ["yes", 1.3, 1.6], + ["so", 4.5, 4.7], + ["uh", 4.75, 4.9], + ["right", 5.3, 5.6], + ], + [clip(0, 5), clip(5, 10)], + { transitions: [{ segmentIndex: 1, type: "cross-fade", duration: 0.5 }] }, + ); + const { edit, skipped } = planAutoClean(context(p, recs), 5); + expect(skipped).toBe(1); + if (!edit) throw new Error("Nothing planned"); + expect(edit.add?.map((cut) => cut.text)).toEqual(["um"]); + expect(commitTranscriptCutEdit(p, edit, recs)).toBe("applied"); + expect(liveWords(p)).toEqual(["Well", "yes", "so", "uh", "right"]); + }); + + it("leaves the silence beside a skipped filler alone", () => { + const recs = recordings(10); + const p = project( + [ + ["You", 1.0, 1.2], + ["know", 2.0, 2.3], + ["uh", 3.8, 4.2], + ["right", 6.5, 6.8], + ], + [clip(0, 5), clip(5, 10)], + { transitions: [{ segmentIndex: 1, type: "cross-fade", duration: 0.5 }] }, + ); + expect(planAutoClean(context(p, recs), 5)).toEqual({ + edit: null, + skipped: 1, + }); + }); + + it("does not treat other languages' words as fillers", () => { + const recs = recordings(10); + const p = project( + [ + ["Eu", 0.5, 0.7], + ["comprei", 0.8, 1.2], + ["um", 1.3, 1.5], + ["carro", 1.6, 2.0], + ], + [clip(0, 10)], + ); + expect(planAutoClean(context(p, recs), 1.5)).toEqual({ + edit: null, + skipped: 0, + }); + }); +}); + +describe("exact restore", () => { + const zoom = (start: number, end: number) => ({ + start, + end, + amount: 2, + mode: "auto" as const, + }); + + function spans(segments: Array<{ start: number; end: number }> | undefined) { + return (segments ?? []).map(({ start, end }) => [ + Number(start.toFixed(6)), + Number(end.toFixed(6)), + ]); + } + + function cutPauseAt(p: Project, recs: SegmentRecordings[], start: number) { + const ctx = context(p, recs); + const pause = ctx.items.find( + (item) => item.type === "pause" && Math.abs(item.start - start) < 1e-6, + ); + if (pause?.type !== "pause") throw new Error(`No pause at ${start}`); + return commitTranscriptCutEdit(p, planPauseCut(ctx, pause), recs); + } + + const restore = (p: Project, recs: SegmentRecordings[], ...ids: string[]) => + commitTranscriptCutEdit(p, { restore: ids }, recs); + + const cutIds = (p: Project) => + (p.captions?.transcriptCuts ?? []).map((cut) => cut.id); + + it("puts back the overlays a pause cut deleted or trimmed", () => { + const recs = recordings(20); + const p = project( + [ + ["before", 1.0, 1.4], + ["after", 6.0, 6.4], + ], + [clip(0, 20)], + { + zoomSegments: [zoom(2, 3), zoom(4.5, 7)], + keyboardSegments: [ + { + id: "keys", + start: 3, + end: 3.5, + displayText: "ab", + keys: [ + { key: "a", timeOffset: 0 }, + { key: "b", timeOffset: 250 }, + ], + }, + ], + }, + ); + const before = structuredClone(p.timeline); + + expect(cutPauseAt(p, recs, 1.4)).toBe("applied"); + expect(clips(p)).toEqual([ + [0, 1.4], + [6.0, 20], + ]); + expect(spans(p.timeline?.zoomSegments)).toEqual([[1.4, 2.4]]); + expect(p.timeline?.keyboardSegments).toEqual([]); + + expect(restore(p, recs, ...cutIds(p))).toBe("applied"); + expect(clips(p)).toEqual([[0, 20]]); + expect(spans(p.timeline?.zoomSegments)).toEqual( + spans(before?.zoomSegments), + ); + expect(p.timeline?.keyboardSegments).toEqual([ + { + ...before?.keyboardSegments?.[0], + start: expect.closeTo(3), + end: expect.closeTo(3.5), + }, + ]); + expect(p.captions?.transcriptCuts).toEqual([]); + }); + + it("returns a word cut across a speed change to the clips it came from", () => { + const recs = recordings(10); + const p = project( + [ + ["hello", 0.5, 0.9], + ["word", 2.0, 2.4], + ["next", 5.0, 5.3], + ], + [clip(0, 2.1), clip(2.1, 10, { timescale: 2 })], + ); + + expect(cut(p, recs, "word")).toBe("applied"); + expect(clips(p)).toEqual([ + [0, 2.0], + [2.4, 10], + ]); + expect(cutRecord(p, "word").removed).toHaveLength(2); + + restore(p, recs, cutRecord(p, "word").id); + expect(clips(p)).toEqual([ + [0, 2.1], + [2.1, 10], + ]); + expect(p.timeline?.segments.map((segment) => segment.timescale)).toEqual([ + 1, 2, + ]); + }); + + it("gives words back the ends that pause and filler cuts trimmed", () => { + const recs = recordings(10); + const stretched = project( + [ + ["so", 1.0, 5.0], + ["next", 5.05, 5.4], + ], + [clip(0, 10)], + ); + cutPauseAt(stretched, recs, 3.5); + expect(stretched.captions?.segments[0].words?.[0].end).toBe(3.5); + restore(stretched, recs, ...cutIds(stretched)); + expect(stretched.captions?.segments[0].words?.[0]).toMatchObject({ + text: "so", + end: 5.0, + }); + expect(clips(stretched)).toEqual([[0, 10]]); + + const filler = project( + [ + ["so", 1.0, 3.8], + ["um", 3.8, 4.1], + ["right", 4.2, 4.5], + ], + [clip(0, 10)], + ); + const { edit } = planAutoClean(context(filler, recs), 5); + if (!edit) throw new Error("Nothing planned"); + commitTranscriptCutEdit(filler, edit, recs); + expect(liveWords(filler)).toEqual(["so", "right"]); + expect(filler.captions?.segments[0].words?.[0].end).toBeCloseTo(3.5); + + restore(filler, recs, cutRecord(filler, "um").id); + expect( + filler.captions?.segments[0].words?.map((word) => [word.text, word.end]), + ).toEqual([ + ["so", 3.8], + ["um", 4.1], + ["right", 4.5], + ]); + expect(clips(filler)).toEqual([[0, 10]]); + }); + + it("brings back a fullscreen text hold together with the time it held", () => { + const recs = recordings(10); + const hold = { ...defaultTextSegment(3, 4), layout: "fullscreen" as const }; + const p = project( + [ + ["intro", 0.5, 1.0], + ["long", 2.5, 3.5], + ["after", 8.0, 8.4], + ], + [clip(0, 10)], + { textSegments: [hold], zoomSegments: [zoom(6, 7)] }, + ); + + cut(p, recs, "long"); + expect(p.timeline?.textSegments).toEqual([]); + expect(spans(p.timeline?.zoomSegments)).toEqual([[4, 5]]); + + restore(p, recs, cutRecord(p, "long").id); + expect(clips(p)).toEqual([[0, 10]]); + expect(spans(p.timeline?.textSegments)).toEqual([[3, 4]]); + expect(p.timeline?.textSegments[0].layout).toBe("fullscreen"); + expect(spans(p.timeline?.zoomSegments)).toEqual([[6, 7]]); + }); + + it("restores one Auto Clean cut exactly while its neighbours stay cut", () => { + const recs = recordings(10); + const p = project( + [ + ["So", 0.5, 0.8], + ["um,", 1.0, 1.2], + ["I", 1.3, 1.4], + ["think", 1.5, 1.9], + ["yes", 3.9, 4.2], + ["uhh", 5.0, 5.2], + ["right", 5.6, 6.0], + ], + [clip(0, 10)], + { + zoomSegments: [zoom(4.4, 4.8), zoom(7, 8)], + keyboardSegments: [ + { + id: "keys", + start: 5.1, + end: 5.3, + displayText: "a", + keys: [{ key: "a", timeOffset: 0 }], + }, + ], + }, + ); + const before = structuredClone(p.timeline); + const { edit } = planAutoClean(context(p, recs), 1.5); + if (!edit) throw new Error("Nothing planned"); + commitTranscriptCutEdit(p, edit, recs); + expect(spans(p.timeline?.zoomSegments)).toEqual([[3.1, 4.1]]); + expect(p.timeline?.keyboardSegments).toEqual([]); + + restore(p, recs, cutRecord(p, "uhh").id); + expect(clips(p)).toEqual([ + [0, 0.8], + [1.3, 1.9], + [3.9, 4.2], + [5.0, 10], + ]); + expect(spans(p.timeline?.keyboardSegments)).toEqual([[1.8, 2.0]]); + expect(spans(p.timeline?.zoomSegments)).toEqual([[3.7, 4.7]]); + + restore(p, recs, ...cutIds(p)); + expect(clips(p)).toEqual([[0, 10]]); + expect(spans(p.timeline?.zoomSegments)).toEqual( + spans(before?.zoomSegments), + ); + expect(spans(p.timeline?.keyboardSegments)).toEqual( + spans(before?.keyboardSegments), + ); + expect(liveWords(p)).toEqual([ + "So", + "um,", + "I", + "think", + "yes", + "uhh", + "right", + ]); + }); + + it("hands footage another cut still claims to that cut and restores it with it", () => { + const recs = recordings(10); + const p = project(helloWorld, [clip(0, 10)], { + zoomSegments: [zoom(1.45, 1.55), zoom(1.7, 1.8)], + }); + const before = structuredClone(p.timeline); + cut(p, recs, "um"); + commitTranscriptCutEdit( + p, + { + padding: [ + { id: cutRecord(p, "um").id, bufferStart: 0.2, bufferEnd: 0 }, + ], + }, + recs, + ); + cut(p, recs, "hello"); + expect(cutRecord(p, "hello").bufferEnd).toBeCloseTo(0.2); + expect(clips(p)).toEqual([ + [0, 1.0], + [1.9, 10], + ]); + expect(p.timeline?.zoomSegments).toEqual([]); + + restore(p, recs, cutRecord(p, "um").id); + expect(clips(p)).toEqual([ + [0, 1.0], + [1.6, 10], + ]); + expect(spans(p.timeline?.zoomSegments)).toEqual([[1.1, 1.2]]); + + restore(p, recs, cutRecord(p, "hello").id); + expect(clips(p)).toEqual([[0, 10]]); + expect(spans(p.timeline?.zoomSegments)).toEqual( + spans(before?.zoomSegments), + ); + }); +}); + +describe("re-transcription", () => { + it("keeps cut words cut when captions are generated again", () => { + const recs = recordings(10); + const p = project(helloWorld, [clip(0, 10)]); + cut(p, recs, "um"); + const fresh = structuredClone(p.captions?.segments ?? []); + fresh[0].words = helloWorld.map(([text, start, end]) => ({ + text, + start, + end, + })); + + applyCaptionResultToProject(p, fresh, recs, 10); + expect(liveWords(p)).toEqual(["hello", "world", "again"]); + expect(p.captions?.transcriptCuts).toHaveLength(1); + }); + + it("restores into the caption that is actually there, not a stale id", () => { + const recs = recordings(20); + const p = project( + [ + ["alpha", 1.0, 1.3], + ["beta", 1.5, 1.8], + ["gamma", 9.0, 9.3], + ["delta", 9.5, 9.8], + ], + [clip(0, 20)], + ); + const segment = (id: string, words: Array<[string, number, number]>) => ({ + id, + start: words[0][1], + end: words[words.length - 1][2], + text: words.map(([text]) => text).join(" "), + words: words.map(([text, start, end]) => ({ text, start, end })), + }); + if (p.captions) + p.captions.segments = [ + segment("segment-0", [ + ["alpha", 1.0, 1.3], + ["beta", 1.5, 1.8], + ]), + segment("segment-1", [ + ["gamma", 9.0, 9.3], + ["delta", 9.5, 9.8], + ]), + ]; + cut(p, recs, "gamma"); + applyCaptionResultToProject( + p, + [ + segment("segment-0", [["alpha", 1.0, 1.3]]), + segment("segment-1", [ + ["beta", 1.5, 1.8], + ["mid", 4.0, 4.3], + ]), + segment("segment-2", [ + ["gamma", 9.0, 9.3], + ["delta", 9.5, 9.8], + ]), + ], + recs, + 20, + ); + + commitTranscriptCutEdit(p, { restore: [cutRecord(p, "gamma").id] }, recs); + const segments = p.captions?.segments ?? []; + expect(segments.find((s) => s.id === "segment-1")?.end).toBe(4.3); + expect( + segments.find((s) => s.words?.some((w) => w.text === "gamma")), + ).toMatchObject({ start: 9.0, end: 9.3 }); + expect(new Set(segments.map((s) => s.id)).size).toBe(segments.length); + }); +}); + +describe("filler words", () => { + it("recognises common fillers in any case, punctuation or length", () => { + for (const word of ["uh", "Um,", "UMMM...", "hmm", "Hmmm?", "erm", "mhm"]) + expect(isFillerWord(word)).toBe(true); + for (const word of ["under", "the", "hello", "am", "uh-huh", ""]) + expect(isFillerWord(word)).toBe(false); + }); + + it("only treats words longer than any spoken word as stretched", () => { + expect(spokenWordEnd({ start: 1, end: 5 })).toBe(3.5); + expect(spokenWordEnd({ start: 1, end: 1.4 })).toBe(1.4); + expect(spokenWordEnd({ start: 1, end: 2 })).toBe(2); + }); + + it("only counts fillers in transcripts that read as English", () => { + expect( + readsAsEnglish(["So", "um", "I", "think", "you", "know", "the", "plan"]), + ).toBe(true); + expect(readsAsEnglish(["Eu", "comprei", "um", "carro", "novo"])).toBe( + false, + ); + expect( + readsAsEnglish(["Er", "kommt", "um", "acht", "Uhr", "nach", "Hause"]), + ).toBe(false); + }); +}); diff --git a/apps/desktop/src/routes/editor/transcript-cuts.ts b/apps/desktop/src/routes/editor/transcript-cuts.ts new file mode 100644 index 00000000000..11e36699265 --- /dev/null +++ b/apps/desktop/src/routes/editor/transcript-cuts.ts @@ -0,0 +1,1522 @@ +import { unwrap } from "solid-js/store"; +import type { + CaptionSegment, + SegmentRecordings, + TimelineSegment, + TranscriptCut, + TranscriptCutOverlay, + TranscriptCutPiece, + TranscriptCutTracks, + TranscriptRange, + TranscriptTrimmedWord, +} from "~/utils/tauri"; +import { + getCaptionTextFromWords, + type MappedTimeRange, + mapSourceRangeToEdited, +} from "./captions"; +import { transitionsAfterClipMerge } from "./clip-merge"; +import { + type ClipTransition, + clipDuration, + clipTimelineDuration, + clipTimelineOffsets, + getClipTransition, + rangeIntersectsClipTransition, +} from "./clip-transitions"; +import type { EditorProjectConfiguration } from "./context"; +import { + isFillerWord, + readsAsEnglish, + spokenWordEnd, +} from "./filler-detection"; +import { + effectiveToOutput, + effectiveToOutputEnd, + holdWindows, +} from "./timeline-holds"; +import { rippleDeleteAllTracks, rippleInsertAllTracks } from "./timeline-utils"; +import { getSegmentTrack } from "./timelineTracks"; +import type { FlatWord } from "./transcript-edits"; + +export const PAUSE_DETECTION_THRESHOLD = 0.5; +export const AUTO_CLEAN_SILENCE_THRESHOLD = 1.5; +export const MAX_CUT_PADDING = 1; + +const RANGE_EPSILON = 1e-4; +const MIN_TIMELINE_CUT = 0.001; +const SNAPSHOT_EPSILON = 1e-6; +const WORD_TIME_EPSILON = 1e-3; + +export type SourceRange = TranscriptRange; + +type TranscriptProject = Pick< + EditorProjectConfiguration, + "captions" | "timeline" +>; +type TranscriptTimeline = NonNullable; +type TranscriptCaptions = NonNullable; + +export function mergeSourceRanges( + ranges: readonly SourceRange[], +): SourceRange[] { + const sorted = ranges + .filter((range) => range.end - range.start > RANGE_EPSILON) + .map((range) => ({ start: range.start, end: range.end })) + .sort((a, b) => a.start - b.start); + const merged: SourceRange[] = []; + for (const range of sorted) { + const last = merged[merged.length - 1]; + if (last && range.start <= last.end + RANGE_EPSILON) { + last.end = Math.max(last.end, range.end); + } else { + merged.push(range); + } + } + return merged; +} + +export function subtractSourceRanges( + from: readonly SourceRange[], + remove: readonly SourceRange[], +): SourceRange[] { + const removals = mergeSourceRanges(remove); + const result: SourceRange[] = []; + for (const range of mergeSourceRanges(from)) { + let cursor = range.start; + for (const removal of removals) { + if (removal.end <= cursor) continue; + if (removal.start >= range.end) break; + if (removal.start > cursor) { + result.push({ start: cursor, end: removal.start }); + } + cursor = Math.max(cursor, removal.end); + if (cursor >= range.end) break; + } + if (range.end > cursor) result.push({ start: cursor, end: range.end }); + } + return result.filter((range) => range.end - range.start > RANGE_EPSILON); +} + +export function intersectSourceRanges( + a: readonly SourceRange[], + b: readonly SourceRange[], +): SourceRange[] { + const left = mergeSourceRanges(a); + const right = mergeSourceRanges(b); + const result: SourceRange[] = []; + let i = 0; + let j = 0; + while (i < left.length && j < right.length) { + const start = Math.max(left[i].start, right[j].start); + const end = Math.min(left[i].end, right[j].end); + if (end - start > RANGE_EPSILON) result.push({ start, end }); + if (left[i].end < right[j].end) i++; + else j++; + } + return result; +} + +export function sourceRangesDuration(ranges: readonly SourceRange[]) { + return ranges.reduce((total, range) => total + (range.end - range.start), 0); +} + +function recordingOffsets(recordingSegments: SegmentRecordings[]) { + const offsets: number[] = []; + let cumulative = 0; + for (const recording of recordingSegments) { + offsets.push(cumulative); + cumulative += recording.display.duration; + } + return offsets; +} + +export function timelineSourceCoverage( + segments: readonly TimelineSegment[], + recordingSegments: SegmentRecordings[], +): SourceRange[] { + const offsets = recordingOffsets(recordingSegments); + return mergeSourceRanges( + segments.map((segment) => { + const offset = offsets[segment.recordingSegment ?? 0] ?? 0; + return { start: offset + segment.start, end: offset + segment.end }; + }), + ); +} + +export function cutClaim( + cut: Pick, +): SourceRange | null { + const start = Math.max(0, cut.start - (cut.bufferStart ?? 0)); + const end = cut.end + (cut.bufferEnd ?? 0); + return end - start > RANGE_EPSILON ? { start, end } : null; +} + +function cutClaims(cuts: readonly TranscriptCut[]) { + return mergeSourceRanges( + cuts.flatMap((cut) => { + const claim = cutClaim(cut); + return claim ? [claim] : []; + }), + ); +} + +export type PaddingRoom = { before: number; after: number }; + +export function cutPaddingLimits( + cut: Pick, + room: PaddingRoom = { before: MAX_CUT_PADDING, after: MAX_CUT_PADDING }, +) { + const half = Math.floor(((cut.end - cut.start) / 2) * 100 + 1e-6) / 100; + const shrink = (other: number | undefined) => + -Math.min(0.5, Math.max(0, half + Math.min(0, other ?? 0))); + return { + before: { + min: shrink(cut.bufferEnd), + max: Math.min(MAX_CUT_PADDING, room.before), + }, + after: { + min: shrink(cut.bufferStart), + max: Math.min(MAX_CUT_PADDING, room.after), + }, + }; +} + +function paddingRoom( + cut: Pick, + obstacles: readonly SourceRange[], +): PaddingRoom { + let before = MAX_CUT_PADDING; + let after = MAX_CUT_PADDING; + for (const range of obstacles) { + if (range.end <= cut.start + RANGE_EPSILON) + before = Math.min(before, cut.start - range.end); + else if (range.start >= cut.end - RANGE_EPSILON) + after = Math.min(after, range.start - cut.end); + } + return { before: Math.max(0, before), after: Math.max(0, after) }; +} + +function transcriptSpeech( + captions: + | Pick + | null + | undefined, +) { + return mergeSourceRanges([ + ...(captions?.transcriptHidden ?? []), + ...(captions?.segments ?? []).filter((segment) => !segment.words?.length), + ]); +} + +export function cutPaddingRoom( + captions: + | Pick + | null + | undefined, + cut: Pick, +) { + return paddingRoom(cut, [ + ...transcriptSpeech(captions), + ...flattenCaptionWords(captions?.segments ?? []).map((word) => ({ + start: word.start, + end: spokenWordEnd(word), + })), + ]); +} + +function clampCutPadding(cut: TranscriptCut, room: PaddingRoom): TranscriptCut { + const clamp = (value: number, range: { min: number; max: number }) => + Math.min(range.max, Math.max(range.min, value)); + const bufferStart = clamp( + cut.bufferStart ?? 0, + cutPaddingLimits(cut, room).before, + ); + const bufferEnd = clamp( + cut.bufferEnd ?? 0, + cutPaddingLimits({ ...cut, bufferStart }, room).after, + ); + return { ...cut, bufferStart, bufferEnd }; +} + +function cutConflictsWithTransition( + segments: TimelineSegment[], + transitions: ClipTransition[], + offsets: number[], + range: MappedTimeRange, +) { + if ( + rangeIntersectsClipTransition(segments, transitions, range.start, range.end) + ) + return true; + const incoming = + getClipTransition(segments, transitions, range.segmentIndex)?.duration ?? 0; + const outgoing = + getClipTransition(segments, transitions, range.segmentIndex + 1) + ?.duration ?? 0; + if (incoming === 0 && outgoing === 0) return false; + const localStart = range.start - offsets[range.segmentIndex]; + const localEnd = range.end - offsets[range.segmentIndex]; + const duration = clipDuration(segments[range.segmentIndex]); + return ( + localStart + RANGE_EPSILON < incoming * 2 || + duration - localEnd + RANGE_EPSILON < outgoing * 2 + ); +} + +function editedRangesForSource( + timeline: TranscriptTimeline, + ranges: readonly SourceRange[], + recordingSegments: SegmentRecordings[], + offsets: number[], +) { + const transitions = timeline.transitions ?? []; + const outputRanges = mergeSourceRanges(ranges) + .flatMap((range) => + mapSourceRangeToEdited( + range.start, + range.end, + timeline.segments, + recordingSegments, + transitions, + ), + ) + .map((range) => { + const clipStart = offsets[range.segmentIndex]; + const clipEnd = + clipStart + clipDuration(timeline.segments[range.segmentIndex]); + return { + ...range, + start: Math.max(range.start, clipStart), + end: Math.min(range.end, clipEnd), + }; + }) + .filter((range) => range.end - range.start > MIN_TIMELINE_CUT) + .sort((a, b) => a.start - b.start || a.segmentIndex - b.segmentIndex); + + const merged: MappedTimeRange[] = []; + for (const range of outputRanges) { + const last = merged[merged.length - 1]; + if ( + last && + last.segmentIndex === range.segmentIndex && + range.start <= last.end + RANGE_EPSILON + ) { + last.end = Math.max(last.end, range.end); + } else { + merged.push({ ...range }); + } + } + return merged; +} + +export function sourceRangeBlockedByTransition( + timeline: TranscriptTimeline, + range: SourceRange, + recordingSegments: SegmentRecordings[], +) { + const transitions = timeline.transitions ?? []; + if (transitions.length === 0) return false; + const offsets = clipTimelineOffsets(timeline.segments, transitions); + return editedRangesForSource( + timeline, + [range], + recordingSegments, + offsets, + ).some((edited) => + cutConflictsWithTransition(timeline.segments, transitions, offsets, edited), + ); +} + +const OVERLAY_TRACKS = [ + "zoomSegments", + "sceneSegments", + "maskSegments", + "textSegments", + "keyboardSegments", + "audioSegments", + "styleSegments", + "imageSegments", + "camera3dSegments", +] as const satisfies readonly (keyof TranscriptCutTracks)[]; + +type OverlayTrack = (typeof OVERLAY_TRACKS)[number]; +type OverlaySegment = { start: number; end: number; track?: number }; +type OverlayTracks = { [K in OverlayTrack]?: OverlaySegment[] | null }; +type OverlayChanges = { + [K in OverlayTrack]?: TranscriptCutOverlay[]; +}; +type TouchedOverlays = Array<{ + key: OverlayTrack; + segments: Array<{ raw: OverlaySegment; before: OverlaySegment }>; +}>; + +function sameValue(a: unknown, b: unknown): boolean { + if (typeof a === "number" && typeof b === "number") + return Math.abs(a - b) <= SNAPSHOT_EPSILON; + if (a === null || a === undefined || b === null || b === undefined) + return (a ?? null) === (b ?? null); + if (typeof a !== "object" || typeof b !== "object") return a === b; + if (Array.isArray(a) !== Array.isArray(b)) return false; + const left = a as Record; + const right = b as Record; + for (const key of new Set([...Object.keys(left), ...Object.keys(right)])) { + if (!sameValue(left[key], right[key])) return false; + } + return true; +} + +function shiftOverlay(segment: T, by: number): T { + return { ...segment, start: segment.start + by, end: segment.end + by }; +} + +function touchOverlays( + tracks: OverlayTracks, + start: number, + end: number, +): TouchedOverlays { + return OVERLAY_TRACKS.map((key) => ({ + key, + segments: (tracks[key] ?? []).flatMap((segment) => { + if (segment.end <= start || segment.start >= end) return []; + const raw = unwrap(segment); + return [{ raw, before: structuredClone(raw) }]; + }), + })); +} + +function overlayChanges( + tracks: OverlayTracks, + touched: TouchedOverlays, + origin: number, +) { + const changes: OverlayChanges = {}; + for (const { key, segments } of touched) { + const remaining = new Set( + (tracks[key] ?? []).map((segment) => unwrap(segment)), + ); + const entries = segments.flatMap(({ raw, before }) => { + const original = shiftOverlay(before, -origin); + if (!remaining.has(raw)) return [{ before: original }]; + const after = structuredClone(raw); + return sameValue(before, after) + ? [] + : [{ before: original, after: shiftOverlay(after, -origin) }]; + }); + if (entries.length > 0) changes[key] = entries; + } + return changes as TranscriptCutTracks; +} + +function takeOverlays( + tracks: OverlayTracks, + overlays: TranscriptCutTracks | null | undefined, + origin: number, +) { + const changes: OverlayChanges = overlays ?? {}; + return OVERLAY_TRACKS.flatMap((key) => + (changes[key] ?? []).flatMap((entry) => { + const after = entry.after; + if (after) { + const track = tracks[key] ?? []; + const index = track.findIndex((segment) => + sameValue(shiftOverlay(unwrap(segment), -origin), after), + ); + if (index === -1) return []; + track.splice(index, 1); + } + return [ + { + key, + segment: shiftOverlay(structuredClone(unwrap(entry.before)), origin), + }, + ]; + }), + ); +} + +function putBackOverlays( + tracks: OverlayTracks, + restored: ReturnType, +) { + for (const { key, segment } of restored) { + if (!tracks[key]) tracks[key] = []; + const track = tracks[key] ?? []; + const index = track.findIndex( + (other) => + (getSegmentTrack(other) - getSegmentTrack(segment) || + other.start - segment.start) > 0, + ); + track.splice(index === -1 ? track.length : index, 0, segment); + } +} + +function removeTimelineRange( + timeline: TranscriptTimeline, + range: MappedTimeRange, + sequence: number, +): TranscriptCutPiece | null { + const clip = timeline.segments[range.segmentIndex]; + if (!clip) return null; + const transitions = timeline.transitions ?? []; + const clipStart = clipTimelineOffsets(timeline.segments, transitions)[ + range.segmentIndex + ]; + const start = Math.max(range.start, clipStart); + const end = Math.min(range.end, clipStart + clipDuration(clip)); + const holds = holdWindows(timeline.textSegments); + const overlayStart = effectiveToOutput(holds, start); + const overlayEnd = effectiveToOutputEnd(holds, end); + const touched = touchOverlays(timeline, overlayStart, overlayEnd); + const original = { ...unwrap(clip) }; + const durationBefore = clipTimelineDuration(timeline.segments, transitions); + + rippleDeleteAllTracks(timeline, start, end, range.segmentIndex); + if ( + clipTimelineDuration(timeline.segments, timeline.transitions ?? []) >= + durationBefore + ) + return null; + + const held = overlayEnd - overlayStart - (end - start); + return { + sequence, + clip: original, + start: original.start + (start - clipStart) * original.timescale, + end: original.start + (end - clipStart) * original.timescale, + held: held > RANGE_EPSILON ? held : 0, + overlays: overlayChanges(timeline, touched, overlayStart), + }; +} + +type OwnedRanges = { owner: number; ranges: SourceRange[] }; + +function claimOwners( + cuts: readonly TranscriptCut[], + ranges: readonly SourceRange[], +): OwnedRanges[] { + let unowned = mergeSourceRanges(ranges); + const owned: OwnedRanges[] = []; + cuts.forEach((cut, owner) => { + const claim = cutClaim(cut); + if (!claim || unowned.length === 0) return; + const mine = intersectSourceRanges(unowned, [claim]); + if (mine.length === 0) return; + owned.push({ owner, ranges: mine }); + unowned = subtractSourceRanges(unowned, mine); + }); + return owned; +} + +function cutTimelineSourceRanges( + timeline: TranscriptTimeline, + owned: readonly OwnedRanges[], + recordingSegments: SegmentRecordings[], + sequence: number, +): "transition" | Array<{ owner: number; piece: TranscriptCutPiece }> { + const transitions = timeline.transitions ?? []; + const offsets = clipTimelineOffsets(timeline.segments, transitions); + const removals = owned.flatMap(({ owner, ranges }) => + editedRangesForSource(timeline, ranges, recordingSegments, offsets).map( + (range) => ({ owner, range }), + ), + ); + + if ( + removals.some(({ range }) => + cutConflictsWithTransition( + timeline.segments, + transitions, + offsets, + range, + ), + ) + ) + return "transition"; + + const pieces: Array<{ owner: number; piece: TranscriptCutPiece }> = []; + for (const { owner, range } of removals.sort( + (a, b) => b.range.start - a.range.start, + )) { + const piece = removeTimelineRange( + timeline, + range, + sequence + pieces.length, + ); + if (piece) pieces.push({ owner, piece }); + } + return pieces; +} + +const CLIP_JOIN_EPSILON = 1e-4; + +function clipSettingsMatch(left: TimelineSegment, right: TimelineSegment) { + const keys = new Set([...Object.keys(left), ...Object.keys(right)]); + keys.delete("start"); + keys.delete("end"); + for (const key of keys) { + const a = left[key as keyof TimelineSegment] ?? null; + const b = right[key as keyof TimelineSegment] ?? null; + if (a !== b) return false; + } + return true; +} + +function insertRecordingRange( + timeline: TranscriptTimeline, + recording: number, + start: number, + end: number, + piece?: TranscriptCutPiece, +): "applied" | "transition" { + const segments = timeline.segments; + const transitions = timeline.transitions ?? []; + const offsets = clipTimelineOffsets(segments, transitions); + const durationBefore = clipTimelineDuration(segments, transitions); + const fromRecording = (index: number) => + (segments[index]?.recordingSegment ?? 0) === recording; + const blocked = (boundaryIndex: number) => + boundaryIndex > 0 && + boundaryIndex < segments.length && + getClipTransition(segments, transitions, boundaryIndex) !== null; + const continuesBefore = + piece !== undefined && piece.clip.start < start - CLIP_JOIN_EPSILON; + const continuesAfter = + piece !== undefined && piece.clip.end > end + CLIP_JOIN_EPSILON; + const joins = (segment: TimelineSegment, continues: boolean) => + !piece || continues || clipSettingsMatch(segment, piece.clip); + + const previous: number[] = []; + const next: number[] = []; + segments.forEach((segment, index) => { + if (!fromRecording(index)) return; + if ( + Math.abs(segment.end - start) <= CLIP_JOIN_EPSILON && + joins(segment, continuesBefore) + ) + previous.push(index); + if ( + Math.abs(segment.start - end) <= CLIP_JOIN_EPSILON && + joins(segment, continuesAfter) + ) + next.push(index); + }); + const joinIndex = previous.find((index) => next.includes(index + 1)); + + let boundary: number; + if (joinIndex !== undefined) { + if (blocked(joinIndex + 1)) return "transition"; + const left = segments[joinIndex]; + const right = segments[joinIndex + 1]; + boundary = offsets[joinIndex] + clipDuration(left); + if (clipSettingsMatch(left, right)) { + left.end = right.end; + segments.splice(joinIndex + 1, 1); + timeline.transitions = transitionsAfterClipMerge(transitions, joinIndex); + } else { + left.end = end; + } + } else if (previous.length > 0) { + const index = previous[0]; + if (blocked(index + 1)) return "transition"; + boundary = offsets[index] + clipDuration(segments[index]); + segments[index].end = end; + } else if (next.length > 0) { + const index = next[0]; + if (blocked(index)) return "transition"; + boundary = offsets[index]; + segments[index].start = start; + } else { + let anchor = -1; + let insertAt = segments.length; + segments.forEach((segment, index) => { + if (!fromRecording(index) || segment.end > start + CLIP_JOIN_EPSILON) + return; + if (anchor === -1 || segment.end >= segments[anchor].end) { + anchor = index; + insertAt = index + 1; + } + }); + if (anchor === -1) { + segments.forEach((segment, index) => { + if (!fromRecording(index) || segment.start < end - CLIP_JOIN_EPSILON) + return; + if (anchor === -1 || segment.start < segments[anchor].start) { + anchor = index; + insertAt = index; + } + }); + } + if (anchor === -1) { + let before = -1; + let after = -1; + segments.forEach((segment, index) => { + const segmentRecording = segment.recordingSegment ?? 0; + if (segmentRecording < recording) before = index; + else if (segmentRecording > recording && after === -1) after = index; + }); + anchor = before !== -1 ? before : after; + insertAt = before !== -1 ? before + 1 : after !== -1 ? after : 0; + } + if (blocked(insertAt)) return "transition"; + boundary = insertAt < segments.length ? offsets[insertAt] : durationBefore; + const template = piece?.clip ?? segments[anchor]; + segments.splice(insertAt, 0, { + ...template, + timescale: template?.timescale ?? 1, + recordingSegment: recording, + start, + end, + name: piece?.clip.name ?? null, + }); + timeline.transitions = transitions.map((transition) => + transition.segmentIndex >= insertAt + ? { ...transition, segmentIndex: transition.segmentIndex + 1 } + : transition, + ); + } + + const shift = + clipTimelineDuration(timeline.segments, timeline.transitions ?? []) - + durationBefore; + const overlayBoundary = effectiveToOutput( + holdWindows(timeline.textSegments), + boundary, + ); + const restored = piece + ? takeOverlays(timeline, piece.overlays, overlayBoundary) + : []; + rippleInsertAllTracks(timeline, overlayBoundary, shift + (piece?.held ?? 0)); + putBackOverlays(timeline, restored); + return "applied"; +} + +function pieceSourceRange( + piece: TranscriptCutPiece, + offsets: readonly number[], +): SourceRange | null { + const offset = offsets[piece.clip.recordingSegment ?? 0]; + return offset === undefined + ? null + : { start: offset + piece.start, end: offset + piece.end }; +} + +function restoreTimelineSourceRanges( + timeline: TranscriptTimeline, + ranges: readonly SourceRange[], + recordingSegments: SegmentRecordings[], + pieces: readonly TranscriptCutPiece[], +): "applied" | "transition" { + const offsets = recordingOffsets(recordingSegments); + for (const piece of [...pieces].sort((a, b) => b.sequence - a.sequence)) { + const source = pieceSourceRange(piece, offsets); + if (!source) continue; + const restorable = subtractSourceRanges( + ranges, + timelineSourceCoverage(timeline.segments, recordingSegments), + ); + if ( + sourceRangesDuration(subtractSourceRanges([source], restorable)) > + RANGE_EPSILON + ) + continue; + if ( + insertRecordingRange( + timeline, + piece.clip.recordingSegment ?? 0, + piece.start, + piece.end, + piece, + ) === "transition" + ) + return "transition"; + } + for (const range of mergeSourceRanges(ranges)) { + for (let recording = 0; recording < recordingSegments.length; recording++) { + const offset = offsets[recording]; + const local = { + start: Math.max(range.start, offset) - offset, + end: + Math.min( + range.end, + offset + recordingSegments[recording].display.duration, + ) - offset, + }; + if (local.end - local.start <= RANGE_EPSILON) continue; + const covered = timeline.segments + .filter((segment) => (segment.recordingSegment ?? 0) === recording) + .map((segment) => ({ start: segment.start, end: segment.end })); + for (const gap of subtractSourceRanges([local], covered)) { + if ( + insertRecordingRange(timeline, recording, gap.start, gap.end) === + "transition" + ) + return "transition"; + } + } + } + return "applied"; +} + +function syncSegmentFromWords(segment: CaptionSegment) { + const words = segment.words ?? []; + if (words.length === 0) return; + segment.text = getCaptionTextFromWords(words); + segment.start = words[0].start; + segment.end = words[words.length - 1].end; +} + +export function removeCaptionWords( + captions: Pick, + words: readonly FlatWord[], +) { + const sorted = [...words].sort( + (a, b) => b.segmentIndex - a.segmentIndex || b.wordIndex - a.wordIndex, + ); + for (const word of sorted) { + const segment = captions.segments[word.segmentIndex]; + if (!segment?.words) continue; + if (word.wordIndex >= 0 && word.wordIndex < segment.words.length) { + segment.words.splice(word.wordIndex, 1); + } + } + for (const index of [...new Set(sorted.map((word) => word.segmentIndex))]) { + const segment = captions.segments[index]; + if (!segment) continue; + if (!segment.words || segment.words.length === 0) { + captions.segments.splice(index, 1); + } else { + syncSegmentFromWords(segment); + } + } +} + +export function hideCaptionSpeech( + captions: Pick, + ranges: readonly SourceRange[], +) { + captions.transcriptHidden = mergeSourceRanges([ + ...(captions.transcriptHidden ?? []), + ...ranges, + ]); +} + +function restoreCaptionWord( + captions: Pick, + cut: TranscriptCut, +) { + const text = cut.text?.trim() ?? ""; + if (text.length === 0) return; + const word = { text, start: cut.start, end: cut.end }; + const midpoint = (word.start + word.end) / 2; + const live = captions.segments.filter( + (candidate) => (candidate.words?.length ?? 0) > 0, + ); + const distance = (candidate: CaptionSegment) => + Math.max(candidate.start - word.end, word.start - candidate.end, 0); + const nearest = Math.min(...live.map(distance)); + const recorded = live.find((candidate) => candidate.id === cut.segmentId); + const segment = + live.find( + (candidate) => midpoint >= candidate.start && midpoint <= candidate.end, + ) ?? + (recorded && distance(recorded) <= nearest + PAUSE_DETECTION_THRESHOLD + ? recorded + : undefined); + + if (!segment) { + const index = captions.segments.findIndex( + (candidate) => candidate.start > word.start, + ); + const idTaken = captions.segments.some( + (candidate) => candidate.id === cut.segmentId, + ); + captions.segments.splice( + index === -1 ? captions.segments.length : index, + 0, + { + id: + cut.segmentId && !idTaken + ? cut.segmentId + : `caption-${Date.now()}-${Math.random().toString(36).slice(2)}`, + start: word.start, + end: word.end, + text: word.text, + words: [word], + }, + ); + return; + } + + segment.words ??= []; + const duplicate = segment.words.some( + (existing) => + existing.text === word.text && + Math.min(existing.end, word.end) - Math.max(existing.start, word.start) > + (word.end - word.start) / 2, + ); + if (duplicate) return; + const index = segment.words.findIndex( + (existing) => existing.start > word.start, + ); + segment.words.splice(index === -1 ? segment.words.length : index, 0, word); + syncSegmentFromWords(segment); +} + +function restoreTrimmedWords( + captions: Pick, + trimmed: readonly TranscriptTrimmedWord[], + claims: readonly SourceRange[], +) { + for (const record of trimmed) { + for (const segment of captions.segments) { + const word = segment.words?.find( + (candidate) => + Math.abs(candidate.start - record.start) <= WORD_TIME_EPSILON && + Math.abs(candidate.end - record.trimmedEnd) <= WORD_TIME_EPSILON, + ); + if (!word) continue; + const limit = + claims.find((claim) => claim.end > record.trimmedEnd + RANGE_EPSILON) + ?.start ?? record.end; + word.end = Math.max(word.end, Math.min(record.end, limit)); + segment.end = Math.max(segment.end, word.end); + break; + } + } +} + +export type TranscriptCutEdit = { + add?: TranscriptCut[]; + cutWords?: FlatWord[]; + trimWords?: Array<{ + segmentIndex: number; + wordIndex: number; + end: number; + cut: string; + }>; + restore?: string[]; + padding?: Array<{ id: string; bufferStart: number; bufferEnd: number }>; +}; + +export type TranscriptCutResult = "applied" | "transition" | "failed" | "empty"; + +/** + * Applies a transcript cut edit in place. The edit list follows the union of + * every cut's padded range: newly claimed source time is cut out, and time no + * cut claims any more is re-inserted when the transcript was what removed it. + * Each cut records the footage it removed, so a piece no cut claims any more + * comes back with its clip settings and overlays as the removal found them. + * The project may be partly modified when this returns anything but + * "applied", so callers run it against a copy first. + */ +export function applyTranscriptCutEdit( + project: TranscriptProject, + edit: TranscriptCutEdit, + recordingSegments: SegmentRecordings[], +): TranscriptCutResult { + const captions = project.captions; + if (!captions) return "empty"; + const currentCuts = captions.transcriptCuts ?? []; + const restoreIds = new Set(edit.restore ?? []); + const padding = new Map( + (edit.padding ?? []).map((change) => [change.id, change]), + ); + const restored = currentCuts.filter((cut) => restoreIds.has(cut.id)); + const added = edit.add ?? []; + const repadded = currentCuts.filter( + (cut) => !restoreIds.has(cut.id) && padding.has(cut.id), + ); + if (restored.length === 0 && added.length === 0 && repadded.length === 0) + return "empty"; + + const nextCuts = [ + ...currentCuts.flatMap((cut) => { + if (restoreIds.has(cut.id)) return []; + const change = padding.get(cut.id); + return [ + change + ? clampCutPadding( + { + ...cut, + bufferStart: change.bufferStart, + bufferEnd: change.bufferEnd, + }, + cutPaddingRoom(captions, cut), + ) + : cut, + ]; + }), + ...added, + ]; + + const previousClaims = cutClaims(currentCuts); + const nextClaims = cutClaims(nextCuts); + const removed = mergeSourceRanges(captions.transcriptRemoved ?? []); + const toRestore = intersectSourceRanges( + subtractSourceRanges(previousClaims, nextClaims), + removed, + ); + const toCut = subtractSourceRanges(nextClaims, previousClaims); + let nextRemoved = subtractSourceRanges(removed, toRestore); + const removedPieces = new Map(); + + const timeline = project.timeline; + if (!timeline && (toRestore.length > 0 || toCut.length > 0)) return "failed"; + if (timeline) { + if ( + toRestore.length > 0 && + restoreTimelineSourceRanges( + timeline, + toRestore, + recordingSegments, + currentCuts.flatMap((cut) => cut.removed ?? []), + ) === "transition" + ) + return "transition"; + + const coverage = timelineSourceCoverage( + timeline.segments, + recordingSegments, + ); + const present = intersectSourceRanges(toCut, coverage); + if (present.length > 0) { + const pieces = cutTimelineSourceRanges( + timeline, + claimOwners(nextCuts, present), + recordingSegments, + nextPieceSequence(currentCuts), + ); + if (pieces === "transition") return "transition"; + const cutOut = subtractSourceRanges( + coverage, + timelineSourceCoverage(timeline.segments, recordingSegments), + ); + if ( + sourceRangesDuration(subtractSourceRanges(present, cutOut)) > + MIN_TIMELINE_CUT + ) + return "failed"; + nextRemoved = mergeSourceRanges([...nextRemoved, ...cutOut]); + for (const { owner, piece } of pieces) { + removedPieces.set(owner, [...(removedPieces.get(owner) ?? []), piece]); + } + } + } + + const trimmedWords = new Map(); + for (const trim of edit.trimWords ?? []) { + const word = captions.segments[trim.segmentIndex]?.words?.[trim.wordIndex]; + if (word && trim.end > word.start && trim.end < word.end) { + const owner = nextCuts.findIndex((cut) => cut.id === trim.cut); + if (owner !== -1) + trimmedWords.set(owner, [ + ...(trimmedWords.get(owner) ?? []), + { start: word.start, end: word.end, trimmedEnd: trim.end }, + ]); + word.end = trim.end; + } + } + removeCaptionWords(captions, edit.cutWords ?? []); + for (const cut of restored) { + if (cut.kind === "word") restoreCaptionWord(captions, cut); + restoreTrimmedWords(captions, cut.trimmedWords ?? [], nextClaims); + } + + const offsets = recordingOffsets(recordingSegments); + const stillRemoved = (piece: TranscriptCutPiece) => { + const source = pieceSourceRange(piece, offsets); + return ( + source !== null && + sourceRangesDuration(subtractSourceRanges([source], nextRemoved)) <= + RANGE_EPSILON + ); + }; + for (const piece of restored.flatMap((cut) => cut.removed ?? [])) { + const source = pieceSourceRange(piece, offsets); + if (!source || !stillRemoved(piece)) continue; + const owner = nextCuts.findIndex((cut) => { + const claim = cutClaim(cut); + return ( + claim !== null && intersectSourceRanges([claim], [source]).length > 0 + ); + }); + if (owner !== -1) + removedPieces.set(owner, [...(removedPieces.get(owner) ?? []), piece]); + } + captions.transcriptCuts = nextCuts.map((cut, index) => { + const kept = (cut.removed ?? []).filter(stillRemoved); + const pieces = removedPieces.get(index) ?? []; + const trims = trimmedWords.get(index) ?? []; + if ( + kept.length === (cut.removed ?? []).length && + pieces.length === 0 && + trims.length === 0 + ) + return cut; + return { + ...cut, + removed: [...kept, ...pieces], + trimmedWords: [...(cut.trimmedWords ?? []), ...trims], + }; + }); + captions.transcriptRemoved = nextRemoved; + return "applied"; +} + +function nextPieceSequence(cuts: readonly TranscriptCut[]) { + let next = 0; + for (const cut of cuts) { + for (const piece of cut.removed ?? []) + next = Math.max(next, piece.sequence + 1); + } + return next; +} + +export type TranscriptItem = + | { type: "word"; token: number; word: FlatWord } + | { type: "cut-word"; token: number; cut: TranscriptCut } + | { type: "pause"; start: number; end: number } + | { type: "cut-pause"; cut: TranscriptCut }; + +export type TranscriptToken = + | { type: "word"; word: FlatWord } + | { type: "cut-word"; cut: TranscriptCut }; + +export function tokenStart(token: TranscriptToken) { + return token.type === "word" ? token.word.start : token.cut.start; +} + +function tokenSpeechEnd(token: TranscriptToken) { + return token.type === "word" ? spokenWordEnd(token.word) : token.cut.end; +} + +export function transcriptTokens( + words: readonly FlatWord[], + cuts: readonly TranscriptCut[], +): TranscriptToken[] { + const cutWords = cuts + .filter((cut) => cut.kind === "word") + .sort((a, b) => a.start - b.start); + const tokens: TranscriptToken[] = []; + let next = 0; + for (const word of words) { + while (next < cutWords.length && cutWords[next].start < word.start) { + tokens.push({ type: "cut-word", cut: cutWords[next++] }); + } + tokens.push({ type: "word", word }); + } + while (next < cutWords.length) { + tokens.push({ type: "cut-word", cut: cutWords[next++] }); + } + return tokens; +} + +function clipToRange( + sorted: readonly SourceRange[], + range: SourceRange, +): SourceRange[] { + let low = 0; + let high = sorted.length; + while (low < high) { + const mid = (low + high) >>> 1; + if (sorted[mid].end <= range.start) low = mid + 1; + else high = mid; + } + const result: SourceRange[] = []; + for (let i = low; i < sorted.length && sorted[i].start < range.end; i++) { + const start = Math.max(sorted[i].start, range.start); + const end = Math.min(sorted[i].end, range.end); + if (end - start > RANGE_EPSILON) result.push({ start, end }); + } + return result; +} + +export function buildTranscriptItems( + tokens: readonly TranscriptToken[], + cuts: readonly TranscriptCut[], + coverage: readonly SourceRange[], + speech: readonly SourceRange[] = [], + threshold = PAUSE_DETECTION_THRESHOLD, +): TranscriptItem[] { + const cutPauses = cuts + .filter((cut) => cut.kind === "pause") + .sort((a, b) => a.start - b.start); + const silence = subtractSourceRanges(coverage, [...cutPauses, ...speech]); + const items: TranscriptItem[] = []; + let nextCutPause = 0; + const flushCutPauses = (before: number) => { + while ( + nextCutPause < cutPauses.length && + cutPauses[nextCutPause].start < before + ) { + items.push({ type: "cut-pause", cut: cutPauses[nextCutPause++] }); + } + }; + + tokens.forEach((token, index) => { + const previous = tokens[index - 1]; + const gap = { + start: previous ? tokenSpeechEnd(previous) : 0, + end: tokenStart(token), + }; + const pauses = + gap.end - gap.start >= threshold + ? clipToRange(silence, gap).filter( + (piece) => piece.end - piece.start >= threshold, + ) + : []; + for (const pause of pauses) { + flushCutPauses(pause.start); + items.push({ type: "pause", start: pause.start, end: pause.end }); + } + flushCutPauses(tokenStart(token)); + items.push( + token.type === "word" + ? { type: "word", token: index, word: token.word } + : { type: "cut-word", token: index, cut: token.cut }, + ); + }); + flushCutPauses(Number.POSITIVE_INFINITY); + return items; +} + +export function newTranscriptCutId() { + return `cut-${Date.now()}-${Math.random().toString(36).slice(2)}`; +} + +function wordCut( + word: FlatWord, + segmentId: string | undefined, + id: string, +): TranscriptCut { + return { + id, + kind: "word", + text: word.text, + start: word.start, + end: word.end, + bufferStart: 0, + bufferEnd: 0, + segmentId: segmentId ?? null, + }; +} + +function pauseCut(range: SourceRange, id: string): TranscriptCut { + return { + id, + kind: "pause", + text: "", + start: range.start, + end: range.end, + bufferStart: 0, + bufferEnd: 0, + segmentId: null, + }; +} + +export type PlanContext = { + items: readonly TranscriptItem[]; + segmentIds: readonly (string | undefined)[]; + coverage: readonly SourceRange[]; + speech: readonly SourceRange[]; + blocked?: (range: SourceRange) => boolean; + createId?: () => string; +}; + +type TokenItem = Extract; + +function tokenItems(items: readonly TranscriptItem[]) { + return items.filter( + (item): item is TokenItem => + item.type === "word" || item.type === "cut-word", + ); +} + +function itemStart(item: TokenItem) { + return item.type === "word" ? item.word.start : item.cut.start; +} + +function itemEnd(item: TokenItem) { + return item.type === "word" ? item.word.end : item.cut.end; +} + +function trimsForCuts( + tokens: readonly TokenItem[], + cuts: readonly TranscriptCut[], + leaving: ReadonlySet, +) { + return tokens.flatMap((item) => { + if (item.type !== "word" || leaving.has(item.token)) return []; + for (const cut of cuts) { + const claim = cutClaim(cut); + if ( + claim && + claim.start > item.word.start + RANGE_EPSILON && + claim.start < item.word.end - RANGE_EPSILON + ) + return [ + { + segmentIndex: item.word.segmentIndex, + wordIndex: item.word.wordIndex, + end: claim.start, + cut: cut.id, + }, + ]; + } + return []; + }); +} + +function planCuts( + context: PlanContext, + cutting: ReadonlySet, + options: { + joinKeepers: boolean; + longPauseThreshold?: number; + skipBlocked?: boolean; + }, +): { edit: TranscriptCutEdit | null; skipped: number } { + const createId = context.createId ?? newTranscriptCutId; + const tokens = tokenItems(context.items); + const silence = subtractSourceRanges(context.coverage, [ + ...context.items.flatMap((item) => + item.type === "cut-pause" ? [item.cut] : [], + ), + ...context.speech, + ]); + const records = new Map(); + for (const item of tokens) { + if (item.type !== "word" || !cutting.has(item.token)) continue; + records.set( + item.token, + wordCut( + item.word, + context.segmentIds[item.word.segmentIndex], + createId(), + ), + ); + } + + const removedAfter = (item: TokenItem) => + item.type === "cut-word" || records.has(item.token); + const gapPauses: Array<{ range: SourceRange; beside: number[] }> = []; + const bufferedFrom = new Map(); + for (let index = 0; index < tokens.length; index++) { + const current = tokens[index]; + const previous = index > 0 ? tokens[index - 1] : undefined; + const currentRecord = records.get(current.token); + const previousRecord = previous ? records.get(previous.token) : undefined; + if (!currentRecord && !previousRecord) continue; + const joinsRemoved = + previous !== undefined && removedAfter(previous) && removedAfter(current); + if (!joinsRemoved && !options.joinKeepers) continue; + + const gapStart = !previous + ? 0 + : previous.type === "word" && !previousRecord + ? spokenWordEnd(previous.word) + : itemEnd(previous); + const gap = itemStart(current) - gapStart; + if (gap <= RANGE_EPSILON) continue; + if (gap < PAUSE_DETECTION_THRESHOLD) { + if (currentRecord) { + currentRecord.bufferStart = gap; + if (previous && previousRecord) + bufferedFrom.set(current.token, previous.token); + } else if (previousRecord) previousRecord.bufferEnd = gap; + continue; + } + if (!options.joinKeepers && !(currentRecord && previousRecord)) continue; + const beside = [previous?.token, current.token].filter( + (token): token is number => token !== undefined && records.has(token), + ); + for (const range of clipToRange(silence, { + start: gapStart, + end: itemStart(current), + })) + gapPauses.push({ range, beside }); + } + + for (const record of records.values()) { + const room = paddingRoom(record, context.speech); + record.bufferStart = Math.min(record.bufferStart ?? 0, room.before); + record.bufferEnd = Math.min(record.bufferEnd ?? 0, room.after); + } + + const longPauses: SourceRange[] = []; + if (options.longPauseThreshold !== undefined) { + for (const item of context.items) { + if ( + item.type === "pause" && + item.end - item.start >= options.longPauseThreshold + ) { + longPauses.push({ start: item.start, end: item.end }); + } + } + } + + let skipped = 0; + const skippedTokens = new Set(); + const blocked = options.skipBlocked ? context.blocked : undefined; + if (blocked) { + for (const [token, record] of [...records]) { + const claim = cutClaim(record); + if (claim && blocked(claim)) { + records.delete(token); + skippedTokens.add(token); + skipped++; + } + } + for (const [token, from] of bufferedFrom) { + const record = records.get(token); + if (record && skippedTokens.has(from)) record.bufferStart = 0; + } + } + let pauseRanges = mergeSourceRanges([ + ...gapPauses.flatMap((gap) => + gap.beside.some((token) => skippedTokens.has(token)) ? [] : [gap.range], + ), + ...longPauses, + ]); + if (blocked) { + const clear = pauseRanges.filter((range) => !blocked(range)); + skipped += pauseRanges.length - clear.length; + pauseRanges = clear; + } + if (records.size === 0 && pauseRanges.length === 0) + return { edit: null, skipped }; + const add = [ + ...records.values(), + ...pauseRanges.map((range) => pauseCut(range, createId())), + ]; + return { + edit: { + add, + cutWords: tokens.flatMap((item) => + item.type === "word" && records.has(item.token) ? [item.word] : [], + ), + trimWords: trimsForCuts(tokens, add, new Set(records.keys())), + }, + skipped, + }; +} + +export function planWordCuts( + context: PlanContext, + tokenIndices: Iterable, +): TranscriptCutEdit | null { + const selected = new Set(tokenIndices); + const live = new Set(); + for (const item of context.items) { + if (item.type === "word" && selected.has(item.token)) live.add(item.token); + } + if (live.size === 0) return null; + return planCuts(context, live, { joinKeepers: false }).edit; +} + +export function planPauseCut( + context: PlanContext, + pause: SourceRange, +): TranscriptCutEdit { + const cut = pauseCut(pause, (context.createId ?? newTranscriptCutId)()); + return { + add: [cut], + trimWords: trimsForCuts(tokenItems(context.items), [cut], new Set()), + }; +} + +export function planAutoClean( + context: PlanContext, + silenceThreshold: number, +): { edit: TranscriptCutEdit | null; skipped: number } { + return planCuts(context, fillerTokens(context.items), { + joinKeepers: true, + longPauseThreshold: silenceThreshold, + skipBlocked: true, + }); +} + +export function fillerTokens(items: readonly TranscriptItem[]): Set { + const tokens = tokenItems(items); + if ( + !readsAsEnglish( + tokens.map((item) => + item.type === "word" ? item.word.text : (item.cut.text ?? ""), + ), + ) + ) + return new Set(); + return new Set( + tokens.flatMap((item) => + item.type === "word" && isFillerWord(item.word.text) ? [item.token] : [], + ), + ); +} + +export function flattenCaptionWords( + segments: readonly CaptionSegment[], +): FlatWord[] { + return segments.flatMap((segment, segmentIndex) => + (segment.words ?? []).map((word, wordIndex) => ({ + text: word.text, + start: word.start, + end: word.end, + segmentIndex, + wordIndex, + })), + ); +} + +export function transcriptPlanContext( + project: TranscriptProject, + recordingSegments: SegmentRecordings[], + words?: readonly FlatWord[], +): PlanContext { + const segments = project.captions?.segments ?? []; + const cuts = project.captions?.transcriptCuts ?? []; + const coverage = project.timeline + ? timelineSourceCoverage(project.timeline.segments, recordingSegments) + : [ + { + start: 0, + end: recordingSegments.reduce( + (total, recording) => total + recording.display.duration, + 0, + ), + }, + ]; + const speech = transcriptSpeech(project.captions); + const timeline = project.timeline; + return { + items: buildTranscriptItems( + transcriptTokens(words ?? flattenCaptionWords(segments), cuts), + cuts, + coverage, + speech, + ), + segmentIds: segments.map((segment) => segment.id), + coverage, + speech, + blocked: (range) => + timeline + ? sourceRangeBlockedByTransition(timeline, range, recordingSegments) + : false, + }; +} + +export function commitTranscriptCutEdit( + project: TranscriptProject, + edit: TranscriptCutEdit, + recordingSegments: SegmentRecordings[], +): TranscriptCutResult { + const draft = structuredClone({ + captions: unwrap(project.captions), + timeline: unwrap(project.timeline), + }); + const result = applyTranscriptCutEdit(draft, edit, recordingSegments); + if (result === "applied") { + applyTranscriptCutEdit(project, edit, recordingSegments); + } + return result; +} diff --git a/apps/desktop/src/routes/editor/transcript-edits.test.ts b/apps/desktop/src/routes/editor/transcript-edits.test.ts index 3aac60cac22..acb876fd7b2 100644 --- a/apps/desktop/src/routes/editor/transcript-edits.test.ts +++ b/apps/desktop/src/routes/editor/transcript-edits.test.ts @@ -4,6 +4,11 @@ import type { SegmentRecordings } from "~/utils/tauri"; import { deriveCaptionTrackSegments } from "./captions"; import { clipTimelineDuration } from "./clip-transitions"; import type { EditorProjectConfiguration } from "./context"; +import { + commitTranscriptCutEdit, + planWordCuts, + transcriptPlanContext, +} from "./transcript-cuts"; import { deleteTranscriptWords, type FlatWord, @@ -60,6 +65,24 @@ function fixture() { return project; } +function cutVideo( + project: Pick, + words: FlatWord[], +) { + const context = transcriptPlanContext(project, recordings); + const keys = new Set(words.map((w) => `${w.segmentIndex}:${w.wordIndex}`)); + const edit = planWordCuts( + context, + context.items.flatMap((item) => + item.type === "word" && + keys.has(`${item.word.segmentIndex}:${item.word.wordIndex}`) + ? [item.token] + : [], + ), + ); + return edit ? commitTranscriptCutEdit(project, edit, recordings) : "empty"; +} + function word( project: ReturnType, segmentIndex: number, @@ -80,9 +103,9 @@ describe("transcript word deletion", () => { project.captions.segments[0].words[0], project.captions.segments[0].words[2], ]; - expect( - deleteTranscriptWords(project, [word(project, 0, 1)], recordings), - ).toBe("deleted"); + expect(deleteTranscriptWords(project, [word(project, 0, 1)])).toBe( + "deleted", + ); expect(project.timeline).toEqual(timeline); expect(clipTimelineDuration(project.timeline.segments, [])).toBe(9); expect(project.captions.segments[0].text).toBe("keep caption"); @@ -103,11 +126,11 @@ describe("transcript word deletion", () => { it("handles multiple words and removes empty captions without deleting unrelated manual captions", () => { const project = fixture(); const timeline = structuredClone(project.timeline); - deleteTranscriptWords( - project, - [word(project, 0, 0), word(project, 1, 0), word(project, 0, 2)], - recordings, - ); + deleteTranscriptWords(project, [ + word(project, 0, 0), + word(project, 1, 0), + word(project, 0, 2), + ]); expect(project.timeline).toEqual(timeline); expect(project.captions.segments.map((segment) => segment.text)).toEqual([ "this", @@ -118,7 +141,7 @@ describe("transcript word deletion", () => { it("keeps ripple deletion available only through the explicit video action", () => { const project = fixture(); - deleteTranscriptWords(project, [word(project, 0, 1)], recordings, "video"); + cutVideo(project, [word(project, 0, 1)]); expect(clipTimelineDuration(project.timeline.segments, [])).toBe(8); expect(project.timeline.segments).toHaveLength(3); expect(project.timeline.zoomSegments[0]).toMatchObject({ @@ -143,13 +166,9 @@ describe("transcript word deletion", () => { wordIndex: 2, }; const before = structuredClone(project); - expect( - deleteTranscriptWords(project, [selected], recordings, "video"), - ).toBe("transition"); + expect(cutVideo(project, [selected])).toBe("transition"); expect(project).toEqual(before); - expect(deleteTranscriptWords(project, [selected], recordings)).toBe( - "deleted", - ); + expect(deleteTranscriptWords(project, [selected])).toBe("deleted"); expect(project.timeline).toEqual(before.timeline); }); }); diff --git a/apps/desktop/src/routes/editor/transcript-edits.ts b/apps/desktop/src/routes/editor/transcript-edits.ts index f1f8e3d67ee..499a723490c 100644 --- a/apps/desktop/src/routes/editor/transcript-edits.ts +++ b/apps/desktop/src/routes/editor/transcript-edits.ts @@ -1,15 +1,5 @@ -import type { SegmentRecordings } from "~/utils/tauri"; -import { - getCaptionTextFromWords, - type MappedTimeRange, - mapSourceRangeToEdited, -} from "./captions"; -import { - clipCutPreservesTransitionGeometry, - rangeIntersectsClipTransition, -} from "./clip-transitions"; import type { EditorProjectConfiguration } from "./context"; -import { rippleDeleteAllTracks } from "./timeline-utils"; +import { hideCaptionSpeech, removeCaptionWords } from "./transcript-cuts"; export interface FlatWord { text: string; @@ -20,113 +10,13 @@ export interface FlatWord { } export function deleteTranscriptWords( - project: Pick, + project: Pick, wordsToDelete: FlatWord[], - recordingSegments: SegmentRecordings[], - mode: "captions" | "video" = "captions", ) { const captions = project.captions; if (!captions || wordsToDelete.length === 0) return "empty"; - const sorted = [...wordsToDelete].sort((a, b) => { - if (a.segmentIndex !== b.segmentIndex) - return b.segmentIndex - a.segmentIndex; - return b.wordIndex - a.wordIndex; - }); - - const sourceRanges = (mode === "video" ? wordsToDelete : []) - .map((w) => ({ start: w.start, end: w.end })) - .sort((a, b) => a.start - b.start); - - const mergedSourceRanges: { start: number; end: number }[] = []; - for (const range of sourceRanges) { - const last = mergedSourceRanges[mergedSourceRanges.length - 1]; - if (last && range.start <= last.end) { - last.end = Math.max(last.end, range.end); - } else { - mergedSourceRanges.push({ ...range }); - } - } - - const outputRanges = mergedSourceRanges - .flatMap((range) => - mapSourceRangeToEdited( - range.start, - range.end, - project.timeline?.segments ?? [], - recordingSegments, - project.timeline?.transitions ?? [], - ), - ) - .sort((a, b) => a.start - b.start || a.segmentIndex - b.segmentIndex); - - const mergedOutputRanges: MappedTimeRange[] = []; - for (const range of outputRanges) { - const last = mergedOutputRanges[mergedOutputRanges.length - 1]; - if ( - last && - last.segmentIndex === range.segmentIndex && - range.start <= last.end + 0.0001 - ) { - last.end = Math.max(last.end, range.end); - } else { - mergedOutputRanges.push({ ...range }); - } - } - - const timeline = project.timeline; - if ( - timeline && - mergedOutputRanges.some( - (range) => - rangeIntersectsClipTransition( - timeline.segments, - timeline.transitions ?? [], - range.start, - range.end, - ) || - !clipCutPreservesTransitionGeometry( - timeline.segments, - timeline.transitions ?? [], - range.segmentIndex, - range.start, - range.end, - ), - ) - ) { - return "transition"; - } - - for (const word of sorted) { - const seg = captions.segments[word.segmentIndex]; - if (!seg?.words) continue; - if (word.wordIndex >= 0 && word.wordIndex < seg.words.length) { - seg.words.splice(word.wordIndex, 1); - } - } - - for (const i of [...new Set(sorted.map((word) => word.segmentIndex))]) { - const seg = captions.segments[i]; - if (!seg) continue; - if (!seg.words || seg.words.length === 0) { - captions.segments.splice(i, 1); - } else { - seg.text = getCaptionTextFromWords(seg.words); - seg.start = seg.words[0].start; - seg.end = seg.words[seg.words.length - 1].end; - } - } - - if (project.timeline) { - for (const range of [...mergedOutputRanges].reverse()) { - if (range.end - range.start <= 0.001) continue; - rippleDeleteAllTracks( - project.timeline, - range.start, - range.end, - range.segmentIndex, - ); - } - } + removeCaptionWords(captions, wordsToDelete); + hideCaptionSpeech(captions, wordsToDelete); return "deleted"; } diff --git a/apps/desktop/src/utils/tauri.ts b/apps/desktop/src/utils/tauri.ts index 767b14c177a..47b81e6818d 100644 --- a/apps/desktop/src/utils/tauri.ts +++ b/apps/desktop/src/utils/tauri.ts @@ -899,7 +899,25 @@ export type CaptionsData = { segments: CaptionSegment[]; settings: CaptionSettin * projects (false) stored segments in already-edited output time and are * migrated to source time on first load. */ -sourceTimed?: boolean } +sourceTimed?: boolean; +/** + * Words and pauses cut out of the video from the transcript editor. A cut + * word leaves `segments`, so it can never reach a rendered caption, and is + * kept here so the editor can restore it or change its padding. + */ +transcriptCuts?: TranscriptCut[]; +/** + * Source-time ranges the transcript editor actually removed from the edit + * list. Restoring a cut only re-inserts footage listed here, so footage + * trimmed out some other way stays out. + */ +transcriptRemoved?: TranscriptRange[]; +/** + * Source-time ranges of words deleted from the captions only. Their + * speech stays in the video, so the transcript editor never offers them + * as pauses to cut. + */ +transcriptHidden?: TranscriptRange[] } export type CaptureDisplay = { id: DisplayId; name: string; refresh_rate: number } export type CaptureDisplayWithThumbnail = { id: DisplayId; name: string; refresh_rate: number; thumbnail: string | null } export type CaptureTargetKind = "display" | "window" | "area" @@ -1355,6 +1373,49 @@ letterSpacing?: number; lineHeight?: number; opacity?: number; shadow?: number; layoutTransition?: number } export type TimelineConfiguration = { segments: TimelineSegment[]; transitions: ClipTransition[]; zoomSegments: ZoomSegment[]; sceneSegments?: SceneSegment[]; maskSegments?: MaskSegment[]; textSegments?: TextSegment[]; captionSegments?: CaptionTrackSegment[]; keyboardSegments?: KeyboardTrackSegment[]; audioSegments?: AudioTrackSegment[]; styleSegments: StyleSegment[]; imageSegments: ImageSegment[]; camera3dSegments?: Camera3DSegment[] } export type TimelineSegment = { recordingSegment?: number; timescale: number; start: number; end: number; name?: string | null; speedAudioMode?: ClipSpeedAudioMode | null; volume?: number | null; hideCursor?: boolean | null } +export type TranscriptCut = { id: string; kind: TranscriptCutKind; text?: string; start: number; end: number; bufferStart?: number; bufferEnd?: number; segmentId?: string | null; +/** + * Footage this cut took out of the timeline, one piece per clip it cut + * into, so restoring the cut can put back exactly what it removed. + */ +removed?: TranscriptCutPiece[]; +/** + * Live words this cut shortened because its claim started inside them. + */ +trimmedWords?: TranscriptTrimmedWord[] } +export type TranscriptCutKind = "word" | "pause" +/** + * An overlay segment as it was before a transcript cut and, when it + * survived the cut, as the cut left it. + */ +export type TranscriptCutOverlay = { before: T; after?: T | null } +export type TranscriptCutPiece = { +/** + * Grows with every removal across all cuts, so restoring several pieces + * undoes the newest removal first. + */ +sequence: number; +/** + * The clip the footage came from, as it was before the removal. + */ +clip: TimelineSegment; +/** + * The removed footage, in `clip`'s recording time. + */ +start: number; end: number; +/** + * Output time that left with the footage because fullscreen text holds + * sat inside it. + */ +held?: number; +/** + * Overlay segments the removal deleted or trimmed, timed from the cut + * point in output time. + */ +overlays?: TranscriptCutTracks } +export type TranscriptCutTracks = { zoomSegments?: TranscriptCutOverlay[]; sceneSegments?: TranscriptCutOverlay[]; maskSegments?: TranscriptCutOverlay[]; textSegments?: TranscriptCutOverlay[]; keyboardSegments?: TranscriptCutOverlay[]; audioSegments?: TranscriptCutOverlay[]; styleSegments?: TranscriptCutOverlay[]; imageSegments?: TranscriptCutOverlay[]; camera3dSegments?: TranscriptCutOverlay[] } +export type TranscriptRange = { start: number; end: number } +export type TranscriptTrimmedWord = { start: number; end: number; trimmedEnd: number } export type TranscriptionEngine = "Whisper" | "Parakeet" export type Trigger = "screenshotTaken" | "studioRecordingFinished" | "instantRecordingFinished" | "recordingStarted" | "uploadCompleted" | "videoImported" | "recordingDeleted" export type UpdateChannel = "stable" | "nightly" diff --git a/crates/project/src/caption_timing.rs b/crates/project/src/caption_timing.rs index aa7661afb46..0f4253bc067 100644 --- a/crates/project/src/caption_timing.rs +++ b/crates/project/src/caption_timing.rs @@ -1,5 +1,6 @@ use crate::{ - CaptionSegment, CaptionTrackSegment, CaptionWord, ProjectConfiguration, TimelineConfiguration, + CaptionSegment, CaptionTrackSegment, CaptionWord, CaptionsData, ProjectConfiguration, + TimelineConfiguration, TranscriptCut, TranscriptCutKind, }; use std::collections::HashMap; @@ -419,10 +420,64 @@ pub fn synchronize_captions(project: &mut ProjectConfiguration, recording_durati derive_caption_track_segments(&captions.segments, timeline, recording_durations); } +/// `reconcileTranscriptCuts` (`captions.ts`): a fresh transcription covers +/// footage the transcript editor already cut, so words inside +/// `transcript_removed` go back to being cut words instead of live captions. +pub fn reconcile_transcript_cuts(captions: &mut CaptionsData) { + if captions.transcript_removed.is_empty() { + return; + } + let mut added: Vec = Vec::new(); + let mut segments = Vec::with_capacity(captions.segments.len()); + for segment in std::mem::take(&mut captions.segments) { + let mut kept = Vec::with_capacity(segment.words.len()); + for word in &segment.words { + let (start, end) = (f64::from(word.start), f64::from(word.end)); + let midpoint = (start + end) / 2.0; + if !captions + .transcript_removed + .iter() + .any(|range| midpoint > range.start && midpoint < range.end) + { + kept.push(word.clone()); + continue; + } + let already_cut = captions.transcript_cuts.iter().chain(&added).any(|cut| { + cut.kind == TranscriptCutKind::Word && cut.start < end && start < cut.end + }); + if !already_cut { + added.push(TranscriptCut { + id: format!("cut-{}", uuid::Uuid::new_v4()), + kind: TranscriptCutKind::Word, + text: word.text.clone(), + start, + end, + buffer_start: 0.0, + buffer_end: 0.0, + segment_id: Some(segment.id.clone()), + ..Default::default() + }); + } + } + if kept.len() == segment.words.len() { + segments.push(segment); + } else if let (Some(first), Some(last)) = (kept.first(), kept.last()) { + segments.push(CaptionSegment { + id: segment.id.clone(), + start: first.start, + end: last.end, + text: caption_text_from_words(&kept), + words: kept, + }); + } + } + captions.segments = segments; + captions.transcript_cuts.extend(added); +} + #[cfg(test)] mod tests { use super::*; - use crate::CaptionsData; fn project(source_timed: bool, start: f32, end: f32) -> ProjectConfiguration { ProjectConfiguration { @@ -501,4 +556,56 @@ mod tests { 1.0 ); } + + #[test] + fn regenerated_captions_keep_cut_words_cut() { + let word = |text: &str, start: f32, end: f32| CaptionWord { + text: text.into(), + start, + end, + }; + let mut captions: CaptionsData = serde_json::from_value(serde_json::json!({ + "segments": [], + "settings": {}, + "transcriptCuts": [{ "id": "old", "kind": "word", "text": "um", "start": 1.6, "end": 1.9 }], + "transcriptRemoved": [{ "start": 1.6, "end": 1.9 }, { "start": 3.0, "end": 3.6 }] + })) + .unwrap(); + captions.segments = vec![ + CaptionSegment { + id: "segment-0".into(), + start: 1.0, + end: 2.5, + text: "hello um world".into(), + words: vec![ + word("hello", 1.0, 1.4), + word("um", 1.6, 1.9), + word("world", 2.0, 2.5), + ], + }, + CaptionSegment { + id: "segment-1".into(), + start: 3.1, + end: 3.5, + text: "gone".into(), + words: vec![word("gone", 3.1, 3.5)], + }, + ]; + + reconcile_transcript_cuts(&mut captions); + + assert_eq!(captions.segments.len(), 1); + assert_eq!(captions.segments[0].text, "hello world"); + assert_eq!(captions.segments[0].end, 2.5); + let cut_text: Vec<_> = captions + .transcript_cuts + .iter() + .map(|cut| cut.text.as_str()) + .collect(); + assert_eq!(cut_text, ["um", "gone"]); + assert_eq!( + captions.transcript_cuts[1].segment_id.as_deref(), + Some("segment-1") + ); + } } diff --git a/crates/project/src/configuration.rs b/crates/project/src/configuration.rs index 66381de2c74..15d8b3f0c65 100644 --- a/crates/project/src/configuration.rs +++ b/crates/project/src/configuration.rs @@ -2390,6 +2390,120 @@ pub struct CaptionsData { /// migrated to source time on first load. #[serde(default)] pub source_timed: bool, + /// Words and pauses cut out of the video from the transcript editor. A cut + /// word leaves `segments`, so it can never reach a rendered caption, and is + /// kept here so the editor can restore it or change its padding. + #[serde(default)] + pub transcript_cuts: Vec, + /// Source-time ranges the transcript editor actually removed from the edit + /// list. Restoring a cut only re-inserts footage listed here, so footage + /// trimmed out some other way stays out. + #[serde(default)] + pub transcript_removed: Vec, + /// Source-time ranges of words deleted from the captions only. Their + /// speech stays in the video, so the transcript editor never offers them + /// as pauses to cut. + #[serde(default)] + pub transcript_hidden: Vec, +} + +#[derive(Type, Serialize, Deserialize, Clone, Copy, Debug, Default, PartialEq, Eq)] +#[serde(rename_all = "camelCase")] +pub enum TranscriptCutKind { + #[default] + Word, + Pause, +} + +#[derive(Type, Serialize, Deserialize, Clone, Debug, Default)] +#[serde(rename_all = "camelCase")] +pub struct TranscriptCut { + pub id: String, + pub kind: TranscriptCutKind, + #[serde(default)] + pub text: String, + pub start: f64, + pub end: f64, + #[serde(default)] + pub buffer_start: f64, + #[serde(default)] + pub buffer_end: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub segment_id: Option, + /// Footage this cut took out of the timeline, one piece per clip it cut + /// into, so restoring the cut can put back exactly what it removed. + #[serde(default)] + pub removed: Vec, + /// Live words this cut shortened because its claim started inside them. + #[serde(default)] + pub trimmed_words: Vec, +} + +#[derive(Type, Serialize, Deserialize, Clone, Debug)] +#[serde(rename_all = "camelCase")] +pub struct TranscriptCutPiece { + /// Grows with every removal across all cuts, so restoring several pieces + /// undoes the newest removal first. + pub sequence: u32, + /// The clip the footage came from, as it was before the removal. + pub clip: TimelineSegment, + /// The removed footage, in `clip`'s recording time. + pub start: f64, + pub end: f64, + /// Output time that left with the footage because fullscreen text holds + /// sat inside it. + #[serde(default)] + pub held: f64, + /// Overlay segments the removal deleted or trimmed, timed from the cut + /// point in output time. + #[serde(default)] + pub overlays: TranscriptCutTracks, +} + +#[derive(Type, Serialize, Deserialize, Clone, Debug, Default)] +#[serde(rename_all = "camelCase")] +pub struct TranscriptCutTracks { + #[serde(default)] + pub zoom_segments: Vec>, + #[serde(default)] + pub scene_segments: Vec>, + #[serde(default)] + pub mask_segments: Vec>, + #[serde(default)] + pub text_segments: Vec>, + #[serde(default)] + pub keyboard_segments: Vec>, + #[serde(default)] + pub audio_segments: Vec>, + #[serde(default)] + pub style_segments: Vec>, + #[serde(default)] + pub image_segments: Vec>, + #[serde(default, rename = "camera3dSegments")] + pub camera3d_segments: Vec>, +} + +/// An overlay segment as it was before a transcript cut and, when it +/// survived the cut, as the cut left it. +#[derive(Type, Serialize, Deserialize, Clone, Debug)] +pub struct TranscriptCutOverlay { + pub before: T, + #[serde(skip_serializing_if = "Option::is_none")] + pub after: Option, +} + +#[derive(Type, Serialize, Deserialize, Clone, Copy, Debug, Default, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct TranscriptTrimmedWord { + pub start: f64, + pub end: f64, + pub trimmed_end: f64, +} + +#[derive(Type, Serialize, Deserialize, Clone, Copy, Debug, Default, PartialEq)] +pub struct TranscriptRange { + pub start: f64, + pub end: f64, } #[derive(Type, Serialize, Deserialize, Clone, Debug)] @@ -3078,6 +3192,106 @@ mod tests { use super::*; use serde_json::Value; + #[test] + fn transcript_cuts_default_for_old_captions_and_round_trip() { + let legacy: CaptionsData = + serde_json::from_str(r#"{"segments":[],"settings":{}}"#).unwrap(); + assert!(legacy.transcript_cuts.is_empty()); + assert!(legacy.transcript_removed.is_empty()); + assert!(legacy.transcript_hidden.is_empty()); + + let edited: CaptionsData = serde_json::from_value(serde_json::json!({ + "segments": [], + "settings": {}, + "sourceTimed": true, + "transcriptCuts": [ + { + "id": "cut-1", + "kind": "word", + "text": "um", + "start": 1.6, + "end": 1.9, + "bufferStart": 0.2, + "bufferEnd": -0.05, + "segmentId": "caption" + }, + { "id": "cut-2", "kind": "pause", "start": 4.2, "end": 5.0 } + ], + "transcriptRemoved": [{ "start": 1.4, "end": 1.85 }, { "start": 4.2, "end": 5.0 }], + "transcriptHidden": [{ "start": 6.0, "end": 6.4 }] + })) + .unwrap(); + assert_eq!(edited.transcript_cuts[1].kind, TranscriptCutKind::Pause); + assert_eq!(edited.transcript_cuts[1].buffer_start, 0.0); + assert_eq!(edited.transcript_cuts[1].segment_id, None); + + let json = serde_json::to_value(&edited).unwrap(); + assert_eq!(json["transcriptCuts"][0]["bufferEnd"], -0.05); + assert_eq!(json["transcriptCuts"][0]["segmentId"], "caption"); + assert_eq!(json["transcriptRemoved"][1]["end"], 5.0); + assert_eq!(json["transcriptHidden"][0]["start"], 6.0); + let reparsed: CaptionsData = serde_json::from_value(json.clone()).unwrap(); + assert_eq!(serde_json::to_value(&reparsed).unwrap(), json); + } + + #[test] + fn transcript_cut_snapshots_default_for_old_cuts_and_round_trip() { + let legacy: TranscriptCut = serde_json::from_value(serde_json::json!({ + "id": "cut-1", "kind": "word", "start": 1.6, "end": 1.9 + })) + .unwrap(); + assert!(legacy.removed.is_empty()); + assert!(legacy.trimmed_words.is_empty()); + + let cut: TranscriptCut = serde_json::from_value(serde_json::json!({ + "id": "cut-2", + "kind": "pause", + "start": 1.4, + "end": 6.0, + "removed": [{ + "sequence": 3, + "clip": { "recordingSegment": 1, "timescale": 2.0, "start": 0.0, "end": 20.0 }, + "start": 1.4, + "end": 6.0, + "overlays": { + "zoomSegments": [ + { "before": { "start": 0.6, "end": 1.6, "amount": 2.0, "mode": "auto" } }, + { + "before": { "start": 3.1, "end": 5.6, "amount": 1.5, "mode": "auto" }, + "after": { "start": 0.0, "end": 1.0, "amount": 1.5, "mode": "auto" } + } + ] + } + }], + "trimmedWords": [{ "start": 1.0, "end": 1.9, "trimmedEnd": 1.4 }] + })) + .unwrap(); + let piece = &cut.removed[0]; + assert_eq!(piece.sequence, 3); + assert_eq!(piece.clip.recording_clip, 1); + assert_eq!(piece.held, 0.0); + assert!(piece.overlays.zoom_segments[0].after.is_none()); + assert_eq!( + piece.overlays.zoom_segments[1] + .after + .as_ref() + .map(|zoom| zoom.end), + Some(1.0) + ); + assert!(piece.overlays.keyboard_segments.is_empty()); + assert_eq!(cut.trimmed_words[0].trimmed_end, 1.4); + + let json = serde_json::to_value(&cut).unwrap(); + assert!( + json["removed"][0]["overlays"]["zoomSegments"][0] + .get("after") + .is_none() + ); + assert_eq!(json["trimmedWords"][0]["trimmedEnd"], 1.4); + let reparsed: TranscriptCut = serde_json::from_value(json.clone()).unwrap(); + assert_eq!(serde_json::to_value(&reparsed).unwrap(), json); + } + #[test] fn studio_sound_defaults_old_projects_to_balanced_and_round_trips_tiers() { let legacy: AudioConfiguration = diff --git a/crates/project/src/lib.rs b/crates/project/src/lib.rs index dea389ee13b..a5158f9567e 100644 --- a/crates/project/src/lib.rs +++ b/crates/project/src/lib.rs @@ -6,7 +6,10 @@ pub mod keyboard; mod meta; pub use animated_gradient::*; -pub use caption_timing::{derive_caption_track_segments, source_caption_id, synchronize_captions}; +pub use caption_timing::{ + derive_caption_track_segments, reconcile_transcript_cuts, source_caption_id, + synchronize_captions, +}; pub use configuration::*; pub use cursor::*; pub use keyboard::*; diff --git a/crates/verify/tests/captions.rs b/crates/verify/tests/captions.rs index d1f3d72f868..e725f2898b9 100644 --- a/crates/verify/tests/captions.rs +++ b/crates/verify/tests/captions.rs @@ -432,6 +432,7 @@ fn set_captions( segments: captions, settings: caption_settings(), source_timed, + ..Default::default() }); } @@ -934,6 +935,7 @@ fn round_trip_on_disk() { segments: random_captions(&mut rng, durations.iter().sum()), settings: styled_settings(&mut rng), source_timed: true, + ..Default::default() }); cap_project::synchronize_captions(&mut config, &durations); random_overrides(&mut rng, &mut config, true); @@ -981,6 +983,7 @@ fn round_trip_on_disk() { segments: random_captions(&mut rng, 5.0), settings: styled_settings(&mut rng), source_timed: false, + ..Default::default() }; std::fs::write( copy.join("captions.json"), @@ -1487,6 +1490,7 @@ fn templates( segments: captions, settings: render_settings(), source_timed: true, + ..Default::default() }); // Projected here so the templates do not depend on the export's own // projection (which `render_*` checks). @@ -1548,6 +1552,7 @@ fn render_case( segments: captions.clone(), settings: render_settings(), source_timed: true, + ..Default::default() }); cap_project::synchronize_captions(&mut config, &durations); if edit.stale_track { @@ -1856,6 +1861,7 @@ fn editor_open() { segments: legacy, settings: caption_settings(), source_timed: false, + ..Default::default() }; (migrated, Some(sidecar)) } From 56ea40ee45607a64b3454d4a98068a07c30713c8 Mon Sep 17 00:00:00 2001 From: Maulik Date: Mon, 19 Oct 2026 19:38:45 +0530 Subject: [PATCH 02/11] fix: text color --- apps/desktop/src/routes/editor/TranscriptPage.tsx | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/apps/desktop/src/routes/editor/TranscriptPage.tsx b/apps/desktop/src/routes/editor/TranscriptPage.tsx index 0d61b5bcf39..97dfd5c503d 100644 --- a/apps/desktop/src/routes/editor/TranscriptPage.tsx +++ b/apps/desktop/src/routes/editor/TranscriptPage.tsx @@ -875,8 +875,10 @@ function CutTranscriptWord(props: { return ( props.onClick(e)} @@ -932,7 +934,7 @@ function PauseBadge(props: { class={cx( "group relative inline-flex items-center gap-0.5 self-center rounded border border-dashed px-1 text-[10px] leading-4 tabular-nums select-none", props.cut - ? "border-gray-4 text-gray-7 line-through decoration-red-9/70" + ? "border-gray-4 text-red-9 line-through decoration-red-9/70" : "border-gray-6 text-gray-9", )} title={ From e3e8b838cc714ae2b13b9e70d2a1360b1954f2ec Mon Sep 17 00:00:00 2001 From: Maulik Date: Mon, 19 Oct 2026 20:07:49 +0530 Subject: [PATCH 03/11] feat: add recording silence detection to improve transcript cut accuracy --- .../src/routes/editor/TranscriptPage.tsx | 39 +++- .../src/routes/editor/transcript-cuts.test.ts | 218 ++++++++++++++++++ .../src/routes/editor/transcript-cuts.ts | 144 +++++++++++- 3 files changed, 392 insertions(+), 9 deletions(-) diff --git a/apps/desktop/src/routes/editor/TranscriptPage.tsx b/apps/desktop/src/routes/editor/TranscriptPage.tsx index 97dfd5c503d..67df7aa9db7 100644 --- a/apps/desktop/src/routes/editor/TranscriptPage.tsx +++ b/apps/desktop/src/routes/editor/TranscriptPage.tsx @@ -44,6 +44,7 @@ import { planAutoClean, planPauseCut, planWordCuts, + recordingSilence, type SourceRange, type TranscriptCutEdit, type TranscriptItem, @@ -89,10 +90,32 @@ export function TranscriptPanel() { previewResolutionBase, playbackIntent, requestHandoffPlayback, + micWaveforms, + systemAudioWaveforms, } = useEditorContext(); const recordingSegments = () => editorInstance.recordings.segments; + const audioSilence = createMemo(() => { + const mic = micWaveforms(); + const system = systemAudioWaveforms(); + return recordingSilence( + recordingSegments(), + recordingSegments().map((_, index) => { + const offsets = project.clips?.find( + (clip) => clip.index === index, + )?.offsets; + return [ + { levels: mic?.[index] ?? [], offset: offsets?.mic ?? 0 }, + { + levels: system?.[index] ?? [], + offset: offsets?.system_audio ?? 0, + }, + ]; + }), + ); + }); + const [textSizeIndex, setTextSizeIndex] = makePersisted(createSignal(1), { name: "editorTranscriptTextSize", }); @@ -124,7 +147,12 @@ export function TranscriptPanel() { ); const transcript = createMemo(() => - transcriptPlanContext(project, recordingSegments(), allWords()), + transcriptPlanContext( + project, + recordingSegments(), + allWords(), + audioSilence(), + ), ); const transcriptItems = () => transcript().items; @@ -764,7 +792,8 @@ function TranscriptWord(props: { data-active-word={props.isActive || undefined} class={cx( "transition-colors duration-100 rounded-xs relative", - props.isFiller && "underline decoration-dotted decoration-amber-9", + props.isFiller && + "underline decoration-dotted decoration-amber-500", props.isSelected && "bg-blue-4/50", props.isActive ? "text-blue-11" @@ -906,7 +935,7 @@ function CutTranscriptWord(props: {