diff --git a/apps/desktop-gpui/src/transcript.rs b/apps/desktop-gpui/src/transcript.rs index 613aa7d12bc..1fbb8ee5ed9 100644 --- a/apps/desktop-gpui/src/transcript.rs +++ b/apps/desktop-gpui/src/transcript.rs @@ -180,6 +180,7 @@ pub(crate) struct TranscriptState { pub energy: Option>, pub energy_loading: bool, pub energy_offsets: Vec<(f64, f64)>, + pub voiced_for: usize, } impl TranscriptState { @@ -213,6 +214,7 @@ impl TranscriptState { energy: None, energy_loading: false, energy_offsets: Vec::new(), + voiced_for: 0, } } @@ -260,6 +262,18 @@ impl TranscriptState { self.cleanup.ignored.clear(); self.doc = Some(Arc::new(doc)); self.edl_key = 0; + self.voiced_for = 0; + changed = true; + } + let energy_key = self + .energy + .as_ref() + .map_or(1, |energy| Arc::as_ptr(energy) as usize); + if energy_key != self.voiced_for + && let Some(doc) = self.doc.as_mut() + { + Arc::make_mut(doc).refine_voiced(self.energy.as_deref()); + self.voiced_for = energy_key; changed = true; } let key = timeline_key(project.timeline.as_ref(), recording_durations); diff --git a/apps/desktop-gpui/src/transcript/automation.rs b/apps/desktop-gpui/src/transcript/automation.rs index 74dd2d2d630..0af0eeff67e 100644 --- a/apps/desktop-gpui/src/transcript/automation.rs +++ b/apps/desktop-gpui/src/transcript/automation.rs @@ -353,6 +353,8 @@ impl EditorWindow { "text": word.text, "start": word.start, "end": word.end, + "voiced_start": doc.voiced[index].start, + "voiced_end": doc.voiced[index].end, "kept": edl.is_kept(index), "output_start": edl.source_to_output(word.start), "output_end": edl.source_to_output(word.end), @@ -369,6 +371,17 @@ impl EditorWindow { .collect::>() }), "words": words, + "energy": self.transcript.energy.is_some(), + "silences": self.transcript.energy.as_ref().map(|energy| energy.silences().to_vec()), + "pauses": self.transcript_pause_plan().iter().map(|pause| { + serde_json::json!({ + "after_word": pause.after_word, + "next_word": pause.next_word, + "length": pause.length, + "saves": pause.saves, + "cuts": pause.cuts, + }) + }).collect::>(), }); match std::fs::write(path, serde_json::to_vec_pretty(&body).unwrap_or_default()) { Ok(()) => format!("wrote {path}"), diff --git a/apps/desktop-gpui/src/transcript/cuts.rs b/apps/desktop-gpui/src/transcript/cuts.rs index fb38fe1150b..8ad32e745f6 100644 --- a/apps/desktop-gpui/src/transcript/cuts.rs +++ b/apps/desktop-gpui/src/transcript/cuts.rs @@ -20,8 +20,18 @@ const TOUCHING_SEARCH: f64 = 0.04; const EDGE_PENALTY_DB: f32 = 6.0; const MAX_SEARCH_STEPS: usize = 4_000; const MIN_PAUSE_CUT: f64 = 0.05; +pub const LONG_GAP: f64 = 0.8; pub fn quietest_point(energy: Option<&EnergyEnvelope>, lo: f64, hi: f64) -> f64 { + quietest_mapped(energy, lo, hi, Some) +} + +fn quietest_mapped( + energy: Option<&EnergyEnvelope>, + lo: f64, + hi: f64, + to_source: impl Fn(f64) -> Option, +) -> f64 { let (lo, hi) = if lo <= hi { (lo, hi) } else { (hi, lo) }; let centre = (lo + hi) / 2.0; let Some(energy) = energy else { @@ -36,7 +46,7 @@ pub fn quietest_point(energy: Option<&EnergyEnvelope>, lo: f64, hi: f64) -> f64 let mut best: Option<(f32, f64)> = None; for index in 0..=steps { let time = (lo + index as f64 * step).min(hi); - let Some(db) = energy.smoothed_db(time) else { + let Some(db) = to_source(time).and_then(|source| energy.smoothed_db(source)) else { continue; }; let score = db + EDGE_PENALTY_DB * ((time - centre).abs() / half) as f32; @@ -47,13 +57,26 @@ pub fn quietest_point(energy: Option<&EnergyEnvelope>, lo: f64, hi: f64) -> f64 best.map_or(centre, |(_, time)| time) } +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Removing { + Before, + After, +} + /// The cut point between word `index - 1` and word `index` (`index` may be 0 -/// or `words.len()` for the edges). Deterministic per gap, so cutting two -/// neighbouring words one at a time lands on exactly the same boundary as -/// cutting them together. -pub fn gap_cut(doc: &TranscriptDoc, energy: Option<&EnergyEnvelope>, index: usize) -> f64 { - let previous = index.checked_sub(1).and_then(|at| doc.words.get(at)); - let next = doc.words.get(index); +/// or `words.len()` for the edges), measured between the words' voiced parts. +/// Up to `LONG_GAP` the point is the same whichever side is removed, so +/// cutting two neighbours one at a time lands where cutting them together +/// does. In a longer silence the removed word takes at most `LONG_GAP / 2` of +/// it, and the rest stays for the pause controls to judge. +pub fn gap_cut( + doc: &TranscriptDoc, + energy: Option<&EnergyEnvelope>, + index: usize, + removing: Removing, +) -> f64 { + let previous = index.checked_sub(1).and_then(|at| doc.voiced.get(at)); + let next = doc.voiced.get(index); let (previous_end, next_start) = match (previous, next) { (Some(previous), Some(next)) => (previous.end, next.start), (None, Some(next)) if next.start <= EDGE_REACH * 2.0 => return 0.0, @@ -62,7 +85,12 @@ pub fn gap_cut(doc: &TranscriptDoc, energy: Option<&EnergyEnvelope>, index: usiz (None, None) => return 0.0, }; let gap = next_start - previous_end; - let (lo, hi) = if gap > 0.0 { + let (lo, hi) = if gap > LONG_GAP && previous.is_some() && next.is_some() { + match removing { + Removing::After => (next_start - LONG_GAP / 2.0, next_start - ONSET_GUARD), + Removing::Before => (previous_end + TAIL_GUARD, previous_end + LONG_GAP / 2.0), + } + } else if gap > 0.0 { ( previous_end + TAIL_GUARD.min(gap * 0.3), next_start - ONSET_GUARD.min(gap * 0.2), @@ -82,12 +110,26 @@ pub fn gap_cut(doc: &TranscriptDoc, energy: Option<&EnergyEnvelope>, index: usiz pub fn plan_word_cuts( doc: &TranscriptDoc, energy: Option<&EnergyEnvelope>, + kept: Option<&[bool]>, runs: &[Range], ) -> Vec> { + let is_kept = |word: usize| kept.is_none_or(|kept| kept.get(word).copied().unwrap_or(true)); merge_ranges( runs.iter() .filter(|run| run.start < run.end && run.end <= doc.words.len()) - .map(|run| gap_cut(doc, energy, run.start)..gap_cut(doc, energy, run.end)) + .map(|run| { + let start = if run.start > 0 && !is_kept(run.start - 1) { + Removing::Before + } else { + Removing::After + }; + let end = if run.end < doc.words.len() && !is_kept(run.end) { + Removing::After + } else { + Removing::Before + }; + gap_cut(doc, energy, run.start, start)..gap_cut(doc, energy, run.end, end) + }) .collect(), ) } @@ -95,9 +137,11 @@ pub fn plan_word_cuts( #[derive(Clone, Debug, PartialEq)] pub struct PauseCut { pub after_word: usize, + pub next_word: usize, pub length: f64, pub saves: f64, - pub cut: Range, + pub output: Range, + pub cuts: Vec>, } pub fn plan_pause_cuts( @@ -114,48 +158,76 @@ pub fn plan_pause_cuts( .iter() .map(|mapping| mapping.timescale) .fold(f64::INFINITY, f64::min); + let to_source = |output: f64| edl.output_to_source(output); let mut pauses = Vec::new(); - for index in 1..doc.words.len() { - if !edl.is_kept(index - 1) || !edl.is_kept(index) { + let mut previous: Option<(usize, Range)> = None; + for index in 0..doc.voiced.len() { + if doc.voiced[index].is_empty() { continue; } - let previous_end = doc.words[index - 1].end; - let next_start = doc.words[index].start; - if slowest > 0.0 && (next_start - previous_end) / slowest <= floor { + let Some(heard) = edl.audible_part(&doc.voiced[index]) else { + continue; + }; + let Some((before, before_heard)) = previous.replace((index, heard.clone())) else { + continue; + }; + let source = before_heard.end..heard.start; + if source.end <= source.start + || (slowest > 0.0 && source.end - source.start <= floor * slowest) + { continue; } - let Some(timescale) = edl.timescale_over(previous_end..next_start) else { + let (Some(from), Some(until)) = ( + edl.output_end_of(&before_heard), + edl.output_start_of(&heard), + ) else { continue; }; - let length = (next_start - previous_end) / timescale; - if length <= longer_than || length <= keep + MIN_PAUSE_CUT { + let length = until - from; + if length <= floor { continue; } - let lead = keep * 0.45 * timescale; - let trail = keep * timescale - lead; - let lo_limit = previous_end + TAIL_GUARD.min(lead); - let hi_limit = next_start - ONSET_GUARD.min(trail); - let start_target = previous_end + lead; - let end_target = next_start - trail; - let start = quietest_point( + let Some(pieces) = edl.source_pieces(from..until) else { + continue; + }; + if pieces + .iter() + .any(|piece| piece.start < source.start - 1e-6 || piece.end > source.end + 1e-6) + { + continue; + } + let lead = keep * 0.45; + let trail = keep - lead; + let lo_limit = from + TAIL_GUARD.min(lead); + let hi_limit = until - ONSET_GUARD.min(trail); + let start_target = from + lead; + let end_target = until - trail; + let start = quietest_mapped( energy, (start_target - 0.06).max(lo_limit), (start_target + 0.06).min(end_target), + to_source, ); - let end = quietest_point( + let end = quietest_mapped( energy, (end_target - 0.06).max(start), (end_target + 0.06).min(hi_limit), + to_source, ); - let saves = (end - start) / timescale; + let saves = end - start; if saves < MIN_PAUSE_CUT { continue; } + let Some(cuts) = edl.source_pieces(start..end) else { + continue; + }; pauses.push(PauseCut { - after_word: index - 1, + after_word: before, + next_word: index, length, saves, - cut: start..end, + output: from..until, + cuts, }); } pauses @@ -405,7 +477,7 @@ pub fn restore_words( let Some(index) = words.clone().find(|word| !edl.is_kept(*word)) else { break; }; - let word = &doc.words[index]; + let word = &doc.voiced[index]; let first = edl .kept_ranges .partition_point(|range| range.end <= word.start); diff --git a/apps/desktop-gpui/src/transcript/energy.rs b/apps/desktop-gpui/src/transcript/energy.rs index 7879dbeead1..1b7c932b988 100644 --- a/apps/desktop-gpui/src/transcript/energy.rs +++ b/apps/desktop-gpui/src/transcript/energy.rs @@ -1,14 +1,25 @@ +use std::ops::Range; use std::sync::Arc; /// 5 ms hops: fine enough to land a cut between two syllables, coarse enough /// that a two hour recording costs under 6 MB. pub const HOP_SECONDS: f64 = 0.005; const SAMPLE_RATE: f64 = 48_000.0; +pub const MIN_SILENCE: f64 = 0.2; +const DIGITAL_SILENCE_DB: f32 = -90.0; +const FLOOR_PERCENTILE: f64 = 0.02; +const SPEECH_SECONDS: f64 = 1.0; +const SPEECH_SHARE: f64 = 0.02; +const MIN_MARGIN_DB: f32 = 6.0; +const MAX_MARGIN_DB: f32 = 15.0; +const MIN_SEPARATION_DB: f32 = 2.0 * MIN_MARGIN_DB; #[derive(Debug, Default)] pub struct EnergyEnvelope { clips: Vec>, clip_offsets: Vec, + thresholds: Vec, + silences: Vec>, } pub struct EnvelopeTrack<'a> { @@ -67,12 +78,43 @@ pub fn clip_envelope(tracks: &[EnvelopeTrack<'_>], duration: f64) -> Vec { impl EnergyEnvelope { pub fn new(clips: Vec>, recording_durations: &[f64]) -> Self { + let clip_offsets = super::model::recording_offsets(recording_durations); + let mut thresholds = Vec::with_capacity(clips.len()); + let mut silences = Vec::new(); + for (clip, offset) in clips.iter().zip(&clip_offsets) { + let (threshold, runs) = clip_silences(clip); + thresholds.push(threshold); + silences.extend(runs.into_iter().map(|run| { + offset + run.start as f64 * HOP_SECONDS..offset + run.end as f64 * HOP_SECONDS + })); + } Self { - clip_offsets: super::model::recording_offsets(recording_durations), + clip_offsets, clips: clips.into_iter().map(Arc::from).collect(), + thresholds, + silences, } } + pub fn silences(&self) -> &[Range] { + &self.silences + } + + pub fn silences_overlapping(&self, range: Range) -> &[Range] { + let first = self + .silences + .partition_point(|silence| silence.end <= range.start); + let last = self + .silences + .partition_point(|silence| silence.start < range.end); + &self.silences[first..last.max(first)] + } + + pub fn silence_threshold_db(&self, source: f64) -> Option { + let (clip, _) = self.locate(source)?; + self.thresholds.get(clip).copied() + } + pub fn is_empty(&self) -> bool { self.clips.iter().all(|clip| clip.is_empty()) } @@ -108,3 +150,81 @@ impl EnergyEnvelope { (count > 0).then(|| 10.0 * (total / count as f32 + 1e-10).log10()) } } + +fn to_db(energy: f32) -> f32 { + 10.0 * (energy + 1e-10).log10() +} + +fn from_db(db: f32) -> f32 { + 10f32.powf(db / 10.0) +} + +fn percentile(values: &mut [f32], fraction: f64) -> f32 { + let index = ((values.len() - 1) as f64 * fraction).round() as usize; + *values + .select_nth_unstable_by(index, |a, b| a.total_cmp(b)) + .1 +} + +fn silence_threshold(smoothed: &[f32], window: usize) -> f32 { + if smoothed.is_empty() { + return DIGITAL_SILENCE_DB; + } + let window = window.clamp(1, smoothed.len()); + let stride = (smoothed.len() / 250_000).max(1); + let mut sums = Vec::with_capacity(smoothed.len() / stride + 1); + let mut sum: f64 = smoothed[..window] + .iter() + .map(|energy| f64::from(*energy)) + .sum(); + for index in window..=smoothed.len() { + if (index - window).is_multiple_of(stride) { + sums.push((sum / window as f64) as f32); + } + if index < smoothed.len() { + sum += f64::from(smoothed[index]) - f64::from(smoothed[index - window]); + } + } + let floor = to_db(percentile(&mut sums, FLOOR_PERCENTILE).max(0.0)); + let mut hops: Vec = smoothed.iter().step_by(stride).copied().collect(); + let loudest = ((SPEECH_SECONDS / HOP_SECONDS) as usize / stride) + .max((hops.len() as f64 * SPEECH_SHARE) as usize); + let fraction = (1.0 - loudest as f64 / hops.len() as f64).max(0.5); + let speech = to_db(percentile(&mut hops, fraction)); + if speech - floor < MIN_SEPARATION_DB { + return DIGITAL_SILENCE_DB; + } + floor + ((speech - floor) * 0.5).clamp(MIN_MARGIN_DB, MAX_MARGIN_DB) +} + +pub fn clip_silences(clip: &[f32]) -> (f32, Vec>) { + let smoothed: Vec = (0..clip.len()) + .map(|index| { + let window = &clip[index.saturating_sub(1)..(index + 2).min(clip.len())]; + window.iter().sum::() / window.len() as f32 + }) + .collect(); + let min_hops = (MIN_SILENCE / HOP_SECONDS).round() as usize; + let threshold = silence_threshold(&smoothed, min_hops); + let quiet = from_db(threshold) - 1e-10; + let mut runs = Vec::new(); + let mut start = None; + for (index, energy) in smoothed.iter().enumerate() { + match (start, *energy < quiet) { + (None, true) => start = Some(index), + (Some(from), false) => { + if index - from >= min_hops { + runs.push(from..index); + } + start = None; + } + _ => {} + } + } + if let Some(from) = start + && smoothed.len() - from >= min_hops + { + runs.push(from..smoothed.len()); + } + (threshold, runs) +} diff --git a/apps/desktop-gpui/src/transcript/model.rs b/apps/desktop-gpui/src/transcript/model.rs index c385d2f8530..aa1cc0867fa 100644 --- a/apps/desktop-gpui/src/transcript/model.rs +++ b/apps/desktop-gpui/src/transcript/model.rs @@ -4,6 +4,7 @@ use cap_project::disfluency::{Disfluency, DisfluencyToken, detect_disfluencies}; use cap_project::{CaptionsData, TimelineConfiguration}; use gpui::SharedString; +use super::energy::EnergyEnvelope; use crate::editor_edits; use crate::editor_timeline; @@ -12,6 +13,9 @@ const SENTENCE_PARAGRAPH_PAUSE: f64 = 0.7; const SOFT_PARAGRAPH_WORDS: usize = 70; const HARD_PARAGRAPH_WORDS: usize = 140; const ACTIVE_WORD_LINGER: f64 = 0.25; +pub const WORD_TRIM_MIN: f64 = 0.25; +const WORD_EDGE_SLACK: f64 = 0.08; +const MIN_VOICED: f64 = 0.04; #[derive(Clone, Debug, PartialEq)] pub struct Word { @@ -41,8 +45,10 @@ impl Paragraph { } } +#[derive(Clone)] pub struct TranscriptDoc { pub words: Vec, + pub voiced: Vec>, pub paragraphs: Vec, pub paragraph_of: Vec, pub fillers: Vec, @@ -213,6 +219,7 @@ impl TranscriptDoc { .collect(); Self { + voiced: words.iter().map(|word| word.start..word.end).collect(), words, paragraphs, paragraph_of, @@ -232,11 +239,18 @@ impl TranscriptDoc { pub fn word_at_source(&self, source: f64) -> Option { let index = self - .words - .partition_point(|word| word.start <= source) + .voiced + .partition_point(|span| span.start <= source) .checked_sub(1)?; - let word = &self.words[index]; - (source <= word.end.max(word.start) + ACTIVE_WORD_LINGER).then_some(index) + let span = &self.voiced[index]; + (source <= span.end.max(span.start) + ACTIVE_WORD_LINGER).then_some(index) + } + + pub fn refine_voiced(&mut self, energy: Option<&EnergyEnvelope>) { + self.voiced = match energy { + Some(energy) => voiced_spans(&self.words, energy), + None => self.words.iter().map(|word| word.start..word.end).collect(), + }; } pub fn filler(&self, word: usize) -> Option<&Disfluency> { @@ -325,6 +339,40 @@ pub struct TranscriptEdl { pub kept_count: usize, } +pub fn voiced_spans(words: &[Word], energy: &EnergyEnvelope) -> Vec> { + words + .iter() + .map(|word| { + let (mut start, mut end) = (word.start, word.end); + if end - start < WORD_TRIM_MIN + MIN_VOICED { + return start..end; + } + let silences = energy.silences_overlapping(start..end); + if let Some(cover) = silences.iter().find(|silence| { + silence.start <= start + WORD_EDGE_SLACK && silence.end >= end - WORD_EDGE_SLACK + }) { + let point = cover.start.clamp(start, end); + return point..point; + } + if let Some(head) = silences.first() + && head.start <= start + WORD_EDGE_SLACK + && head.end - start >= WORD_TRIM_MIN + && head.end + MIN_VOICED <= end + { + start = head.end; + } + if let Some(tail) = silences.last() + && tail.end >= end - WORD_EDGE_SLACK + && end - tail.start >= WORD_TRIM_MIN + && tail.start - MIN_VOICED >= start + { + end = tail.start; + } + start..end + }) + .collect() +} + pub fn merge_ranges(mut ranges: Vec>) -> Vec> { ranges.retain(|range| range.end > range.start); ranges.sort_by(|a, b| a.start.total_cmp(&b.start)); @@ -351,9 +399,9 @@ impl TranscriptEdl { .map(|mapping| mapping.source_start..mapping.source_end) .collect(), ); - let mut kept = Vec::with_capacity(doc.words.len()); + let mut kept = Vec::with_capacity(doc.voiced.len()); let mut cursor = 0; - for word in &doc.words { + for word in &doc.voiced { while kept_ranges .get(cursor) .is_some_and(|range| range.end <= word.start) @@ -430,7 +478,25 @@ impl TranscriptEdl { )) } - pub fn output_start_of(&self, word: &Word) -> Option { + pub fn audible_part(&self, span: &Range) -> Option> { + let first = self + .kept_ranges + .partition_point(|range| range.end <= span.start); + let mut heard: Option> = None; + for range in self.kept_ranges[first..] + .iter() + .take_while(|range| range.start < span.end) + { + let start = range.start.max(span.start); + let end = range.end.min(span.end); + if end > start { + heard = Some(heard.map_or(start, |heard| heard.start)..end); + } + } + heard + } + + pub fn output_start_of(&self, word: &Range) -> Option { self.source_to_output(word.start).or_else(|| { let index = self .kept_ranges @@ -443,7 +509,7 @@ impl TranscriptEdl { }) } - pub fn output_end_of(&self, word: &Word) -> Option { + pub fn output_end_of(&self, word: &Range) -> Option { self.source_to_output(word.end).or_else(|| { let index = self .kept_ranges @@ -457,15 +523,40 @@ impl TranscriptEdl { }) } - /// The speed `range` plays at when one clip plays all of it; `None` when it - /// is cut, or crosses into another clip where the speed may differ. - pub fn timescale_over(&self, range: Range) -> Option { - self.mappings + pub fn source_pieces(&self, output: Range) -> Option>> { + if self + .holds .iter() - .find(|mapping| { - mapping.source_start <= range.start + 1e-9 && range.end <= mapping.source_end + 1e-9 - }) - .map(|mapping| mapping.timescale) + .any(|(start, end)| *start < output.end && output.start < *end) + { + return None; + } + let from = output.start - editor_edits::held_time_before(&self.holds, output.start); + let until = from + (output.end - output.start); + let first = self + .mappings + .partition_point(|mapping| mapping.effective_end() <= from + 1e-9); + let mut pieces = Vec::new(); + let mut previous_end: Option = None; + for mapping in &self.mappings[first..] { + if mapping.effective_start >= until - 1e-9 { + break; + } + if previous_end.is_some_and(|end| mapping.effective_start < end - 1e-6) { + return None; + } + let start = from.max(mapping.effective_start); + let end = until.min(mapping.effective_end()); + if end > start { + pieces.push( + mapping.source_start + (start - mapping.effective_start) * mapping.timescale + ..mapping.source_start + + (end - mapping.effective_start) * mapping.timescale, + ); + } + previous_end = Some(mapping.effective_end()); + } + Some(pieces) } pub fn output_to_source(&self, output: f64) -> Option { diff --git a/apps/desktop-gpui/src/transcript/tests.rs b/apps/desktop-gpui/src/transcript/tests.rs index 8847e7e82c2..8af1d3cbf1a 100644 --- a/apps/desktop-gpui/src/transcript/tests.rs +++ b/apps/desktop-gpui/src/transcript/tests.rs @@ -6,8 +6,8 @@ use cap_project::{ }; use super::cuts::{ - self, CutReport, ONSET_GUARD, RestoreBlocker, TAIL_GUARD, apply_source_cuts, gap_cut, - plan_pause_cuts, plan_word_cuts, quietest_point, restore_words, + self, CutReport, LONG_GAP, ONSET_GUARD, Removing, RestoreBlocker, TAIL_GUARD, + apply_source_cuts, gap_cut, plan_pause_cuts, plan_word_cuts, quietest_point, restore_words, }; use super::energy::{EnergyEnvelope, EnvelopeTrack, HOP_SECONDS, clip_envelope}; use super::model::{TranscriptDoc, TranscriptEdl, flatten_words}; @@ -105,7 +105,7 @@ fn cut_words( ) -> CutReport { let doc = TranscriptDoc::build(project.captions.as_ref().unwrap()); let runs: Vec> = runs.iter().map(|(start, end)| *start..*end).collect(); - let cuts = plan_word_cuts(&doc, None, &runs); + let cuts = plan_word_cuts(&doc, None, None, &runs); apply_source_cuts(timeline_mut(project), durations, &cuts) } @@ -355,9 +355,15 @@ fn words_in_later_recordings_map_through_the_recording_offsets() { cut_words(&mut project, &durations, &[(2, 3)]); assert_eq!(kept(&project, &durations), [true, true, false, true]); let segments = &timeline(&project).segments; - assert_eq!(segments.len(), 2); - assert_eq!(segments[1].recording_clip, 1); - assert!(segments[1].start > 1.4 && segments[1].start < 1.6); + assert_eq!(segments.len(), 3); + assert!( + segments[1..] + .iter() + .all(|segment| segment.recording_clip == 1) + ); + assert!(close(segments[1].start, 0.0)); + assert!(segments[1].end >= 1.0 - LONG_GAP / 2.0 && segments[1].end < 1.0 - ONSET_GUARD); + assert!(segments[2].start > 1.4 && segments[2].start < 1.6); } #[test] @@ -432,7 +438,7 @@ fn slivers_at_clip_edges_are_absorbed() { fn touching_words_cut_at_their_shared_boundary() { let data = captions(&[("one", 0.0, 0.5), ("two", 0.5, 1.0), ("three", 1.0, 1.5)]); let doc = TranscriptDoc::build(&data); - let point = gap_cut(&doc, None, 1); + let point = gap_cut(&doc, None, 1, Removing::After); assert!(close(point, 0.5)); } @@ -514,7 +520,7 @@ fn shortening_pauses_leaves_the_target_silence() { let pauses = plan_pause_cuts(&doc, &edl, None, 1.0, 0.5); assert_eq!(pauses.len(), 1); assert_eq!(pauses[0].after_word, 0); - let cuts: Vec<_> = pauses.iter().map(|pause| pause.cut.clone()).collect(); + let cuts: Vec<_> = pauses.iter().flat_map(|pause| pause.cuts.clone()).collect(); apply_source_cuts(timeline_mut(&mut project), &durations, &cuts); let (_, edl) = model(&project, &durations); let gap = edl.source_to_output(4.0).unwrap() - edl.source_to_output(1.4).unwrap(); @@ -550,7 +556,7 @@ fn hostile_transcripts_do_not_panic() { empty.captions = Some(captions(&[])); let doc = TranscriptDoc::build(empty.captions.as_ref().unwrap()); assert!(doc.is_empty()); - assert!(plan_word_cuts(&doc, None, std::slice::from_ref(&(0..3))).is_empty()); + assert!(plan_word_cuts(&doc, None, None, std::slice::from_ref(&(0..3))).is_empty()); } #[test] @@ -606,7 +612,7 @@ fn removing_hundreds_of_fillers_from_twenty_thousand_words_is_fast() { assert_eq!(runs.len(), 500); let started = std::time::Instant::now(); - let cuts = plan_word_cuts(&doc, None, &runs); + let cuts = plan_word_cuts(&doc, None, None, &runs); let report = apply_source_cuts(timeline_mut(&mut project), &durations, &cuts); let apply = started.elapsed(); assert_eq!(report.applied, 500); @@ -776,7 +782,7 @@ fn a_restored_take_keeps_the_speed_of_its_neighbours() { } #[test] -fn pauses_across_a_clip_boundary_are_left_alone() { +fn a_pause_across_a_clip_boundary_is_measured_at_each_clip_speed() { let words = [("before", 1.0, 1.4), ("after", 5.0, 5.4)]; let durations = [6.0]; let mut project = project(&words, &durations); @@ -787,9 +793,56 @@ fn pauses_across_a_clip_boundary_are_left_alone() { )); timeline_mut(&mut project).segments[1].timescale = 2.0; let (doc, edl) = model(&project, &durations); + let pauses = plan_pause_cuts(&doc, &edl, None, 1.0, 0.5); + assert_eq!(pauses.len(), 1); + assert!(close(pauses[0].length, 1.6 + 1.0), "{}", pauses[0].length); + assert_eq!(pauses[0].cuts.len(), 2); + let cuts: Vec<_> = pauses.iter().flat_map(|pause| pause.cuts.clone()).collect(); + apply_source_cuts(timeline_mut(&mut project), &durations, &cuts); + let (_, edl) = model(&project, &durations); + let gap = edl.source_to_output(5.0).unwrap() - edl.source_to_output(1.4).unwrap(); + assert!((gap - 0.5).abs() < 1e-6, "{gap}"); + assert!(plan_pause_cuts(&doc, &edl, None, 1.0, 0.5).is_empty()); +} + +#[test] +fn a_pause_that_crosses_a_transition_is_left_alone() { + let words = [("before", 1.0, 1.4), ("after", 5.0, 5.4)]; + let durations = [6.0]; + let mut project = project(&words, &durations); + let timeline = timeline_mut(&mut project); + assert!(editor_edits::split_clip_segment(timeline, 3.0, None)); + timeline.transitions.push(ClipTransition { + segment_index: 1, + kind: ClipTransitionType::CrossFade, + duration: 0.5, + }); + let (doc, edl) = model(&project, &durations); assert!(plan_pause_cuts(&doc, &edl, None, 1.0, 0.5).is_empty()); } +#[test] +fn a_pause_left_by_an_earlier_cut_joins_into_one() { + let words = [("before", 1.0, 1.4), ("um", 2.2, 2.5), ("after", 3.3, 3.7)]; + let durations = [5.0]; + let mut project = project(&words, &durations); + let (doc, edl) = model(&project, &durations); + assert!(plan_pause_cuts(&doc, &edl, None, 1.0, 0.5).is_empty()); + apply_source_cuts(timeline_mut(&mut project), &durations, &[2.15..2.55]); + let (doc, edl) = model(&project, &durations); + assert_eq!(edl.kept, [true, false, true]); + let pauses = plan_pause_cuts(&doc, &edl, None, 1.0, 0.5); + assert_eq!(pauses.len(), 1); + assert_eq!((pauses[0].after_word, pauses[0].next_word), (0, 2)); + assert!(close(pauses[0].length, 1.9 - 0.4), "{}", pauses[0].length); + let cuts: Vec<_> = pauses.iter().flat_map(|pause| pause.cuts.clone()).collect(); + assert_eq!(cuts.len(), 2); + apply_source_cuts(timeline_mut(&mut project), &durations, &cuts); + let (_, edl) = model(&project, &durations); + let gap = edl.source_to_output(3.3).unwrap() - edl.source_to_output(1.4).unwrap(); + assert!((gap - 0.5).abs() < 1e-6, "{gap}"); +} + #[test] fn pauses_are_measured_and_kept_in_playback_time() { let words = [("before", 1.0, 1.4), ("after", 5.0, 5.4)]; @@ -801,7 +854,7 @@ fn pauses_are_measured_and_kept_in_playback_time() { let pauses = plan_pause_cuts(&doc, &edl, None, 1.5, 0.5); assert_eq!(pauses.len(), 1); assert!(close(pauses[0].length, 1.8)); - let cuts: Vec<_> = pauses.iter().map(|pause| pause.cut.clone()).collect(); + let cuts: Vec<_> = pauses.iter().flat_map(|pause| pause.cuts.clone()).collect(); apply_source_cuts(timeline_mut(&mut project), &durations, &cuts); let (_, edl) = model(&project, &durations); let gap = edl.source_to_output(5.0).unwrap() - edl.source_to_output(1.4).unwrap(); @@ -983,11 +1036,11 @@ fn partly_trimmed_words_map_to_their_surviving_part() { assert_eq!(edl.source_to_output(doc.words[0].start), None); assert_eq!(edl.source_to_output(doc.words[2].end), None); - let start = edl.output_start_of(&doc.words[0]).unwrap(); + let start = edl.output_start_of(&doc.voiced[0]).unwrap(); assert!(close(start, 0.0), "{start}"); - let end = edl.output_end_of(&doc.words[2]).unwrap(); + let end = edl.output_end_of(&doc.voiced[2]).unwrap(); assert!(close(end, 2.2 - 0.65), "{end}"); - let middle = edl.output_start_of(&doc.words[1]).unwrap(); + let middle = edl.output_start_of(&doc.voiced[1]).unwrap(); assert!(close(middle, 1.2 - 0.65), "{middle}"); } @@ -1043,3 +1096,675 @@ fn a_restored_take_comes_back_with_its_own_settings() { 2.0 + 1.0 + 2.0 )); } + +struct Speech { + envelope: EnergyEnvelope, + voiced: Vec<(f64, f64)>, + duration: f64, +} + +fn synthetic_speech(voiced: &[(f64, f64)], duration: f64) -> Speech { + synthetic_speech_in(voiced, duration, |_| 0.002) +} + +fn synthetic_speech_in( + voiced: &[(f64, f64)], + duration: f64, + room_level: impl Fn(f64) -> f64, +) -> Speech { + let rate = 48_000.0; + let mut state: u32 = 0x9e37_79b9; + let mut noise = move || { + state ^= state << 13; + state ^= state >> 17; + state ^= state << 5; + (state as f64 / u32::MAX as f64) * 2.0 - 1.0 + }; + let samples: Vec = (0..(duration * rate) as usize) + .map(|index| { + let time = index as f64 / rate; + let room = noise() * room_level(time); + let Some(&(start, end)) = voiced + .iter() + .find(|(start, end)| (*start..*end).contains(&time)) + else { + return room as f32; + }; + let local = time - start; + let closure = end - start > 0.3 + && ((end - start) / 2.0..(end - start) / 2.0 + 0.06).contains(&local); + let voice = if local < 0.05 { + noise() * 0.015 + } else if closure { + 0.0 + } else { + let syllable = 0.6 + 0.4 * (std::f64::consts::TAU * 4.0 * local).sin(); + (1..=4) + .map(|harmonic| { + (std::f64::consts::TAU * 140.0 * harmonic as f64 * time).sin() + / harmonic as f64 + }) + .sum::() + * 0.05 + * syllable + }; + (room + voice) as f32 + }) + .collect(); + let clip = clip_envelope( + &[EnvelopeTrack { + slices: vec![samples.as_slice()], + channels: 1, + offset_seconds: 0.0, + }], + duration, + ); + Speech { + envelope: EnergyEnvelope::new(vec![clip], &[duration]), + voiced: voiced.to_vec(), + duration, + } +} + +impl Speech { + fn overlaps_voice(&self, range: &Range) -> bool { + self.voiced + .iter() + .any(|(start, end)| range.start < *end && *start < range.end) + } + + fn all_quiet(&self, range: &Range) -> bool { + let threshold = self.envelope.silence_threshold_db(range.start).unwrap(); + let mut time = range.start; + while time <= range.end { + if self.envelope.smoothed_db(time).unwrap() >= threshold { + return false; + } + time += HOP_SECONDS; + } + true + } +} + +const RICHIE_VOICED: [(f64, f64); 8] = [ + (0.50, 0.80), + (0.86, 1.25), + (1.30, 1.75), + (2.95, 3.40), + (4.70, 5.10), + (5.16, 5.50), + (7.70, 8.10), + (8.16, 8.70), +]; + +const RICHIE_WORDS: [(&str, f64, f64); 8] = [ + ("Just", 0.50, 0.86), + ("doing", 0.86, 1.30), + ("works.", 1.30, 2.95), + ("Um", 2.95, 4.60), + ("Yeah,", 4.60, 5.16), + ("should", 5.16, 7.30), + ("make", 7.30, 8.16), + ("faster.", 8.16, 9.90), +]; + +fn stretched_fixture() -> (Speech, ProjectConfiguration, TranscriptDoc) { + let speech = synthetic_speech(&RICHIE_VOICED, 10.0); + let project = project(&RICHIE_WORDS, &[speech.duration]); + let mut doc = TranscriptDoc::build(project.captions.as_ref().unwrap()); + doc.refine_voiced(Some(&speech.envelope)); + (speech, project, doc) +} + +#[test] +fn silences_are_found_from_the_audio_in_room_noise() { + let voiced = [ + (0.5, 1.0), + (1.1, 1.6), + (1.75, 2.2), + (2.6, 3.1), + (4.3, 4.8), + (6.8, 7.3), + ]; + let speech = synthetic_speech(&voiced, 8.0); + let found = speech.envelope.silences(); + let threshold = speech.envelope.silence_threshold_db(1.0).unwrap(); + assert!((-50.0..-40.0).contains(&threshold), "{threshold}"); + for silence in found { + assert!(!speech.overlaps_voice(silence), "{silence:?}"); + } + let between: Vec<_> = found + .iter() + .filter(|silence| silence.start > 0.5 && silence.end <= 6.8 + 1e-6) + .collect(); + assert_eq!(between.len(), 3, "{found:?}"); + for (silence, (start, end)) in between.iter().zip([(2.2, 2.6), (3.1, 4.3), (4.8, 6.8)]) { + assert!( + silence.start - start < 0.03 && end - silence.end < 0.03, + "{silence:?}" + ); + } +} + +#[test] +fn stretched_words_are_trimmed_to_their_voiced_part() { + let (_, _, doc) = stretched_fixture(); + let near = |a: f64, b: f64| (a - b).abs() < 0.03; + for (index, word) in doc.words.iter().enumerate() { + let span = &doc.voiced[index]; + let (start, end) = match index { + 2 => (word.start, 1.75), + 3 => (word.start, 3.40), + 5 => (word.start, 5.50), + 6 => (7.70, word.end), + 7 => (word.start, 8.70), + _ => (word.start, word.end), + }; + assert!( + near(span.start, start) && near(span.end, end), + "{index} {span:?}" + ); + if !matches!(index, 2 | 3 | 5 | 6 | 7) { + assert_eq!(*span, word.start..word.end); + } + } +} + +#[test] +fn accurate_word_times_are_left_as_they_are() { + let speech = synthetic_speech(&RICHIE_VOICED, 10.0); + let words: Vec<_> = [ + "Just", "doing", "works.", "Um", "Yeah,", "should", "make", "faster.", + ] + .iter() + .zip(RICHIE_VOICED) + .map(|(text, (start, end))| (*text, start, end)) + .collect(); + let project = project(&words, &[speech.duration]); + let mut doc = TranscriptDoc::build(project.captions.as_ref().unwrap()); + let plain = doc.voiced.clone(); + doc.refine_voiced(Some(&speech.envelope)); + assert_eq!(doc.voiced, plain); +} + +#[test] +fn stretched_words_get_their_pauses_from_the_audio() { + let (speech, mut project, doc) = stretched_fixture(); + let durations = [speech.duration]; + let plain = TranscriptDoc::build(project.captions.as_ref().unwrap()); + let edl = TranscriptEdl::build(&plain, timeline(&project), &durations); + assert!(plan_pause_cuts(&plain, &edl, Some(&speech.envelope), 1.0, 0.5).is_empty()); + + let edl = TranscriptEdl::build(&doc, timeline(&project), &durations); + let pauses = plan_pause_cuts(&doc, &edl, Some(&speech.envelope), 1.0, 0.5); + let found: Vec<_> = pauses + .iter() + .map(|pause| (pause.after_word, pause.next_word)) + .collect(); + assert_eq!(found, [(2, 3), (3, 4), (5, 6)]); + for (pause, length) in pauses.iter().zip([1.2, 1.2, 2.2]) { + assert!((pause.length - length).abs() < 0.05, "{pause:?}"); + for cut in &pause.cuts { + assert!(!speech.overlaps_voice(cut), "{cut:?}"); + assert!(speech.all_quiet(cut), "{cut:?}"); + } + } + let cuts: Vec<_> = pauses.iter().flat_map(|pause| pause.cuts.clone()).collect(); + apply_source_cuts(timeline_mut(&mut project), &durations, &cuts); + let edl = TranscriptEdl::build(&doc, timeline(&project), &durations); + assert!(edl.kept.iter().all(|kept| *kept)); + for (before, after) in [(2, 3), (3, 4), (5, 6)] { + let gap = edl.output_start_of(&doc.voiced[after]).unwrap() + - edl.output_end_of(&doc.voiced[before]).unwrap(); + assert!((gap - 0.5).abs() < 0.01, "{before} {gap}"); + } + assert!(plan_pause_cuts(&doc, &edl, Some(&speech.envelope), 1.0, 0.5).is_empty()); +} + +#[test] +fn deleting_a_stretched_word_keeps_the_silence_beside_it() { + let (speech, mut project, doc) = stretched_fixture(); + let durations = [speech.duration]; + let cuts = plan_word_cuts(&doc, Some(&speech.envelope), None, &[3..4]); + assert_eq!(cuts.len(), 1); + let cut = &cuts[0]; + assert!( + cut.start <= 2.95 - ONSET_GUARD && cut.end >= 3.40 + TAIL_GUARD, + "{cut:?}" + ); + let silence_removed = (2.95 - cut.start) + (cut.end - 3.40); + assert!(silence_removed <= LONG_GAP + 1e-9, "{cut:?}"); + for (start, end) in RICHIE_VOICED.iter().filter(|(start, _)| *start != 2.95) { + assert!(!(cut.start < *end && *start < cut.end), "{cut:?}"); + } + + apply_source_cuts(timeline_mut(&mut project), &durations, &cuts); + let edl = TranscriptEdl::build(&doc, timeline(&project), &durations); + assert_eq!(edl.kept, [true, true, true, false, true, true, true, true]); + let pauses = plan_pause_cuts(&doc, &edl, Some(&speech.envelope), 1.0, 0.5); + assert_eq!( + (pauses[0].after_word, pauses[0].next_word), + (2, 4), + "{pauses:?}" + ); + assert!(pauses[0].length > 1.5, "{:?}", pauses[0]); +} + +#[test] +fn deleting_neighbours_one_at_a_time_matches_deleting_them_together() { + let (speech, _, doc) = stretched_fixture(); + let together = plan_word_cuts(&doc, Some(&speech.envelope), None, &[2..4]); + let first = plan_word_cuts(&doc, Some(&speech.envelope), None, &[2..3]); + let mut kept = vec![true; doc.words.len()]; + kept[2] = false; + let second = plan_word_cuts(&doc, Some(&speech.envelope), Some(&kept), &[3..4]); + assert!(close(first[0].start, together[0].start)); + assert!(close(second[0].end, together[0].end)); + assert!( + second[0].start <= first[0].end + 1e-9, + "{first:?} {second:?}" + ); +} + +#[test] +fn short_gaps_cut_at_the_same_point_from_either_side() { + let (speech, _, doc) = stretched_fixture(); + for index in [1, 2, 5, 7] { + let after = gap_cut(&doc, Some(&speech.envelope), index, Removing::After); + let before = gap_cut(&doc, Some(&speech.envelope), index, Removing::Before); + let gap = doc.voiced[index].start - doc.voiced[index - 1].end; + if gap <= LONG_GAP { + assert!(close(after, before), "{index}"); + } + } +} + +#[test] +fn silence_detection_on_two_hours_is_fast() { + let hops = (7200.0 / HOP_SECONDS) as usize; + let clip: Vec = (0..hops) + .map(|hop| { + let phase = hop % 400; + if phase < 300 { + 0.003 * (1.0 + (hop % 7) as f32) + } else { + 0.000_002 * (1.0 + (hop % 3) as f32) + } + }) + .collect(); + let started = std::time::Instant::now(); + let envelope = EnergyEnvelope::new(vec![clip], &[7200.0]); + let elapsed = started.elapsed(); + assert_eq!(envelope.silences().len(), hops / 400); + let limit = std::time::Duration::from_millis(if cfg!(debug_assertions) { 3000 } else { 200 }); + println!("2 h silence detection {elapsed:?}"); + assert!(elapsed < limit, "{elapsed:?}"); +} + +#[test] +fn a_word_whose_audio_sits_in_its_neighbour_is_treated_as_silence() { + let speech = synthetic_speech(&[(0.2, 0.9), (2.2, 2.9)], 3.5); + let words = [ + ("as", 0.2, 0.85), + ("fast.", 0.85, 1.9), + ("Hopefully", 1.9, 2.9), + ]; + let durations = [speech.duration]; + let mut project = project(&words, &durations); + let mut doc = TranscriptDoc::build(project.captions.as_ref().unwrap()); + doc.refine_voiced(Some(&speech.envelope)); + assert!(doc.voiced[1].is_empty(), "{:?}", doc.voiced[1]); + assert!( + (doc.voiced[1].start - 0.9).abs() < 0.03, + "{:?}", + doc.voiced[1] + ); + assert!( + (doc.voiced[2].start - 2.2).abs() < 0.03, + "{:?}", + doc.voiced[2] + ); + + let edl = TranscriptEdl::build(&doc, timeline(&project), &durations); + let pauses = plan_pause_cuts(&doc, &edl, Some(&speech.envelope), 1.0, 0.5); + assert_eq!(pauses.len(), 1, "{pauses:?}"); + assert_eq!((pauses[0].after_word, pauses[0].next_word), (0, 2)); + for cut in &pauses[0].cuts { + assert!(!speech.overlaps_voice(cut), "{cut:?}"); + assert!(speech.all_quiet(cut), "{cut:?}"); + } + let cuts: Vec<_> = pauses.iter().flat_map(|pause| pause.cuts.clone()).collect(); + apply_source_cuts(timeline_mut(&mut project), &durations, &cuts); + let edl = TranscriptEdl::build(&doc, timeline(&project), &durations); + assert_eq!(edl.kept, [true, true, true]); +} + +fn shape(start: f64, end: f64) -> cap_project::ShapeSegment { + cap_project::ShapeSegment { + start, + end, + ..Default::default() + } +} + +fn shape_bounds(project: &ProjectConfiguration) -> Vec<(f64, f64)> { + timeline(project) + .shape_segments + .iter() + .map(|segment| (segment.start, segment.end)) + .collect() +} + +#[test] +fn shapes_follow_shortened_pauses_and_come_back_on_undo() { + let (speech, mut project, doc) = stretched_fixture(); + let durations = [speech.duration]; + timeline_mut(&mut project).shape_segments = + vec![shape(0.6, 0.9), shape(5.2, 7.9), shape(8.2, 8.6)]; + let original = shape_bounds(&project); + let mut history = editor_edits::ProjectHistory::new(project.clone()); + let before = editor_edits::clip_timeline_duration(timeline(&project)); + + let edl = TranscriptEdl::build(&doc, timeline(&project), &durations); + let pauses = plan_pause_cuts(&doc, &edl, Some(&speech.envelope), 1.0, 0.5); + assert_eq!(pauses.len(), 3); + let inside_spanning: f64 = pauses + .iter() + .filter(|pause| pause.after_word == 5) + .map(|pause| pause.saves) + .sum(); + let cuts: Vec<_> = pauses.iter().flat_map(|pause| pause.cuts.clone()).collect(); + apply_source_cuts(timeline_mut(&mut project), &durations, &cuts); + history.record(&project); + let removed = before - editor_edits::clip_timeline_duration(timeline(&project)); + let saved: f64 = pauses.iter().map(|pause| pause.saves).sum(); + assert!((removed - saved).abs() < 1e-6, "{removed} {saved}"); + + let shapes = shape_bounds(&project); + assert_eq!(shapes[0], original[0]); + let before_spanning = saved - inside_spanning; + assert!( + close(shapes[1].0, original[1].0 - before_spanning), + "{shapes:?}" + ); + assert!(close(shapes[1].1, original[1].1 - saved), "{shapes:?}"); + assert!(close(shapes[2].0, original[2].0 - removed), "{shapes:?}"); + assert!(close(shapes[2].1, original[2].1 - removed), "{shapes:?}"); + + let undone = history.undo().unwrap().clone(); + assert_eq!(shape_bounds(&undone), original); +} + +#[test] +fn shapes_follow_a_deleted_stretched_word_and_come_back_on_restore() { + let (speech, mut project, doc) = stretched_fixture(); + let durations = [speech.duration]; + timeline_mut(&mut project).shape_segments = vec![shape(1.0, 1.2), shape(5.0, 5.4)]; + let original = shape_bounds(&project); + let before = editor_edits::clip_timeline_duration(timeline(&project)); + + let cuts = plan_word_cuts(&doc, Some(&speech.envelope), None, &[3..4]); + apply_source_cuts(timeline_mut(&mut project), &durations, &cuts); + let removed = before - editor_edits::clip_timeline_duration(timeline(&project)); + assert!(close(removed, cuts[0].end - cuts[0].start)); + let shapes = shape_bounds(&project); + assert_eq!(shapes[0], original[0]); + assert!(close(shapes[1].0, original[1].0 - removed), "{shapes:?}"); + assert!(close(shapes[1].1, original[1].1 - removed), "{shapes:?}"); + + let restored = restore_words(timeline_mut(&mut project), &durations, &[], &doc, 3..4).unwrap(); + assert_eq!(restored, 1); + let shapes = shape_bounds(&project); + for (shape, original) in shapes.iter().zip(&original) { + assert!( + close(shape.0, original.0) && close(shape.1, original.1), + "{shapes:?}" + ); + } +} + +#[test] +fn a_noise_gated_recording_finds_its_digital_silence_and_keeps_every_word() { + let speech = synthetic_speech_in(&RICHIE_VOICED, 10.0, |_| 0.0); + let threshold = speech.envelope.silence_threshold_db(1.0).unwrap(); + assert!(threshold < -80.0, "{threshold}"); + for silence in speech.envelope.silences() { + assert!(!speech.overlaps_voice(silence), "{silence:?}"); + } + let words: Vec<_> = [ + "Just", "doing", "works.", "Um", "Yeah,", "should", "make", "faster.", + ] + .iter() + .zip(RICHIE_VOICED) + .map(|(text, (start, end))| (*text, start, end)) + .collect(); + let accurate = project(&words, &[speech.duration]); + let mut doc = TranscriptDoc::build(accurate.captions.as_ref().unwrap()); + let plain = doc.voiced.clone(); + doc.refine_voiced(Some(&speech.envelope)); + assert_eq!(doc.voiced, plain); + + let stretched = project(&RICHIE_WORDS, &[speech.duration]); + let mut doc = TranscriptDoc::build(stretched.captions.as_ref().unwrap()); + doc.refine_voiced(Some(&speech.envelope)); + assert!(doc.voiced.iter().all(|span| !span.is_empty())); + let edl = TranscriptEdl::build(&doc, timeline(&stretched), &[speech.duration]); + let pauses = plan_pause_cuts(&doc, &edl, Some(&speech.envelope), 1.0, 0.5); + assert_eq!(pauses.len(), 3, "{pauses:?}"); + for cut in pauses.iter().flat_map(|pause| &pause.cuts) { + assert!(!speech.overlaps_voice(cut), "{cut:?}"); + } +} + +#[test] +fn a_recording_with_no_quiet_moment_reports_no_silence() { + let speech = synthetic_speech_in(&[(0.0, 6.0)], 6.0, |_| 0.0); + assert!( + speech.envelope.silences().is_empty(), + "{:?}", + speech.envelope.silences() + ); + let quiet: Vec = (0..1200) + .map(|hop| 0.001 * (1.0 + 0.3 * ((hop % 9) as f32 / 9.0))) + .collect(); + let envelope = EnergyEnvelope::new(vec![quiet], &[6.0]); + assert!(envelope.silences().is_empty()); + assert!(envelope.silence_threshold_db(1.0).unwrap() <= -90.0); +} + +#[test] +fn restoring_a_trimmed_word_leaves_a_shortened_pause_cut() { + let speech = synthetic_speech(&[(0.5, 0.9), (3.5, 4.0), (4.1, 4.5)], 5.0); + let words = [("a", 0.5, 0.9), ("long", 1.0, 4.0), ("b", 4.0, 4.5)]; + let durations = [speech.duration]; + let mut project = project(&words, &durations); + let mut doc = TranscriptDoc::build(project.captions.as_ref().unwrap()); + doc.refine_voiced(Some(&speech.envelope)); + assert!( + (doc.voiced[1].start - 3.5).abs() < 0.03, + "{:?}", + doc.voiced[1] + ); + + let edl = TranscriptEdl::build(&doc, timeline(&project), &durations); + let pauses = plan_pause_cuts(&doc, &edl, Some(&speech.envelope), 1.0, 0.5); + assert_eq!(pauses.len(), 1, "{pauses:?}"); + apply_source_cuts(timeline_mut(&mut project), &durations, &pauses[0].cuts); + let shortened = bounds(&project); + + let edl = TranscriptEdl::build(&doc, timeline(&project), &durations); + let cuts = plan_word_cuts(&doc, Some(&speech.envelope), Some(&edl.kept), &[1..2]); + apply_source_cuts(timeline_mut(&mut project), &durations, &cuts); + let edl = TranscriptEdl::build(&doc, timeline(&project), &durations); + assert_eq!(edl.kept, [true, false, true]); + + let restored = restore_words(timeline_mut(&mut project), &durations, &[], &doc, 1..2).unwrap(); + assert_eq!(restored, 1); + let edl = TranscriptEdl::build(&doc, timeline(&project), &durations); + assert_eq!(edl.kept, [true, true, true]); + let after = bounds(&project); + assert_eq!(after.len(), shortened.len(), "{after:?} {shortened:?}"); + for (a, b) in after.iter().zip(&shortened) { + assert!( + close(a.0, b.0) && close(a.1, b.1), + "{after:?} {shortened:?}" + ); + } +} + +#[test] +fn a_few_words_in_a_long_quiet_recording_still_find_their_pause() { + let voiced = [(1.0, 1.4), (1.5, 1.9), (30.0, 30.4), (30.5, 30.9)]; + let speech = synthetic_speech(&voiced, 40.0); + let threshold = speech.envelope.silence_threshold_db(1.0).unwrap(); + assert!((-55.0..-35.0).contains(&threshold), "{threshold}"); + let words = [ + ("one", 1.0, 1.45), + ("two", 1.45, 29.0), + ("three", 29.0, 30.45), + ("four", 30.45, 30.9), + ]; + let durations = [speech.duration]; + let project = project(&words, &durations); + let mut doc = TranscriptDoc::build(project.captions.as_ref().unwrap()); + doc.refine_voiced(Some(&speech.envelope)); + assert!( + (doc.voiced[1].end - 1.9).abs() < 0.03, + "{:?}", + doc.voiced[1] + ); + assert!( + (doc.voiced[2].start - 30.0).abs() < 0.03, + "{:?}", + doc.voiced[2] + ); + let edl = TranscriptEdl::build(&doc, timeline(&project), &durations); + let pauses = plan_pause_cuts(&doc, &edl, Some(&speech.envelope), 1.0, 0.5); + assert_eq!(pauses.len(), 1, "{pauses:?}"); + assert_eq!((pauses[0].after_word, pauses[0].next_word), (1, 2)); + for cut in &pauses[0].cuts { + assert!(!speech.overlaps_voice(cut), "{cut:?}"); + assert!(speech.all_quiet(cut), "{cut:?}"); + } +} + +#[test] +fn a_background_that_changes_level_still_counts_as_quiet() { + let voiced = [ + (3.0, 3.5), + (3.6, 4.1), + (6.0, 6.5), + (6.6, 7.1), + (10.0, 10.5), + (10.6, 11.1), + (14.0, 14.5), + (14.6, 15.1), + ]; + let speech = synthetic_speech_in( + &voiced, + 20.0, + |time| if time < 2.0 { 0.0008 } else { 0.0035 }, + ); + let threshold = speech.envelope.silence_threshold_db(1.0).unwrap(); + assert!((-55.0..-35.0).contains(&threshold), "{threshold}"); + let found = speech.envelope.silences(); + for silence in found { + assert!(!speech.overlaps_voice(silence), "{silence:?}"); + } + for (start, end) in [(4.1, 6.0), (7.1, 10.0), (11.1, 14.0)] { + assert!( + found + .iter() + .any(|silence| silence.start - start < 0.03 && end - silence.end < 0.03), + "{start} {found:?}" + ); + } +} + +#[test] +fn a_brief_loud_sound_does_not_turn_a_quiet_word_into_silence() { + let level = |db: f64| 10f64.powf(db / 10.0) as f32; + let hops = (60.0 / HOP_SECONDS) as usize; + let at = |seconds: f64| (seconds / HOP_SECONDS) as usize; + let mut clip: Vec = (0..hops) + .map(|hop| level(-60.0 + (hop % 5) as f64 * 0.4)) + .collect(); + let mut fill = |from: f64, until: f64, db: f64| { + for (offset, hop) in clip[at(from)..at(until)].iter_mut().enumerate() { + *hop = level(db + (offset % 5) as f64 * 0.25 - 0.5); + } + }; + for second in 0..18 { + let start = 2.0 + second as f64 * 3.0; + fill(start, start + 1.0, -40.0); + } + fill(10.2, 10.7, -48.0); + fill(30.2, 30.7, -20.0); + let envelope = EnergyEnvelope::new(vec![clip], &[60.0]); + let threshold = envelope.silence_threshold_db(1.0).unwrap(); + assert!(threshold < -48.5, "{threshold}"); + assert!( + envelope.silences_overlapping(10.21..10.69).is_empty(), + "{:?}", + envelope.silences_overlapping(10.21..10.69) + ); + let between = envelope.silences_overlapping(3.0..5.0); + assert!( + between + .iter() + .any(|silence| silence.start < 3.05 && silence.end > 4.95), + "{between:?}" + ); +} + +fn three_words_with_a_cut(cut: Range) -> (ProjectConfiguration, TranscriptDoc, TranscriptEdl) { + let words = [ + ("before", 1.0, 1.4), + ("middle", 2.2, 2.8), + ("after", 4.0, 4.4), + ]; + let durations = [5.0]; + let mut project = project(&words, &durations); + apply_source_cuts(timeline_mut(&mut project), &durations, &[cut]); + let (doc, edl) = model(&project, &durations); + (project, doc, edl) +} + +#[test] +fn a_pause_never_cuts_the_audible_tail_of_a_mostly_cut_word() { + let (_, doc, edl) = three_words_with_a_cut(2.2..2.55); + assert_eq!(edl.kept, [true, false, true]); + let pauses = plan_pause_cuts(&doc, &edl, None, 1.0, 0.5); + assert_eq!(pauses.len(), 1, "{pauses:?}"); + assert_eq!((pauses[0].after_word, pauses[0].next_word), (1, 2)); + assert!(close(pauses[0].length, 1.2), "{:?}", pauses[0]); + for cut in pauses.iter().flat_map(|pause| &pause.cuts) { + assert!(cut.end <= 2.55 || cut.start >= 2.8, "{cut:?}"); + } +} + +#[test] +fn a_pause_never_cuts_the_audible_head_of_a_mostly_cut_word() { + let (_, doc, edl) = three_words_with_a_cut(2.45..2.8); + assert_eq!(edl.kept, [true, false, true]); + let pauses = plan_pause_cuts(&doc, &edl, None, 1.0, 0.5); + assert_eq!(pauses.len(), 1, "{pauses:?}"); + assert_eq!((pauses[0].after_word, pauses[0].next_word), (1, 2)); + assert!(close(pauses[0].length, 1.2), "{:?}", pauses[0]); + for cut in pauses.iter().flat_map(|pause| &pause.cuts) { + assert!(cut.end <= 2.2 || cut.start >= 2.45, "{cut:?}"); + } +} + +#[test] +fn a_word_cut_entirely_still_lets_the_pause_around_it_join() { + let (_, doc, edl) = three_words_with_a_cut(2.15..2.85); + assert_eq!(edl.kept, [true, false, true]); + let pauses = plan_pause_cuts(&doc, &edl, None, 1.0, 0.5); + assert_eq!(pauses.len(), 1, "{pauses:?}"); + assert_eq!((pauses[0].after_word, pauses[0].next_word), (0, 2)); + assert!(close(pauses[0].length, 0.75 + 1.15), "{:?}", pauses[0]); + for cut in pauses.iter().flat_map(|pause| &pause.cuts) { + assert!(cut.end <= 2.15 || cut.start >= 2.85, "{cut:?}"); + } +} diff --git a/apps/desktop-gpui/src/transcript/view.rs b/apps/desktop-gpui/src/transcript/view.rs index 89d27dc43ae..7fc0a9a9752 100644 --- a/apps/desktop-gpui/src/transcript/view.rs +++ b/apps/desktop-gpui/src/transcript/view.rs @@ -265,7 +265,7 @@ impl ParagraphPainter { let first_kept = paragraph.words.clone().find(|word| self.is_kept(*word)); let stamp = first_kept - .and_then(|word| self.edl.as_ref()?.output_start_of(&self.doc.words[word])) + .and_then(|word| self.edl.as_ref()?.output_start_of(&self.doc.voiced[word])) .map(crate::editor_timeline::format_time); let hovering_cut_here = self .hovered_cut @@ -401,7 +401,7 @@ fn filler_row( }, )]); let stamp = edl - .output_start_of(&doc.words[words.start]) + .output_start_of(&doc.voiced[words.start]) .map(crate::editor_timeline::format_time) .unwrap_or_default(); let on_row = { @@ -495,18 +495,15 @@ fn pause_row( theme: &Theme, palette: Palette, doc: &TranscriptDoc, - edl: &TranscriptEdl, pause: &cuts::PauseCut, keep: f64, editor: WeakEntity, ) -> AnyElement { let word = pause.after_word; - let stamp = edl - .output_end_of(&doc.words[word]) - .map(crate::editor_timeline::format_time) - .unwrap_or_default(); + let next = pause.next_word; + let stamp = crate::editor_timeline::format_time(pause.output.start); let before = doc.text_of(word.saturating_sub(3)..word + 1); - let after = doc.text_of(word + 1..(word + 4).min(doc.words.len())); + let after = doc.text_of(next..(next + 3).min(doc.words.len())); let text = format!( "{before} {} → {} {after}", seconds_label(pause.length), @@ -528,7 +525,7 @@ fn pause_row( editor .update(cx, |this, cx| { window.focus(&this.transcript.focus, cx); - this.transcript_focus_filler(word..word + 2, true, cx); + this.transcript_focus_filler(word..next + 1, true, cx); }) .ok(); }) @@ -694,7 +691,7 @@ impl EditorWindow { return; }; let Some(output) = doc - .words + .voiced .get(word) .and_then(|word| edl.output_start_of(word)) else { @@ -1020,8 +1017,8 @@ impl EditorWindow { }; let last = kept.next_back().unwrap_or(first); let (Some(from), Some(until)) = ( - edl.output_start_of(&doc.words[first]), - edl.output_end_of(&doc.words[last]), + edl.output_start_of(&doc.voiced[first]), + edl.output_end_of(&doc.voiced[last]), ) else { return; }; @@ -1039,7 +1036,13 @@ impl EditorWindow { return CutReport::default(); }; let energy = self.transcript.energy.clone(); - let cuts = cuts::plan_word_cuts(&doc, energy.as_deref(), runs); + let edl = self.transcript.edl.clone(); + let cuts = cuts::plan_word_cuts( + &doc, + energy.as_deref(), + edl.as_ref().map(|edl| edl.kept.as_slice()), + runs, + ); self.transcript_apply_cuts(&cuts, reason, window, cx) } @@ -1134,7 +1137,7 @@ impl EditorWindow { { let join = (first..doc.words.len()) .find(|word| edl.is_kept(*word)) - .and_then(|word| edl.output_start_of(&doc.words[word])); + .and_then(|word| edl.output_start_of(&doc.voiced[word])); if let Some(join) = join { self.seek_to_time(join, cx); self.transcript_sync_active(false, cx); @@ -1375,8 +1378,8 @@ impl EditorWindow { self.transcript_reveal(words.start, false); if listen && let (Some(start), Some(end)) = ( - edl.output_start_of(&doc.words[words.start]), - edl.output_end_of(&doc.words[words.end - 1]), + edl.output_start_of(&doc.voiced[words.start]), + edl.output_end_of(&doc.voiced[words.end - 1]), ) { self.play_range((start - LISTEN_BEFORE).max(0.0), end + LISTEN_AFTER, cx); @@ -1386,7 +1389,7 @@ impl EditorWindow { self.invalidate_transcript(cx); } - fn transcript_pause_plan(&self) -> Vec { + pub(super) fn transcript_pause_plan(&self) -> Vec { let (Some(doc), Some(edl)) = (&self.transcript.doc, &self.transcript.edl) else { return Vec::new(); }; @@ -1407,7 +1410,7 @@ impl EditorWindow { let cuts: Vec> = self .transcript_pause_plan() .into_iter() - .map(|pause| pause.cut) + .flat_map(|pause| pause.cuts) .collect(); self.transcript_apply_cuts(&cuts, "transcript-shorten-pauses", window, cx); self.invalidate_transcript(cx); @@ -1802,7 +1805,7 @@ impl EditorWindow { .child(action); let body = if on_pauses { - self.render_transcript_pause_list(&doc, &edl, pauses, saved, palette, cx) + self.render_transcript_pause_list(&doc, pauses, saved, palette, cx) } else { self.render_transcript_filler_list(&doc, &edl, listed, counts, palette, cx) }; @@ -1987,7 +1990,6 @@ impl EditorWindow { fn render_transcript_pause_list( &self, doc: &Arc, - edl: &Arc, pauses: Vec, saved: f64, palette: Palette, @@ -2064,16 +2066,13 @@ impl EditorWindow { let count = pauses.len(); let rows = { let doc = doc.clone(); - let edl = edl.clone(); let pauses = Arc::new(pauses); let keep = cleanup.pause_keep; let editor = cx.entity().downgrade(); gpui::uniform_list("transcript-pause-rows", count, move |range, _, _| { range .filter_map(|row| pauses.get(row)) - .map(|pause| { - pause_row(&theme, palette, &doc, &edl, pause, keep, editor.clone()) - }) + .map(|pause| pause_row(&theme, palette, &doc, pause, keep, editor.clone())) .collect::>() }) .track_scroll(&cleanup.pause_rows) @@ -2130,8 +2129,8 @@ impl EditorWindow { let first = kept_words.next().unwrap_or(range.start); let last = kept_words.next_back().unwrap_or(first); let seconds = edl - .output_end_of(&doc.words[last]) - .zip(edl.output_start_of(&doc.words[first])) + .output_end_of(&doc.voiced[last]) + .zip(edl.output_start_of(&doc.voiced[first])) .map_or(0.0, |(end, start)| (end - start).max(0.0)); tr::editor::transcript::selection( kept, @@ -2309,6 +2308,7 @@ impl EditorWindow { } if !envelope.is_empty() { self.transcript.energy = Some(Arc::new(envelope)); + self.transcript.dirty = true; } self.invalidate_transcript(cx); true @@ -2374,6 +2374,8 @@ impl EditorWindow { .await; tracing::info!( elapsed_ms = started.elapsed().as_secs_f64() * 1000.0, + silences = envelope.silences().len(), + silence_threshold_db = envelope.silence_threshold_db(0.0), "transcript loudness envelope ready" ); this.update(cx, |this, cx| {