Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
fix(camera): fall back to compatibility capture on macOS 26 no-frame sessions
Richie McIlroy8ff9d972355c
diff --git a/crates/camera-avfoundation/src/lib.rs b/crates/camera-avfoundation/src/lib.rsindex 22ebb692a..00121793f 100644--- a/crates/camera-avfoundation/src/lib.rs+++ b/crates/camera-avfoundation/src/lib.rs@@ -86,6 +86,7 @@ pub type OutputDelegateCallback = Box<dyn FnMut(CallbackData)>;pub struct CallbackOutputDelegateInner {callback: OutputDelegateCallback,stream_start: Option<(Instant, Duration)>,+ dropped_frames: u64,}impl CallbackOutputDelegateInner {@@ -93,6 +94,7 @@ impl CallbackOutputDelegateInner {Self {callback,stream_start: None,+ dropped_frames: 0,}}}@@ -148,6 +150,39 @@ impl VideoDataOutputSampleBufDelegateImpl for CallbackOutputDelegate {warn!("Suppressed panic in AVFoundation output delegate");}}++ extern "C" fn impl_capture_output_did_drop_sample_buf_from_connection(+ &mut self,+ _cmd: Option<&cidre::objc::Sel>,+ _output: &av::CaptureOutput,+ sample_buf: &cm::SampleBuf,+ _connection: &av::CaptureConnection,+ ) {+ let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {+ let inner = self.inner_mut();+ inner.dropped_frames += 1;++ if inner.dropped_frames == 1 || inner.dropped_frames.is_multiple_of(100) {+ let reason = sample_buf+ .attach(+ cm::sample_buffer::buf_attach_keys::dropped_frame_reason(),+ std::ptr::null_mut(),+ )+ .map(|value| value.desc().to_string())+ .unwrap_or_else(|| "unknown".to_string());++ warn!(+ count = inner.dropped_frames,+ reason = %reason,+ "AVFoundation dropped camera sample buffer(s)"+ );+ }+ }));++ if result.is_err() {+ warn!("Suppressed panic in AVFoundation drop delegate");+ }+ }}fn mach_time_to_microseconds(mach_time: u64) -> Duration {diff --git a/crates/camera/Cargo.toml b/crates/camera/Cargo.tomlindex e678b535b..9cbfcef81 100644--- a/crates/camera/Cargo.toml+++ b/crates/camera/Cargo.toml@@ -6,6 +6,7 @@ license = "MIT"[dependencies]thiserror = { workspace = true }+tracing = { workspace = true }serde = { workspace = true, optional = true }specta = { workspace = true, optional = true }workspace-hack = { version = "0.1", path = "../workspace-hack" }diff --git a/crates/camera/src/lib.rs b/crates/camera/src/lib.rsindex 2c5f09a17..3125b3e71 100644--- a/crates/camera/src/lib.rs+++ b/crates/camera/src/lib.rs@@ -197,6 +197,20 @@ pub enum StartCapturingError {Native(String),}+/// How the capture session negotiates pixel format and device format.+/// Only affects macOS; other platforms ignore it.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]+pub enum CaptureMode {+ /// Pin the device's active format and request its native pixel format from+ /// the output, avoiding conversion overhead.+ #[default]+ Native,+ /// Leave format and pixel-format negotiation entirely to the OS capture+ /// stack, like a stock AVFoundation app. Costs a conversion but works with+ /// devices that stall when the native format is forced.+ Compatibility,+}+#[derive(Debug)]pub struct CapturedFrame {native: NativeCapturedFrame,@@ -220,10 +234,25 @@ impl CameraInfo {&self,format: Format,callback: impl FnMut(CapturedFrame) + Send + 'static,+ ) -> Result<CaptureHandle, StartCapturingError> {+ self.start_capturing_with_mode(format, CaptureMode::default(), callback)+ }++ #[cfg_attr(not(target_os = "macos"), allow(unused_variables))]+ pub fn start_capturing_with_mode(+ &self,+ format: Format,+ mode: CaptureMode,+ callback: impl FnMut(CapturedFrame) + Send + 'static,) -> Result<CaptureHandle, StartCapturingError> {Ok(CaptureHandle {#[cfg(target_os = "macos")]- native: Some(start_capturing_impl(self, format, Box::new(callback))?),+ native: Some(start_capturing_impl(+ self,+ format,+ mode,+ Box::new(callback),+ )?),#[cfg(windows)]native: Some(start_capturing_impl(self, format, Box::new(callback))?),#[cfg(target_os = "linux")]diff --git a/crates/camera/src/macos.rs b/crates/camera/src/macos.rsindex ec4409895..e7337366b 100644--- a/crates/camera/src/macos.rs+++ b/crates/camera/src/macos.rs@@ -96,9 +96,15 @@ fn find_device(info: &CameraInfo) -> Option<arc::R<av::CaptureDevice>> {.map(|v| v.retained())}+fn fourcc_display(fourcc: u32) -> String {+ let mut bytes = fourcc.to_be_bytes();+ cidre::four_cc_to_str(&mut bytes).to_string()+}+pub(super) fn start_capturing_impl(camera: &CameraInfo,format: Format,+ mode: CaptureMode,mut callback: impl FnMut(CapturedFrame) + 'static,) -> Result<AVFoundationRecordingHandle, StartCapturingError> {let mut device = find_device(camera)@@ -109,9 +115,17 @@ pub(super) fn start_capturing_impl(av::capture::DeviceInput::with_device(&device).map_err(AVFoundationError::Static)?;let queue = dispatch::Queue::new();+ let mut missing_image_bufs: u64 = 0;let delegate =CallbackOutputDelegate::with(CallbackOutputDelegateInner::new(Box::new(move |data| {if data.sample_buf.image_buf().is_none() {+ missing_image_bufs += 1;+ if missing_image_bufs == 1 || missing_image_bufs.is_multiple_of(100) {+ tracing::warn!(+ count = missing_image_bufs,+ "Camera output delivered sample buffer(s) without an image buffer"+ );+ }return;};@@ -124,7 +138,6 @@ pub(super) fn start_capturing_impl(let mut output = av::capture::VideoDataOutput::new();let mut session = av::capture::Session::new();let mut added_input = false;- let pixel_format = format.native().format_desc().media_sub_type();session.configure(|s| {if s.can_add_input(&input) {@@ -144,28 +157,52 @@ pub(super) fn start_capturing_impl(.into());}- let video_settings = ns::Dictionary::with_keys_values(- &[cv::pixel_buffer_keys::pixel_format().as_ns()],- &[ns::Number::with_u32(pixel_format).as_id_ref()],- );- output- .set_video_settings(Some(video_settings.as_ref()))- .map_err(|err| {- AVFoundationError::Message(format!("Failed to set camera video settings: {err}"))- })?;+ if mode == CaptureMode::Native {+ let pixel_format = format.native().format_desc().media_sub_type();+ let is_available = output+ .available_video_cv_pixel_formats()+ .iter()+ .any(|n| n.as_u32() == pixel_format);++ if is_available {+ let video_settings = ns::Dictionary::with_keys_values(+ &[cv::pixel_buffer_keys::pixel_format().as_ns()],+ &[ns::Number::with_u32(pixel_format).as_id_ref()],+ );+ if let Err(err) = output.set_video_settings(Some(video_settings.as_ref())) {+ tracing::warn!(+ pixel_format = %fourcc_display(pixel_format),+ "Failed to request native camera pixel format, using default conversion: {err}"+ );+ }+ } else {+ tracing::warn!(+ pixel_format = %fourcc_display(pixel_format),+ "Native camera pixel format not offered by video output, using default conversion"+ );+ }+ }output.set_sample_buf_delegate(Some(delegate.as_ref()), Some(&queue));- // The device config must stay locked while running starts,- // otherwise start_running can overwrite the active format on macOS- // https://stackoverflow.com/questions/36689578/avfoundation-capturing-video-with-custom-resolution{let _session_lifecycle_guard = avfoundation_session_lifecycle_guard();- let mut _lock = device.config_lock().map_err(AVFoundationError::Retained)?;- _lock.set_active_format(format.native());+ match mode {+ CaptureMode::Native => {+ // The device config must stay locked while running starts,+ // otherwise start_running can overwrite the active format on macOS+ // https://stackoverflow.com/questions/36689578/avfoundation-capturing-video-with-custom-resolution+ let mut _lock = device.config_lock().map_err(AVFoundationError::Retained)?;++ _lock.set_active_format(format.native());- session.start_running();+ session.start_running();+ }+ CaptureMode::Compatibility => {+ session.start_running();+ }+ }}Ok(AVFoundationRecordingHandle {diff --git a/crates/recording/src/feeds/camera.rs b/crates/recording/src/feeds/camera.rsindex dee6497f3..0bbf4c887 100644--- a/crates/recording/src/feeds/camera.rs+++ b/crates/recording/src/feeds/camera.rs@@ -28,6 +28,9 @@ use crate::ffmpeg::FFmpegVideoFrame;use crate::output_pipeline::NativeCameraFrame;const CAMERA_INIT_TIMEOUT: Duration = Duration::from_secs(4);+/// Outer deadline for camera readiness. Must cover both capture attempts on+/// macOS (native + compatibility fallback) plus session teardown in between.+const CAMERA_READY_TIMEOUT: Duration = Duration::from_secs(10);#[cfg(target_os = "macos")]static CAMERA_CAPTURE_LIFECYCLE_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());@@ -407,6 +410,7 @@ fn spawn_camera_setup(native_frame_recipient,ffmpeg_sender_count,native_sender_count,+ &done_rx_thread,).await;@@ -542,7 +546,7 @@ fn camera_ready_future(flow: CameraSetupFlow,) -> BoxFuture<'static, Result<(CameraInfo, VideoInfo), SetInputError>> {async move {- match tokio::time::timeout(CAMERA_INIT_TIMEOUT, ready).await {+ match tokio::time::timeout(CAMERA_READY_TIMEOUT, ready).await {Ok(result) => result.map(|v| (v.camera_info, v.video_info)),Err(err) => {if matches!(flow, CameraSetupFlow::Open) {@@ -775,16 +779,86 @@ async fn setup_camera(native_recipient: Recipient<NewNativeFrame>,ffmpeg_sender_count: Arc<std::sync::atomic::AtomicUsize>,native_sender_count: Arc<std::sync::atomic::AtomicUsize>,+ cancel_rx: &mpsc::Receiver<()>,) -> Result<SetupCameraResult, SetInputError> {let camera = find_camera(id).ok_or(SetInputError::DeviceNotFound)?;let format = select_camera_format(&camera, settings)?;++ {+ let mut fourcc = format.native().format_desc().media_sub_type().to_be_bytes();+ tracing::info!(+ camera = camera.display_name(),+ width = format.width(),+ height = format.height(),+ frame_rate = format.frame_rate(),+ pixel_format = cidre::four_cc_to_str(&mut fourcc),+ "Starting camera capture"+ );+ }++ let first_attempt = start_camera_capture_attempt(+ &camera,+ format.clone(),+ cap_camera::CaptureMode::Native,+ recipient.clone(),+ native_recipient.clone(),+ ffmpeg_sender_count.clone(),+ native_sender_count.clone(),+ )+ .await;++ match first_attempt {+ Ok(result) => Ok(result),+ // Some cameras start a session but never deliver frames when the+ // native format is pinned (seen on Apple cameras on macOS 26.4 beta).+ // Retry once letting AVFoundation negotiate everything itself.+ Err(err @ (SetInputError::Timeout(_) | SetInputError::StartCapturing(_))) => {+ if cancel_rx.try_recv().is_ok() {+ return Err(err);+ }++ warn!(+ camera = camera.display_name(),+ "Camera produced no frames in native mode ({err}), retrying in compatibility mode"+ );++ tokio::time::sleep(Duration::from_millis(150)).await;++ start_camera_capture_attempt(+ &camera,+ format,+ cap_camera::CaptureMode::Compatibility,+ recipient,+ native_recipient,+ ffmpeg_sender_count,+ native_sender_count,+ )+ .await+ .inspect(|_| {+ tracing::info!("Camera capture recovered in compatibility mode");+ })+ }+ Err(err) => Err(err),+ }+}++#[cfg(target_os = "macos")]+async fn start_camera_capture_attempt(+ camera: &cap_camera::CameraInfo,+ format: cap_camera::Format,+ mode: cap_camera::CaptureMode,+ recipient: Recipient<NewFrame>,+ native_recipient: Recipient<NewNativeFrame>,+ ffmpeg_sender_count: Arc<std::sync::atomic::AtomicUsize>,+ native_sender_count: Arc<std::sync::atomic::AtomicUsize>,+) -> Result<SetupCameraResult, SetInputError> {let frame_rate = format.frame_rate().round().max(1.0) as u32;let (ready_tx, ready_rx) = oneshot::channel();let mut ready_signal = Some(ready_tx);let capture_handle = camera- .start_capturing(format.clone(), move |frame| {+ .start_capturing_with_mode(format.clone(), mode, move |frame| {let callback_num =CAMERA_CALLBACK_COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed);@@ -850,7 +924,7 @@ async fn setup_camera(Ok(SetupCameraResult {handle: capture_handle,- camera_info: camera,+ camera_info: camera.clone(),video_info,})}@@ -863,6 +937,7 @@ async fn setup_camera(native_recipient: Recipient<NewNativeFrame>,ffmpeg_sender_count: Arc<std::sync::atomic::AtomicUsize>,native_sender_count: Arc<std::sync::atomic::AtomicUsize>,+ _cancel_rx: &mpsc::Receiver<()>,) -> Result<SetupCameraResult, SetInputError> {let camera = find_camera(id).ok_or(SetInputError::DeviceNotFound)?;let format = select_camera_format(&camera, settings)?;@@ -978,6 +1053,7 @@ async fn setup_camera(_native_recipient: Recipient<NewNativeFrame>,_ffmpeg_sender_count: Arc<std::sync::atomic::AtomicUsize>,_native_sender_count: Arc<std::sync::atomic::AtomicUsize>,+ _cancel_rx: &mpsc::Receiver<()>,) -> Result<SetupCameraResult, SetInputError> {let camera = find_camera(id).ok_or(SetInputError::DeviceNotFound)?;let format = select_camera_format(&camera, settings)?;@@ -1438,7 +1514,7 @@ impl Message<Lock> for CameraFeed {if let Some(connecting) = &mut state.connecting {let ready = &mut connecting.ready;- let data = tokio::time::timeout(CAMERA_INIT_TIMEOUT, ready)+ let data = tokio::time::timeout(CAMERA_READY_TIMEOUT, ready).await.map_err(|err| {LockFeedError::InitializeFailed(SetInputError::Timeout(err.to_string()))