Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

Improve camera initialization and recording state handling

Richie McIlroy41fbc5c5c04c
diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs
index 0841ea068..284f8b322 100644
--- a/apps/desktop/src-tauri/src/lib.rs
+++ b/apps/desktop/src-tauri/src/lib.rs
@@ -444,12 +444,39 @@ async fn set_camera_input(
.map_err(|e| e.to_string())?;
}
Some(id) => {
- camera_feed
- .ask(feeds::camera::SetInput { id: id.clone() })
- .await
- .map_err(|e| e.to_string())?
- .await
- .map_err(|e| e.to_string())?;
+ let mut attempts = 0;
+ loop {
+ attempts += 1;
+
+ // We first ask the actor to set the input
+ // This returns a future that resolves when the camera is actually ready
+ let request = camera_feed
+ .ask(feeds::camera::SetInput { id: id.clone() })
+ .await
+ .map_err(|e| e.to_string());
+
+ let result = match request {
+ Ok(future) => future.await.map_err(|e| e.to_string()),
+ Err(e) => Err(e),
+ };
+
+ match result {
+ Ok(_) => break,
+ Err(e) => {
+ if attempts >= 3 {
+ return Err(format!(
+ "Failed to initialize camera after {} attempts: {}",
+ attempts, e
+ ));
+ }
+ warn!(
+ "Failed to set camera input (attempt {}): {}. Retrying...",
+ attempts, e
+ );
+ tokio::time::sleep(Duration::from_millis(500)).await;
+ }
+ }
+ }
ShowCapWindow::Camera
.show(&app_handle)
@@ -726,11 +753,19 @@ enum CurrentRecordingTarget {
},
}
+#[derive(Serialize, Type)]
+#[serde(rename_all = "camelCase")]
+pub enum RecordingStatus {
+ Pending,
+ Recording,
+}
+
#[derive(Serialize, Type)]
#[serde(rename_all = "camelCase")]
struct CurrentRecording {
target: CurrentRecordingTarget,
mode: RecordingMode,
+ status: RecordingStatus,
}
#[tauri::command]
@@ -741,10 +776,14 @@ async fn get_current_recording(
) -> Result<JsonValue<Option<CurrentRecording>>, ()> {
let state = state.read().await;
- let (mode, capture_target) = match &state.recording_state {
+ let (mode, capture_target, status) = match &state.recording_state {
RecordingState::None => return Ok(JsonValue::new(&None)),
- RecordingState::Pending { mode, target } => (*mode, target),
- RecordingState::Active(inner) => (inner.mode(), inner.capture_target()),
+ RecordingState::Pending { mode, target } => (*mode, target, RecordingStatus::Pending),
+ RecordingState::Active(inner) => (
+ inner.mode(),
+ inner.capture_target(),
+ RecordingStatus::Recording,
+ ),
};
let target = match capture_target {
@@ -762,7 +801,11 @@ async fn get_current_recording(
},
};
- Ok(JsonValue::new(&Some(CurrentRecording { target, mode })))
+ Ok(JsonValue::new(&Some(CurrentRecording {
+ target,
+ mode,
+ status,
+ })))
}
#[derive(Serialize, Type, tauri_specta::Event, Clone)]
@@ -2596,37 +2639,37 @@ pub async fn run(recording_logging_handle: LoggingHandle, logs_dir: PathBuf) {
match event {
WindowEvent::Destroyed => {
- if let Ok(window_id) = CapWindowId::from_str(label) {
- match window_id {
- CapWindowId::Main => {
- let app = app.clone();
-
- for (id, window) in app.webview_windows() {
- if let Ok(CapWindowId::TargetSelectOverlay { .. }) =
- CapWindowId::from_str(&id)
- {
- let _ = window.close();
- }
- }
-
- tokio::spawn(async move {
- let state = app.state::<ArcLock<App>>();
- let app_state = &mut *state.write().await;
-
- if !app_state.is_recording_active_or_pending() {
- let _ =
- app_state.mic_feed.ask(microphone::RemoveInput).await;
- let _ = app_state
- .camera_feed
- .ask(feeds::camera::RemoveInput)
- .await;
-
- app_state.selected_mic_label = None;
- app_state.selected_camera_id = None;
- app_state.camera_in_use = false;
- }
- });
- }
+ if let Ok(window_id) = CapWindowId::from_str(label) {
+ match window_id {
+ CapWindowId::Main => {
+ let app = app.clone();
+
+ for (id, window) in app.webview_windows() {
+ if let Ok(CapWindowId::TargetSelectOverlay { .. }) =
+ CapWindowId::from_str(&id)
+ {
+ let _ = window.close();
+ }
+ }
+
+ tokio::spawn(async move {
+ let state = app.state::<ArcLock<App>>();
+ let app_state = &mut *state.write().await;
+
+ if !app_state.is_recording_active_or_pending() {
+ let _ =
+ app_state.mic_feed.ask(microphone::RemoveInput).await;
+ let _ = app_state
+ .camera_feed
+ .ask(feeds::camera::RemoveInput)
+ .await;
+
+ app_state.selected_mic_label = None;
+ app_state.selected_camera_id = None;
+ app_state.camera_in_use = false;
+ }
+ });
+ }
CapWindowId::Editor { id } => {
let window_ids = EditorWindowIds::get(window.app_handle());
window_ids.ids.lock().unwrap().retain(|(_, _id)| *_id != id);
@@ -2681,11 +2724,18 @@ pub async fn run(recording_logging_handle: LoggingHandle, logs_dir: PathBuf) {
CapWindowId::Camera => {
let app = app.clone();
tokio::spawn(async move {
- app.state::<ArcLock<App>>()
- .write()
- .await
- .camera_preview
- .on_window_close();
+ let state = app.state::<ArcLock<App>>();
+ let mut app_state = state.write().await;
+
+ app_state.camera_preview.on_window_close();
+
+ if !app_state.is_recording_active_or_pending() {
+ let _ = app_state
+ .camera_feed
+ .ask(feeds::camera::RemoveInput)
+ .await;
+ app_state.camera_in_use = false;
+ }
});
}
_ => {}
diff --git a/apps/desktop/src-tauri/src/recording.rs b/apps/desktop/src-tauri/src/recording.rs
index d70995116..1c821f87b 100644
--- a/apps/desktop/src-tauri/src/recording.rs
+++ b/apps/desktop/src-tauri/src/recording.rs
@@ -545,16 +545,57 @@ pub async fn start_recording(
let inputs = inputs.clone();
async move {
fail!("recording::spawn_actor");
- let mut state = state_mtx.write().await;
-
use kameo::error::SendError;
- let camera_feed = match state.camera_feed.ask(camera::Lock).await {
- Ok(lock) => Some(Arc::new(lock)),
- Err(SendError::HandlerError(camera::LockFeedError::NoInput)) => None,
+ // Initialize camera if selected but not active
+ let (camera_feed_actor, selected_camera_id) = {
+ let state = state_mtx.read().await;
+ (state.camera_feed.clone(), state.selected_camera_id.clone())
+ };
+
+ let camera_lock_result = camera_feed_actor.ask(camera::Lock).await;
+
+ let camera_feed_lock = match camera_lock_result {
+ Ok(lock) => Some(lock),
+ Err(SendError::HandlerError(camera::LockFeedError::NoInput)) => {
+ if let Some(id) = selected_camera_id {
+ info!(
+ "Camera selected but not initialized, initializing: {:?}",
+ id
+ );
+ match camera_feed_actor
+ .ask(camera::SetInput { id: id.clone() })
+ .await
+ {
+ Ok(fut) => match fut.await {
+ Ok(_) => match camera_feed_actor.ask(camera::Lock).await {
+ Ok(lock) => Some(lock),
+ Err(e) => {
+ warn!("Failed to lock camera after initialization: {}", e);
+ None
+ }
+ },
+ Err(e) => {
+ warn!("Failed to initialize camera: {}", e);
+ None
+ }
+ },
+ Err(e) => {
+ warn!("Failed to ask SetInput: {}", e);
+ None
+ }
+ }
+ } else {
+ None
+ }
+ }
Err(e) => return Err(anyhow!(e.to_string())),
};
+ let mut state = state_mtx.write().await;
+
+ let camera_feed = camera_feed_lock.map(Arc::new);
+
state.camera_in_use = camera_feed.is_some();
#[cfg(target_os = "macos")]
@@ -1024,21 +1065,21 @@ async fn handle_recording_end(
let _ = window.close();
}
- if let Some(window) = CapWindowId::Main.get(&handle) {
- window.unminimize().ok();
- } else {
- if let Some(v) = CapWindowId::Camera.get(&handle) {
- let _ = v.close();
- }
- let _ = app.mic_feed.ask(microphone::RemoveInput).await;
- let _ = app.camera_feed.ask(camera::RemoveInput).await;
- app.selected_mic_label = None;
- app.selected_camera_id = None;
- app.camera_in_use = false;
- if let Some(win) = CapWindowId::Camera.get(&handle) {
- win.close().ok();
- }
- }
+ if let Some(window) = CapWindowId::Main.get(&handle) {
+ window.unminimize().ok();
+ } else {
+ if let Some(v) = CapWindowId::Camera.get(&handle) {
+ let _ = v.close();
+ }
+ let _ = app.mic_feed.ask(microphone::RemoveInput).await;
+ let _ = app.camera_feed.ask(camera::RemoveInput).await;
+ app.selected_mic_label = None;
+ app.selected_camera_id = None;
+ app.camera_in_use = false;
+ if let Some(win) = CapWindowId::Camera.get(&handle) {
+ win.close().ok();
+ }
+ }
CurrentRecordingChanged.emit(&handle).ok();
diff --git a/apps/desktop/src-tauri/src/windows.rs b/apps/desktop/src-tauri/src/windows.rs
index d6c29095c..3d567e579 100644
--- a/apps/desktop/src-tauri/src/windows.rs
+++ b/apps/desktop/src-tauri/src/windows.rs
@@ -28,6 +28,7 @@ use crate::{
target_select_overlay::WindowFocusManager,
window_exclusion::WindowExclusion,
};
+use cap_recording::feeds;
#[cfg(target_os = "macos")]
const DEFAULT_TRAFFIC_LIGHTS_INSET: LogicalPosition<f64> = LogicalPosition::new(12.0, 12.0);
@@ -500,6 +501,13 @@ impl ShowCapWindow {
let window = window_builder.build()?;
if enable_native_camera_preview {
+ if let Some(id) = state.selected_camera_id.clone()
+ && !state.camera_in_use
+ {
+ let _ = state.camera_feed.ask(feeds::camera::SetInput { id }).await;
+ state.camera_in_use = true;
+ }
+
let camera_feed = state.camera_feed.clone();
if let Err(err) = state
.camera_preview
diff --git a/crates/recording/src/feeds/camera.rs b/crates/recording/src/feeds/camera.rs
index a7300ad73..d75dde0b1 100644
--- a/crates/recording/src/feeds/camera.rs
+++ b/crates/recording/src/feeds/camera.rs
@@ -592,8 +592,7 @@ impl Message<ListenForReady> for CameraFeed {
match self.state {
State::Locked { .. }
| State::Open(OpenState {
- connecting: None,
- attached: Some(..),
+ connecting: None, ..
}) => {
msg.0.send(()).ok();
}
@@ -743,6 +742,10 @@ impl Message<InputConnectFailed> for CameraFeed {
&& connecting.id == msg.id
{
state.connecting = None;
+
+ for tx in &mut self.on_ready.drain(..) {
+ tx.send(()).ok();
+ }
}
Ok(())