Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
feat(recording): add camera-only recording mode to capture pipeline
Richie McIlroy7598dc349656
diff --git a/crates/recording/src/capture_pipeline.rs b/crates/recording/src/capture_pipeline.rsindex c333957bb..53c168e3e 100644--- a/crates/recording/src/capture_pipeline.rs+++ b/crates/recording/src/capture_pipeline.rs@@ -325,6 +325,9 @@ pub fn target_to_display_and_crop())}}+ ScreenCaptureTarget::CameraOnly => {+ return Err(anyhow!("Camera-only target has no display"));+ }};Ok((display, crop_bounds))diff --git a/crates/recording/src/instant_recording.rs b/crates/recording/src/instant_recording.rsindex 58b3ddd22..af0644f43 100644--- a/crates/recording/src/instant_recording.rs+++ b/crates/recording/src/instant_recording.rs@@ -1,3 +1,5 @@+#[cfg(target_os = "macos")]+use crate::SendableShareableContent;use crate::{RecordingBaseInputs,capture_pipeline::{@@ -273,6 +275,7 @@ pub struct ActorBuilder {capture_target: ScreenCaptureTarget,system_audio: bool,mic_feed: Option<Arc<MicrophoneFeedLock>>,+ camera_feed: Option<Arc<crate::feeds::camera::CameraFeedLock>>,max_output_size: Option<u32>,#[cfg(target_os = "macos")]excluded_windows: Vec<scap_targets::WindowId>,@@ -285,6 +288,7 @@ impl ActorBuilder {capture_target,system_audio: false,mic_feed: None,+ camera_feed: None,max_output_size: None,#[cfg(target_os = "macos")]excluded_windows: Vec::new(),@@ -301,6 +305,14 @@ impl ActorBuilder {self}+ pub fn with_camera_feed(+ mut self,+ camera_feed: Arc<crate::feeds::camera::CameraFeedLock>,+ ) -> Self {+ self.camera_feed = Some(camera_feed);+ self+ }+pub fn with_max_output_size(mut self, max_output_size: u32) -> Self {self.max_output_size = Some(max_output_size);self@@ -314,7 +326,7 @@ impl ActorBuilder {pub async fn build(self,- #[cfg(target_os = "macos")] shareable_content: cidre::arc::R<cidre::sc::ShareableContent>,+ #[cfg(target_os = "macos")] shareable_content: Option<SendableShareableContent>,) -> anyhow::Result<ActorHandle> {spawn_instant_recording_actor(self.output_path,@@ -322,7 +334,7 @@ impl ActorBuilder {capture_target: self.capture_target,capture_system_audio: self.system_audio,mic_feed: self.mic_feed,- camera_feed: None,+ camera_feed: self.camera_feed,#[cfg(target_os = "macos")]shareable_content,#[cfg(target_os = "macos")]@@ -343,7 +355,6 @@ pub async fn spawn_instant_recording_actor(ensure_dir(&recording_dir)?;let timestamps = Timestamps::now();- let start_time = timestamps.system_time();trace!("creating recording actor");@@ -352,41 +363,95 @@ pub async fn spawn_instant_recording_actor(#[cfg(windows)]cap_mediafoundation_utils::thread_init();- #[cfg(windows)]- let d3d_device = crate::capture_pipeline::create_d3d_device()?;+ let (pipeline, video_info) = match inputs.capture_target {+ ScreenCaptureTarget::CameraOnly => {+ let camera_feed = inputs+ .camera_feed+ .clone()+ .ok_or_else(|| anyhow::anyhow!("Camera feed missing for camera-only recording"))?;- let (display, crop_bounds) =- target_to_display_and_crop(&inputs.capture_target).context("target_display_crop")?;+ let output_path = content_dir.join("output.mp4");- let screen_source = ScreenCaptureConfig::<ScreenCaptureMethod>::init(- display,- crop_bounds,- true,- 30,- start_time,- inputs.capture_system_audio,- #[cfg(windows)]- d3d_device,- #[cfg(target_os = "macos")]- inputs.shareable_content.retained(),- #[cfg(target_os = "macos")]- inputs.excluded_windows,- )- .await- .context("screen capture init")?;+ let mut builder = OutputPipeline::builder(output_path.clone())+ .with_video::<crate::sources::NativeCamera>(camera_feed.clone())+ .with_timestamps(timestamps);- debug!("screen capture: {screen_source:#?}");+ if let Some(mic_feed) = inputs.mic_feed.clone() {+ builder = builder.with_audio_source::<crate::sources::Microphone>(mic_feed);+ }- let pipeline = create_pipeline(- content_dir.join("output.mp4"),- screen_source.clone(),- inputs.mic_feed.clone(),- max_output_size,- timestamps,- )- .await?;+ #[cfg(target_os = "macos")]+ let pipeline = builder+ .build::<output_pipeline::AVFoundationCameraMuxer>(+ output_pipeline::AVFoundationCameraMuxerConfig::default(),+ )+ .await+ .context("camera-only pipeline setup")?;++ #[cfg(windows)]+ let pipeline = builder+ .build::<output_pipeline::WindowsCameraMuxer>(+ output_pipeline::WindowsCameraMuxerConfig {+ encoder_preferences: crate::capture_pipeline::EncoderPreferences::default(),+ ..Default::default()+ },+ )+ .await+ .context("camera-only pipeline setup")?;++ let video_info = camera_feed.video_info().clone();+ (+ Pipeline {+ output: pipeline,+ video_info,+ },+ video_info,+ )+ }+ _ => {+ #[cfg(windows)]+ let d3d_device = crate::capture_pipeline::create_d3d_device()?;++ let (display, crop_bounds) = target_to_display_and_crop(&inputs.capture_target)+ .context("target_display_crop")?;++ let screen_source = ScreenCaptureConfig::<ScreenCaptureMethod>::init(+ display,+ crop_bounds,+ true,+ 30,+ timestamps.system_time(),+ inputs.capture_system_audio,+ #[cfg(windows)]+ d3d_device,+ #[cfg(target_os = "macos")]+ inputs+ .shareable_content+ .clone()+ .ok_or_else(|| anyhow::anyhow!("Missing shareable content"))?,+ #[cfg(target_os = "macos")]+ inputs.excluded_windows,+ )+ .await+ .context("screen capture init")?;++ debug!("screen capture: {screen_source:#?}");++ let pipeline = create_pipeline(+ content_dir.join("output.mp4"),+ screen_source.clone(),+ inputs.mic_feed.clone(),+ max_output_size,+ timestamps,+ )+ .await?;++ let video_info = pipeline.video_info;++ (pipeline, video_info)+ }+ };- let video_info = pipeline.video_info;let segment_start_time = current_time_f64();trace!("spawning recording actor");diff --git a/crates/recording/src/lib.rs b/crates/recording/src/lib.rsindex 95bc7b1df..c3e0cf34e 100644--- a/crates/recording/src/lib.rs+++ b/crates/recording/src/lib.rs@@ -59,11 +59,34 @@ pub struct RecordingBaseInputs {pub mic_feed: Option<Arc<MicrophoneFeedLock>>,pub camera_feed: Option<Arc<CameraFeedLock>>,#[cfg(target_os = "macos")]- pub shareable_content: cidre::arc::R<cidre::sc::ShareableContent>,+ pub shareable_content: Option<SendableShareableContent>,#[cfg(target_os = "macos")]pub excluded_windows: Vec<scap_targets::WindowId>,}+#[cfg(target_os = "macos")]+#[derive(Clone)]+pub struct SendableShareableContent(cidre::arc::R<cidre::sc::ShareableContent>);++#[cfg(target_os = "macos")]+impl SendableShareableContent {+ pub fn retained(&self) -> cidre::arc::R<cidre::sc::ShareableContent> {+ self.0.clone()+ }+}++#[cfg(target_os = "macos")]+impl From<cidre::arc::R<cidre::sc::ShareableContent>> for SendableShareableContent {+ fn from(value: cidre::arc::R<cidre::sc::ShareableContent>) -> Self {+ Self(value)+ }+}++#[cfg(target_os = "macos")]+unsafe impl Send for SendableShareableContent {}+#[cfg(target_os = "macos")]+unsafe impl Sync for SendableShareableContent {}+#[derive(specta::Type, Serialize, Deserialize, Clone, Debug)]#[serde(rename_all = "camelCase")]pub enum RecordingOptionCaptureTarget {diff --git a/crates/recording/src/screenshot.rs b/crates/recording/src/screenshot.rsindex 68a11b3bf..e70128053 100644--- a/crates/recording/src/screenshot.rs+++ b/crates/recording/src/screenshot.rs@@ -188,6 +188,9 @@ fn try_fast_capture(target: &ScreenCaptureTarget) -> Option<RgbImage> {}unsafe { core_graphics::image::CGImage::from_ptr(image) }}+ ScreenCaptureTarget::CameraOnly => {+ return None;+ }};let width = cg_image.width();@@ -275,6 +278,10 @@ fn frame_to_rgb(frame: &Frame) -> anyhow::Result<RgbImage> {#[cfg(target_os = "windows")]fn windows_capture_settings(target: &ScreenCaptureTarget) -> anyhow::Result<(Settings, bool)> {+ if matches!(target, ScreenCaptureTarget::CameraOnly) {+ return Err(anyhow!("Camera-only not supported for screenshots"));+ }+let mut settings = Settings {is_cursor_capture_enabled: Some(false),pixel_format: PixelFormat::B8G8R8A8Unorm,@@ -543,6 +550,7 @@ fn capture_screenshot_fallback(target: ScreenCaptureTarget) -> anyhow::Result<Rgdebug!("Windows GDI area capture");Ok(image)}+ ScreenCaptureTarget::CameraOnly => Err(unsupported_error()),}}@@ -582,6 +590,9 @@ fn try_fast_capture(target: &ScreenCaptureTarget) -> Option<RgbImage> {let display = scap_targets::Display::from_id(&screen)?;display.raw_handle().try_as_capture_item().ok()?}+ ScreenCaptureTarget::CameraOnly => {+ return None;+ }};let (settings, _) = windows_capture_settings(target).ok()?;@@ -661,7 +672,6 @@ pub async fn capture_screenshot(target: ScreenCaptureTarget) -> anyhow::Result<R.await.map_err(|e| anyhow!("Failed to get shareable content: {e}"))?,)- .await.ok_or_else(|| anyhow!("Failed to get content filter"))?}ScreenCaptureTarget::Window { id } => {@@ -674,7 +684,6 @@ pub async fn capture_screenshot(target: ScreenCaptureTarget) -> anyhow::Result<Rlet sc_window = window.raw_handle().as_sc(sc_content)- .await.ok_or_else(|| anyhow!("Failed to get SCWindow"))?;sc::ContentFilter::with_desktop_independent_window(sc_window.as_ref())@@ -690,9 +699,11 @@ pub async fn capture_screenshot(target: ScreenCaptureTarget) -> anyhow::Result<R.await.map_err(|e| anyhow!("Failed to get shareable content: {e}"))?,)- .await.ok_or_else(|| anyhow!("Failed to get content filter"))?}+ ScreenCaptureTarget::CameraOnly => {+ return Err(anyhow!("Camera-only not supported for screenshots"));+ }};let width = match target.clone() {@@ -708,6 +719,9 @@ pub async fn capture_screenshot(target: ScreenCaptureTarget) -> anyhow::Result<R.and_then(|d| d.physical_size()).map(|s| s.width()).unwrap_or(1920.0),+ ScreenCaptureTarget::CameraOnly => {+ return Err(anyhow!("Camera-only not supported for screenshots"));+ }} as usize;let height = match target.clone() {@@ -723,6 +737,9 @@ pub async fn capture_screenshot(target: ScreenCaptureTarget) -> anyhow::Result<R.and_then(|d| d.physical_size()).map(|s| s.height()).unwrap_or(1080.0),+ ScreenCaptureTarget::CameraOnly => {+ return Err(anyhow!("Camera-only not supported for screenshots"));+ }} as usize;let config = StreamCfgBuilder::default()@@ -789,6 +806,9 @@ pub async fn capture_screenshot(target: ScreenCaptureTarget) -> anyhow::Result<R.try_as_capture_item().map_err(|e| anyhow!("Failed to get capture item: {e:?}"))?}+ ScreenCaptureTarget::CameraOnly => {+ return Err(anyhow!("Camera-only not supported for screenshots"));+ }};let (settings, cropped) = windows_capture_settings(&target)?;diff --git a/crates/recording/src/sources/screen_capture/mod.rs b/crates/recording/src/sources/screen_capture/mod.rsindex d30ec3706..576b8d2ca 100644--- a/crates/recording/src/sources/screen_capture/mod.rs+++ b/crates/recording/src/sources/screen_capture/mod.rs@@ -1,3 +1,5 @@+#[cfg(target_os = "macos")]+use crate::SendableShareableContent;use cap_cursor_capture::CursorCropBounds;#[cfg(target_os = "macos")]use cap_media_info::ensure_even;@@ -62,6 +64,7 @@ pub enum ScreenCaptureTarget {screen: DisplayId,bounds: LogicalBounds,},+ CameraOnly,}impl ScreenCaptureTarget {@@ -70,6 +73,7 @@ impl ScreenCaptureTarget {Self::Display { id } => Display::from_id(id),Self::Window { id } => Window::from_id(id).and_then(|w| w.display()),Self::Area { screen, .. } => Display::from_id(screen),+ Self::CameraOnly => None,}}@@ -168,6 +172,7 @@ impl ScreenCaptureTarget {)));}}+ Self::CameraOnly => None,}}@@ -185,6 +190,7 @@ impl ScreenCaptureTarget {size.height() * scale,))}+ Self::CameraOnly => None,}}@@ -193,6 +199,7 @@ impl ScreenCaptureTarget {Self::Display { id } => Display::from_id(id).and_then(|d| d.name()),Self::Window { id } => Window::from_id(id).and_then(|w| w.name()),Self::Area { screen, .. } => Display::from_id(screen).and_then(|d| d.name()),+ Self::CameraOnly => Some("Camera".to_string()),}}@@ -201,6 +208,7 @@ impl ScreenCaptureTarget {ScreenCaptureTarget::Display { .. } => "Display",ScreenCaptureTarget::Window { .. } => "Window",ScreenCaptureTarget::Area { .. } => "Area",+ ScreenCaptureTarget::CameraOnly => "Camera",}}}@@ -299,7 +307,7 @@ impl<TCaptureFormat: ScreenCaptureFormat> ScreenCaptureConfig<TCaptureFormat> {start_time: SystemTime,system_audio: bool,#[cfg(windows)] d3d_device: ::windows::Win32::Graphics::Direct3D11::ID3D11Device,- #[cfg(target_os = "macos")] shareable_content: cidre::arc::R<cidre::sc::ShareableContent>,+ #[cfg(target_os = "macos")] shareable_content: SendableShareableContent,#[cfg(target_os = "macos")] excluded_windows: Vec<WindowId>,) -> Result<Self, ScreenCaptureInitError> {cap_fail::fail!("ScreenCaptureSource::init");diff --git a/crates/recording/src/studio_recording.rs b/crates/recording/src/studio_recording.rsindex fdf7dae09..9ffac3442 100644--- a/crates/recording/src/studio_recording.rs+++ b/crates/recording/src/studio_recording.rs@@ -1,3 +1,10 @@+#[cfg(target_os = "macos")]+use crate::SendableShareableContent;+#[cfg(target_os = "macos")]+use crate::output_pipeline::{+ AVFoundationCameraMuxer, AVFoundationCameraMuxerConfig, MacOSFragmentedM4SCameraMuxer,+ MacOSFragmentedM4SCameraMuxerConfig,+};use crate::{ActorError, H264_MAX_DIMENSION, MediaError, RecordingBaseInputs, RecordingError,SharedPauseState, calculate_gpu_compatible_size,@@ -12,12 +19,6 @@ use crate::{sources::{self, screen_capture},};-#[cfg(target_os = "macos")]-use crate::output_pipeline::{- AVFoundationCameraMuxer, AVFoundationCameraMuxerConfig, MacOSFragmentedM4SCameraMuxer,- MacOSFragmentedM4SCameraMuxerConfig,-};-#[cfg(windows)]use crate::output_pipeline::{WindowsCameraMuxer, WindowsCameraMuxerConfig, WindowsFragmentedM4SCameraMuxer,@@ -537,7 +538,7 @@ impl ActorBuilder {pub async fn build(self,- #[cfg(target_os = "macos")] shareable_content: cidre::arc::R<cidre::sc::ShareableContent>,+ #[cfg(target_os = "macos")] shareable_content: Option<SendableShareableContent>,) -> anyhow::Result<ActorHandle> {spawn_studio_recording_actor(self.output_path,@@ -954,32 +955,6 @@ async fn create_segment_pipeline(let d3d_device = crate::capture_pipeline::create_d3d_device().context("D3D11 device creation failed - this may happen in VMs, RDP sessions, or systems without GPU drivers")?;- let (display, crop) =- target_to_display_and_crop(&base_inputs.capture_target).context("target_display_crop")?;-- let screen_config = ScreenCaptureConfig::<ScreenCaptureMethod>::init(- display,- crop,- !custom_cursor_capture,- max_fps,- start_time.system_time(),- base_inputs.capture_system_audio,- #[cfg(windows)]- d3d_device,- #[cfg(target_os = "macos")]- base_inputs.shareable_content,- #[cfg(target_os = "macos")]- base_inputs.excluded_windows,- )- .await- .context("screen capture init")?;-- let screen_info = screen_config.info();- let output_size =- calculate_gpu_compatible_size(screen_info.width, screen_info.height, H264_MAX_DIMENSION);-- let (capture_source, system_audio) = screen_config.to_sources().await?;-let dir = ensure_dir(&segments_dir.join(format!("segment-{index}")))?;let screen_output_path = dir.join("display.mp4");@@ -1004,22 +979,98 @@ async fn create_segment_pipeline(None};- let screen = ScreenCaptureMethod::make_studio_mode_pipeline(- capture_source,- screen_output_path.clone(),- start_time,- fragmented,- shared_pause_state.clone(),- output_size,+ let camera_only = matches!(+ base_inputs.capture_target,+ screen_capture::ScreenCaptureTarget::CameraOnly+ );++ let (screen, system_audio, cursor_display) = if camera_only {+ let camera_feed = base_inputs+ .camera_feed+ .clone()+ .ok_or_else(|| anyhow!("Camera feed missing for camera-only recording"))?;++ #[cfg(target_os = "macos")]+ let screen = OutputPipeline::builder(screen_output_path.clone())+ .with_video::<sources::NativeCamera>(camera_feed.clone())+ .with_timestamps(start_time)+ .build::<AVFoundationCameraMuxer>(AVFoundationCameraMuxerConfig::default())+ .instrument(error_span!("screen-out"))+ .await+ .context("camera-only screen pipeline setup")?;++ #[cfg(windows)]+ let screen = OutputPipeline::builder(screen_output_path.clone())+ .with_video::<sources::NativeCamera>(camera_feed.clone())+ .with_timestamps(start_time)+ .build::<WindowsCameraMuxer>(WindowsCameraMuxerConfig {+ encoder_preferences: encoder_preferences.clone(),+ ..Default::default()+ })+ .instrument(error_span!("screen-out"))+ .await+ .context("camera-only screen pipeline setup")?;++ (screen, None, None)+ } else {+ let capture_target = base_inputs.capture_target.clone();+#[cfg(windows)]- encoder_preferences.clone(),- )- .instrument(error_span!("screen-out"))- .await- .context("screen pipeline setup")?;+ let d3d_device = d3d_device;++ let (display, crop) =+ target_to_display_and_crop(&capture_target).context("target_display_crop")?;++ let screen_config = ScreenCaptureConfig::<ScreenCaptureMethod>::init(+ display,+ crop,+ !custom_cursor_capture,+ max_fps,+ start_time.system_time(),+ base_inputs.capture_system_audio,+ #[cfg(windows)]+ d3d_device,+ #[cfg(target_os = "macos")]+ base_inputs+ .shareable_content+ .clone()+ .ok_or_else(|| anyhow!("Missing shareable content"))?,+ #[cfg(target_os = "macos")]+ base_inputs.excluded_windows.clone(),+ )+ .await+ .context("screen capture init")?;++ let screen_info = screen_config.info();+ let output_size = calculate_gpu_compatible_size(+ screen_info.width,+ screen_info.height,+ H264_MAX_DIMENSION,+ );++ let (capture_source, system_audio) = screen_config.to_sources().await?;++ let screen = ScreenCaptureMethod::make_studio_mode_pipeline(+ capture_source,+ screen_output_path.clone(),+ start_time,+ fragmented,+ shared_pause_state.clone(),+ output_size,+ #[cfg(windows)]+ encoder_preferences.clone(),+ )+ .instrument(error_span!("screen-out"))+ .await+ .context("screen pipeline setup")?;++ (screen, system_audio, Some(display))+ };#[cfg(target_os = "macos")]- let camera = if let Some(camera_feed) = base_inputs.camera_feed {+ let camera = if camera_only {+ None+ } else if let Some(camera_feed) = base_inputs.camera_feed {let pipeline = if fragmented {let fragments_dir = dir.join("camera");OutputPipeline::builder(fragments_dir)@@ -1045,7 +1096,9 @@ async fn create_segment_pipeline(};#[cfg(windows)]- let camera = if let Some(camera_feed) = base_inputs.camera_feed {+ let camera = if camera_only {+ None+ } else if let Some(camera_feed) = base_inputs.camera_feed {let pipeline = if fragmented {let fragments_dir = dir.join("camera");OutputPipeline::builder(fragments_dir)@@ -1121,36 +1174,44 @@ async fn create_segment_pipeline(None};- let cursor = custom_cursor_capture- .then(move || {- let cursor_crop_bounds = base_inputs- .capture_target- .cursor_crop()- .ok_or(CreateSegmentPipelineError::NoBounds)?;-- let cursor_output_path = dir.join("cursor.json");- let incremental_output = if fragmented {- Some(cursor_output_path.clone())- } else {- None- };-- let cursor = spawn_cursor_recorder(- cursor_crop_bounds,- display,- cursors_dir.to_path_buf(),- prev_cursors,- next_cursors_id,- start_time,- incremental_output,- );-- Ok::<_, CreateSegmentPipelineError>(CursorPipeline {- output_path: cursor_output_path,- actor: cursor,+ let cursor = if camera_only {+ None+ } else {+ custom_cursor_capture+ .then(move || {+ let cursor_crop_bounds = base_inputs+ .capture_target+ .cursor_crop()+ .ok_or(CreateSegmentPipelineError::NoBounds)?;++ let cursor_output_path = dir.join("cursor.json");+ let incremental_output = if fragmented {+ Some(cursor_output_path.clone())+ } else {+ None+ };++ let cursor_display = cursor_display+ .clone()+ .ok_or(CreateSegmentPipelineError::NoDisplay)?;++ let cursor = spawn_cursor_recorder(+ cursor_crop_bounds,+ cursor_display,+ cursors_dir.to_path_buf(),+ prev_cursors,+ next_cursors_id,+ start_time,+ incremental_output,+ );++ Ok::<_, CreateSegmentPipelineError>(CursorPipeline {+ output_path: cursor_output_path,+ actor: cursor,+ })})- })- .transpose()?;+ .transpose()?+ };info!("pipeline playing");