Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
feat(recording): improve recovery inspection and keyboard capture pipeline
Richie McIlroy6bb6b5045c3a
diff --git a/crates/recording/src/cursor.rs b/crates/recording/src/cursor.rsindex a0d3972c8..7b5dd2189 100644--- a/crates/recording/src/cursor.rs+++ b/crates/recording/src/cursor.rs@@ -37,6 +37,11 @@ pub struct CursorActor {pub rx: Shared<oneshot::Receiver<CursorActorResponse>>,}+pub struct IncrementalCaptureOutputs {+ pub cursor: Option<PathBuf>,+ pub keyboard: Option<PathBuf>,+}+impl CursorActor {pub fn stop(&mut self) {drop(self.stop.take());@@ -65,9 +70,7 @@ fn flush_keyboard_data(output_path: &Path, presses: &[KeyPressEvent]) {let events = KeyboardEvents {presses: presses.to_vec(),};- if let Ok(json) = serde_json::to_string_pretty(&events)- && let Err(e) = std::fs::write(output_path, json)- {+ if let Err(e) = events.write_to_file(output_path) {tracing::error!("Failed to write keyboard data to {}: {}",output_path.display(),@@ -191,8 +194,7 @@ pub fn spawn_cursor_recorder(prev_cursors: Cursors,next_cursor_id: u32,start_time: Timestamps,- output_path: Option<PathBuf>,- keyboard_output_path: Option<PathBuf>,+ incremental_outputs: IncrementalCaptureOutputs,) -> CursorActor {use cap_utils::spawn_actor;use device_query::{DeviceQuery, DeviceState};@@ -358,11 +360,11 @@ pub fn spawn_cursor_recorder(last_keys = current_keys;- if let Some(ref path) = output_path- && last_flush.elapsed() >= flush_interval- {- flush_cursor_data(path, &response.moves, &response.clicks);- if let Some(ref kb_path) = keyboard_output_path {+ if last_flush.elapsed() >= flush_interval {+ if let Some(ref path) = incremental_outputs.cursor {+ flush_cursor_data(path, &response.moves, &response.clicks);+ }+ if let Some(ref kb_path) = incremental_outputs.keyboard {flush_keyboard_data(kb_path, &response.keyboard_presses);}last_flush = Instant::now();@@ -371,11 +373,11 @@ pub fn spawn_cursor_recorder(info!("cursor recorder done");- if let Some(ref path) = output_path {+ if let Some(ref path) = incremental_outputs.cursor {flush_cursor_data(path, &response.moves, &response.clicks);}- if let Some(ref kb_path) = keyboard_output_path {+ if let Some(ref kb_path) = incremental_outputs.keyboard {flush_keyboard_data(kb_path, &response.keyboard_presses);}diff --git a/crates/recording/src/recovery.rs b/crates/recording/src/recovery.rsindex fa99ba3ce..1a81ff905 100644--- a/crates/recording/src/recovery.rs+++ b/crates/recording/src/recovery.rs@@ -68,6 +68,20 @@ pub enum RecoveryError {pub struct RecoveryManager;impl RecoveryManager {+ pub fn inspect_recording(project_path: &Path) -> Option<IncompleteRecording> {+ if !project_path.is_dir() {+ return None;+ }++ if !project_path.join("recording-meta.json").exists() {+ return None;+ }++ let meta = RecordingMeta::load_for_project(project_path).ok()?;++ Self::analyze_incomplete(project_path, &meta)+ }+pub fn find_incomplete_single(project_path: &Path) -> Option<IncompleteRecording> {if !project_path.is_dir() {return None;@@ -255,6 +269,7 @@ impl RecoveryManager {use crate::fragmentation::CURRENT_MANIFEST_VERSION;let manifest_path = dir.join("manifest.json");+ let mut manifest_init_segment = None;if manifest_path.exists()&& let Ok(content) = std::fs::read_to_string(&manifest_path)@@ -288,6 +303,7 @@ impl RecoveryManager {.and_then(|i| i.as_str()).map(|name| dir.join(name)).filter(|p| p.exists());+ manifest_init_segment = init_segment.clone();let entries = if manifest_type == "m4s_segments" {manifest.get("segments").and_then(|s| s.as_array())@@ -368,6 +384,16 @@ impl RecoveryManager {}}+ if let Some(init_segment) = manifest_init_segment {+ let fragments = Self::probe_m4s_fragments_with_init(dir);+ if !fragments.is_empty() {+ return FragmentsInfo {+ fragments,+ init_segment: Some(init_segment),+ };+ }+ }+FragmentsInfo {fragments: Self::probe_fragments_in_dir(dir),init_segment: None,@@ -415,6 +441,28 @@ impl RecoveryManager {fragments}+ fn probe_m4s_fragments_with_init(dir: &Path) -> Vec<PathBuf> {+ const MIN_VALID_FRAGMENT_SIZE: u64 = 100;++ let Ok(entries) = std::fs::read_dir(dir) else {+ return Vec::new();+ };++ let mut fragments: Vec<_> = entries+ .filter_map(|e| e.ok())+ .map(|e| e.path())+ .filter(|p| p.extension().is_some_and(|e| e.eq_ignore_ascii_case("m4s")))+ .filter(|p| {+ std::fs::metadata(p)+ .map(|metadata| metadata.len() >= MIN_VALID_FRAGMENT_SIZE)+ .unwrap_or(false)+ })+ .collect();++ fragments.sort();+ fragments+ }+fn probe_single_file(path: &Path) -> Option<PathBuf> {if !path.exists() {return None;@@ -802,6 +850,14 @@ impl RecoveryManager {let mic_path = segment_dir.join("audio-input.ogg");let system_audio_path = segment_dir.join("system_audio.ogg");let cursor_path = segment_dir.join("cursor.json");+ let keyboard_path = {+ let binary = segment_dir.join(cap_project::KEYBOARD_EVENTS_FILE_NAME);+ if binary.exists() {+ binary+ } else {+ segment_dir.join(cap_project::LEGACY_KEYBOARD_EVENTS_FILE_NAME)+ }+ };let display_start_time = original_segment.and_then(|s| s.display.start_time);@@ -884,7 +940,12 @@ impl RecoveryManager {} else {None},- keyboard: None,+ keyboard: if keyboard_path.exists() {+ let file_name = keyboard_path.file_name().unwrap().to_string_lossy();+ Some(RelativePathBuf::from(format!("{segment_base}/{file_name}")))+ } else {+ None+ },}}).collect();diff --git a/crates/recording/src/studio_recording.rs b/crates/recording/src/studio_recording.rsindex 6256af190..1ed8cc1db 100644--- a/crates/recording/src/studio_recording.rs+++ b/crates/recording/src/studio_recording.rs@@ -11,7 +11,7 @@ use crate::{capture_pipeline::{MakeCapturePipeline, ScreenCaptureMethod, Stop, target_to_display_and_crop,},- cursor::{CursorActor, Cursors, spawn_cursor_recorder},+ cursor::{CursorActor, Cursors, IncrementalCaptureOutputs, spawn_cursor_recorder},feeds::{camera::CameraFeedLock, microphone::MicrophoneFeedLock},ffmpeg::{FragmentedAudioMuxer, FragmentedAudioMuxerConfig, OggMuxer},output_pipeline::{DoneFut, FinishedOutputPipeline, OutputPipeline, PipelineDoneError},@@ -27,8 +27,8 @@ use crate::output_pipeline::{use anyhow::{Context as _, anyhow, bail};use cap_media_info::VideoInfo;use cap_project::{- CursorEvents, MultipleSegment, MultipleSegments, Platform, RecordingMeta, RecordingMetaInner,- StudioRecordingMeta, StudioRecordingStatus,+ CursorEvents, KeyboardEvents, MultipleSegment, MultipleSegments, Platform, RecordingMeta,+ RecordingMetaInner, StudioRecordingMeta, StudioRecordingStatus,};use cap_timestamp::{Timestamp, Timestamps};use futures::{FutureExt, StreamExt, future::OptionFuture, stream::FuturesUnordered};@@ -94,13 +94,25 @@ impl Actor {let cursors = if let Some(cursor) = pipeline.cursor.as_mut()&& let Ok(res) = cursor.actor.rx.clone().await{- std::fs::write(- &cursor.output_path,- serde_json::to_string_pretty(&CursorEvents {- clicks: res.clicks,- moves: res.moves,- })?,- )?;+ if let Some(output_path) = cursor.output_path.as_ref() {+ std::fs::write(+ output_path,+ serde_json::to_string_pretty(&CursorEvents {+ clicks: res.clicks,+ moves: res.moves,+ })?,+ )?;+ }++ if !res.keyboard_presses.is_empty()+ && let Some(keyboard_output_path) = cursor.keyboard_output_path.as_ref()+ {+ KeyboardEvents {+ presses: res.keyboard_presses,+ }+ .write_to_file(keyboard_output_path)+ .map_err(anyhow::Error::msg)?;+ }(res.cursors, res.next_cursor_id)} else {@@ -597,7 +609,8 @@ impl Pipeline {}struct CursorPipeline {- output_path: PathBuf,+ output_path: Option<PathBuf>,+ keyboard_output_path: Option<PathBuf>,actor: CursorActor,}@@ -657,6 +670,7 @@ pub struct ActorBuilder {mic_feed: Option<Arc<MicrophoneFeedLock>>,camera_feed: Option<Arc<CameraFeedLock>>,custom_cursor: bool,+ keyboard_capture: bool,fragmented: bool,max_fps: u32,#[cfg(target_os = "macos")]@@ -672,6 +686,7 @@ impl ActorBuilder {mic_feed: None,camera_feed: None,custom_cursor: false,+ keyboard_capture: true,fragmented: false,max_fps: 60,#[cfg(target_os = "macos")]@@ -699,6 +714,11 @@ impl ActorBuilder {self}+ pub fn with_keyboard_capture(mut self, keyboard_capture: bool) -> Self {+ self.keyboard_capture = keyboard_capture;+ self+ }+pub fn with_fragmented(mut self, fragmented: bool) -> Self {self.fragmented = fragmented;self@@ -732,6 +752,7 @@ impl ActorBuilder {excluded_windows: self.excluded_windows,},self.custom_cursor,+ self.keyboard_capture,self.fragmented,self.max_fps,)@@ -744,6 +765,7 @@ async fn spawn_studio_recording_actor(recording_dir: PathBuf,base_inputs: RecordingBaseInputs,custom_cursor_capture: bool,+ keyboard_capture: bool,fragmented: bool,max_fps: u32,) -> anyhow::Result<ActorHandle> {@@ -773,6 +795,7 @@ async fn spawn_studio_recording_actor(cursors_dir,base_inputs.clone(),custom_cursor_capture,+ keyboard_capture,fragmented,max_fps,completion_tx.clone(),@@ -979,7 +1002,14 @@ async fn stop_recording(.pipeline.cursor.as_ref()- .map(|cursor| make_relative(&cursor.output_path)),+ .and_then(|cursor| cursor.output_path.as_ref().map(make_relative)),+ keyboard: s.pipeline.cursor.as_ref().and_then(|cursor| {+ cursor+ .keyboard_output_path+ .as_ref()+ .filter(|path| path.exists())+ .map(make_relative)+ }),},diagnostics,}@@ -1061,6 +1091,7 @@ struct SegmentPipelineFactory {cursors_dir: PathBuf,base_inputs: RecordingBaseInputs,custom_cursor_capture: bool,+ keyboard_capture: bool,fragmented: bool,max_fps: u32,index: u32,@@ -1076,6 +1107,7 @@ impl SegmentPipelineFactory {cursors_dir: PathBuf,base_inputs: RecordingBaseInputs,custom_cursor_capture: bool,+ keyboard_capture: bool,fragmented: bool,max_fps: u32,completion_tx: watch::Sender<Option<Result<(), PipelineDoneError>>>,@@ -1085,6 +1117,7 @@ impl SegmentPipelineFactory {cursors_dir,base_inputs,custom_cursor_capture,+ keyboard_capture,fragmented,max_fps,index: 0,@@ -1108,6 +1141,7 @@ impl SegmentPipelineFactory {cursors,next_cursors_id,self.custom_cursor_capture,+ self.keyboard_capture,self.fragmented,self.max_fps,segment_start_time,@@ -1192,6 +1226,7 @@ async fn create_segment_pipeline(prev_cursors: Cursors,next_cursors_id: u32,custom_cursor_capture: bool,+ keyboard_capture: bool,fragmented: bool,max_fps: u32,start_time: Timestamps,@@ -1427,7 +1462,7 @@ async fn create_segment_pipeline(let cursor = if camera_only {None} else {- custom_cursor_capture+ (custom_cursor_capture || keyboard_capture).then(move || {let cursor_crop_bounds = base_inputs.capture_target@@ -1435,11 +1470,17 @@ async fn create_segment_pipeline(.ok_or(CreateSegmentPipelineError::NoBounds)?;let cursor_output_path = dir.join("cursor.json");- let incremental_output = if fragmented {+ let keyboard_output_path = dir.join(cap_project::KEYBOARD_EVENTS_FILE_NAME);+ let incremental_output = if fragmented && custom_cursor_capture {Some(cursor_output_path.clone())} else {None};+ let keyboard_incremental_output = if fragmented && keyboard_capture {+ Some(keyboard_output_path.clone())+ } else {+ None+ };let cursor_display = cursor_display.ok_or(CreateSegmentPipelineError::NoDisplay)?;@@ -1450,11 +1491,15 @@ async fn create_segment_pipeline(prev_cursors,next_cursors_id,start_time,- incremental_output,+ IncrementalCaptureOutputs {+ cursor: incremental_output,+ keyboard: keyboard_incremental_output,+ },);Ok::<_, CreateSegmentPipelineError>(CursorPipeline {- output_path: cursor_output_path,+ output_path: custom_cursor_capture.then_some(cursor_output_path),+ keyboard_output_path: keyboard_capture.then_some(keyboard_output_path),actor: cursor,})})@@ -1559,18 +1604,18 @@ mod tests {impl Muxer for SuccessfulVideoMuxer {type Config = ();- fn setup(+ async fn setup(_config: Self::Config,_output_path: PathBuf,_video_config: Option<VideoInfo>,_audio_config: Option<cap_media_info::AudioInfo>,_pause_flag: Arc<std::sync::atomic::AtomicBool>,_tasks: &mut TaskPool,- ) -> impl Future<Output = anyhow::Result<Self>> + Send+ ) -> anyhow::Result<Self>whereSelf: Sized,{- async move { Ok(Self) }+ Ok(Self)}fn finish(&mut self, _timestamp: Duration) -> anyhow::Result<anyhow::Result<()>> {@@ -1613,23 +1658,21 @@ mod tests {impl Muxer for FailingAudioMuxer {type Config = FailingAudioMuxerConfig;- fn setup(+ async fn setup(config: Self::Config,_output_path: PathBuf,_video_config: Option<VideoInfo>,_audio_config: Option<cap_media_info::AudioInfo>,_pause_flag: Arc<std::sync::atomic::AtomicBool>,_tasks: &mut TaskPool,- ) -> impl Future<Output = anyhow::Result<Self>> + Send+ ) -> anyhow::Result<Self>whereSelf: Sized,{- async move {- Ok(Self {- fail_after_frame: config.fail_after_frame,- sent_frames: 0,- })- }+ Ok(Self {+ fail_after_frame: config.fail_after_frame,+ sent_frames: 0,+ })}fn finish(&mut self, _timestamp: Duration) -> anyhow::Result<anyhow::Result<()>> {diff --git a/crates/recording/tests/recovery.rs b/crates/recording/tests/recovery.rsindex d739821d1..845b40da4 100644--- a/crates/recording/tests/recovery.rs+++ b/crates/recording/tests/recovery.rs@@ -116,6 +116,7 @@ impl TestRecording {mic: None,system_audio: None,cursor: None,+ keyboard: None,}],cursors: Cursors::default(),status: Some(status),@@ -477,6 +478,55 @@ fn test_fallback_to_directory_scan_when_no_manifest() {assert_eq!(entries.len(), 2, "Should find 2 video files by scanning");}+#[test]+fn test_inspect_recording_recovers_orphaned_m4s_fragments_with_init() {+ test_utils::init_tracing();++ let recording = TestRecording::new().unwrap();+ let display_dir = recording.create_display_dir(0).unwrap();++ recording+ .write_manifest(+ 0,+ "display",+ &[("segment_001.m4s", false, 150)],+ Some("init.mp4"),+ )+ .unwrap();+ std::fs::write(display_dir.join("init.mp4"), create_minimal_mp4_data()).unwrap();+ std::fs::write(display_dir.join("segment_001.m4s"), vec![1u8; 150]).unwrap();+ std::fs::write(display_dir.join("segment_002.m4s"), vec![2u8; 175]).unwrap();+ std::fs::write(display_dir.join("segment_003.m4s.tmp"), vec![3u8; 200]).unwrap();+ recording+ .write_recording_meta(StudioRecordingStatus::Failed {+ error: "No recoverable segments found".to_string(),+ })+ .unwrap();++ let incomplete = RecoveryManager::inspect_recording(recording.path()).unwrap();++ assert_eq!(incomplete.recoverable_segments.len(), 1);++ let segment = &incomplete.recoverable_segments[0];+ assert_eq!(segment.display_fragments.len(), 2);+ assert_eq!(+ segment+ .display_fragments+ .iter()+ .map(|path| path.file_name().unwrap().to_string_lossy().to_string())+ .collect::<Vec<_>>(),+ vec!["segment_001.m4s".to_string(), "segment_002.m4s".to_string()]+ );+ assert_eq!(+ segment+ .display_init_segment+ .as_ref()+ .and_then(|path| path.file_name())+ .map(|name| name.to_string_lossy().to_string()),+ Some("init.mp4".to_string())+ );+}+#[test]fn test_corrupt_data_detection() {test_utils::init_tracing();