Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
perf(project): skip disjoint caption word scans
Ehsan-hash398552be7027
diff --git a/crates/project/examples/caption-projection-benchmark.rs b/crates/project/examples/caption-projection-benchmark.rsnew file mode 100644index 000000000..7a46b527a--- /dev/null+++ b/crates/project/examples/caption-projection-benchmark.rs@@ -0,0 +1,121 @@+use cap_project::{+ CaptionSegment, CaptionWord, CaptionsData, ProjectConfiguration, TimelineConfiguration,+ synchronize_captions,+};+use std::{+ collections::hash_map::DefaultHasher,+ error::Error,+ hash::{Hash, Hasher},+ hint::black_box,+ time::Instant,+};++fn fixture(seconds: usize, clips: usize, spacing: usize) -> ProjectConfiguration {+ let source_segments = (0..seconds / 4)+ .map(|index| {+ let start = 5.0 + (index * 4) as f32;+ CaptionSegment {+ id: format!("caption-{index}"),+ start,+ end: start + 4.0,+ text: "spoken words".into(),+ words: (0..10)+ .map(|word| {+ let start = start + word as f32 * 0.4;+ CaptionWord {+ text: "word".into(),+ start,+ end: start + 0.3,+ }+ })+ .collect(),+ }+ })+ .collect();+ let segments: Vec<_> = (0..clips)+ .map(|index| {+ let start = index * spacing;+ let end = if clips == 1 { seconds } else { start + 4 };+ serde_json::json!({+ "start": start, "end": end, "timescale": 1.0, "recordingSegment": 1+ })+ })+ .collect();+ let timeline: TimelineConfiguration = serde_json::from_value(serde_json::json!({+ "segments": segments, "zoomSegments": []+ }))+ .unwrap();+ assert!(+ timeline+ .segments+ .iter()+ .all(|clip| clip.recording_clip == 1)+ );+ ProjectConfiguration {+ captions: Some(CaptionsData {+ source_timed: true,+ segments: source_segments,+ ..Default::default()+ }),+ timeline: Some(timeline),+ ..Default::default()+ }+}++fn main() -> Result<(), Box<dyn Error>> {+ let mut arguments = std::env::args().skip(1);+ let iterations: usize = arguments.next().unwrap_or_else(|| "20".into()).parse()?;+ if iterations == 0 {+ return Err("iterations must be positive".into());+ }+ let selected: Option<usize> = arguments.next().map(|value| value.parse()).transpose()?;+ let cases = [(3600, 1, 0), (600, 20, 28), (3600, 60, 60)];+ if selected.is_some_and(|case| case >= cases.len()) || arguments.next().is_some() {+ return Err("case must be 0, 1 or 2; no additional arguments are accepted".into());+ }+ println!("case,clips,captions,words,sample,elapsed_ms,fingerprint");+ for (case, (seconds, clips, spacing)) in cases.into_iter().enumerate() {+ if selected.is_some_and(|selected| selected != case) {+ continue;+ }+ let mut project = fixture(seconds, clips, spacing);+ let durations = [5.0, seconds as f64];+ for _ in 0..3 {+ synchronize_captions(&mut project, &durations);+ }+ let track = &project.timeline.as_ref().unwrap().caption_segments;+ let expected_captions = if clips == 1 { seconds / 4 } else { clips };+ let words: usize = track.iter().map(|caption| caption.words.len()).sum();+ assert_eq!(track.len(), expected_captions);+ assert_eq!(words, expected_captions * 10);+ assert_eq!(track[0].start, 0.0);+ assert_eq!(track[0].words[0].start, 0.0);+ assert!(+ track+ .iter()+ .all(|caption| caption.words.iter().all(|word| word.text == "word"))+ );+ let mut hasher = DefaultHasher::new();+ serde_json::to_vec(track)?.hash(&mut hasher);+ let fingerprint = hasher.finish();+ for sample in 0..5 {+ let started = Instant::now();+ for _ in 0..iterations {+ synchronize_captions(black_box(&mut project), black_box(&durations));+ black_box(&project.timeline.as_ref().unwrap().caption_segments);+ }+ let elapsed_ms = started.elapsed().as_secs_f64() * 1000.0 / iterations as f64;+ assert_eq!(+ project.timeline.as_ref().unwrap().caption_segments.len(),+ expected_captions+ );+ println!(+ "{case},{clips},{expected_captions},{words},{sample},{elapsed_ms:.6},{fingerprint}"+ );+ }+ let mut hasher = DefaultHasher::new();+ serde_json::to_vec(&project.timeline.as_ref().unwrap().caption_segments)?.hash(&mut hasher);+ assert_eq!(hasher.finish(), fingerprint);+ }+ Ok(())+}diff --git a/crates/project/src/caption_timing.rs b/crates/project/src/caption_timing.rsindex aa7661afb..e0d27cd5b 100644--- a/crates/project/src/caption_timing.rs+++ b/crates/project/src/caption_timing.rs@@ -240,9 +240,31 @@ fn map_captions_to_edited_timeline(for caption in &sanitized {let mut mapped_caption_segments: Vec<MappedCaption> = Vec::new();+ let word_bounds = if caption.words.is_empty() {+ None+ } else {+ caption.words.iter().try_fold(+ (f64::INFINITY, f64::NEG_INFINITY),+ |(start, end), word| {+ let word_start = f64::from(word.start);+ let word_end = f64::from(word.end);+ if word_start.is_nan() || word_end.is_nan() {+ None+ } else {+ Some((start.min(word_start), end.max(word_end)))+ }+ },+ )+ };for mapping in &mappings {if !caption.words.is_empty() {+ if let Some((word_start, word_end)) = word_bounds+ && (word_end <= mapping.source_start || word_start >= mapping.source_end)+ {+ continue;+ }+let mut mapped_words = Vec::new();for word in &caption.words {let Some((start, end)) = map_time_range_within_mapping(@@ -501,4 +523,109 @@ mod tests {1.0);}++ #[test]+ fn unsorted_words_outside_caption_bounds_keep_both_clip_projections() {+ let timeline = project(true, 0.0, 0.5).timeline.unwrap();+ let captions = [CaptionSegment {+ id: "unsorted".into(),+ start: 0.0,+ end: 0.5,+ text: "parent".into(),+ words: vec![+ CaptionWord {+ text: "late-first".into(),+ start: 4.0,+ end: 4.5,+ },+ CaptionWord {+ text: "second-clip".into(),+ start: 7.0,+ end: 7.5,+ },+ CaptionWord {+ text: "early-last".into(),+ start: 1.0,+ end: 1.5,+ },+ ],+ }];++ let track = derive_caption_track_segments(&captions, &timeline, &[10.0]);+ assert_eq!(track.len(), 2);+ assert_eq!(track[0].id, "unsorted::edl0");+ assert_eq!(track[0].start, 4.0);+ assert_eq!(track[0].end, 1.5);+ assert_eq!(track[0].text, "late-first early-last");+ assert_eq!(+ track[0]+ .words+ .iter()+ .map(|word| (word.text.as_str(), word.start, word.end))+ .collect::<Vec<_>>(),+ vec![("late-first", 4.0, 4.5), ("early-last", 1.0, 1.5)]+ );+ assert_eq!(track[1].id, "unsorted::edl1");+ assert_eq!(track[1].start, 6.0);+ assert_eq!(track[1].end, 6.5);+ assert_eq!(track[1].text, "second-clip");+ assert_eq!(+ track[1]+ .words+ .iter()+ .map(|word| (word.text.as_str(), word.start, word.end))+ .collect::<Vec<_>>(),+ vec![("second-clip", 6.0, 6.5)]+ );+ }++ #[test]+ fn nan_word_timestamp_keeps_the_existing_mapping_path() {+ let timeline = project(true, 0.0, 0.5).timeline.unwrap();+ let captions = [CaptionSegment {+ id: "nan".into(),+ start: 0.0,+ end: 0.5,+ text: "parent".into(),+ words: vec![+ CaptionWord {+ text: "nan-start".into(),+ start: f32::NAN,+ end: 1.0,+ },+ CaptionWord {+ text: "second-clip".into(),+ start: 7.0,+ end: 7.5,+ },+ ],+ }];++ let track = derive_caption_track_segments(&captions, &timeline, &[10.0]);+ assert_eq!(track.len(), 2);+ assert_eq!(track[0].id, "nan::edl0");+ assert_eq!(track[0].start, 0.0);+ assert_eq!(track[0].end, 1.0);+ assert_eq!(track[0].text, "nan-start");+ assert_eq!(+ track[0]+ .words+ .iter()+ .map(|word| (word.text.as_str(), word.start, word.end))+ .collect::<Vec<_>>(),+ vec![("nan-start", 0.0, 1.0)]+ );+ assert_eq!(track[1].id, "nan::edl1");+ assert_eq!(track[1].start, 6.0);+ assert_eq!(track[1].end, 6.5);+ assert_eq!(track[1].text, "second-clip");+ assert_eq!(+ track[1]+ .words+ .iter()+ .map(|word| (word.text.as_str(), word.start, word.end))+ .collect::<Vec<_>>(),+ vec![("second-clip", 6.0, 6.5)]+ );+ }}