Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

Merge branch 'main' into 60fps-custom-options

Richie McIlroy089ee2644ebe
diff --cc apps/desktop/src-tauri/src/export.rs
index 75d4d8c33,3e24e1cfb..a7ae71de8
--- a/apps/desktop/src-tauri/src/export.rs
+++ b/apps/desktop/src-tauri/src/export.rs
@@@ -16,19 -16,36 +16,42 @@@ pub async fn export_video
force: bool,
use_custom_muxer: bool,
) -> Result<PathBuf, String> {
- let VideoRecordingMetadata { duration, .. } =
- get_video_metadata(app.clone(), video_id.clone(), Some(VideoType::Screen))
- .await
- .unwrap();
+ let screen_metadata =
+ match get_video_metadata(app.clone(), video_id.clone(), Some(VideoType::Screen)).await {
+ Ok(meta) => meta,
+ Err(e) => {
+ sentry::capture_message(
+ &format!("Failed to get video metadata: {}", e),
+ sentry::Level::Error,
+ );
+ return Err(
+ "Failed to read video metadata. The recording may be from an incompatible version."
+ .to_string(),
+ );
+ }
+ };
+ // Get FPS from general settings
+ let fps = GeneralSettingsStore::get(&app)?
+ .and_then(|s| s.recording_config)
+ .unwrap_or_default()
+ .fps;
+
+ // Get camera metadata if it exists
+ let camera_metadata =
+ get_video_metadata(app.clone(), video_id.clone(), Some(VideoType::Camera))
+ .await
+ .ok();
+
+ // Use the longer duration between screen and camera
+ let duration = screen_metadata.duration.max(
+ camera_metadata
+ .map(|m| m.duration)
+ .unwrap_or(screen_metadata.duration),
+ );
+
- // Calculate total frames with ceiling to ensure we don't exceed 100%
- let total_frames = ((duration * 30.0).ceil() as u32).max(1);
+ // Use configured FPS for output video
+ let total_frames = (duration * fps as f64).round() as u32;
let editor_instance = upsert_editor_instance(&app, video_id.clone()).await;
@@@ -43,15 -60,25 +66,26 @@@
.send(RenderProgress::EstimatedTotalFrames { total_frames })
.ok();
+ // Create a modified project configuration that accounts for different video lengths
+ let mut modified_project = project.clone();
+ if let Some(timeline) = &mut modified_project.timeline {
+ // Ensure timeline duration matches the longest video
+ for segment in timeline.segments.iter_mut() {
+ if segment.end > duration {
+ segment.end = duration;
+ }
+ }
+ }
+
let exporter = cap_export::Exporter::new(
+ &app,
- project,
+ modified_project,
output_path.clone(),
move |frame_index| {
+ // Ensure progress never exceeds total frames
+ let current_frame = (frame_index + 1).min(total_frames);
progress
- .send(RenderProgress::FrameRendered {
- current_frame: frame_index + 1,
- })
+ .send(RenderProgress::FrameRendered { current_frame })
.ok();
},
editor_instance.project_path.clone(),
diff --cc crates/recording/src/actor.rs
index bfa4bc4a0,79b4e65a5..6d523fbfc
--- a/crates/recording/src/actor.rs
+++ b/crates/recording/src/actor.rs
@@@ -23,15 -22,252 +23,120 @@@ use crate::
RecordingOptions,
};
-pub enum ActorControlMessage {
- Stop(oneshot::Sender<Result<CompletedRecording, RecordingError>>),
-}
-
-pub struct Actor {
- id: String,
- recording_dir: PathBuf,
- options: RecordingOptions,
- pipeline: RecordingPipeline,
- start_time: f64,
- stop_signal: Arc<AtomicBool>,
- cursor: Option<CursorActor>,
-}
-
-pub struct ActorHandle {
- ctrl_tx: flume::Sender<ActorControlMessage>,
- pub options: RecordingOptions,
-}
-
-#[derive(Error, Debug)]
-pub enum ActorError {
- #[error("Actor has stopped")]
- ActorStopped,
-
- #[error("Failed to send to actor")]
- SendFailed(#[from] flume::SendError<ActorControlMessage>),
-}
-
-#[derive(Error, Debug)]
-pub enum RecordingError {
- #[error("Media/{0}")]
- Media(#[from] MediaError),
-
- #[error("Actor/{0}")]
- Actor(#[from] ActorError),
-
- #[error("Serde/{0}")]
- Serde(#[from] serde_json::Error),
-
- #[error("IO/{0}")]
- Io(#[from] std::io::Error),
-}
-
-macro_rules! send_message {
- ($ctrl_tx:expr, $variant:path) => {{
- let (tx, rx) = oneshot::channel();
- $ctrl_tx.send($variant(tx)).map_err(ActorError::from)?;
- rx.await.map_err(|_| ActorError::ActorStopped)?
- }};
-}
-
-impl ActorHandle {
- pub async fn stop(&self) -> Result<CompletedRecording, RecordingError> {
- send_message!(self.ctrl_tx, ActorControlMessage::Stop)
- }
-
- pub async fn pause(&self) -> Result<(), RecordingError> {
- Ok(())
- }
-
- pub async fn resume(&self) -> Result<(), RecordingError> {
- Ok(())
- }
-}
-
-pub async fn spawn_recording_actor(
- id: String,
- recording_dir: impl Into<PathBuf>,
- options: RecordingOptions,
- camera_feed: Option<Arc<Mutex<CameraFeed>>>,
- audio_input_feed: Option<AudioInputFeed>,
-) -> Result<ActorHandle, RecordingError> {
- let recording_dir = recording_dir.into();
-
- let content_dir = ensure_dir(recording_dir.join("content"))?;
- let cursors_dir = ensure_dir(content_dir.join("cursors"))?;
-
- let screen_source = create_screen_capture(&options);
-
- let pipeline = create_pipeline(
- &content_dir,
- screen_source.clone(),
- camera_feed.as_deref(),
- audio_input_feed.as_ref(),
- )
- .await?;
-
- let start_time = current_time_f64();
-
- let (ctrl_tx, ctrl_rx) = flume::bounded(1);
-
- let stop_signal = Arc::new(AtomicBool::new(false));
-
- // Initialize default values for cursor channels
- let cursor = FLAGS.record_mouse.then(|| {
- spawn_cursor_recorder(
- screen_source.get_bounds(),
- cursors_dir,
- Default::default(),
- 0,
- )
- });
-
- tokio::spawn({
- let options = options.clone();
- async move {
- let actor = Actor {
- recording_dir,
- options,
- pipeline,
- start_time,
- cursor,
- stop_signal,
- id,
- };
-
- loop {
- let Ok(ActorControlMessage::Stop(tx)) = ctrl_rx.recv_async().await else {
- return;
- };
-
- let resp = stop_recording(actor).await;
-
- tx.send(resp).ok();
- return;
- }
- }
- });
-
- Ok(ActorHandle { ctrl_tx, options })
+struct CursorPipeline {
+ pub output_path: PathBuf,
+ pub actor: CursorActor,
}
- pub struct RecordingSegment {
- pub start: f64,
- pub end: f64,
- pub pipeline: RecordingPipeline,
+ pub struct CompletedRecording {
+ pub id: String,
+ pub recording_dir: PathBuf,
+ pub display_source: ScreenCaptureTarget,
+ pub meta: RecordingMeta,
+ pub cursor_data: cap_project::CursorData,
+ pub segments: Vec<f64>,
+ }
+
+ async fn stop_recording(mut actor: Actor) -> Result<CompletedRecording, RecordingError> {
+ let segment = (actor.start_time, current_time_f64());
+
+ use cap_project::*;
+
+ let meta = RecordingMeta {
+ project_path: actor.recording_dir.clone(),
+ sharing: None,
+ pretty_name: format!(
+ "Cap {}",
+ chrono::Local::now().format("%Y-%m-%d at %H.%M.%S")
+ ),
+ content: Content::SingleSegment {
+ segment: SingleSegment {
+ display: Display {
+ path: actor
+ .pipeline
+ .display_output_path
+ .strip_prefix(&actor.recording_dir)
+ .unwrap()
+ .to_owned(),
+ },
+ camera: actor
+ .pipeline
+ .camera_output_path
+ .as_ref()
+ .map(|path| CameraMeta {
+ path: path.strip_prefix(&actor.recording_dir).unwrap().to_owned(),
+ }),
+ audio: actor
+ .pipeline
+ .audio_output_path
+ .as_ref()
+ .map(|path| AudioMeta {
+ path: path.strip_prefix(&actor.recording_dir).unwrap().to_owned(),
+ }),
+ cursor: Some(PathBuf::from("content/cursor.json")),
+ },
+ },
+ };
+
+ actor.pipeline.inner.shutdown().await?;
+
+ actor
+ .stop_signal
+ .store(true, std::sync::atomic::Ordering::Relaxed);
+
+ let cursor_data = if let Some(cursor) = actor.cursor {
+ let resp = cursor.stop().await;
+ cap_project::CursorData {
+ clicks: resp.clicks,
+ moves: resp.moves,
+ cursor_images: CursorImages(
+ resp.cursors
+ .into_values()
+ .map(|(filename, id)| (id.to_string(), filename))
+ .collect(),
+ ),
+ }
+ } else {
+ Default::default()
+ };
+
+ std::fs::write(
+ actor.recording_dir.join("content/cursor.json"),
+ serde_json::to_string_pretty(&cursor_data)?,
+ )?;
+
+ meta.save_for_project()
+ .map_err(Either::either_into::<RecordingError>)?;
+
- let project_config = cap_project::ProjectConfiguration::default();
- project_config
- .write(&actor.recording_dir)
- .map_err(RecordingError::from)?;
-
+ Ok(CompletedRecording {
+ id: actor.id,
+ meta,
+ cursor_data,
+ recording_dir: actor.recording_dir,
+ display_source: actor.options.capture_target,
+ segments: vec![segment.0, segment.1],
+ })
+ }
+
+ fn create_screen_capture(
+ recording_options: &RecordingOptions,
+ ) -> ScreenCaptureSource<impl MakeCapturePipeline> {
+ #[cfg(target_os = "macos")]
+ {
+ ScreenCaptureSource::<cap_media::sources::CMSampleBufferCapture>::init(
+ dbg!(&recording_options.capture_target),
+ None,
+ None,
+ )
+ }
+ #[cfg(not(target_os = "macos"))]
+ {
+ ScreenCaptureSource::<cap_media::sources::AVFrameCapture>::init(
+ dbg!(&recording_options.capture_target),
+ None,
+ None,
+ )
+ }
}
struct RecordingPipeline {