Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
feat: Add post-recording sync calibration analysis
Cursor Agentdd9be56bb512
diff --git a/crates/editor/src/editor_instance.rs b/crates/editor/src/editor_instance.rsindex 56211e472..370608957 100644--- a/crates/editor/src/editor_instance.rs+++ b/crates/editor/src/editor_instance.rs@@ -140,15 +140,25 @@ impl EditorInstance {}if project.clips.is_empty() {+ let calibration_store = load_calibration_store(&recording_meta.project_path);+match meta {StudioRecordingMeta::MultipleSegments { inner } => {project.clips = inner.segments.iter().enumerate()- .map(|(i, segment)| cap_project::ClipConfiguration {- index: i as u32,- offsets: segment.calculate_audio_offsets(),+ .map(|(i, segment)| {+ let calibration_offset = get_calibration_offset(+ segment.camera_device_id(),+ segment.mic_device_id(),+ &calibration_store,+ );+ cap_project::ClipConfiguration {+ index: i as u32,+ offsets: segment+ .calculate_audio_offsets_with_calibration(calibration_offset),+ }}).collect();}@@ -574,3 +584,24 @@ pub async fn create_segments(}}}++fn load_calibration_store(project_path: &std::path::Path) -> cap_audio::CalibrationStore {+ let calibration_dir = project_path+ .parent()+ .and_then(|p| p.parent())+ .map(|p| p.to_path_buf())+ .unwrap_or_else(|| project_path.to_path_buf());++ cap_audio::CalibrationStore::load(&calibration_dir)+}++fn get_calibration_offset(+ camera_id: Option<&str>,+ mic_id: Option<&str>,+ store: &cap_audio::CalibrationStore,+) -> Option<f32> {+ match (camera_id, mic_id) {+ (Some(cam), Some(mic)) => store.get_offset(cam, mic).map(|o| o as f32),+ _ => None,+ }+}diff --git a/crates/project/src/meta.rs b/crates/project/src/meta.rsindex dee73392c..a8e44e22a 100644--- a/crates/project/src/meta.rs+++ b/crates/project/src/meta.rs@@ -22,6 +22,8 @@ pub struct VideoMeta {pub fps: u32,#[serde(default, skip_serializing_if = "Option::is_none")]pub start_time: Option<f64>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub device_id: Option<String>,}fn legacy_static_video_fps() -> u32 {@@ -34,6 +36,8 @@ pub struct AudioMeta {pub path: RelativePathBuf,#[serde(default, skip_serializing_if = "Option::is_none")]pub start_time: Option<f64>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub device_id: Option<String>,}#[derive(Debug, Clone, Serialize, Deserialize, Type)]@@ -410,11 +414,20 @@ impl MultipleSegment {}pub fn calculate_audio_offsets(&self) -> crate::ClipOffsets {+ self.calculate_audio_offsets_with_calibration(None)+ }++ pub fn calculate_audio_offsets_with_calibration(+ &self,+ calibration_offset: Option<f32>,+ ) -> crate::ClipOffsets {let latest = match self.latest_start_time() {Some(t) => t,None => return crate::ClipOffsets::default(),};+ let cal_offset = calibration_offset.unwrap_or(0.0);+let camera_offset = self.camera.as_ref()@@ -426,14 +439,14 @@ impl MultipleSegment {.mic.as_ref().and_then(|m| m.start_time)- .map(|t| (latest - t) as f32)+ .map(|t| (latest - t) as f32 + cal_offset).unwrap_or(0.0);let system_audio_offset = self.system_audio.as_ref().and_then(|s| s.start_time)- .map(|t| (latest - t) as f32)+ .map(|t| (latest - t) as f32 + cal_offset).unwrap_or(0.0);crate::ClipOffsets {@@ -442,6 +455,14 @@ impl MultipleSegment {system_audio: system_audio_offset,}}++ pub fn camera_device_id(&self) -> Option<&str> {+ self.camera.as_ref().and_then(|c| c.device_id.as_deref())+ }++ pub fn mic_device_id(&self) -> Option<&str> {+ self.mic.as_ref().and_then(|m| m.device_id.as_deref())+ }}#[cfg(test)]diff --git a/crates/recording/src/feeds/microphone.rs b/crates/recording/src/feeds/microphone.rsindex 32ba88df3..30d34c7bf 100644--- a/crates/recording/src/feeds/microphone.rs+++ b/crates/recording/src/feeds/microphone.rs@@ -364,6 +364,7 @@ pub struct MicrophoneFeedLock {audio_info: AudioInfo,buffer_size_frames: Option<u32>,drop_tx: Option<oneshot::Sender<()>>,+ device_name: String,}impl MicrophoneFeedLock {@@ -378,6 +379,10 @@ impl MicrophoneFeedLock {pub fn buffer_size_frames(&self) -> Option<u32> {self.buffer_size_frames}++ pub fn device_name(&self) -> &str {+ &self.device_name+ }}impl Deref for MicrophoneFeedLock {@@ -715,6 +720,7 @@ impl Message<Lock> for MicrophoneFeed {let config = attached.config.clone();let buffer_size_frames = attached.buffer_size_frames;+ let device_name = attached.label.clone();self.state = State::Locked { inner: attached };@@ -732,6 +738,7 @@ impl Message<Lock> for MicrophoneFeed {config,buffer_size_frames,drop_tx: Some(drop_tx),+ device_name,})}}diff --git a/crates/recording/src/lib.rs b/crates/recording/src/lib.rsindex 965c70920..96f6991a2 100644--- a/crates/recording/src/lib.rs+++ b/crates/recording/src/lib.rs@@ -10,6 +10,7 @@ pub mod recovery;pub mod screenshot;pub mod sources;pub mod studio_recording;+pub mod sync_calibration;#[cfg(any(test, feature = "test-utils"))]pub mod test_sources;diff --git a/crates/recording/src/studio_recording.rs b/crates/recording/src/studio_recording.rsindex 9400991c4..72147ecb8 100644--- a/crates/recording/src/studio_recording.rs+++ b/crates/recording/src/studio_recording.rs@@ -103,10 +103,15 @@ impl Actor {(Default::default(), 0)};+ let camera_device_id = self.segment_factory.camera_device_id();+ let mic_device_id = self.segment_factory.mic_device_id();+self.segments.push(RecordingSegment {start: segment_start_time,end: segment_stop_time,pipeline,+ camera_device_id,+ mic_device_id,});Ok(cursors)@@ -299,6 +304,8 @@ pub struct RecordingSegment {pub start: f64,pub end: f64,pipeline: FinishedPipeline,+ pub camera_device_id: Option<String>,+ pub mic_device_id: Option<String>,}pub struct ScreenPipelineOutput {@@ -697,6 +704,7 @@ async fn stop_recording(DEFAULT_FPS}),start_time: Some(to_start_time(s.pipeline.screen.first_timestamp)),+ device_id: None,},camera: s.pipeline.camera.map(|camera| VideoMeta {path: make_relative(&camera.path),@@ -708,14 +716,17 @@ async fn stop_recording(DEFAULT_FPS}),start_time: Some(to_start_time(camera.first_timestamp)),+ device_id: s.camera_device_id.clone(),}),mic: s.pipeline.microphone.map(|mic| AudioMeta {path: make_relative(&mic.path),start_time: Some(to_start_time(mic.first_timestamp)),+ device_id: s.mic_device_id.clone(),}),system_audio: s.pipeline.system_audio.map(|audio| AudioMeta {path: make_relative(&audio.path),start_time: Some(to_start_time(audio.first_timestamp)),+ device_id: None,}),cursor: s.pipeline@@ -855,6 +866,20 @@ impl SegmentPipelineFactory {pub fn set_camera_feed(&mut self, camera_feed: Option<Arc<CameraFeedLock>>) {self.base_inputs.camera_feed = camera_feed;}++ pub fn camera_device_id(&self) -> Option<String> {+ self.base_inputs+ .camera_feed+ .as_ref()+ .map(|f| f.camera_info().device_id().to_string())+ }++ pub fn mic_device_id(&self) -> Option<String> {+ self.base_inputs+ .mic_feed+ .as_ref()+ .map(|f| f.device_name().to_string())+ }}fn completion_rx_to_done_fut(diff --git a/crates/recording/src/sync_calibration.rs b/crates/recording/src/sync_calibration.rsnew file mode 100644index 000000000..236738c54--- /dev/null+++ b/crates/recording/src/sync_calibration.rs@@ -0,0 +1,164 @@+use cap_audio::{+ calculate_frame_motion_score, CalibrationStore, DeviceSyncCalibration, SyncAnalyzer,+};+use std::path::{Path, PathBuf};+use tracing::{debug, info, warn};++pub struct PostRecordingSyncAnalysis {+ analyzer: SyncAnalyzer,+ camera_device_id: Option<String>,+ mic_device_id: Option<String>,+ calibration_dir: PathBuf,+ previous_frame: Option<Vec<u8>>,+ frame_width: u32,+ frame_height: u32,+}++impl PostRecordingSyncAnalysis {+ pub fn new(+ sample_rate: u32,+ fps: f64,+ camera_device_id: Option<String>,+ mic_device_id: Option<String>,+ calibration_dir: PathBuf,+ frame_width: u32,+ frame_height: u32,+ ) -> Self {+ Self {+ analyzer: SyncAnalyzer::new(sample_rate, fps),+ camera_device_id,+ mic_device_id,+ calibration_dir,+ previous_frame: None,+ frame_width,+ frame_height,+ }+ }++ pub fn process_video_frame(&mut self, frame_data: &[u8], time_secs: f64) {+ if let Some(prev) = &self.previous_frame {+ let motion =+ calculate_frame_motion_score(frame_data, prev, self.frame_width, self.frame_height);+ self.analyzer.add_video_frame_motion(time_secs, motion);+ }+ self.previous_frame = Some(frame_data.to_vec());+ }++ pub fn process_audio_samples(&mut self, samples: &[f32], start_time_secs: f64) {+ self.analyzer.add_audio_samples(samples, start_time_secs);+ }++ pub fn finalize_and_save(&mut self) -> Option<f64> {+ let (camera_id, mic_id) = match (&self.camera_device_id, &self.mic_device_id) {+ (Some(cam), Some(mic)) => (cam.clone(), mic.clone()),+ _ => {+ debug!("Skipping sync calibration: missing device IDs");+ return None;+ }+ };++ let result = self.analyzer.calculate_sync_offset()?;++ if result.confidence < 0.5 {+ debug!(+ "Sync analysis confidence too low: {:.0}%",+ result.confidence * 100.0+ );+ return None;+ }++ info!(+ "Sync analysis complete: offset={:.1}ms, confidence={:.0}%, events={}",+ result.offset_secs * 1000.0,+ result.confidence * 100.0,+ result.detected_events.len()+ );++ let mut store = CalibrationStore::load(&self.calibration_dir);++ let mut calibration = DeviceSyncCalibration::new(camera_id, mic_id);+ calibration.update_with_measurement(result.offset_secs, result.confidence);++ if let Some(existing) =+ store.get_calibration(&calibration.camera_id, &calibration.microphone_id)+ {+ calibration.measured_offset_secs = existing.offset_secs;+ calibration.confidence = existing.confidence;+ calibration.measurement_count = existing.measurement_count;+ calibration.update_with_measurement(result.offset_secs, result.confidence);+ }++ store.update_calibration(&calibration);++ if let Err(e) = store.save(&self.calibration_dir) {+ warn!("Failed to save calibration store: {}", e);+ } else {+ info!(+ "Saved calibration: offset={:.1}ms after {} measurements",+ calibration.measured_offset_secs * 1000.0,+ calibration.measurement_count+ );+ }++ Some(calibration.measured_offset_secs)+ }+}++pub fn analyze_recording_for_sync(+ audio_path: &Path,+ video_path: &Path,+ camera_device_id: Option<&str>,+ mic_device_id: Option<&str>,+ calibration_dir: &Path,+) -> Option<f64> {+ use cap_audio::AudioData;+ use cap_rendering::Video;++ let audio = match AudioData::from_file(audio_path) {+ Ok(a) => a,+ Err(e) => {+ warn!("Failed to load audio for sync analysis: {}", e);+ return None;+ }+ };++ let video = match Video::new(video_path, 0.0) {+ Ok(v) => v,+ Err(e) => {+ warn!("Failed to load video for sync analysis: {}", e);+ return None;+ }+ };++ let sample_rate = AudioData::SAMPLE_RATE;+ let fps = video.fps as f64;++ let mut analyzer = PostRecordingSyncAnalysis::new(+ sample_rate,+ fps,+ camera_device_id.map(String::from),+ mic_device_id.map(String::from),+ calibration_dir.to_path_buf(),+ video.width,+ video.height,+ );++ let samples = audio.samples();+ let chunk_size = (sample_rate as usize) / 10;+ for (i, chunk) in samples.chunks(chunk_size).enumerate() {+ let time = i as f64 * (chunk_size as f64 / sample_rate as f64);+ analyzer.process_audio_samples(chunk, time);+ }++ let frame_count = (video.duration * fps).ceil() as u32;+ let sample_interval = (frame_count / 100).max(1);++ for frame_idx in (0..frame_count).step_by(sample_interval as usize) {+ let time = frame_idx as f64 / fps;+ if let Some(frame) = video.get_frame(time as f32) {+ analyzer.process_video_frame(&frame.data, time);+ }+ }++ analyzer.finalize_and_save()+}