Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
feat(recording): implement screen capture auto-restart on macOS
Richie McIlroye4862b008137
diff --git a/crates/recording/src/sources/screen_capture/macos.rs b/crates/recording/src/sources/screen_capture/macos.rsindex e8685feb5..d23642131 100644--- a/crates/recording/src/sources/screen_capture/macos.rs+++ b/crates/recording/src/sources/screen_capture/macos.rs@@ -23,7 +23,10 @@ use tokio_util::{future::FutureExt as _,sync::{CancellationToken, DropGuard},};-use tracing::{debug, info, warn};+use tracing::{debug, error, info, warn};++const MAX_CAPTURE_RESTARTS: u32 = 3;+const RESTART_DELAY: Duration = Duration::from_secs(2);struct FrameScaler {session: arc::R<cidre::vt::PixelTransferSession>,@@ -297,14 +300,29 @@ impl ScreenCaptureConfig<CMSampleBufferCapture> {PixelBufferCopier::new(expected_width, expected_height),));+ let rebuild_params = Arc::new(CapturerRebuildParams {+ display_id: self.config.display.clone(),+ config: self.config.clone(),+ system_audio: self.system_audio,+ excluded_windows: self.excluded_windows.clone(),+ video_info: self.video_info,+ video_tx: video_tx.clone(),+ audio_tx: audio_tx.clone(),+ error_tx: error_tx.clone(),+ video_frame_counter: video_frame_counter.clone(),+ drop_counter: drop_counter.clone(),+ system_audio_frame_counter: system_audio_frame_counter.clone(),+ system_audio_drop_counter: system_audio_drop_counter.clone(),+ frame_scaler: frame_scaler.clone(),+ scaling_logged: scaling_logged.clone(),+ scaled_frame_count: scaled_frame_count.clone(),+ pixel_buffer_copier: pixel_buffer_copier.clone(),+ });+let builder = scap_screencapturekit::Capturer::builder(content_filter, settings).with_output_sample_buf_cb({let video_frame_count = video_frame_counter.clone();let drop_counter = drop_counter.clone();- let frame_scaler = frame_scaler.clone();- let scaling_logged = scaling_logged.clone();- let scaled_frame_count = scaled_frame_count.clone();- let pixel_buffer_copier = pixel_buffer_copier.clone();let sys_audio_drop_counter = system_audio_drop_counter.clone();let sys_audio_frame_counter = system_audio_frame_counter.clone();move |frame| {@@ -469,6 +487,7 @@ impl ScreenCaptureConfig<CMSampleBufferCapture> {}).with_stop_with_err_cb({let video_frame_count = video_frame_counter.clone();+ let error_tx = error_tx.clone();move |_, err| {debug!("Capturer stopping after creating {} video frames",@@ -491,6 +510,7 @@ impl ScreenCaptureConfig<CMSampleBufferCapture> {drop_counter,cancel_token: cancel_token.clone(),drop_guard: cancel_token.drop_guard(),+ rebuild_params: rebuild_params.clone(),},audio_rx.map(|rx| {SystemAudioSourceConfig(@@ -499,6 +519,7 @@ impl ScreenCaptureConfig<CMSampleBufferCapture> {error_rx,system_audio_frame_counter,system_audio_drop_counter,+ rebuild_params,)}),))@@ -540,6 +561,10 @@ impl Capturer {}}+ fn mark_stopped(&self) {+ self.started.store(false, atomic::Ordering::Relaxed);+ }+async fn start(&self) -> anyhow::Result<()> {if self.started@@ -586,6 +611,7 @@ pub struct VideoSourceConfig {drop_guard: DropGuard,video_frame_counter: Arc<AtomicU32>,drop_counter: Arc<AtomicU64>,+ rebuild_params: Arc<CapturerRebuildParams>,}pub struct VideoSource {inner: ChannelVideoSource<VideoFrame>,@@ -595,6 +621,7 @@ pub struct VideoSource {drop_counter: Arc<AtomicU64>,_drop_guard: DropGuard,health_tx: output_pipeline::HealthSender,+ active_capturer: Arc<Mutex<Option<Capturer>>>,}impl output_pipeline::VideoSource for VideoSource {@@ -617,10 +644,17 @@ impl output_pipeline::VideoSource for VideoSource {drop_guard,video_frame_counter,drop_counter,+ rebuild_params,} = config;let monitor_cancel = cancel_token.clone();+ let health_tx = ctx.health_tx().clone();+ let active_capturer: Arc<Mutex<Option<Capturer>>> = Arc::new(Mutex::new(None));+ let active_capturer_for_stop = active_capturer.clone();+ let original_capturer = capturer.clone();ctx.tasks().spawn("screen-capture-monitor", async move {+ let mut restart_count = 0u32;+loop {select! {_ = monitor_cancel.cancelled() => break Ok(()),@@ -638,8 +672,70 @@ impl output_pipeline::VideoSource for VideoSource {if monitor_cancel.is_cancelled() {break Ok(());}- warn!("Screen capture stream stopped by the system");- return Err(anyhow!(system_stop_message()));++ if let Ok(guard) = active_capturer.lock() {+ match guard.as_ref() {+ Some(c) => c.mark_stopped(),+ None => original_capturer.mark_stopped(),+ }+ } else {+ original_capturer.mark_stopped();+ }++ if restart_count >= MAX_CAPTURE_RESTARTS {+ error!(+ restart_count,+ max_restarts = MAX_CAPTURE_RESTARTS,+ "Screen capture failed after max restart attempts"+ );+ return Err(anyhow!(system_stop_message()));+ }++ restart_count += 1;+ warn!(+ restart_count,+ max_restarts = MAX_CAPTURE_RESTARTS,+ "Screen capture stream stopped by system, attempting restart"+ );++ output_pipeline::emit_health(+ &health_tx,+ output_pipeline::PipelineHealthEvent::SourceRestarting,+ );++ tokio::time::sleep(RESTART_DELAY).await;++ if monitor_cancel.is_cancelled() {+ break Ok(());+ }++ match rebuild_capturer(&rebuild_params).await {+ Ok(new_capturer) => {+ if let Ok(mut guard) = active_capturer.lock() {+ *guard = Some(new_capturer);+ }+ info!(+ restart_count,+ "macOS screen capture restarted successfully"+ );+ output_pipeline::emit_health(+ &health_tx,+ output_pipeline::PipelineHealthEvent::SourceRestarted,+ );+ continue;+ }+ Err(e) => {+ error!(+ restart_count,+ error = %e,+ "Failed to restart macOS screen capture"+ );+ return Err(anyhow!(+ "Screen capture restart failed after {} attempts: {e}",+ restart_count+ ));+ }+ }}return Err(anyhow!(format!("{err}")));@@ -659,6 +755,7 @@ impl output_pipeline::VideoSource for VideoSource {video_frame_counter,drop_counter,health_tx: stats_health_tx,+ active_capturer: active_capturer_for_stop,})}@@ -732,8 +829,16 @@ impl output_pipeline::VideoSource for VideoSource {self.cancel_token.cancel();+ let capturer_to_stop = self+ .active_capturer+ .lock()+ .ok()+ .and_then(|mut guard| guard.take());++ let target = capturer_to_stop.as_ref().unwrap_or(&self.capturer);+let stop_result =- tokio::time::timeout(std::time::Duration::from_secs(5), self.capturer.stop()).await;+ tokio::time::timeout(std::time::Duration::from_secs(5), target.stop()).await;match stop_result {Ok(result) => result,@@ -762,12 +867,301 @@ fn system_stop_message() -> &'static str {"Screen capture stopped because macOS made the display unavailable. This commonly happens when the lid is closed or the display sleeps."}+struct CapturerRebuildParams {+ display_id: DisplayId,+ config: Config,+ system_audio: bool,+ excluded_windows: Vec<WindowId>,+ video_info: VideoInfo,+ video_tx: flume::Sender<VideoFrame>,+ audio_tx: Option<mpsc::Sender<AudioFrame>>,+ error_tx: broadcast::Sender<arc::R<ns::Error>>,+ video_frame_counter: Arc<AtomicU32>,+ drop_counter: Arc<AtomicU64>,+ system_audio_frame_counter: Arc<AtomicU64>,+ system_audio_drop_counter: Arc<AtomicU64>,+ frame_scaler: Arc<Mutex<Option<FrameScaler>>>,+ scaling_logged: Arc<AtomicBool>,+ scaled_frame_count: Arc<AtomicU64>,+ pixel_buffer_copier: Arc<Mutex<Option<PixelBufferCopier>>>,+}++unsafe impl Send for CapturerRebuildParams {}+unsafe impl Sync for CapturerRebuildParams {}++async fn rebuild_capturer(params: &CapturerRebuildParams) -> anyhow::Result<Capturer> {+ let shareable_content = sc::ShareableContent::current()+ .await+ .map_err(|e| anyhow!("Failed to get shareable content during restart: {e}"))?;++ let display = Display::from_id(¶ms.display_id)+ .ok_or_else(|| anyhow!("Display not found during restart: {:?}", params.display_id))?;++ let excluded_sc_windows = if params.excluded_windows.is_empty() {+ Vec::new()+ } else {+ let mut collected = Vec::new();+ for window_id in ¶ms.excluded_windows {+ let Some(window) = Window::from_id(window_id) else {+ continue;+ };+ if let Some(sc_window) = window.raw_handle().as_sc(shareable_content.clone()) {+ collected.push(sc_window);+ }+ }+ collected+ };++ let content_filter = display+ .raw_handle()+ .as_content_filter_excluding_windows(shareable_content, excluded_sc_windows)+ .ok_or_else(|| anyhow!("Failed to create content filter during restart"))?;++ let size = {+ let logical_size = params+ .config+ .crop_bounds+ .map(|bounds| bounds.size())+ .or_else(|| display.logical_size())+ .ok_or_else(|| anyhow!("Display has no logical size during restart"))?;++ let physical_size = display+ .physical_size()+ .ok_or_else(|| anyhow!("Display has no physical size during restart"))?;+ let display_logical_size = display.logical_size().ok_or_else(|| {+ anyhow!("Display has no logical size for scale computation during restart")+ })?;++ let scale = physical_size.width() / display_logical_size.width();+ let width = ensure_even((logical_size.width() * scale) as u32) as f64;+ let height = ensure_even((logical_size.height() * scale) as u32) as f64;+ PhysicalSize::new(width, height)+ };++ let max_queue_depth = get_max_queue_depth();+ let queue_depth =+ ((params.config.fps as f32 / 30.0 * 5.0).ceil() as isize).clamp(3, max_queue_depth);++ let mut settings = scap_screencapturekit::StreamCfgBuilder::default()+ .with_width(size.width() as usize)+ .with_height(size.height() as usize)+ .with_fps(params.config.fps as f32)+ .with_shows_cursor(params.config.show_cursor)+ .with_captures_audio(params.system_audio)+ .with_queue_depth(queue_depth)+ .build();++ settings.set_pixel_format(cv::PixelFormat::_420V);+ settings.set_color_space_name(cg::color_space::names::srgb());++ if let Some(crop_bounds) = params.config.crop_bounds {+ settings.set_src_rect(cg::Rect::new(+ crop_bounds.position().x(),+ crop_bounds.position().y(),+ crop_bounds.size().width(),+ crop_bounds.size().height(),+ ));+ }++ let expected_width = params.video_info.width as usize;+ let expected_height = params.video_info.height as usize;++ let video_tx = params.video_tx.clone();+ let mut audio_tx = params.audio_tx.clone();+ let error_tx = params.error_tx.clone();++ let builder = scap_screencapturekit::Capturer::builder(content_filter, settings)+ .with_output_sample_buf_cb({+ let video_frame_count = params.video_frame_counter.clone();+ let drop_counter = params.drop_counter.clone();+ let frame_scaler = params.frame_scaler.clone();+ let scaling_logged = params.scaling_logged.clone();+ let scaled_frame_count = params.scaled_frame_count.clone();+ let pixel_buffer_copier = params.pixel_buffer_copier.clone();+ let sys_audio_drop_counter = params.system_audio_drop_counter.clone();+ let sys_audio_frame_counter = params.system_audio_frame_counter.clone();+ move |frame| {+ let sample_buffer = frame.sample_buf();++ let mach_timestamp =+ cm::Clock::convert_host_time_to_sys_units(sample_buffer.pts());+ let timestamp = Timestamp::MachAbsoluteTime(+ cap_timestamp::MachAbsoluteTimestamp::new(mach_timestamp),+ );++ match &frame {+ scap_screencapturekit::Frame::Screen(frame) => {+ let Some(image_buf) = frame.image_buf() else {+ return;+ };+ if image_buf.height() == 0 || image_buf.width() == 0 {+ return;+ }++ let frame_width = image_buf.width();+ let frame_height = image_buf.height();++ let final_sample_buf =+ if frame_width != expected_width || frame_height != expected_height {+ let Ok(mut scaler_guard) = frame_scaler.lock() else {+ drop_counter.fetch_add(1, atomic::Ordering::Relaxed);+ return;+ };++ if scaler_guard.is_none() {+ *scaler_guard =+ FrameScaler::new(expected_width, expected_height);++ if scaler_guard.is_some() {+ info!(+ expected_width,+ expected_height,+ frame_width,+ frame_height,+ "Display configuration changed, scaling frames to match original dimensions"+ );+ } else {+ warn!(+ "Failed to create frame scaler, dropping mismatched frames"+ );+ }+ scaling_logged.store(true, atomic::Ordering::Relaxed);+ }++ let Some(scaler) = scaler_guard.as_ref() else {+ drop_counter.fetch_add(1, atomic::Ordering::Relaxed);+ return;+ };++ let Some(scaled) = scaler.scale_frame(sample_buffer) else {+ drop_counter.fetch_add(1, atomic::Ordering::Relaxed);+ return;+ };++ let count =+ scaled_frame_count.fetch_add(1, atomic::Ordering::Relaxed) + 1;+ if count.is_multiple_of(300) {+ debug!(scaled_frames = count, "Scaling frames");+ }++ scaled+ } else {+ if scaling_logged.swap(false, atomic::Ordering::Relaxed) {+ let count =+ scaled_frame_count.swap(0, atomic::Ordering::Relaxed);+ info!(+ scaled_frames = count,+ "Display dimensions restored, resuming direct capture"+ );+ if let Ok(mut guard) = frame_scaler.lock() {+ *guard = None;+ }+ }++ let copied =+ if let Ok(copier_guard) = pixel_buffer_copier.lock() {+ if let Some(copier) = copier_guard.as_ref() {+ copier.copy_frame(sample_buffer)+ } else {+ None+ }+ } else {+ None+ };++ match copied {+ Some(buf) => buf,+ None => {+ drop_counter.fetch_add(1, atomic::Ordering::Relaxed);+ return;+ }+ }+ };++ cap_fail::fail_ret!("screen_capture video frame skip");++ video_frame_count.fetch_add(1, atomic::Ordering::Relaxed);++ if video_tx+ .try_send(VideoFrame {+ sample_buf: final_sample_buf,+ timestamp,+ })+ .is_err()+ {+ drop_counter.fetch_add(1, atomic::Ordering::Relaxed);+ }+ }+ scap_screencapturekit::Frame::Audio(_) => {+ use ffmpeg::ChannelLayout;++ cap_fail::fail_ret!("screen_capture audio frame skip");++ let Some(audio_tx) = &mut audio_tx else {+ return;+ };++ let Ok(buf_list) = sample_buffer.audio_buf_list::<2>() else {+ warn!("Failed to extract audio buffer list from sample, dropping audio chunk");+ return;+ };+ let Ok(slice) = buf_list.block().as_slice() else {+ warn!("Failed to get audio buffer slice, dropping audio chunk");+ return;+ };++ let mut frame = ffmpeg::frame::Audio::new(+ ffmpeg::format::Sample::F32(ffmpeg::format::sample::Type::Planar),+ sample_buffer.num_samples() as usize,+ ChannelLayout::STEREO,+ );+ frame.set_rate(48_000);+ let data_bytes_size = buf_list.list().buffers[0].data_bytes_size;+ for i in 0..frame.planes() {+ frame.data_mut(i).copy_from_slice(+ &slice[i * data_bytes_size as usize+ ..(i + 1) * data_bytes_size as usize],+ );+ }++ match audio_tx.try_send(AudioFrame::new(frame, timestamp)) {+ Ok(()) => {+ sys_audio_frame_counter+ .fetch_add(1, atomic::Ordering::Relaxed);+ }+ Err(_) => {+ sys_audio_drop_counter+ .fetch_add(1, atomic::Ordering::Relaxed);+ }+ }+ }+ _ => {}+ }+ }+ })+ .with_stop_with_err_cb({+ let video_frame_count = params.video_frame_counter.clone();+ move |_, err| {+ debug!(+ "Capturer stopping after creating {} video frames",+ video_frame_count.load(atomic::Ordering::Relaxed)+ );+ let _ = error_tx.send(err.retained());+ }+ });++ let capturer = Capturer::new(Arc::new(builder.build()?));+ capturer.start().await?;+ Ok(capturer)+}+pub struct SystemAudioSourceConfig(ChannelAudioSourceConfig,Capturer,broadcast::Receiver<arc::R<ns::Error>>,Arc<AtomicU64>,Arc<AtomicU64>,+ Arc<CapturerRebuildParams>,);pub struct SystemAudioSource {@@ -793,6 +1187,7 @@ impl output_pipeline::AudioSource for SystemAudioSource {mut error_rx,frame_counter,drop_counter,+ _rebuild_params,) = config;let cancel_token = CancellationToken::new();@@ -800,6 +1195,8 @@ impl output_pipeline::AudioSource for SystemAudioSource {ctx.tasks().spawn("system-audio", {let cancel = cancel_token.child_token();async move {+ let mut system_stop_count = 0u32;+loop {tokio::select! {biased;@@ -808,8 +1205,17 @@ impl output_pipeline::AudioSource for SystemAudioSource {match result {Ok(err) => {if is_system_stop_error(err.as_ref()) {- warn!("Screen capture audio stream stopped by the system");- return Err(anyhow!(system_stop_message()));+ system_stop_count += 1;+ if system_stop_count > MAX_CAPTURE_RESTARTS {+ warn!("Screen capture audio stream stopped by the system (exhausted restarts)");+ return Err(anyhow!(system_stop_message()));+ }+ warn!(+ system_stop_count,+ "Screen capture audio stream stopped by system, waiting for restart"+ );+ tokio::time::sleep(RESTART_DELAY + Duration::from_secs(1)).await;+ continue;}return Err(anyhow!("{err}"));}