Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
more stuff working
Brendan Allana3e421ffb1bd
diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rsindex 9a175161a..dc1ff217f 100644--- a/apps/desktop/src-tauri/src/lib.rs+++ b/apps/desktop/src-tauri/src/lib.rs@@ -1236,7 +1236,15 @@ async fn upload_exported_video(}.await?;- match upload_video(&app, video_id.clone(), output_path, Some(s3_config)).await {+ match upload_video(+ &app,+ video_id.clone(),+ output_path,+ Some(s3_config),+ Some(meta.project_path.join("screenshots/display.jpg")),+ )+ .await+ {Ok(uploaded_video) => {// Emit upload completeUploadProgress {diff --git a/apps/desktop/src-tauri/src/recording.rs b/apps/desktop/src-tauri/src/recording.rsindex df9652735..c91bcadea 100644--- a/apps/desktop/src-tauri/src/recording.rs+++ b/apps/desktop/src-tauri/src/recording.rs@@ -130,27 +130,38 @@ pub async fn start_recording(.join("recordings").join(format!("{id}.cap"));- if matches!(state.recording_options.mode, RecordingMode::Instant) {- match AuthStore::get(&app) {- Ok(Some(auth)) => {- if auth.is_upgraded() && get_s3_config(&app, false, None).await.is_ok() {- let s3_config = get_s3_config(&app, false, None).await.unwrap();- let link = web_api::make_url(format!("/s/{}", s3_config.id()));-- state.pre_created_video = Some(PreCreatedVideo {- id: s3_config.id().to_string(),- link: link.clone(),- config: s3_config,- });-- info!("Pre-created shareable link: {}", link);+ let camera_window = CapWindowId::Camera.get(&app);+ match state.recording_options.mode {+ RecordingMode::Instant => {+ match AuthStore::get(&app) {+ Ok(Some(_)) => {+ // Pre-create the video and get the shareable link+ if let Ok(s3_config) = get_s3_config(&app, false, None).await {+ let link = web_api::make_url(format!("/s/{}", s3_config.id()));++ state.pre_created_video = Some(PreCreatedVideo {+ id: s3_config.id().to_string(),+ link: link.clone(),+ config: s3_config,+ });+ info!("Pre-created shareable link: {}", link);+ }}// Allow the recording to proceed without error for any signed-in user+ _ => {+ // User is not signed in+ ShowCapWindow::SignIn.show(&app).ok();+ Err("Please sign in to use instant recording")?;+ }+ }++ if let Some(window) = camera_window {+ let _ = window.set_content_protected(false);}- _ => {- // User is not signed in- ShowCapWindow::SignIn.show(&app).ok();- Err("Please sign in to use instant recording")?;+ }+ RecordingMode::Studio => {+ if let Some(window) = camera_window {+ let _ = window.set_content_protected(true);}}}@@ -366,68 +377,61 @@ async fn handle_recording_finish(spawn_actor({let app = app.clone();async move {- if let Some(auth) = AuthStore::get(&app).ok().flatten() {- if auth.is_upgraded() {- // Copy link to clipboard- let _ = app.clipboard().write_text(pre_created_video.link.clone());-- // Send notification for shareable link- notifications::send_notification(- &app,- notifications::NotificationType::ShareableLinkCopied,- );-- // Open the pre-created shareable link- open_external_link(app.clone(), pre_created_video.link.clone())- .ok();-- // Start the upload process in the background with retry mechanism- let app = app.clone();-- tauri::async_runtime::spawn(async move {- let max_retries = 3;- let mut retry_count = 0;-- while retry_count < max_retries {- match upload_exported_video(- app.clone(),- id.clone(),- UploadMode::Initial {- pre_created_video: Some(pre_created_video.clone()),- },- )- .await- {- Ok(_) => {- println!("Video uploaded successfully");- // Don't send notification here since we already did it above- break;- }- Err(e) => {- retry_count += 1;- println!(- "Error during auto-upload (attempt {}/{}): {}",- retry_count, max_retries, e- );-- if retry_count < max_retries {- tokio::time::sleep(- std::time::Duration::from_secs(5),- )- .await;- } else {- println!("Max retries reached. Upload failed.");- notifications::send_notification(- &app,- notifications::NotificationType::UploadFailed,- );- }- }+ // Copy link to clipboard+ let _ = app.clipboard().write_text(pre_created_video.link.clone());++ // Send notification for shareable link+ notifications::send_notification(+ &app,+ notifications::NotificationType::ShareableLinkCopied,+ );++ // Open the pre-created shareable link+ open_external_link(app.clone(), pre_created_video.link.clone()).ok();++ // Start the upload process in the background with retry mechanism+ let app = app.clone();++ tauri::async_runtime::spawn(async move {+ let max_retries = 3;+ let mut retry_count = 0;++ while retry_count < max_retries {+ match upload_exported_video(+ app.clone(),+ id.clone(),+ UploadMode::Initial {+ pre_created_video: Some(pre_created_video.clone()),+ },+ )+ .await+ {+ Ok(_) => {+ println!("Video uploaded successfully");+ // Don't send notification here since we already did it above+ break;+ }+ Err(e) => {+ retry_count += 1;+ println!(+ "Error during auto-upload (attempt {}/{}): {}",+ retry_count, max_retries, e+ );++ if retry_count < max_retries {+ tokio::time::sleep(std::time::Duration::from_secs(5))+ .await;+ } else {+ println!("Max retries reached. Upload failed.");+ notifications::send_notification(+ &app,+ notifications::NotificationType::UploadFailed,+ );}}- });+ }}- }+ });}});}diff --git a/apps/desktop/src-tauri/src/upload.rs b/apps/desktop/src-tauri/src/upload.rsindex 47cd6219b..072267015 100644--- a/apps/desktop/src-tauri/src/upload.rs+++ b/apps/desktop/src-tauri/src/upload.rs@@ -181,6 +181,7 @@ pub async fn upload_video(video_id: String,file_path: PathBuf,existing_config: Option<S3UploadMeta>,+ screenshot_path: Option<PathBuf>,) -> Result<UploadedVideo, String> {println!("Uploading video {video_id}...");@@ -264,19 +265,12 @@ pub async fn upload_video(let form = form.part("file", file_part);- // Prepare screenshot upload- let screenshot_path = file_path- .parent()- .unwrap()- .parent()- .unwrap()- .join("screenshots")- .join("display.jpg");-- let screenshot_upload = if screenshot_path.exists() {- Some(prepare_screenshot_upload(app, &s3_config, screenshot_path).await?)- } else {- None+ dbg!(&screenshot_path);+ let screenshot_upload = match screenshot_path {+ Some(screenshot_path) if screenshot_path.exists() => {+ Some(prepare_screenshot_upload(app, &s3_config, screenshot_path).await?)+ }+ _ => None,};let (video_upload, screenshot_result): (diff --git a/apps/desktop/src-tauri/src/windows.rs b/apps/desktop/src-tauri/src/windows.rsindex 76521e276..bfded9e48 100644--- a/apps/desktop/src-tauri/src/windows.rs+++ b/apps/desktop/src-tauri/src/windows.rs@@ -240,7 +240,7 @@ impl ShowCapWindow {.shadow(false).fullscreen(false).always_on_top(true)- // .content_protected(true)+ .title("Cap Camera").visible_on_all_workspaces(true).skip_taskbar(true).position(diff --git a/crates/media/src/sources/screen_capture.rs b/crates/media/src/sources/screen_capture.rsindex cbfaacac4..08bb266f0 100644--- a/crates/media/src/sources/screen_capture.rs+++ b/crates/media/src/sources/screen_capture.rs@@ -94,6 +94,8 @@ pub struct ScreenCaptureSource<TCaptureFormat> {fps: u32,video_info: VideoInfo,options: Arc<Options>,+ show_camera: bool,+ force_show_cursor: bool,_phantom: std::marker::PhantomData<TCaptureFormat>,}@@ -106,6 +108,8 @@ impl<TCaptureFormat> Clone for ScreenCaptureSource<TCaptureFormat> {fps: self.fps,video_info: self.video_info.clone(),options: self.options.clone(),+ show_camera: self.show_camera,+ force_show_cursor: self.force_show_cursor,_phantom: std::marker::PhantomData,}}@@ -117,6 +121,8 @@ impl<TCaptureFormat> ScreenCaptureSource<TCaptureFormat> {pub fn init(target: &ScreenCaptureTarget,output_type: Option<FrameType>,+ show_camera: bool,+ force_show_cursor: bool,) -> Result<Self, String> {cap_fail::fail!("media::screen_capture::init");@@ -127,6 +133,8 @@ impl<TCaptureFormat> ScreenCaptureSource<TCaptureFormat> {fps: target.recording_fps(),video_info: VideoInfo::from_raw(RawVideoFormat::Bgra, 0, 0, MAX_FPS),options: Arc::new(Options::default()),+ show_camera,+ force_show_cursor,_phantom: std::marker::PhantomData,};@@ -154,9 +162,15 @@ impl<TCaptureFormat> ScreenCaptureSource<TCaptureFormat> {let excluded_targets: Vec<scap::Target> = targets.iter()- .filter(|target| {- matches!(target, Target::Window(scap_window)- if EXCLUDED_WINDOWS.contains(&scap_window.title.as_str()))+ .filter(|target| match target {+ Target::Window(scap_window) => {+ if scap_window.title == "Cap Window" && self.show_camera {+ false+ } else {+ EXCLUDED_WINDOWS.contains(&scap_window.title.as_str())+ }+ }+ Target::Display(_) => false,}).cloned().collect();@@ -237,7 +251,7 @@ impl<TCaptureFormat> ScreenCaptureSource<TCaptureFormat> {Ok(Options {fps: self.fps,- show_cursor: !FLAGS.record_mouse_state,+ show_cursor: self.force_show_cursor || !FLAGS.record_mouse_state,show_highlight: true,target: Some(target),crop_area,diff --git a/crates/recording/src/actor.rs b/crates/recording/src/actor.rsdeleted file mode 100644index 061d4c29b..000000000--- a/crates/recording/src/actor.rs+++ /dev/null@@ -1,784 +0,0 @@-use std::{- fs::File,- path::PathBuf,- sync::Arc,- time::{SystemTime, UNIX_EPOCH},-};--use cap_flags::FLAGS;-use cap_media::{- data::Pixel,- encoders::{H264Encoder, MP4AVAssetWriterEncoder, MP4File, OggFile, OpusEncoder},- feeds::{AudioInputFeed, CameraFeed},- pipeline::{builder::PipelineBuilder, Pipeline, RealTimeClock},- sources::{AudioInputSource, CameraSource, ScreenCaptureSource, ScreenCaptureTarget},- MediaError,-};-use cap_project::{CursorEvents, RecordingMeta};-use cap_utils::spawn_actor;-use either::Either;-use relative_path::{RelativePath, RelativePathBuf};-use thiserror::Error;-use tokio::sync::{oneshot, Mutex};-use tracing::{- debug, info,- instrument::{self, WithSubscriber},- trace, Instrument,-};-use tracing_subscriber::{fmt::FormatFields, layer::SubscriberExt, Layer};--use crate::{- cursor::{spawn_cursor_recorder, CursorActor, Cursors},- RecordingOptions,-};--enum StudioRecordingActorState {- Recording {- pipeline: StudioRecordingPipeline,- pipeline_done_rx: oneshot::Receiver<()>,- index: u32,- segment_start_time: f64,- },- Paused {- next_index: u32,- cursors: Cursors,- next_cursor_id: u32,- },- Stopped,-}--pub enum StudioRecordingActorControlMessage {- Pause(oneshot::Sender<Result<(), RecordingError>>),- Resume(oneshot::Sender<Result<(), RecordingError>>),- Stop(oneshot::Sender<Result<CompletedStudioRecording, RecordingError>>),-}--pub struct StudioRecordingActor {- id: String,- recording_dir: PathBuf,- options: RecordingOptions,- segments: Vec<StudioRecordingSegment>,-}--pub struct StudioRecordingSegment {- pub start: f64,- pub end: f64,- pipeline: StudioRecordingPipeline,-}--struct StudioRecordingPipeline {- pub inner: Pipeline<RealTimeClock<()>>,- pub display_output_path: PathBuf,- pub audio_output_path: Option<PathBuf>,- pub camera: Option<CameraPipelineInfo>,- pub cursor: Option<CursorPipeline>,-}--struct CursorPipeline {- output_path: PathBuf,- actor: Option<CursorActor>,-}--#[derive(Clone)]-pub struct StudioRecordingHandle {- ctrl_tx: flume::Sender<StudioRecordingActorControlMessage>,- pub options: RecordingOptions,-}--#[derive(Error, Debug)]-pub enum ActorError {- #[error("Actor has stopped")]- ActorStopped,-- #[error("Failed to send to actor")]- SendFailed(#[from] flume::SendError<StudioRecordingActorControlMessage>),-}--#[derive(Error, Debug)]-pub enum RecordingError {- #[error("Media error: {0}")]- Media(#[from] MediaError),-- #[error("Actor error: {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 StudioRecordingHandle {- pub async fn stop(&self) -> Result<CompletedStudioRecording, RecordingError> {- send_message!(self.ctrl_tx, StudioRecordingActorControlMessage::Stop)- }-- pub async fn pause(&self) -> Result<(), RecordingError> {- send_message!(self.ctrl_tx, StudioRecordingActorControlMessage::Pause)- }-- pub async fn resume(&self) -> Result<(), RecordingError> {- send_message!(self.ctrl_tx, StudioRecordingActorControlMessage::Resume)- }-}--pub async fn spawn_stuido_recording_actor(- id: String,- recording_dir: PathBuf,- options: RecordingOptions,- camera_feed: Option<Arc<Mutex<CameraFeed>>>,- audio_input_feed: Option<AudioInputFeed>,-) -> Result<(StudioRecordingHandle, tokio::sync::oneshot::Receiver<()>), RecordingError> {- ensure_dir(&recording_dir)?;- let logfile = File::create(recording_dir.join("recording-logs.log"))?;-- let collector = tracing_subscriber::registry()- .with(- tracing_subscriber::fmt::layer()- .with_ansi(false)- .with_target(false)- .with_writer(logfile)- .with_filter(- tracing_subscriber::filter::EnvFilter::builder()- .with_default_directive(tracing::level_filters::LevelFilter::TRACE.into())- .from_env_lossy(),- ),- )- .with(- tracing_subscriber::fmt::layer()- .with_ansi(true)- .with_target(false)- .with_filter(- tracing_subscriber::filter::EnvFilter::builder()- .with_default_directive(tracing::level_filters::LevelFilter::TRACE.into())- .from_env_lossy(),- ),- );-- let (done_tx, done_rx) = tokio::sync::oneshot::channel::<()>();-- async {- async {- trace!("creating recording actor");-- let content_dir = ensure_dir(&recording_dir.join("content"))?;-- let segments_dir = ensure_dir(&content_dir.join("segments"))?;- let cursors_dir = ensure_dir(&content_dir.join("cursors"))?;-- let screen_source = create_screen_capture(&options);-- debug!("screen capture: {screen_source:#?}");-- if let Some(camera_feed) = &camera_feed {- let camera_feed = camera_feed.lock().await;- debug!("camera device info: {:#?}", camera_feed.camera_info());- debug!("camera video info: {:#?}", camera_feed.video_info());- }-- if let Some(audio_feed) = &audio_input_feed {- debug!("mic audio info: {:#?}", audio_feed.audio_info())- }-- let index = 0;- let (pipeline, pipeline_done_rx) = create_segment_pipeline(- &segments_dir,- &cursors_dir,- index,- screen_source.clone(),- camera_feed.as_deref(),- audio_input_feed.as_ref(),- Default::default(),- index,- )- .await?;-- let segment_start_time = current_time_f64();-- let (ctrl_tx, ctrl_rx) = flume::bounded(1);-- trace!("spawning recording actor");-- spawn_actor({- let options = options.clone();- async move {- let mut actor = StudioRecordingActor {- id,- recording_dir,- options,- segments: Vec::new(),- };-- let mut state = StudioRecordingActorState::Recording {- pipeline,- pipeline_done_rx,- index,- segment_start_time,- };-- 'outer: loop {- state = match state {- StudioRecordingActorState::Recording {- mut pipeline,- mut pipeline_done_rx,- index,- segment_start_time,- } => {- info!("recording actor recording");- loop {- let msg = tokio::select! {- _ = &mut pipeline_done_rx => {- if let Some(cursor) = &mut pipeline.cursor {- if let Some(actor) = cursor.actor.take() {- actor.stop().await;- }- }-- break 'outer;- }- msg = ctrl_rx.recv_async() => {- let Ok(msg) = msg else {- break 'outer;- };-- msg- }- };-- async fn shutdown(- mut pipeline: StudioRecordingPipeline,- actor: &mut StudioRecordingActor,- segment_start_time: f64,- ) -> Result<(Cursors, u32), RecordingError>- {- pipeline.inner.shutdown().await?;-- let segment_stop_time = current_time_f64();-- let cursors = if let Some(cursor) = &mut pipeline.cursor {- if let Some(actor) = cursor.actor.take() {- let res = actor.stop().await;-- std::fs::write(- &cursor.output_path,- serde_json::to_string_pretty(&CursorEvents {- clicks: res.clicks,- moves: res.moves,- })?,- )?;-- (res.cursors, res.next_cursor_id)- } else {- Default::default()- }- } else {- Default::default()- };-- actor.segments.push(StudioRecordingSegment {- start: segment_start_time,- end: segment_stop_time,- pipeline,- });-- Ok(cursors)- }-- break match msg {- StudioRecordingActorControlMessage::Pause(tx) => {- let (res, cursors, next_cursor_id) = match shutdown(- pipeline,- &mut actor,- segment_start_time,- )- .await- {- Ok((cursors, next_cursor_id)) => {- (Ok(()), cursors, next_cursor_id)- }- Err(e) => (Err(e), Default::default(), 0),- };-- tx.send(res.map_err(Into::into)).ok();- StudioRecordingActorState::Paused {- next_index: index + 1,- cursors,- next_cursor_id,- }- }- StudioRecordingActorControlMessage::Stop(tx) => {- let res =- shutdown(pipeline, &mut actor, segment_start_time)- .await;- let res = match res {- Ok((cursors, _)) => {- stop_recording(actor, cursors).await- }- Err(e) => Err(e),- };-- tx.send(res).ok();-- break 'outer;- }- _ => continue,- };- }- }- StudioRecordingActorState::Paused {- next_index,- cursors,- next_cursor_id,- } => {- info!("recording actor paused");- loop {- let Ok(msg) = ctrl_rx.recv_async().await else {- break 'outer;- };-- break match msg {- StudioRecordingActorControlMessage::Stop(tx) => {- tx.send(stop_recording(actor, cursors).await).ok();- break 'outer;- }- StudioRecordingActorControlMessage::Resume(tx) => {- let (state, res) = match create_segment_pipeline(- &segments_dir,- &cursors_dir,- next_index,- screen_source.clone(),- camera_feed.as_deref(),- audio_input_feed.as_ref(),- cursors,- next_cursor_id,- )- .await- {- Ok((pipeline, pipeline_done_rx)) => (- StudioRecordingActorState::Recording {- pipeline,- pipeline_done_rx,- index: next_index,- segment_start_time: current_time_f64(),- },- Ok(()),- ),- Err(e) => (- StudioRecordingActorState::Stopped,- Err(e.into()),- ),- };-- tx.send(res).ok();-- state- }- _ => continue,- };- }- }- StudioRecordingActorState::Stopped => {- info!("recording actor paused");- break;- }- };- }-- info!("recording actor finished");-- done_tx.send(()).ok();- }- .in_current_span()- });-- Ok(StudioRecordingHandle { ctrl_tx, options })- }- .instrument(tracing::info_span!("recording"))- .await- }- .with_subscriber(collector)- .await- .map(|a| (a, done_rx))-}--pub struct CompletedStudioRecording {- pub id: String,- pub recording_dir: PathBuf,- pub display_source: ScreenCaptureTarget,- pub meta: RecordingMeta,- pub cursor_data: cap_project::CursorImages,- pub segments: Vec<StudioRecordingSegment>,-}--async fn stop_recording(- actor: StudioRecordingActor,- cursors: Cursors,-) -> Result<CompletedStudioRecording, RecordingError> {- 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")- ),- inner: RecordingMetaInner::Instant(InstantRecordingMeta {- fps: actor.options.capture_target.recording_fps(),- sample_rate: None,- }),- // inner: RecordingMetaInner::Studio(StudioRecordingMeta::MultipleSegments {- // inner: MultipleSegments {- // segments: {- // actor- // .segments- // .iter()- // .map(|s| MultipleSegment {- // display: Display {- // path: RelativePathBuf::from_path(- // s.pipeline- // .display_output_path- // .strip_prefix(&actor.recording_dir)- // .unwrap(),- // )- // .unwrap(),- // fps: actor.options.capture_target.recording_fps(),- // },- // camera: s.pipeline.camera.as_ref().map(|camera| CameraMeta {- // path: RelativePathBuf::from_path(- // camera- // .output_path- // .strip_prefix(&actor.recording_dir)- // .unwrap()- // .to_owned(),- // )- // .unwrap(),- // fps: camera.fps,- // }),- // audio: s.pipeline.audio_output_path.as_ref().map(|path| AudioMeta {- // path: RelativePathBuf::from_path(- // path.strip_prefix(&actor.recording_dir).unwrap().to_owned(),- // )- // .unwrap(),- // }),- // cursor: s.pipeline.cursor.as_ref().map(|cursor| {- // RelativePathBuf::from_path(- // cursor- // .output_path- // .strip_prefix(&actor.recording_dir)- // .unwrap()- // .to_owned(),- // )- // .unwrap()- // }),- // })- // .collect()- // },- // cursors: cap_project::Cursors::Correct(- // cursors- // .into_values()- // .map(|cursor| {- // (- // cursor.id.to_string(),- // CursorMeta {- // image_path: RelativePathBuf::from("content/cursors")- // .join(&cursor.file_name),- // hotspot: cursor.hotspot,- // },- // )- // })- // .collect(),- // ),- // },- // }),- };-- 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(CompletedStudioRecording {- id: actor.id,- meta,- cursor_data: Default::default(),- recording_dir: actor.recording_dir,- display_source: actor.options.capture_target,- segments: actor.segments,- })-}--fn create_screen_capture(- recording_options: &RecordingOptions,-) -> ScreenCaptureSource<impl MakeCapturePipeline> {- #[cfg(target_os = "macos")]- {- ScreenCaptureSource::<cap_media::sources::CMSampleBufferCapture>::init(- &recording_options.capture_target,- None,- )- }- #[cfg(not(target_os = "macos"))]- {- ScreenCaptureSource::<cap_media::sources::AVFrameCapture>::init(- &recording_options.capture_target,- None,- )- }-}--#[tracing::instrument(skip_all, name = "segment", fields(index = index))]-async fn create_segment_pipeline<TCaptureFormat: MakeCapturePipeline>(- segments_dir: &PathBuf,- cursors_dir: &PathBuf,- index: u32,- screen_source: ScreenCaptureSource<TCaptureFormat>,- camera_feed: Option<&Mutex<CameraFeed>>,- audio_input_feed: Option<&AudioInputFeed>,- prev_cursors: Cursors,- next_cursors_id: u32,-) -> Result<(StudioRecordingPipeline, oneshot::Receiver<()>), MediaError> {- let camera_feed = match camera_feed.as_ref() {- Some(camera_feed) => Some(camera_feed.lock().await),- None => None,- };- let camera_feed = camera_feed.as_deref();-- let dir = ensure_dir(&segments_dir.join(format!("segment-{index}")))?;-- let clock = RealTimeClock::<()>::new();- let mut pipeline_builder = Pipeline::builder(clock);-- let display_output_path = dir.join("display.mp4");-- trace!("preparing segment pipeline {index}");-- let screen_bounds = screen_source.get_bounds();- pipeline_builder = TCaptureFormat::make_capture_pipeline(- pipeline_builder,- screen_source,- &display_output_path,- )?;-- info!(- r#"screen pipeline prepared, will output to "{}""#,- display_output_path- .strip_prefix(&segments_dir)- .unwrap()- .display()- );- let audio_output_path = if let Some(mic_source) = audio_input_feed.map(AudioInputSource::init) {- let mic_config = mic_source.info();- let output_path = dir.join("audio-input.ogg");-- let mic_encoder = OggFile::init(- output_path.clone(),- OpusEncoder::factory("microphone", mic_config),- )?;-- pipeline_builder = pipeline_builder- .source("microphone_capture", mic_source)- .sink("microphone_encoder", mic_encoder);-- info!(- "mic pipeline prepared, will output to {}",- output_path.strip_prefix(&segments_dir).unwrap().display()- );-- Some(output_path)- } else {- None- };-- let camera = if let Some(camera_source) = camera_feed.map(CameraSource::init) {- let camera_config = camera_source.info();- let output_path = dir.join("camera.mp4");-- let camera_encoder = MP4File::init(- "camera",- output_path.clone(),- H264Encoder::factory("camera", camera_config),- |_| None,- )?;-- pipeline_builder = pipeline_builder- .source("camera_capture", camera_source)- .sink("camera_encoder", camera_encoder);-- info!(- "camera pipeline prepared, will output to {}",- output_path.strip_prefix(&segments_dir).unwrap().display()- );-- Some(CameraPipelineInfo {- output_path,- fps: (camera_config.frame_rate.0 / camera_config.frame_rate.1) as u32,- })- } else {- None- };-- let (mut pipeline, pipeline_done_rx) = pipeline_builder.build().await?;-- let cursor = FLAGS.record_mouse_state.then(|| {- let cursor = spawn_cursor_recorder(- screen_bounds,- cursors_dir.clone(),- prev_cursors,- next_cursors_id,- );-- CursorPipeline {- output_path: dir.join("cursor.json"),- actor: Some(cursor),- }- });-- pipeline.play().await?;-- info!("pipeline playing");-- Ok((- StudioRecordingPipeline {- inner: pipeline,- display_output_path,- audio_output_path,- camera,- cursor,- },- pipeline_done_rx,- ))-}--struct CameraPipelineInfo {- output_path: PathBuf,- fps: u32,-}--fn ensure_dir(path: &PathBuf) -> Result<PathBuf, MediaError> {- std::fs::create_dir_all(&path)?;- Ok(path.clone())-}--type CapturePipelineBuilder = PipelineBuilder<RealTimeClock<()>>;--trait MakeCapturePipeline: std::fmt::Debug + 'static {- fn make_capture_pipeline(- builder: CapturePipelineBuilder,- source: ScreenCaptureSource<Self>,- output_path: impl Into<PathBuf>,- ) -> Result<CapturePipelineBuilder, MediaError>- where- Self: Sized;-- fn make_instant_mode_pipeline(- builder: CapturePipelineBuilder,- source: ScreenCaptureSource<Self>,- audio: Option<AudioInputSource>,- output_path: impl Into<PathBuf>,- ) -> Result<CapturePipelineBuilder, MediaError>- where- Self: Sized;-}--#[cfg(target_os = "macos")]-impl MakeCapturePipeline for cap_media::sources::CMSampleBufferCapture {- fn make_capture_pipeline(- builder: CapturePipelineBuilder,- source: ScreenCaptureSource<Self>,- output_path: impl Into<PathBuf>,- ) -> Result<CapturePipelineBuilder, MediaError> {- let screen_config = source.info();- let screen_encoder = cap_media::encoders::MP4AVAssetWriterEncoder::init(- "screen",- screen_config,- None,- output_path.into(),- None,- )?;-- Ok(builder- .source("screen_capture", source)- .sink("screen_capture_encoder", screen_encoder))- }-- fn make_instant_mode_pipeline(- builder: CapturePipelineBuilder,- source: ScreenCaptureSource<Self>,- audio: Option<AudioInputSource>,- output_path: impl Into<PathBuf>,- ) -> Result<CapturePipelineBuilder, MediaError> {- let mp4 = Arc::new(std::sync::Mutex::new(MP4AVAssetWriterEncoder::init(- "mp4",- source.info(),- audio.as_ref().map(|f| f.info()),- output_path.into(),- Some(1080),- )?));-- let mut builder = builder- .source("screen_capture", source)- .sink("screen_encoder", mp4.clone());-- if let Some(audio) = audio {- builder = builder- .source("microphone_capture", audio)- .sink("mic_encoder", mp4.clone());- }-- Ok(builder)- }-}--impl MakeCapturePipeline for cap_media::sources::AVFrameCapture {- fn make_capture_pipeline(- builder: CapturePipelineBuilder,- source: ScreenCaptureSource<Self>,- output_path: impl Into<PathBuf>,- ) -> Result<CapturePipelineBuilder, MediaError>- where- Self: Sized,- {- let screen_config = source.info();- let screen_encoder = MP4File::init(- "screen",- output_path.into(),- H264Encoder::factory("screen", screen_config),- |_| None,- )?;- Ok(builder- .source("screen_capture", source)- .sink("screen_capture_encoder", screen_encoder))- }-- fn make_instant_mode_pipeline(- builder: CapturePipelineBuilder,- source: ScreenCaptureSource<Self>,- audio: Option<AudioInputSource>,- output_path: impl Into<PathBuf>,- ) -> Result<CapturePipelineBuilder, MediaError>- where- Self: Sized,- {- todo!()- }-}--fn current_time_f64() -> f64 {- SystemTime::now()- .duration_since(UNIX_EPOCH)- .unwrap()- .as_secs_f64()-}diff --git a/crates/recording/src/capture_pipeline.rs b/crates/recording/src/capture_pipeline.rsindex 33caac83b..7629686df 100644--- a/crates/recording/src/capture_pipeline.rs+++ b/crates/recording/src/capture_pipeline.rs@@ -115,11 +115,18 @@ impl MakeCapturePipeline for cap_media::sources::AVFrameCapture {pub fn create_screen_capture(capture_target: &ScreenCaptureTarget,+ show_camera: bool,+ force_show_cursor: bool,) -> Result<ScreenCaptureSource<impl MakeCapturePipeline>, RecordingError> {#[cfg(target_os = "macos")]{- ScreenCaptureSource::<cap_media::sources::CMSampleBufferCapture>::init(capture_target, None)- .map_err(|e| RecordingError::Media(MediaError::TaskLaunch(e)))+ ScreenCaptureSource::<cap_media::sources::CMSampleBufferCapture>::init(+ capture_target,+ None,+ show_camera,+ force_show_cursor,+ )+ .map_err(|e| RecordingError::Media(MediaError::TaskLaunch(e)))}#[cfg(not(target_os = "macos"))]{diff --git a/crates/recording/src/instant_recording.rs b/crates/recording/src/instant_recording.rsindex 66178e399..ff9f4d8eb 100644--- a/crates/recording/src/instant_recording.rs+++ b/crates/recording/src/instant_recording.rs@@ -167,7 +167,7 @@ pub async fn spawn_instant_recording_actor(let content_dir = ensure_dir(&recording_dir.join("content"))?;- let screen_source = create_screen_capture(&options.capture_target)?;+ let screen_source = create_screen_capture(&options.capture_target, true, true)?;debug!("screen capture: {screen_source:#?}");diff --git a/crates/recording/src/studio_recording.rs b/crates/recording/src/studio_recording.rsindex ecbd2317b..24b23fbeb 100644--- a/crates/recording/src/studio_recording.rs+++ b/crates/recording/src/studio_recording.rs@@ -148,7 +148,7 @@ pub async fn spawn_studio_recording_actor(let segments_dir = ensure_dir(&content_dir.join("segments"))?;let cursors_dir = ensure_dir(&content_dir.join("cursors"))?;- let screen_source = create_screen_capture(&options.capture_target)?;+ let screen_source = create_screen_capture(&options.capture_target, false, false)?;debug!("screen capture: {screen_source:#?}");