diff --git a/Cargo.lock b/Cargo.lock index 31774499228..7f1950d8890 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1560,6 +1560,7 @@ dependencies = [ "gdkwayland-sys", "global-hotkey", "gtk", + "hound", "image 0.25.8", "kameo", "keyed_priority_queue", diff --git a/apps/desktop-gpui/src/transcription.rs b/apps/desktop-gpui/src/transcription.rs index bc7ad223b00..6a86ea3c639 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. @@ -1652,6 +1652,10 @@ fn process_with_parakeet( if samples.is_empty() { return Err("No speech detected in the audio".to_string()); } + let pauses = cap_audio::SpeechPauses::detect(&samples, sample_rate); + if pauses.is_none() { + tracing::info!("Speech is not clearly above the noise; keeping word ends"); + } let mut tokens = Vec::new(); { @@ -1678,16 +1682,18 @@ fn process_with_parakeet( tracing::info!("Parakeet produced {} timed tokens", tokens.len()); - caption_segments_from_tokens(tokens) + caption_segments_from_tokens(tokens, pauses.as_ref()) } /// Parakeet's timed word tokens -> caption segments: drop empty tokens, -/// normalize the words and chunk them. +/// normalize the words, end them where their speech stops in the +/// transcription audio, and chunk them. #[cfg(any(test, not(all(target_os = "macos", target_arch = "x86_64"))))] fn caption_segments_from_tokens( tokens: impl IntoIterator, + pauses: Option<&cap_audio::SpeechPauses>, ) -> Result, String> { - let words = normalize_caption_words( + let mut words = normalize_caption_words( tokens .into_iter() .filter(|token| !token.text.trim().is_empty()) @@ -1698,6 +1704,9 @@ fn caption_segments_from_tokens( }) .collect(), ); + if let Some(pauses) = pauses { + end_words_where_speech_stops(&mut words, pauses); + } if words.is_empty() { return Err("No speech detected in the audio".to_string()); @@ -1926,6 +1935,23 @@ fn normalize_caption_words(words: Vec) -> Vec { normalized } +/// `end_words_where_speech_stops` (`captions.rs`). +#[cfg(any(test, not(all(target_os = "macos", target_arch = "x86_64"))))] +fn end_words_where_speech_stops(words: &mut [CaptionWord], pauses: &cap_audio::SpeechPauses) { + let mut moved = 0; + for word in words.iter_mut() { + let end = pauses.audible_end(word.start, word.end); + if end < word.end { + word.end = end; + moved += 1; + } + } + tracing::info!( + "Ended {moved} of {} words where their speech stops", + words.len() + ); +} + /// `caption_text_from_words` (`captions.rs:833-849`). fn caption_text_from_words<'a>(words: impl IntoIterator) -> String { let mut text = String::new(); @@ -2182,9 +2208,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 +2252,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`). @@ -2474,6 +2501,40 @@ mod tests { } } + #[test] + fn parakeet_words_end_where_their_speech_stops() { + let mut samples = vec![0.0_f32; 16_000 * 5]; + for (index, sample) in samples.iter_mut().enumerate() { + let time = index as f32 / 16_000.0; + if (1.0..1.5).contains(&time) || (2.5..3.0).contains(&time) { + *sample = 0.1 * (std::f32::consts::TAU * 220.0 * time).sin(); + } + } + let pauses = cap_audio::SpeechPauses::detect(&samples, 16_000).expect("speech is audible"); + let token = |text: &str, start: f32, end: f32| CaptionWord { + text: text.to_string(), + start, + end, + }; + + let segments = caption_segments_from_tokens( + [ + token(" hello", 1.0, 2.5), + token(" world", 2.5, 3.04), + token(".", 3.04, 4.2), + ], + Some(&pauses), + ) + .expect("segments"); + + let words = &segments[0].words; + assert_eq!(caption_text_from_words(words), "hello world."); + assert_eq!((words[0].start, words[1].start), (1.0, 2.5)); + assert!((words[0].end - 1.6).abs() < 0.02, "{}", words[0].end); + assert!((words[1].end - 3.1).abs() < 0.02, "{}", words[1].end); + assert_eq!(segments[0].end, words[1].end); + } + // -- Model paths ---------------------------------------------------------- #[test] @@ -2694,6 +2755,7 @@ mod tests { ..CaptionSettings::default() }, source_timed: false, + ..Default::default() }); apply_caption_result( @@ -2716,6 +2778,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-gpui/src/transcription/verify_tests.rs b/apps/desktop-gpui/src/transcription/verify_tests.rs index 39a2af3bec2..22212298869 100644 --- a/apps/desktop-gpui/src/transcription/verify_tests.rs +++ b/apps/desktop-gpui/src/transcription/verify_tests.rs @@ -7,7 +7,8 @@ //! timed tokens (one word per marker, some followed by a punctuation token //! and empty tokens). Every word must sit at its source time on the //! concatenated recordings, and the caption segments built by the Parakeet -//! path ([`caption_segments_from_tokens`]) must match the reference +//! path ([`caption_segments_from_tokens`], without the audio pause pass +//! that `cap_audio::SpeechPauses` covers) must match the reference //! segmentation below. Multi-segment Studio projects with per-track start //! offsets, legacy single-segment Studio projects, and Instant projects //! (refused: Instant recordings are transcribed by the web app). @@ -337,7 +338,7 @@ fn check_project(case: &mut Case, project: &Path, takes: &Takes) { let mut tokens = Vec::new(); let result = transcribe_project_with(project, |audio_path| { tokens = fake_tokens(audio_path)?; - caption_segments_from_tokens(tokens.clone()) + caption_segments_from_tokens(tokens.clone(), None) }); let segments = match result { Ok(segments) => segments, @@ -606,7 +607,7 @@ fn segmentation_case(id: &str, unicode: bool) { unicode, ); let reference = reference_segments(&tokens); - match caption_segments_from_tokens(tokens.clone()) { + match caption_segments_from_tokens(tokens.clone(), None) { Err(e) if reference.is_empty() && e.contains("No speech") => empty += 1, Err(e) => { failed += 1; diff --git a/apps/desktop/src-tauri/Cargo.toml b/apps/desktop/src-tauri/Cargo.toml index a5572b8197c..bf7c7fcf24d 100644 --- a/apps/desktop/src-tauri/Cargo.toml +++ b/apps/desktop/src-tauri/Cargo.toml @@ -153,6 +153,7 @@ cap-camera-ffmpeg = { path = "../../../crates/camera-ffmpeg" } [target.'cfg(not(all(target_os = "macos", target_arch = "x86_64")))'.dependencies] parakeet-rs = "0.3.4" +hound = "3.5" [target.'cfg(target_os = "linux")'.dependencies] libappindicator = "0.9.0" diff --git a/apps/desktop/src-tauri/src/captions.rs b/apps/desktop/src-tauri/src/captions.rs index b64305aa478..27bcbe38cb9 100644 --- a/apps/desktop/src-tauri/src/captions.rs +++ b/apps/desktop/src-tauri/src/captions.rs @@ -865,6 +865,22 @@ fn normalize_caption_words(words: Vec) -> Vec { normalized } +#[cfg(not(all(target_os = "macos", target_arch = "x86_64")))] +fn end_words_where_speech_stops(words: &mut [CaptionWord], pauses: &cap_audio::SpeechPauses) { + let mut moved = 0; + for word in words.iter_mut() { + let end = pauses.audible_end(word.start, word.end); + if end < word.end { + word.end = end; + moved += 1; + } + } + tracing::info!( + "Ended {moved} of {} words where their speech stops", + words.len() + ); +} + fn caption_text_from_words<'a>(words: impl IntoIterator) -> String { let mut text = String::new(); @@ -1284,19 +1300,35 @@ fn process_with_parakeet( } }; + let mut reader = hound::WavReader::open(audio_path) + .map_err(|e| format!("Failed to open audio file: {e} at path: {audio_path:?}"))?; + let spec = reader.spec(); + if spec.channels != 1 || spec.sample_rate != WHISPER_SAMPLE_RATE { + return Err(format!( + "Expected 16 kHz mono audio, got {} Hz with {} channels", + spec.sample_rate, spec.channels + )); + } + let samples = reader + .samples::() + .map(|sample| sample.map(|sample| f32::from(sample) / 32768.0)) + .collect::, _>>() + .map_err(|e| format!("Failed to read audio file: {e}"))?; + let pauses = cap_audio::SpeechPauses::detect(&samples, spec.sample_rate); + let result = { let mut parakeet = model_arc .lock() .map_err(|e| format!("Failed to lock Parakeet model: {e}"))?; parakeet - .transcribe_file(audio_path, Some(TimestampMode::Words)) + .transcribe_samples(samples, spec.sample_rate, 1, Some(TimestampMode::Words)) .map_err(|e| format!("Parakeet transcription failed: {e}"))? }; tracing::info!("Transcription text: {}", result.text); tracing::info!("Got {} timed tokens", result.tokens.len()); - let words = normalize_caption_words( + let mut words = normalize_caption_words( result .tokens .iter() @@ -1308,6 +1340,10 @@ fn process_with_parakeet( }) .collect(), ); + match &pauses { + Some(pauses) => end_words_where_speech_stops(&mut words, pauses), + None => tracing::info!("Speech is not clearly above the noise; keeping word ends"), + } if words.is_empty() { tracing::warn!("Parakeet produced no words"); @@ -2885,9 +2921,40 @@ mod tests { #[cfg(not(all(target_os = "macos", target_arch = "x86_64")))] mod parakeet { - use super::super::parakeet_model_dir_matches; + use super::super::{CaptionWord, end_words_where_speech_stops, parakeet_model_dir_matches}; use tempfile::tempdir; + #[test] + fn stretched_words_end_where_their_speech_stops() { + let mut samples = vec![0.0_f32; 16_000 * 4]; + for (index, sample) in samples.iter_mut().enumerate() { + let time = index as f32 / 16_000.0; + if (1.0..1.5).contains(&time) || (2.5..3.0).contains(&time) { + *sample = 0.1 * (std::f32::consts::TAU * 220.0 * time).sin(); + } + } + let pauses = + cap_audio::SpeechPauses::detect(&samples, 16_000).expect("speech is audible"); + let mut words = vec![ + CaptionWord { + text: "hello".to_string(), + start: 1.0, + end: 2.5, + }, + CaptionWord { + text: "world.".to_string(), + start: 2.5, + end: 3.0, + }, + ]; + + end_words_where_speech_stops(&mut words, &pauses); + + assert_eq!(words[0].start, 1.0); + assert!((words[0].end - 1.6).abs() < 0.02, "{}", words[0].end); + assert_eq!((words[1].start, words[1].end), (2.5, 3.0)); + } + #[test] fn parakeet_model_dir_match_uses_full_directory_path() { let dir = tempdir().unwrap(); 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..c510f51266a 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,24 @@ 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, + recordingAudio, + type SourceRange, + type TranscriptCutEdit, + type TranscriptItem, + transcriptPlanContext, +} from "./transcript-cuts"; import { deleteTranscriptWords, type FlatWord, @@ -43,11 +64,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 +71,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, @@ -67,13 +90,45 @@ export function TranscriptPanel() { previewResolutionBase, playbackIntent, requestHandoffPlayback, + micWaveforms, + systemAudioWaveforms, } = useEditorContext(); const recordingSegments = () => editorInstance.recordings.segments; + const recordedAudio = createMemo(() => { + const mic = micWaveforms(); + const system = systemAudioWaveforms(); + return recordingAudio( + 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", }); + 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 +142,55 @@ 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(), + recordedAudio(), + ), + ); + + 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 +199,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 +224,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 +321,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 +331,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 +357,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 +394,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 +575,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 +740,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 +789,11 @@ 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 +1174,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 +1246,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 +1281,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 +1346,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 +1377,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 +1419,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/clip-transitions.ts b/apps/desktop/src/routes/editor/clip-transitions.ts index ecca62ae6b8..05e51f31323 100644 --- a/apps/desktop/src/routes/editor/clip-transitions.ts +++ b/apps/desktop/src/routes/editor/clip-transitions.ts @@ -185,6 +185,7 @@ export function clipCutPreservesTransitionGeometry( segmentIndex: number, cutStart: number, cutEnd: number, + tolerance = Number.EPSILON, ) { const segment = segments[segmentIndex]; if (!segment) return false; @@ -193,15 +194,19 @@ export function clipCutPreservesTransitionGeometry( const duration = clipDuration(segment); const localStart = cutStart - segmentStart; const localEnd = cutEnd - segmentStart; - if (localStart < 0 || localEnd > duration || localStart >= localEnd) + if ( + localStart < -tolerance || + localEnd > duration + tolerance || + localStart >= localEnd + ) return false; const incomingDuration = getClipTransition(segments, transitions, segmentIndex)?.duration ?? 0; const outgoingDuration = getClipTransition(segments, transitions, segmentIndex + 1)?.duration ?? 0; return ( - localStart + Number.EPSILON >= incomingDuration * 2 && - duration - localEnd + Number.EPSILON >= outgoingDuration * 2 + localStart + tolerance >= incomingDuration * 2 && + duration - localEnd + tolerance >= outgoingDuration * 2 ); } 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..71948f8c037 --- /dev/null +++ b/apps/desktop/src/routes/editor/filler-detection.ts @@ -0,0 +1,71 @@ +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", +]); + +// "err" is a verb and an all-caps "ER" an acronym, yet both collapse to the +// filler "er". Drawn-out forms like "errr" or "UMMM" still count. +const NOT_FILLERS = new Set(["err"]); + +export function isFillerWord(text: string): boolean { + const letters = text.replace(/[^a-z]/gi, ""); + if ( + letters.length > 1 && + letters === letters.toUpperCase() && + !/(.)\1/.test(letters) + ) + return false; + const lower = letters.toLowerCase(); + return ( + !NOT_FILLERS.has(lower) && FILLER_WORDS.has(lower.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..67b794abe4c --- /dev/null +++ b/apps/desktop/src/routes/editor/transcript-cuts.test.ts @@ -0,0 +1,2351 @@ +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, + cutClaim, + cutPaddingLimits, + cutPaddingRoom, + intersectSourceRanges, + mergeSourceRanges, + planAutoClean, + planPauseCut, + planWordCuts, + type RecordingAudio, + recordingAudio, + type SourceRange, + 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].start).toBeCloseTo(4.7); + expect(p.timeline?.textSegments[0].end).toBeCloseTo(6.7); + expect(p.timeline?.zoomSegments[0].start).toBeCloseTo(7.9); + expect(p.timeline?.zoomSegments[0].end).toBeCloseTo(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"]); + }); + + it("drops the pause between cut words once their padding takes the silence", () => { + const recs = recordings(10); + const p = project( + [ + ["hello", 1.0, 1.4], + ["um", 1.6, 1.9], + ["uh", 2.6, 2.8], + ["world", 3.0, 3.4], + ], + [clip(0, 10)], + ); + const pauses = () => + context(p, recs).items.flatMap((item) => + item.type === "pause" + ? [[Number(item.start.toFixed(6)), Number(item.end.toFixed(6))]] + : [], + ); + cut(p, recs, "um"); + cut(p, recs, "uh"); + expect(pauses()).toEqual([ + [0, 1], + [1.9, 2.6], + ]); + + commitTranscriptCutEdit( + p, + { + padding: [ + { id: cutRecord(p, "um").id, bufferStart: 0, bufferEnd: 0.3 }, + { id: cutRecord(p, "uh").id, bufferStart: 0.3, bufferEnd: 0 }, + ], + }, + recs, + ); + expect(clips(p)).toEqual([ + [0, 1.6], + [2.2, 2.3], + [2.8, 10], + ]); + expect(pauses()).toEqual([[0, 1]]); + }); +}); + +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("pauses heard in the recording", () => { + const SPEECH_DB = -20; + const ROOM_DB = -58; + + function levels( + duration: number, + speech: Array<[number, number]>, + quiet = ROOM_DB, + loud = SPEECH_DB, + ) { + return Array.from({ length: Math.round(duration * 10) }, (_, block) => + speech.some( + ([start, end]) => block / 10 < end && (block + 1) / 10 > start, + ) + ? loud + : quiet, + ); + } + + function heard(recs: SegmentRecordings[], speech: Array<[number, number]>) { + return recordingAudio(recs, [ + [{ levels: levels(recs[0].display.duration, speech), offset: 0 }], + ]); + } + + function audioContext( + p: Project, + recs: SegmentRecordings[], + audio: RecordingAudio, + ) { + return { + ...transcriptPlanContext(p, recs, undefined, audio), + createId, + }; + } + + function pauses(items: readonly TranscriptItem[]) { + return items.flatMap((item) => + item.type === "pause" + ? [[Number(item.start.toFixed(6)), Number(item.end.toFixed(6))]] + : [], + ); + } + + const rounded = (ranges: readonly SourceRange[]) => + ranges.map((range) => [ + Number(range.start.toFixed(6)), + Number(range.end.toFixed(6)), + ]); + + it("finds where every track is quiet and where one is audible, across recordings and clip offsets", () => { + const recs = recordings(4, 2, 1); + const audio = recordingAudio(recs, [ + [ + { + levels: levels(4, [ + [0, 1], + [2, 2.5], + ]), + offset: 0, + }, + { levels: levels(4, [[1.5, 1.7]]), offset: 0.2 }, + ], + [{ levels: levels(2, [[0.5, 1]]), offset: 0 }], + [], + ]); + expect(rounded(audio.silence)).toEqual([ + [1, 1.3], + [1.5, 2], + [2.5, 4.5], + [5, 6], + ]); + expect(rounded(audio.audible)).toEqual([ + [0, 1], + [1.3, 1.5], + [2, 2.5], + [4.5, 5], + ]); + }); + + it("knows neither silence nor sound without waveforms or without speech clearly above the noise", () => { + const recs = recordings(4); + const unknown = { silence: [], audible: [] }; + expect(recordingAudio(recs, [])).toEqual(unknown); + expect(recordingAudio(recs, [[{ levels: [], offset: 0 }]])).toEqual( + unknown, + ); + expect( + recordingAudio(recs, [ + [{ levels: levels(4, [[1, 3]], -50, -50), offset: 0 }], + ]), + ).toEqual(unknown); + expect( + recordingAudio(recs, [ + [{ levels: levels(4, [[1, 3]], ROOM_DB, -48), offset: 0 }], + ]), + ).toEqual(unknown); + }); + + it("starts the pause where the audio goes quiet, even under a word stamped late", () => { + const recs = recordings(8); + const p = project( + [ + ["these", 1.0, 1.3], + ["two?", 1.3, 3.8], + ["See", 5.0, 5.4], + ["now", 5.4, 5.8], + ], + [clip(0, 8)], + ); + const audio = heard(recs, [ + [1.0, 1.2], + [5.0, 5.8], + ]); + expect(pauses(context(p, recs).items)).toEqual([ + [0, 1], + [3.8, 5], + ]); + const ctx = audioContext(p, recs, audio); + expect(pauses(ctx.items)).toEqual([ + [0, 1], + [1.4, 5], + ]); + + const pause = ctx.items.find( + (item) => item.type === "pause" && item.start > 1, + ); + if (pause?.type !== "pause") throw new Error("No pause"); + expect(commitTranscriptCutEdit(p, planPauseCut(ctx, pause), recs)).toBe( + "applied", + ); + expect(clips(p)).toEqual([ + [0, 1.4], + [5, 8], + ]); + expect(liveWords(p)).toEqual(["these", "two?", "See", "now"]); + expect(p.captions?.segments[0].words?.[1].end).toBeCloseTo(1.4); + + commitTranscriptCutEdit( + p, + { restore: [p.captions?.transcriptCuts?.[0]?.id ?? ""] }, + recs, + ); + expect(clips(p)).toEqual([[0, 8]]); + expect(p.captions?.segments[0].words?.[1]).toMatchObject({ + text: "two?", + end: 3.8, + }); + }); + + it("finds a pause the transcript hides entirely inside a word", () => { + const recs = recordings(4); + const p = project( + [ + ["so", 1.0, 2.4], + ["next", 2.4, 2.8], + ], + [clip(0, 4)], + ); + const audio = heard(recs, [ + [1.0, 1.4], + [2.4, 2.8], + ]); + expect(pauses(context(p, recs).items)).toEqual([[0, 1]]); + expect(pauses(audioContext(p, recs, audio).items)).toEqual([ + [0, 1], + [1.5, 2.4], + ]); + }); + + it("never reaches into audio that runs up to the next word", () => { + const recs = recordings(4); + const p = project( + [ + ["so", 1.0, 2.4], + ["next", 2.4, 2.8], + ], + [clip(0, 4)], + ); + expect( + pauses(audioContext(p, recs, heard(recs, [[1.0, 2.8]])).items), + ).toEqual([[0, 1]]); + const early: Array<[number, number]> = [ + [1.0, 1.4], + [2.3, 2.8], + ]; + expect(pauses(audioContext(p, recs, heard(recs, early)).items)).toEqual([ + [0, 1], + [1.5, 2.3], + ]); + }); + + it("lets Auto Clean take the silence a stretched word hides before a filler", () => { + const recs = recordings(5); + const words: Array<[string, number, number]> = [ + ["so", 1.0, 2.0], + ["um", 2.0, 2.3], + ["right", 2.3, 2.7], + ]; + const audio = heard(recs, [ + [1.0, 1.3], + [2.0, 2.7], + ]); + + const transcriptOnly = project(words, [clip(0, 5)]); + const plain = planAutoClean(context(transcriptOnly, recs), 5).edit; + if (!plain) throw new Error("Nothing planned"); + commitTranscriptCutEdit(transcriptOnly, plain, recs); + expect(clips(transcriptOnly)).toEqual([ + [0, 2], + [2.3, 5], + ]); + + const p = project(words, [clip(0, 5)]); + const { edit } = planAutoClean(audioContext(p, recs, audio), 5); + if (!edit) throw new Error("Nothing planned"); + expect(commitTranscriptCutEdit(p, edit, recs)).toBe("applied"); + expect(clips(p)).toEqual([ + [0, 1.4], + [2.3, 5], + ]); + expect(liveWords(p)).toEqual(["so", "right"]); + expect(p.captions?.segments[0].words?.[0].end).toBeCloseTo(1.4); + }); + + it("keeps speech the transcript missed out of the pauses Auto Clean cuts", () => { + const recs = recordings(6); + const p = project( + [ + ["hello", 1.0, 1.4], + ["again", 4.0, 4.4], + ], + [clip(0, 6)], + ); + expect(pauses(context(p, recs).items)).toEqual([ + [0, 1], + [1.4, 4], + ]); + const ctx = audioContext( + p, + recs, + heard(recs, [ + [1.0, 1.3], + [2.0, 3.0], + [4.0, 4.4], + ]), + ); + expect(pauses(ctx.items)).toEqual([ + [0, 1], + [1.4, 2], + [3, 4], + ]); + expect(planAutoClean(ctx, 1.5)).toEqual({ edit: null, skipped: 0 }); + + const { edit } = planAutoClean(ctx, 0.5); + if (!edit) throw new Error("Nothing planned"); + expect(commitTranscriptCutEdit(p, edit, recs)).toBe("applied"); + expect(clips(p)).toEqual([ + [1, 1.4], + [2, 3], + [4, 6], + ]); + }); + + it("cuts a filler with only the quiet beside it, not speech the transcript missed", () => { + const recs = recordings(6); + const words: Array<[string, number, number]> = [ + ["hello", 1.0, 1.4], + ["um", 4.0, 4.3], + ["right", 4.4, 4.8], + ]; + + const transcriptOnly = project(words, [clip(0, 6)]); + const plain = planAutoClean(context(transcriptOnly, recs), 5).edit; + if (!plain) throw new Error("Nothing planned"); + commitTranscriptCutEdit(transcriptOnly, plain, recs); + expect(clips(transcriptOnly)).toEqual([ + [0, 1.4], + [4.4, 6], + ]); + + const p = project(words, [clip(0, 6)]); + const audio = heard(recs, [ + [1.0, 1.3], + [2.0, 3.0], + [3.9, 4.8], + ]); + const { edit } = planAutoClean(audioContext(p, recs, audio), 5); + if (!edit) throw new Error("Nothing planned"); + expect(commitTranscriptCutEdit(p, edit, recs)).toBe("applied"); + expect(clips(p)).toEqual([ + [0, 3], + [4.4, 6], + ]); + expect(liveWords(p)).toEqual(["hello", "right"]); + }); + + it("leaves a kept word's audible end to it when the filler after it is cut", () => { + const recs = recordings(5); + const p = project( + [ + ["hello", 1.0, 1.3], + ["um", 2.0, 2.3], + ["right", 2.3, 2.7], + ], + [clip(0, 5)], + ); + const audio = heard(recs, [ + [1.0, 1.6], + [2.0, 2.7], + ]); + const { edit } = planAutoClean(audioContext(p, recs, audio), 5); + if (!edit) throw new Error("Nothing planned"); + expect(commitTranscriptCutEdit(p, edit, recs)).toBe("applied"); + expect(clips(p)).toEqual([ + [0, 1.6], + [2.3, 5], + ]); + }); + + it("joins cut words across audio an earlier cut already took", () => { + const recs = recordings(5); + const p = project( + [ + ["hello", 1.0, 1.4], + ["big", 1.5, 1.8], + ["world", 2.2, 2.5], + ], + [clip(0, 5)], + ); + const audio = heard(recs, [ + [1.0, 1.8], + [1.9, 2.0], + [2.2, 2.5], + ]); + const cutWord = (text: string) => { + const ctx = audioContext(p, recs, audio); + const edit = planWordCuts(ctx, [token(ctx.items, text)]); + if (!edit) throw new Error(`Nothing to cut for ${text}`); + return commitTranscriptCutEdit(p, edit, recs); + }; + expect(cutWord("big")).toBe("applied"); + commitTranscriptCutEdit( + p, + { + padding: [ + { id: cutRecord(p, "big").id, bufferStart: 0, bufferEnd: 0.2 }, + ], + }, + recs, + ); + expect(clips(p)).toEqual([ + [0, 1.5], + [2, 5], + ]); + + expect(cutWord("world")).toBe("applied"); + expect(clips(p)).toEqual([ + [0, 1.5], + [2.5, 5], + ]); + }); + + it("finds the pause after a stretched word when the next word starts between waveform blocks", () => { + const recs = recordings(5); + for (const next of [2.5, 2.53, 2.58]) { + const p = project( + [ + ["the", 1.0, next], + ["and", next, next + 0.4], + ], + [clip(0, 5)], + ); + const audio = heard(recs, [ + [1.0, 1.3], + [next, next + 0.4], + ]); + expect(pauses(audioContext(p, recs, audio).items)).toEqual([ + [0, 1], + [1.4, 2.5], + ]); + } + }); + + it("ends a pause where the next word becomes audible, not at its late stamp", () => { + const recs = recordings(5); + const p = project( + [ + ["so", 1.0, 1.3], + ["and", 3.2, 3.6], + ], + [clip(0, 5)], + ); + const ctx = audioContext( + p, + recs, + heard(recs, [ + [1.0, 1.3], + [3.0, 3.6], + ]), + ); + expect(pauses(ctx.items)).toEqual([ + [0, 1], + [1.3, 3], + ]); + const pause = ctx.items.find( + (item) => item.type === "pause" && item.start > 1, + ); + if (pause?.type !== "pause") throw new Error("No pause"); + expect(commitTranscriptCutEdit(p, planPauseCut(ctx, pause), recs)).toBe( + "applied", + ); + expect(clips(p)).toEqual([ + [0, 1.3], + [3, 5], + ]); + }); + + it("gives a word back its full length when it was cut after a pause cut trimmed it", () => { + const recs = recordings(6); + const speech: Array<[number, number]> = [ + [1.0, 1.3], + [2.0, 2.5], + [4.5, 4.9], + ]; + for (const together of [false, true]) { + const p = project( + [ + ["the", 1.0, 1.3], + ["that", 2.0, 4.5], + ["and", 4.5, 4.9], + ], + [clip(0, 6)], + ); + const ctx = audioContext(p, recs, heard(recs, speech)); + const pause = ctx.items.find( + (item) => item.type === "pause" && item.start > 2, + ); + if (pause?.type !== "pause") throw new Error("No pause"); + commitTranscriptCutEdit(p, planPauseCut(ctx, pause), recs); + expect(p.captions?.segments[0].words?.[1].end).toBeCloseTo(2.6); + expect(cut(p, recs, "that")).toBe("applied"); + + const [pauseCut, wordCut] = (p.captions?.transcriptCuts ?? []).map( + (record) => record.id, + ); + if (together) { + commitTranscriptCutEdit(p, { restore: [pauseCut, wordCut] }, recs); + } else { + commitTranscriptCutEdit(p, { restore: [pauseCut] }, recs); + commitTranscriptCutEdit(p, { restore: [wordCut] }, recs); + } + expect(clips(p)).toEqual([[0, 6]]); + expect(p.captions?.segments[0].words?.[1]).toMatchObject({ + text: "that", + end: 4.5, + }); + } + }); +}); + +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); + + const pause = (id: string, start: number, end: number): TranscriptCut => ({ + id, + kind: "pause", + text: "", + start, + end, + bufferStart: 0, + bufferEnd: 0, + segmentId: null, + }); + + 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("keeps a shrunk cut's overlays for both the part that returns and the part still cut", () => { + const sorted = (segments: Array<{ start: number; end: number }> = []) => + spans(segments).sort((a, b) => a[0] - b[0]); + const zooms = [ + zoom(1.5, 2.1), + zoom(2.15, 2.25), + zoom(2.3, 2.8), + zoom(3, 4), + zoom(5.5, 7), + ]; + for (const [bufferStart, bufferEnd, shrunk] of [ + [ + -0.5, + 0, + [ + [1.5, 2.1], + [2.15, 2.25], + [2.3, 2.5], + [2.5, 3.5], + ], + ], + [ + -0.5, + -0.5, + [ + [1.5, 2.1], + [2.15, 2.25], + [2.3, 2.5], + [2.5, 4], + ], + ], + ] as const) { + const recs = recordings(10); + const p = project( + [ + ["first", 1.5, 2.0], + ["next", 6.0, 6.4], + ], + [clip(0, 10)], + { zoomSegments: structuredClone(zooms) }, + ); + cutPauseAt(p, recs, 2); + const [id] = cutIds(p); + expect( + commitTranscriptCutEdit( + p, + { padding: [{ id, bufferStart, bufferEnd }] }, + recs, + ), + ).toBe("applied"); + expect(sorted(p.timeline?.zoomSegments)).toEqual(shrunk); + + expect(restore(p, recs, id)).toBe("applied"); + expect(clips(p)).toEqual([[0, 10]]); + expect(sorted(p.timeline?.zoomSegments)).toEqual(sorted(zooms)); + expect(p.captions?.transcriptCuts).toEqual([]); + } + }); + + it("keeps a fullscreen text hold that stays inside a shrunk cut", () => { + const recs = recordings(10); + const hold = { ...defaultTextSegment(3, 4), layout: "fullscreen" as const }; + const p = project( + [ + ["intro", 0.5, 1.0], + ["after", 8.0, 8.4], + ], + [clip(0, 10)], + { textSegments: [hold], zoomSegments: [zoom(9.5, 10.5)] }, + ); + cutPauseAt(p, recs, 1); + const [id] = cutIds(p); + commitTranscriptCutEdit( + p, + { padding: [{ id, bufferStart: -0.5, bufferEnd: 0 }] }, + recs, + ); + expect(clips(p)).toEqual([ + [0, 1.5], + [8, 10], + ]); + expect(p.timeline?.textSegments).toEqual([]); + expect(spans(p.timeline?.zoomSegments)).toEqual([[2, 3]]); + + restore(p, recs, 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([[9.5, 10.5]]); + }); + + it("shrinks a cut across a speed change and returns both clips exactly", () => { + const recs = recordings(10); + const p = project( + [ + ["hello", 0.5, 0.9], + ["next", 5.0, 5.3], + ], + [clip(0, 2.1), clip(2.1, 10, { timescale: 2 })], + { zoomSegments: [zoom(1.2, 1.5), zoom(3, 3.5)] }, + ); + cutPauseAt(p, recs, 0.9); + const [id] = cutIds(p); + expect(p.captions?.transcriptCuts?.[0].removed).toHaveLength(2); + commitTranscriptCutEdit( + p, + { padding: [{ id, bufferStart: -0.5, bufferEnd: 0 }] }, + recs, + ); + expect(clips(p)).toEqual([ + [0, 1.4], + [5, 10], + ]); + expect(spans(p.timeline?.zoomSegments)).toEqual([[1.2, 1.4]]); + + restore(p, recs, id); + expect(clips(p)).toEqual([ + [0, 2.1], + [2.1, 10], + ]); + expect(p.timeline?.segments.map((segment) => segment.timescale)).toEqual([ + 1, 2, + ]); + expect(spans(p.timeline?.zoomSegments)).toEqual([ + [1.2, 1.5], + [3, 3.5], + ]); + }); + + it("hands the rest of a restored cut's footage and overlays to the cut still claiming it", () => { + const recs = recordings(10); + const p = project(helloWorld, [clip(0, 10)], { + zoomSegments: [zoom(3.2, 3.6)], + }); + commitTranscriptCutEdit(p, { add: [pause("first", 2, 4)] }, recs); + commitTranscriptCutEdit(p, { add: [pause("second", 3, 5)] }, recs); + expect(clips(p)).toEqual([ + [0, 2], + [5, 10], + ]); + + restore(p, recs, "first"); + expect(clips(p)).toEqual([ + [0, 3], + [5, 10], + ]); + expect(p.timeline?.zoomSegments).toEqual([]); + + restore(p, recs, "second"); + expect(clips(p)).toEqual([[0, 10]]); + expect(spans(p.timeline?.zoomSegments)).toEqual([[3.2, 3.6]]); + }); + + it("restores an earlier cut's mask movements while a later cut on the same mask stays", () => { + const recs = recordings(10); + const p = project(helloWorld, [clip(0, 10)], { + maskSegments: [ + { + ...defaultMaskSegment(1, 9), + keyframes: { + position: [ + { time: 0.5, x: 0.1, y: 0.1 }, + { time: 1.5, x: 0.2, y: 0.2 }, + { time: 3.0, x: 0.3, y: 0.3 }, + { time: 4.5, x: 0.4, y: 0.4 }, + { time: 7.0, x: 0.5, y: 0.5 }, + ], + size: [], + intensity: [], + }, + }, + ], + }); + const mask = () => { + const segment = p.timeline?.maskSegments[0]; + return { + end: Number(segment?.end.toFixed(6)), + times: segment?.keyframes?.position?.map((keyframe) => + Number(keyframe.time.toFixed(6)), + ), + }; + }; + commitTranscriptCutEdit(p, { add: [pause("first", 2, 3)] }, recs); + commitTranscriptCutEdit(p, { add: [pause("second", 5, 6)] }, recs); + expect(mask()).toEqual({ end: 7, times: [0.5, 2, 5] }); + + restore(p, recs, "first"); + expect(clips(p)).toEqual([ + [0, 5], + [6, 10], + ]); + expect(mask()).toEqual({ end: 8, times: [0.5, 1.5, 3, 6] }); + + restore(p, recs, "second"); + expect(clips(p)).toEqual([[0, 10]]); + expect(mask()).toEqual({ end: 9, times: [0.5, 1.5, 3, 4.5, 7] }); + }); + + it("restores cuts sharing overlays exactly, in any order", () => { + const recs = recordings(12); + const words: Array<[string, number, number]> = [ + ["intro", 0.2, 0.6], + ["outro", 11.2, 11.6], + ]; + const fresh = () => + project(words, [clip(0, 12)], { + zoomSegments: [zoom(1.5, 10.5), zoom(5.5, 6.5)], + maskSegments: [ + { + ...defaultMaskSegment(1, 11), + keyframes: { + position: [0.5, 1.5, 2.5, 4.5, 5.5, 7.5, 8.5, 9.5].map( + (time, index) => ({ time, x: index / 10, y: index / 10 }), + ), + size: [], + intensity: [], + }, + }, + ], + }); + const cuts = [pause("a", 2, 3), pause("b", 6, 7), pause("c", 9, 10)]; + const state = (p: Project) => ({ + clips: clips(p), + zooms: spans(p.timeline?.zoomSegments).sort((x, y) => x[0] - y[0]), + masks: p.timeline?.maskSegments.map((segment) => ({ + start: Number(segment.start.toFixed(6)), + end: Number(segment.end.toFixed(6)), + times: segment.keyframes?.position?.map((keyframe) => + Number(keyframe.time.toFixed(6)), + ), + })), + }); + const expected = (ids: readonly string[]) => { + const p = fresh(); + const add = cuts.filter((cut) => ids.includes(cut.id)); + if (add.length > 0) commitTranscriptCutEdit(p, { add }, recs); + return state(p); + }; + const orders = [ + ["a", "b", "c"], + ["a", "c", "b"], + ["b", "a", "c"], + ["b", "c", "a"], + ["c", "a", "b"], + ["c", "b", "a"], + ]; + for (const batch of [false, true]) { + for (const order of orders) { + const p = fresh(); + if (batch) commitTranscriptCutEdit(p, { add: cuts }, recs); + else + for (const cut of cuts) + commitTranscriptCutEdit(p, { add: [cut] }, recs); + expect(state(p)).toEqual(expected(["a", "b", "c"])); + const remaining = ["a", "b", "c"]; + for (const id of order) { + expect(restore(p, recs, id)).toBe("applied"); + remaining.splice(remaining.indexOf(id), 1); + expect(state(p)).toEqual(expected(remaining)); + } + expect(p.captions?.transcriptCuts).toEqual([]); + } + } + }); + + it("moves an overlay an adjacent cut trimmed when the other cut comes back", () => { + const recs = recordings(20); + const p = project( + [ + ["intro", 0.1, 0.3], + ["outro", 19.6, 19.9], + ], + [clip(0, 20)], + { zoomSegments: [zoom(5.15, 8.85)] }, + ); + commitTranscriptCutEdit(p, { add: [pause("first", 2.7, 4.4)] }, recs); + commitTranscriptCutEdit(p, { add: [pause("second", 4.4, 5.3)] }, recs); + expect(spans(p.timeline?.zoomSegments)).toEqual([[2.7, 6.25]]); + + restore(p, recs, "first"); + expect(spans(p.timeline?.zoomSegments)).toEqual([[4.4, 7.95]]); + + restore(p, recs, "second"); + expect(spans(p.timeline?.zoomSegments)).toEqual([[5.15, 8.85]]); + }); + + it("restores an earlier cut's zoom trim while a later cut before it stays", () => { + const recs = recordings(10); + const p = project(helloWorld, [clip(0, 10)], { + zoomSegments: [zoom(2.5, 5.5)], + }); + commitTranscriptCutEdit(p, { add: [pause("first", 5, 6)] }, recs); + commitTranscriptCutEdit(p, { add: [pause("second", 2, 3)] }, recs); + expect(spans(p.timeline?.zoomSegments)).toEqual([[2, 4]]); + + restore(p, recs, "first"); + expect(clips(p)).toEqual([ + [0, 2], + [3, 10], + ]); + expect(spans(p.timeline?.zoomSegments)).toEqual([[2, 4.5]]); + + restore(p, recs, "second"); + expect(clips(p)).toEqual([[0, 10]]); + expect(spans(p.timeline?.zoomSegments)).toEqual([[2.5, 5.5]]); + }); + + it("puts footage cut up to a closing title back ahead of it", () => { + const recs = recordings(10); + const p = project( + [ + ["thanks", 8.0, 8.4], + ["bye", 9.0, 9.5], + ], + [clip(0, 10)], + { + textSegments: [ + { ...defaultTextSegment(10, 12), layout: "fullscreen" as const }, + ], + zoomSegments: [zoom(9.2, 11.5)], + }, + ); + cut(p, recs, "bye"); + const { id } = cutRecord(p, "bye"); + commitTranscriptCutEdit( + p, + { padding: [{ id, bufferStart: 0, bufferEnd: 0.5 }] }, + recs, + ); + expect(clips(p)).toEqual([[0, 9]]); + expect(spans(p.timeline?.textSegments)).toEqual([[9, 11]]); + + expect(restore(p, recs, id)).toBe("applied"); + expect(clips(p)).toEqual([[0, 10]]); + expect(spans(p.timeline?.textSegments)).toEqual([[10, 12]]); + expect(spans(p.timeline?.zoomSegments)).toEqual([[9.2, 11.5]]); + }); + + it("treats a closing title a hair off the clips' end as sitting at it", () => { + for (const offset of [-1e-12, 1e-12]) { + const recs = recordings(10); + const p = project( + [ + ["thanks", 8.0, 8.4], + ["bye", 9.0, 9.5], + ], + [clip(0, 10)], + { + textSegments: [ + { + ...defaultTextSegment(10 + offset, 12), + layout: "fullscreen" as const, + }, + ], + }, + ); + cut(p, recs, "bye"); + const { id } = cutRecord(p, "bye"); + commitTranscriptCutEdit( + p, + { padding: [{ id, bufferStart: 0, bufferEnd: 0.5 }] }, + recs, + ); + expect(spans(p.timeline?.textSegments)).toEqual([[9, 11]]); + + expect(restore(p, recs, id)).toBe("applied"); + expect(clips(p)).toEqual([[0, 10]]); + expect(spans(p.timeline?.textSegments)).toEqual([[10, 12]]); + } + }); + + it("keeps a fullscreen hold between two adjacent cuts in either restore order", () => { + for (const order of [ + ["first", "second"], + ["second", "first"], + ]) { + const recs = recordings(10); + const p = project( + [ + ["intro", 0.5, 1.0], + ["outro", 9.0, 9.4], + ], + [clip(0, 10)], + { + textSegments: [ + { ...defaultTextSegment(4, 5), layout: "fullscreen" as const }, + ], + zoomSegments: [zoom(3.5, 6.5)], + }, + ); + commitTranscriptCutEdit(p, { add: [pause("first", 3, 4)] }, recs); + commitTranscriptCutEdit(p, { add: [pause("second", 4, 5)] }, recs); + expect(clips(p)).toEqual([ + [0, 3], + [5, 10], + ]); + expect(spans(p.timeline?.textSegments)).toEqual([[3, 4]]); + + expect(restore(p, recs, order[0])).toBe("applied"); + expect(spans(p.timeline?.textSegments)).toEqual([ + order[0] === "first" ? [4, 5] : [3, 4], + ]); + expect(restore(p, recs, order[1])).toBe("applied"); + expect(clips(p)).toEqual([[0, 10]]); + expect(spans(p.timeline?.textSegments)).toEqual([[4, 5]]); + expect(spans(p.timeline?.zoomSegments)).toEqual([[3.5, 6.5]]); + } + }); + + it("restores a cut that another cut overlaps by a sliver on a sped-up clip", () => { + const recs = recordings(10); + const p = project( + [ + ["intro", 0.2, 0.6], + ["outro", 9.2, 9.6], + ], + [clip(0, 10, { timescale: 2 })], + { zoomSegments: [zoom(1.75, 2.25)] }, + ); + commitTranscriptCutEdit(p, { add: [pause("second", 3, 5)] }, recs); + commitTranscriptCutEdit(p, { add: [pause("first", 2, 3.0015)] }, recs); + expect(clips(p)).toEqual([ + [0, 2], + [5, 10], + ]); + + expect(restore(p, recs, "second")).toBe("applied"); + expect(clips(p)).toEqual([ + [0, 2], + [3, 10], + ]); + expect(spans(p.timeline?.zoomSegments)).toEqual([[1.25, 1.75]]); + expect(p.captions?.transcriptRemoved).toEqual([{ start: 2, end: 3 }]); + + expect(restore(p, recs, "first")).toBe("applied"); + expect(clips(p)).toEqual([[0, 10]]); + expect(spans(p.timeline?.zoomSegments)).toEqual([[1.75, 2.25]]); + }); + + 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), + ); + }); + + it("restores a keyboard segment one cut at a time after a cut took all its keys", () => { + const recs = recordings(20); + for (const order of [ + ["w1", "w3", "w2"], + ["w3", "w1", "w2"], + ]) { + const p = project( + [ + ["w1", 2.9, 3.4], + ["w2", 3.6, 4.0], + ["w3", 4.4, 4.6], + ["tail", 9.0, 9.5], + ], + [clip(0, 20)], + { + keyboardSegments: [ + { + id: "keys", + start: 3, + end: 6, + displayText: "ab", + keys: [ + { key: "a", timeOffset: 0 }, + { key: "b", timeOffset: 1500 }, + ], + }, + ], + }, + ); + for (const word of order) cut(p, recs, word); + expect(p.timeline?.keyboardSegments).toEqual([]); + + expect(restore(p, recs, cutRecord(p, order[0]).id)).toBe("applied"); + expect(restore(p, recs, ...cutIds(p))).toBe("applied"); + expect(clips(p)).toEqual([[0, 20]]); + expect( + p.timeline?.keyboardSegments?.map((segment) => [ + ...spans([segment])[0], + segment.displayText, + ]), + ).toEqual([[3, 6, "ab"]]); + } + }); + + it("takes the sub-millisecond leftover a cut drops at a clip edge and gives it back", () => { + const recs = recordings(20); + const p = project( + [ + ["start", 1.0, 1.4], + ["edge", 11.952, 12.236], + ["after", 14.0, 14.4], + ], + [clip(0, 12.237), clip(12.998, 20)], + { zoomSegments: [zoom(11, 15)] }, + ); + expect(cut(p, recs, "edge")).toBe("applied"); + expect(clips(p)).toEqual([ + [0, 11.952], + [12.998, 20], + ]); + expect(cutClaim(cutRecord(p, "edge"))?.end).toBeCloseTo(12.237, 6); + + expect(restore(p, recs, cutRecord(p, "edge").id)).toBe("applied"); + expect(clips(p)).toEqual([ + [0, 12.237], + [12.998, 20], + ]); + expect(spans(p.timeline?.zoomSegments)).toEqual([[11, 15]]); + }); + + it("gives a restored word its footage back from padding that reached over it", () => { + const recs = recordings(20); + const p = project( + [ + ["hello", 1.0, 1.4], + ["it", 3.0, 3.5], + ["world", 6.0, 6.5], + ], + [clip(0, 20)], + ); + cut(p, recs, "it"); + expect(cutPauseAt(p, recs, 1.4)).toBe("applied"); + const gap = p.captions?.transcriptCuts?.find( + (record) => record.kind === "pause", + ); + if (!gap) throw new Error("No pause cut"); + commitTranscriptCutEdit( + p, + { padding: [{ id: gap.id, bufferStart: 0, bufferEnd: 0.5 }] }, + recs, + ); + expect(clips(p)).toEqual([ + [0, 1.4], + [3.5, 20], + ]); + + expect(restore(p, recs, cutRecord(p, "it").id)).toBe("applied"); + expect(liveWords(p)).toEqual(["hello", "it", "world"]); + expect(clips(p)).toEqual([ + [0, 1.4], + [3, 20], + ]); + }); + + it("gives a word the rest of its length once the cut still holding it comes back", () => { + const recs = recordings(10); + const p = project( + [ + ["it", 1.0, 4.0], + ["next", 4.0, 4.5], + ], + [clip(0, 10)], + ); + const cutRange = (start: number, end: number) => + commitTranscriptCutEdit( + p, + planPauseCut(context(p, recs), { start, end }), + recs, + ); + expect(cutRange(2.0, 3.0)).toBe("applied"); + expect(cutRange(3.0, 3.5)).toBe("applied"); + const [first, second] = cutIds(p); + + expect(restore(p, recs, first)).toBe("applied"); + expect(p.captions?.segments[0].words?.[0].end).toBeCloseTo(3.0); + expect(restore(p, recs, second)).toBe("applied"); + expect(clips(p)).toEqual([[0, 10]]); + expect(p.captions?.segments[0].words?.[0]).toMatchObject({ + text: "it", + end: 4, + }); + }); + + it("gives a cut no padding room into a kept word that overlaps it", () => { + const p = project( + [ + ["um", 3.0, 5.5], + ["and", 5.5, 5.9], + ], + [clip(0, 8)], + ); + expect(cutPaddingRoom(p.captions, { start: 3.6, end: 5.5 })).toEqual({ + before: 0, + after: 0, + }); + }); +}); + +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("keeps real words that collapse to a filler", () => { + for (const word of ["err", "Err,", "ER"]) + expect(isFillerWord(word)).toBe(false); + for (const word of ["Errr", "er", "UMMM"]) + expect(isFillerWord(word)).toBe(true); + }); + + 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..03b44086505 --- /dev/null +++ b/apps/desktop/src/routes/editor/transcript-cuts.ts @@ -0,0 +1,2027 @@ +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, + clipCutPreservesTransitionGeometry, + 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; +const EDGE_SNAP = 1e-9; + +const WAVEFORM_BLOCKS_PER_SECOND = 10; +const WAVEFORM_FLOOR_DB = -60; +const SILENCE_ABOVE_NOISE_DB = 6; +const MAX_SILENCE_DB = -45; +const MIN_SPEECH_HEADROOM_DB = 15; +const SPEECH_RELEASE = 0.1; +const MIN_WORD_SPEECH = 0.1; +const NEXT_ONSET = 0.25; + +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 type RecordedAudioTrack = { levels: readonly number[]; offset: number }; + +export type RecordingAudio = { + silence: readonly SourceRange[]; + audible: readonly SourceRange[]; +}; + +const UNKNOWN_AUDIO: RecordingAudio = { silence: [], audible: [] }; + +function waveformLevel(value: number | undefined) { + return typeof value === "number" && Number.isFinite(value) + ? Math.max(value, WAVEFORM_FLOOR_DB) + : WAVEFORM_FLOOR_DB; +} + +function percentile(sorted: readonly number[], fraction: number) { + return sorted[ + Math.min(sorted.length - 1, Math.floor(sorted.length * fraction)) + ]; +} + +function recordingBlockLevels( + duration: number, + tracks: readonly RecordedAudioTrack[], +): Array { + const sources = tracks.filter((track) => track.levels.length > 0); + const count = Math.ceil(duration * WAVEFORM_BLOCKS_PER_SECOND - 1e-6); + const levels: Array = []; + for (let block = 0; block < count; block++) { + let level: number | null = null; + for (const track of sources) { + const shift = track.offset * WAVEFORM_BLOCKS_PER_SECOND; + const first = Math.max(0, Math.floor(block + shift + 1e-6)); + const last = Math.min( + track.levels.length - 1, + Math.ceil(block + 1 + shift - 1e-6) - 1, + ); + for (let index = first; index <= last; index++) { + level = Math.max( + level ?? WAVEFORM_FLOOR_DB, + waveformLevel(track.levels[index]), + ); + } + } + levels.push(level); + } + return levels; +} + +function levelRuns( + levels: ReadonlyArray, + offset: number, + duration: number, + matches: (level: number) => boolean, +) { + const runs: SourceRange[] = []; + let runStart = -1; + for (let block = 0; block <= levels.length; block++) { + const level = levels[block]; + if (typeof level === "number" && matches(level)) { + if (runStart === -1) runStart = block; + continue; + } + if (runStart === -1) continue; + runs.push({ + start: offset + runStart / WAVEFORM_BLOCKS_PER_SECOND, + end: offset + Math.min(block / WAVEFORM_BLOCKS_PER_SECOND, duration), + }); + runStart = -1; + } + return runs; +} + +/** + * Source ranges where every recorded track is quiet, and where one is + * audible, from the editor's 100 ms waveform peaks. The threshold follows the + * recording's noise floor; when speech doesn't stand clearly above it, neither + * is known. Time without a waveform is neither. + */ +export function recordingAudio( + recordingSegments: SegmentRecordings[], + tracks: ReadonlyArray, +): RecordingAudio { + const offsets = recordingOffsets(recordingSegments); + const blocks = recordingSegments.map((recording, index) => + recordingBlockLevels(recording.display.duration, tracks[index] ?? []), + ); + const known = blocks + .flat() + .filter((level): level is number => level !== null) + .sort((a, b) => a - b); + if (known.length === 0) return UNKNOWN_AUDIO; + const threshold = Math.min( + percentile(known, 0.1) + SILENCE_ABOVE_NOISE_DB, + MAX_SILENCE_DB, + ); + if (percentile(known, 0.9) - threshold < MIN_SPEECH_HEADROOM_DB) + return UNKNOWN_AUDIO; + + const runs = (matches: (level: number) => boolean) => + mergeSourceRanges( + blocks.flatMap((levels, index) => + levelRuns( + levels, + offsets[index], + recordingSegments[index].display.duration, + matches, + ), + ), + ); + return { + silence: runs((level) => level < threshold), + audible: runs((level) => level >= threshold), + }; +} + +function silenceAround(silence: readonly SourceRange[], time: number) { + let low = 0; + let high = silence.length; + while (low < high) { + const mid = (low + high) >>> 1; + if (silence[mid].end < time - RANGE_EPSILON) low = mid + 1; + else high = mid; + } + const range = silence[low]; + return range && range.start < time - RANGE_EPSILON ? range : undefined; +} + +function silenceEndingBefore(silence: readonly SourceRange[], time: number) { + let low = 0; + let high = silence.length; + while (low < high) { + const mid = (low + high) >>> 1; + if (silence[mid].end <= time + RANGE_EPSILON) low = mid + 1; + else high = mid; + } + const range = silence[low - 1]; + return range && range.end >= time - NEXT_ONSET ? range : undefined; +} + +// parakeet-rs ends each token where the next begins, so a word's end runs +// through the silence after it (up to MAX_CAPTION_WORD_DURATION); only the +// audio shows where speech stopped. Its timestamps also drift ~0.2s either +// way, so a word can sit wholly in that silence: it keeps a sliver so a cut +// there trims it rather than swallowing it. The waveform comes in 100 ms +// blocks, so the next word's start (where this word's end was stretched to) +// usually lands in the block where it becomes audible, just past the silence. +function audibleWordEnd( + word: { start: number; end: number }, + silence: readonly SourceRange[], +) { + const end = spokenWordEnd(word); + const quiet = + silenceAround(silence, end) ?? silenceBeforeOnset(word, end, silence); + if (!quiet) return end; + return Math.min( + end, + Math.max(quiet.start + SPEECH_RELEASE, word.start + MIN_WORD_SPEECH), + ); +} + +function silenceBeforeOnset( + word: { start: number; end: number }, + end: number, + silence: readonly SourceRange[], +) { + const quiet = silenceEndingBefore(silence, end); + if (!quiet || quiet.start <= word.start + RANGE_EPSILON) return undefined; + const heard = sourceRangesDuration( + subtractSourceRanges([{ start: word.start, end: quiet.start }], silence), + ); + return end - quiet.end > heard ? undefined : quiet; +} + +// A word stamped after it became audible starts where the silence before it +// ends, so a pause cut stops short of its first syllable. +function audibleWordStart( + word: { start: number; end: number }, + silence: readonly SourceRange[], +) { + if (silenceAround(silence, word.start)) return word.start; + return silenceEndingBefore(silence, word.start)?.end ?? word.start; +} + +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); + else { + if (range.start < cut.start) before = 0; + if (range.end > cut.end) after = 0; + } + } + 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 }; +} + +// Restoring a cut brings its footage back even where another cut's padding +// had reached over it, so that padding gives way. +function clearOf( + cut: TranscriptCut, + ranges: readonly SourceRange[], +): TranscriptCut { + let bufferStart = cut.bufferStart ?? 0; + let bufferEnd = cut.bufferEnd ?? 0; + for (const range of ranges) { + if (range.start < cut.start - RANGE_EPSILON) + bufferStart = Math.min(bufferStart, Math.max(0, cut.start - range.end)); + if (range.end > cut.end + RANGE_EPSILON) + bufferEnd = Math.min(bufferEnd, Math.max(0, range.start - cut.end)); + } + return bufferStart === (cut.bufferStart ?? 0) && + bufferEnd === (cut.bufferEnd ?? 0) + ? cut + : { ...cut, bufferStart, bufferEnd }; +} + +function coverClaim(cut: TranscriptCut, range: SourceRange): TranscriptCut { + const claim = cutClaim(cut); + if (!claim) return cut; + const before = claim.start - range.start; + const after = range.end - claim.end; + if (before <= RANGE_EPSILON && after <= RANGE_EPSILON) return cut; + return { + ...cut, + bufferStart: (cut.bufferStart ?? 0) + (before > RANGE_EPSILON ? before : 0), + bufferEnd: (cut.bufferEnd ?? 0) + (after > RANGE_EPSILON ? after : 0), + }; +} + +function cutConflictsWithTransition( + segments: TimelineSegment[], + transitions: ClipTransition[], + range: MappedTimeRange, +) { + return ( + rangeIntersectsClipTransition( + segments, + transitions, + range.start, + range.end, + ) || + !clipCutPreservesTransitionGeometry( + segments, + transitions, + range.segmentIndex, + range.start, + range.end, + RANGE_EPSILON, + ) + ); +} + +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, 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 }; +} + +// A trim leaves an overlay edge on the cut point, but computed along a +// different float path than the boundary a later cut or restore uses there. +// Off by a hair, the edge lands on the wrong side: a restore stretches the +// overlay instead of moving it, and a cut keeps a sliver instead of removing it. +function snapOverlayEdges(tracks: OverlayTracks, edges: readonly number[]) { + for (const key of OVERLAY_TRACKS) { + for (const segment of tracks[key] ?? []) { + for (const edge of edges) { + if (Math.abs(segment.start - edge) <= EDGE_SNAP) segment.start = edge; + if (Math.abs(segment.end - edge) <= EDGE_SNAP) segment.end = edge; + } + } + } +} + +// A hold sits at one point of recording-flow time but is stored in output +// time, so one meant to sit right at a cut point (a closing title at the +// clips' end) can land a hair before or after it. Off by a hair, a cut +// swallows the hold, or a restore puts footage back on the wrong side of it. +function snapHoldsTo(timeline: TranscriptTimeline, time: number) { + let output = time; + for (const [start, end] of holdWindows(timeline.textSegments)) { + if (output < start - EDGE_SNAP) return; + if (output <= start + EDGE_SNAP && output !== start) { + const by = output - start; + for (const segment of timeline.textSegments ?? []) { + if ( + segment.layout !== "fullscreen" || + segment.enabled === false || + segment.start < start || + segment.end > end + ) + continue; + segment.start = segment.start === start ? output : segment.start + by; + segment.end += by; + } + } + output += end - start; + } +} + +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 overlayShape(segment: OverlaySegment) { + return shiftOverlay(unwrap(segment), -segment.start); +} + +function editsOverlayAfter( + earlier: TranscriptCutPiece, + later: TranscriptCutPiece, +) { + const left: OverlayChanges = earlier.overlays ?? {}; + const right: OverlayChanges = later.overlays ?? {}; + return OVERLAY_TRACKS.some((key) => + (left[key] ?? []).some((entry) => { + const after = entry.after; + return ( + !!after && + (right[key] ?? []).some((other) => + sameValue(overlayShape(after), overlayShape(other.before)), + ) + ); + }), + ); +} + +// Overlays are saved as whole snapshots, so they only go back exactly in +// reverse removal order: a later removal that edited the same overlay (its +// "before" matches this piece's "after"), and any removal that edited it after +// that, has to come back first. +function laterOverlayEdits( + restoring: readonly TranscriptCutPiece[], + staying: readonly TranscriptCutPiece[], +) { + const found = new Set(); + const queue = [...restoring]; + for (let piece = queue.pop(); piece; piece = queue.pop()) { + const everyLater = deletesOverlayPastItself(piece); + for (const other of staying) { + if ( + found.has(other) || + other.sequence <= piece.sequence || + !(everyLater || editsOverlayAfter(piece, other)) + ) + continue; + found.add(other); + queue.push(other); + } + } + return [...found]; +} + +// A keyboard segment goes once a cut takes all its key presses, even where it +// reaches past the cut. Its snapshot then sits on a timeline that later cuts +// under that reach change without touching it, so they all come back first. +function deletesOverlayPastItself(piece: TranscriptCutPiece) { + const length = + (piece.end - piece.start) / piece.clip.timescale + (piece.held ?? 0); + const changes: OverlayChanges = piece.overlays ?? {}; + return OVERLAY_TRACKS.some((key) => + (changes[key] ?? []).some( + (entry) => + !entry.after && + (entry.before.start < -RANGE_EPSILON || + entry.before.end > length + RANGE_EPSILON), + ), + ); +} + +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 clipEnd = clipStart + clipDuration(clip); + const requestedStart = Math.max(range.start, clipStart); + const requestedEnd = Math.min(range.end, clipEnd); + // cutClipSegmentsForRange drops a leftover of 1 ms or less, so the cut + // takes it too and the piece matches the footage that actually leaves. + const keepsBefore = + clip.start + (requestedStart - clipStart) * clip.timescale > + clip.start + 0.001; + const keepsAfter = + clip.end > clip.start + (requestedEnd - clipStart) * clip.timescale + 0.001; + const start = keepsBefore ? requestedStart : clipStart; + const end = keepsAfter ? requestedEnd : clipEnd; + snapHoldsTo(timeline, start); + snapHoldsTo(timeline, end); + const holds = holdWindows(timeline.textSegments); + const overlayStart = effectiveToOutput(holds, start); + const overlayEnd = effectiveToOutputEnd(holds, end); + snapOverlayEdges(timeline, [overlayStart, overlayEnd]); + 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); + const heldAfter = effectiveToOutput(holds, end) - overlayEnd; + return { + sequence, + clip: original, + start: keepsBefore + ? original.start + (start - clipStart) * original.timescale + : original.start, + end: keepsAfter + ? original.start + (end - clipStart) * original.timescale + : original.end, + held: held > RANGE_EPSILON ? held : 0, + heldAfter: heldAfter > RANGE_EPSILON ? heldAfter : 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, 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; + // Holds that sat right where the removed footage ended (a closing title + // after a cut reaching the end of the clips) stayed with what follows, so + // the footage goes back in ahead of them. + snapHoldsTo(timeline, boundary); + const holds = holdWindows(timeline.textSegments); + const overlayBoundary = Math.max( + effectiveToOutputEnd(holds, boundary), + effectiveToOutput(holds, boundary) - (piece?.heldAfter ?? 0), + ); + const restored = piece + ? takeOverlays(timeline, piece.overlays, overlayBoundary) + : []; + snapOverlayEdges(timeline, [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[], +) { + const unapplied: TranscriptTrimmedWord[] = []; + const stillTrimmed: TranscriptTrimmedWord[] = []; + for (const record of trimmed) { + const matches = (candidate: { start: number; end: number }) => + Math.abs(candidate.start - record.start) <= WORD_TIME_EPSILON && + Math.abs(candidate.end - record.trimmedEnd) <= WORD_TIME_EPSILON; + const segment = captions.segments.find((candidate) => + candidate.words?.some(matches), + ); + const word = segment?.words?.find(matches); + if (!segment || !word) { + unapplied.push(record); + 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); + if (word.end < record.end - RANGE_EPSILON) + stillTrimmed.push({ ...record, trimmedEnd: word.end }); + } + return { unapplied, stillTrimmed }; +} + +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 freed = restored.map((cut) => ({ start: cut.start, end: cut.end })); + const nextCuts = [ + ...currentCuts.flatMap((cut) => { + if (restoreIds.has(cut.id)) return []; + const change = padding.get(cut.id); + return [ + clearOf( + change + ? clampCutPadding( + { + ...cut, + bufferStart: change.bufferStart, + bufferEnd: change.bufferEnd, + }, + cutPaddingRoom(captions, cut), + ) + : cut, + freed, + ), + ]; + }), + ...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 offsets = recordingOffsets(recordingSegments); + const savedPieces = currentCuts.flatMap((cut) => cut.removed ?? []); + const reinserted = new Set(); + + const timeline = project.timeline; + if (!timeline && (toRestore.length > 0 || toCut.length > 0)) return "failed"; + if (timeline) { + // A saved piece only goes back whole, and after any later removal that + // edited the same overlays. Those pieces are restored with it, and + // whatever stays claimed (a shrunk cut's rest, another cut's footage) is + // cut again so it gets a fresh piece of its own. + const restoring = savedPieces.filter((piece) => { + const source = pieceSourceRange(piece, offsets); + return ( + source !== null && intersectSourceRanges([source], toRestore).length > 0 + ); + }); + const returning = [ + ...restoring, + ...laterOverlayEdits( + restoring, + savedPieces.filter((piece) => !restoring.includes(piece)), + ), + ]; + for (const piece of returning) reinserted.add(piece.sequence); + const recut = subtractSourceRanges( + intersectSourceRanges( + subtractSourceRanges( + returning.flatMap((piece) => { + const source = pieceSourceRange(piece, offsets); + return source ? [source] : []; + }), + toRestore, + ), + nextClaims, + ), + timelineSourceCoverage(timeline.segments, recordingSegments), + ); + if ( + toRestore.length > 0 && + restoreTimelineSourceRanges( + timeline, + mergeSourceRanges([...toRestore, ...recut]), + recordingSegments, + savedPieces, + ) === "transition" + ) + return "transition"; + + const coverage = timelineSourceCoverage( + timeline.segments, + recordingSegments, + ); + const present = intersectSourceRanges( + mergeSourceRanges([...toCut, ...recut]), + 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), + ); + // What a cut leaves behind is measured on the timeline, as the cut + // itself skips ranges too short there to remove. In source time a + // sliver on a sped-up clip would count as a cut that failed. + const left = subtractSourceRanges(present, cutOut); + if ( + editedRangesForSource( + timeline, + left, + recordingSegments, + clipTimelineOffsets(timeline.segments, timeline.transitions ?? []), + ).length > 0 + ) + return "failed"; + nextRemoved = subtractSourceRanges( + mergeSourceRanges([...nextRemoved, ...cutOut]), + left, + ); + for (const { owner, piece } of pieces) { + removedPieces.set(owner, [...(removedPieces.get(owner) ?? []), piece]); + const source = pieceSourceRange(piece, offsets); + if (source) nextCuts[owner] = coverClaim(nextCuts[owner], source); + } + } + } + + 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); + } + // A word trimmed by several cuts only matches the latest trim, so the trims + // go back newest first. Whatever stays trimmed moves to the cut that still + // holds it: a cut claiming the rest of the word, or the word's own cut when + // it is cut right now, so restoring that cut later gives back the rest. + let unapplied = restored.flatMap((cut) => cut.trimmedWords ?? []); + const stillTrimmed: TranscriptTrimmedWord[] = []; + for (let left = -1; unapplied.length !== left; ) { + left = unapplied.length; + const result = restoreTrimmedWords(captions, unapplied, nextClaims); + unapplied = result.unapplied; + stillTrimmed.push(...result.stillTrimmed); + } + const handOver = (record: TranscriptTrimmedWord, owner: number) => { + if (owner !== -1) + trimmedWords.set(owner, [...(trimmedWords.get(owner) ?? []), record]); + }; + for (const record of unapplied) + handOver( + record, + nextCuts.findIndex( + (other) => + other.kind === "word" && + Math.abs(other.start - record.start) <= WORD_TIME_EPSILON && + Math.abs(other.end - record.trimmedEnd) <= WORD_TIME_EPSILON, + ), + ); + for (const record of stillTrimmed) + handOver( + record, + nextCuts.findIndex((other) => { + const claim = cutClaim(other); + return ( + !!claim && + claim.start <= record.trimmedEnd + RANGE_EPSILON && + claim.end > record.trimmedEnd + RANGE_EPSILON + ); + }), + ); + + const stillRemoved = (piece: TranscriptCutPiece) => { + const source = pieceSourceRange(piece, offsets); + return ( + !reinserted.has(piece.sequence) && + 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, + audioSilence: readonly SourceRange[], +) { + return token.type === "word" + ? audibleWordEnd(token.word, audioSilence) + : token.cut.end; +} + +function tokenSpeechStart( + token: TranscriptToken, + audioSilence: readonly SourceRange[], +) { + return token.type === "word" + ? audibleWordStart(token.word, audioSilence) + : token.cut.start; +} + +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[] = [], + audio: RecordingAudio = UNKNOWN_AUDIO, + 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, + ...audio.audible, + ]); + 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, audio.silence) : 0, + end: tokenSpeechStart(token, audio.silence), + }; + 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[]; + audio?: RecordingAudio; + 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 audio = context.audio ?? UNKNOWN_AUDIO; + 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(); + const join = ( + start: number, + end: number, + previous: TokenItem | undefined, + current: TokenItem | undefined, + ) => { + const previousRecord = previous && records.get(previous.token); + const currentRecord = current && records.get(current.token); + const gap = end - start; + if ((!currentRecord && !previousRecord) || gap <= RANGE_EPSILON) return; + if (gap < PAUSE_DETECTION_THRESHOLD) { + if (current && currentRecord) { + currentRecord.bufferStart = gap; + if (previous && previousRecord) + bufferedFrom.set(current.token, previous.token); + } else if (previousRecord) previousRecord.bufferEnd = gap; + return; + } + if (!options.joinKeepers && !(currentRecord && previousRecord)) return; + const beside = [previous?.token, current?.token].filter( + (token): token is number => token !== undefined && records.has(token), + ); + for (const range of clipToRange(silence, { start, end })) + gapPauses.push({ range, beside }); + }; + 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 previousRemoved = previous !== undefined && removedAfter(previous); + const currentRemoved = removedAfter(current); + if (!(previousRemoved && currentRemoved) && !options.joinKeepers) continue; + + const gapStart = !previous + ? 0 + : previous.type === "word" && !previousRecord + ? audibleWordEnd(previous.word, audio.silence) + : itemEnd(previous); + const gapEnd = + current.type === "word" && !currentRecord + ? audibleWordStart(current.word, audio.silence) + : itemStart(current); + // Transcription can miss speech, so audio heard between two words stays + // as if it were a word nobody cut. Audio running into a removed word is + // that word's own and goes with it; audio a cut already took is gone. + const heard = intersectSourceRanges( + clipToRange(audio.audible, { start: gapStart, end: gapEnd }).filter( + (run) => + !(previousRemoved && run.start <= gapStart + RANGE_EPSILON) && + !(currentRemoved && run.end >= gapEnd - RANGE_EPSILON), + ), + context.coverage, + ); + if (heard.length === 0) join(gapStart, gapEnd, previous, current); + else if (options.joinKeepers) { + join(gapStart, heard[0].start, previous, undefined); + join(heard[heard.length - 1].end, gapEnd, undefined, current); + } + } + + 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[], + audio: RecordingAudio = UNKNOWN_AUDIO, +): 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, + audio, + ), + segmentIds: segments.map((segment) => segment.id), + coverage, + speech, + audio, + 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..66a272d0767 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,55 @@ 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; +/** + * Output time of fullscreen text holds that sat right where the removed + * footage ended. They stay with what follows the cut, so restoring puts + * the footage back in ahead of them. + */ +heldAfter?: 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/audio/src/lib.rs b/crates/audio/src/lib.rs index ef0e71c45e3..314be80fae6 100644 --- a/crates/audio/src/lib.rs +++ b/crates/audio/src/lib.rs @@ -3,6 +3,7 @@ mod calibration_store; mod latency; mod progressive; mod renderer; +mod speech_pauses; mod streaming; mod sync_analysis; mod transcription_timing; @@ -14,6 +15,7 @@ pub use calibration_store::*; pub use latency::*; pub use progressive::*; pub use renderer::*; +pub use speech_pauses::*; pub use streaming::*; pub use sync_analysis::*; pub use transcription_timing::*; diff --git a/crates/audio/src/speech_pauses.rs b/crates/audio/src/speech_pauses.rs new file mode 100644 index 00000000000..7c96aea66bc --- /dev/null +++ b/crates/audio/src/speech_pauses.rs @@ -0,0 +1,292 @@ +use std::ops::Range; + +const FRAMES_PER_SECOND: u32 = 100; +const LEVEL_FLOOR_DB: f32 = -90.0; +const NOISE_PERCENTILE: f32 = 0.1; +const SPEECH_PERCENTILE: f32 = 0.9; +const MIN_SPEECH_ABOVE_NOISE_DB: f32 = 20.0; +const QUIET_ABOVE_NOISE_DB: f32 = 6.0; +const QUIET_BELOW_SPEECH_DB: f32 = 40.0; +const MAX_QUIET_DB: f32 = -45.0; +const SPEECH_BELOW_PEAK_DB: f32 = 20.0; +const MIN_PAUSE_SECS: f32 = 0.2; +const MIN_SPEECH_SECS: f32 = 0.05; +const SPEECH_RELEASE_SECS: f32 = 0.1; +const MIN_WORD_SECS: f32 = 0.1; +const NEXT_ONSET_SECS: f32 = 0.25; + +#[derive(Debug, Clone, PartialEq)] +pub struct SpeechPauses { + frame_secs: f32, + pauses: Vec>, + speech_frames: Vec, +} + +impl SpeechPauses { + pub fn detect(samples: &[f32], sample_rate: u32) -> Option { + let hop = (sample_rate / FRAMES_PER_SECOND) as usize; + if hop == 0 || samples.is_empty() { + return None; + } + + let energies = samples + .chunks(hop) + .map(|frame| { + frame.iter().map(|sample| sample * sample).sum::() / frame.len() as f32 + }) + .collect::>(); + let levels = (0..energies.len()) + .map(|index| { + let window = &energies[index.saturating_sub(1)..(index + 2).min(energies.len())]; + let energy = window.iter().sum::() / window.len() as f32; + (10.0 * energy.log10()).max(LEVEL_FLOOR_DB) + }) + .collect::>(); + + let mut sorted = levels.clone(); + sorted.sort_by(f32::total_cmp); + let audible = &sorted[sorted.partition_point(|level| *level <= LEVEL_FLOOR_DB)..]; + let noise = percentile(&sorted, NOISE_PERCENTILE)?; + let speech = percentile(audible, SPEECH_PERCENTILE)?; + if speech - noise < MIN_SPEECH_ABOVE_NOISE_DB { + return None; + } + + // Noise-gated mics leave digital silence in pauses, which pins the + // noise floor at the bottom of the scale while the gate's tail after + // each word still sits far above it; following the speech level too + // keeps that tail out of the word. + let quiet = (noise + QUIET_ABOVE_NOISE_DB) + .max(speech - QUIET_BELOW_SPEECH_DB) + .min(MAX_QUIET_DB); + let loud = speech - SPEECH_BELOW_PEAK_DB; + + let frame_secs = hop as f32 / sample_rate as f32; + let min_pause_frames = (MIN_PAUSE_SECS / frame_secs).round() as usize; + let mut pauses = Vec::new(); + let mut quiet_from = None; + for (index, level) in levels.iter().chain([&f32::INFINITY]).enumerate() { + match (*level < quiet, quiet_from) { + (true, None) => quiet_from = Some(index), + (false, Some(from)) => { + if index - from >= min_pause_frames { + pauses.push(from as f32 * frame_secs..index as f32 * frame_secs); + } + quiet_from = None; + } + _ => {} + } + } + + let speech_frames = std::iter::once(0) + .chain(levels.iter().scan(0, |count, level| { + *count += u32::from(*level > loud); + Some(*count) + })) + .collect(); + + Some(Self { + frame_secs, + pauses, + speech_frames, + }) + } + + // parakeet-rs ends each word where the next one starts, so a word's end + // runs through the pause after it; only the audio shows where speech + // stopped. Its word starts drift ~0.2s either way (sometimes more), so the + // next word may already be audible in the last moments before the stored + // end, and a word's own speech may only begin after a pause inside its + // span. Breaths and clicks in a pause stay below speech level. + pub fn audible_end(&self, start: f32, end: f32) -> f32 { + let first = self.pauses.partition_point(|pause| pause.start <= start); + for pause in self.pauses[first..] + .iter() + .take_while(|pause| pause.start < end) + { + let next_onset = (end - NEXT_ONSET_SECS).max(pause.end); + if self.speech_secs(pause.end..next_onset) >= MIN_SPEECH_SECS { + continue; + } + let late = self.speech_secs(next_onset..end); + if late >= MIN_SPEECH_SECS && late > self.speech_secs(start..pause.start) { + continue; + } + return end.min((pause.start + SPEECH_RELEASE_SECS).max(start + MIN_WORD_SECS)); + } + + if first + .checked_sub(1) + .is_some_and(|index| self.pauses[index].end >= end) + { + return end.min(start + MIN_WORD_SECS); + } + + end + } + + fn speech_secs(&self, range: Range) -> f32 { + let last_frame = self.speech_frames.len() - 1; + let frame = + |time: f32| ((time / self.frame_secs).round().max(0.0) as usize).min(last_frame); + let (first, last) = (frame(range.start), frame(range.end)); + if last <= first { + return 0.0; + } + (self.speech_frames[last] - self.speech_frames[first]) as f32 * self.frame_secs + } +} + +fn percentile(sorted: &[f32], fraction: f32) -> Option { + let last = sorted.len().checked_sub(1)?; + Some(sorted[((sorted.len() as f32 * fraction) as usize).min(last)]) +} + +#[cfg(test)] +mod tests { + use super::SpeechPauses; + use std::ops::Range; + + const RATE: u32 = 16_000; + + fn silence(secs: f32) -> Vec { + vec![0.0; (secs * RATE as f32) as usize] + } + + fn sample_range(samples: &[f32], range: Range) -> Range { + let index = |time: f32| ((time * RATE as f32) as usize).min(samples.len()); + index(range.start)..index(range.end) + } + + fn hiss(samples: &mut [f32], range: Range, db: f32) { + let amplitude = 10f32.powf(db / 20.0) * 3f32.sqrt(); + let mut state = 0x2545_f491_u32 ^ range.start.to_bits(); + for index in sample_range(samples, range) { + state ^= state << 13; + state ^= state >> 17; + state ^= state << 5; + samples[index] += (state as f32 / u32::MAX as f32 * 2.0 - 1.0) * amplitude; + } + } + + fn tone(samples: &mut [f32], range: Range, db: f32) { + let amplitude = 10f32.powf(db / 20.0) * 2f32.sqrt(); + for index in sample_range(samples, range) { + let time = index as f32 / RATE as f32; + samples[index] += amplitude * (std::f32::consts::TAU * 220.0 * time).sin(); + } + } + + fn speech(noise_db: f32, speech_db: f32, words: &[Range]) -> Vec { + let mut samples = silence(5.0); + hiss(&mut samples, 0.0..5.0, noise_db); + for word in words { + tone(&mut samples, word.clone(), speech_db); + } + samples + } + + fn pauses(samples: &[f32]) -> SpeechPauses { + SpeechPauses::detect(samples, RATE).expect("speech stands above the noise") + } + + fn assert_close(actual: f32, expected: f32) { + assert!( + (actual - expected).abs() <= 0.02, + "{actual} is not within 20ms of {expected}" + ); + } + + #[test] + fn stretched_word_ends_where_its_speech_stops() { + let pauses = pauses(&speech(-60.0, -20.0, &[1.0..1.6, 3.0..3.5])); + + assert_close(pauses.audible_end(1.0, 3.0), 1.7); + assert_eq!(pauses.audible_end(3.0, 3.5), 3.5); + } + + #[test] + fn word_followed_immediately_by_speech_keeps_its_end() { + let pauses = pauses(&speech(-60.0, -20.0, &[1.0..1.47, 1.53..2.0, 3.5..4.0])); + + assert_eq!(pauses.audible_end(1.0, 1.5), 1.5); + assert_eq!(pauses.audible_end(1.5, 2.0), 2.0); + } + + #[test] + fn next_word_heard_just_before_its_start_still_ends_at_the_pause() { + let pauses = pauses(&speech(-60.0, -20.0, &[1.0..1.6, 2.8..3.3])); + + assert_close(pauses.audible_end(1.0, 3.0), 1.7); + assert_eq!(pauses.audible_end(1.0, 3.2), 3.2); + } + + #[test] + fn speech_after_a_pause_inside_the_word_keeps_its_end() { + let pauses = pauses(&speech(-60.0, -20.0, &[1.0..1.3, 1.6..2.4])); + + assert_eq!(pauses.audible_end(1.0, 2.0), 2.0); + } + + #[test] + fn short_word_heard_after_a_pause_keeps_its_end() { + let pauses = pauses(&speech(-60.0, -20.0, &[1.0..2.05, 2.3..2.45, 2.5..3.0])); + + assert_eq!(pauses.audible_end(2.0, 2.5), 2.5); + } + + #[test] + fn clicks_and_breaths_in_a_pause_do_not_hold_the_word() { + let mut samples = speech(-60.0, -20.0, &[1.0..1.5, 4.0..4.5]); + tone(&mut samples, 2.0..2.02, -30.0); + hiss(&mut samples, 2.5..2.8, -50.0); + let pauses = pauses(&samples); + + assert_close(pauses.audible_end(1.0, 3.5), 1.6); + } + + #[test] + fn noise_gate_tail_after_a_word_counts_as_quiet() { + let mut samples = silence(5.0); + tone(&mut samples, 1.0..1.6, -20.0); + hiss(&mut samples, 1.6..1.9, -65.0); + tone(&mut samples, 3.0..3.5, -20.0); + let pauses = pauses(&samples); + + assert_close(pauses.audible_end(1.0, 3.0), 1.7); + } + + #[test] + fn word_inside_a_pause_keeps_a_sliver_from_its_start() { + let pauses = pauses(&speech(-60.0, -20.0, &[1.0..1.5, 4.0..4.5])); + + assert_close(pauses.audible_end(2.0, 3.0), 2.1); + } + + #[test] + fn pause_before_the_words_own_speech_keeps_its_end() { + let pauses = pauses(&speech(-60.0, -20.0, &[1.0..1.5, 2.2..2.6])); + + assert_eq!(pauses.audible_end(2.0, 2.4), 2.4); + } + + #[test] + fn threshold_follows_the_clips_noise_floor() { + let quiet = pauses(&speech(-85.0, -45.0, &[1.0..1.6, 3.0..3.5])); + let noisy = pauses(&speech(-50.0, -15.0, &[1.0..1.6, 3.0..3.5])); + + assert_close(quiet.audible_end(1.0, 3.0), 1.7); + assert_close(noisy.audible_end(1.0, 3.0), 1.7); + } + + #[test] + fn noisy_or_quiet_clips_are_left_alone() { + let words = [1.0..1.6, 3.0..3.5]; + + assert!(SpeechPauses::detect(&speech(-30.0, -20.0, &words), RATE).is_none()); + assert!(SpeechPauses::detect(&speech(-40.0, -30.0, &words), RATE).is_none()); + assert!(SpeechPauses::detect(&speech(-70.0, -70.0, &[]), RATE).is_none()); + assert!(SpeechPauses::detect(&silence(5.0), RATE).is_none()); + assert!(SpeechPauses::detect(&[], RATE).is_none()); + } +} diff --git a/crates/project/src/caption_timing.rs b/crates/project/src/caption_timing.rs index 63700fc2abd..4b84762d0a5 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; @@ -424,10 +425,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 { @@ -568,4 +623,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 8b7f2dd2e6e..04ccd4e84e5 100644 --- a/crates/project/src/configuration.rs +++ b/crates/project/src/configuration.rs @@ -2429,6 +2429,125 @@ 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, + /// Output time of fullscreen text holds that sat right where the removed + /// footage ended. They stay with what follows the cut, so restoring puts + /// the footage back in ahead of them. + #[serde(default)] + pub held_after: 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)] @@ -3117,6 +3236,107 @@ 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_eq!(piece.held_after, 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)) }