Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

initialise camera in background to account for hanging (#631)

Brendan Allan6b508985a958
diff --git a/apps/desktop/src-tauri/src/deeplink_actions.rs b/apps/desktop/src-tauri/src/deeplink_actions.rs
index 0d0c79d9d..101e69dc1 100644
--- a/apps/desktop/src-tauri/src/deeplink_actions.rs
+++ b/apps/desktop/src-tauri/src/deeplink_actions.rs
@@ -106,7 +106,7 @@ impl DeepLinkAction {
} => {
let state = app.state::<ArcLock<App>>();
- crate::set_camera_input(app.clone(), state.clone(), camera_label).await?;
+ crate::set_camera_input(state.clone(), camera_label).await?;
crate::set_mic_input(state.clone(), mic_label).await?;
use cap_media::sources::ScreenCaptureTarget;
diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs
index c707ca078..35340ed9d 100644
--- a/apps/desktop/src-tauri/src/lib.rs
+++ b/apps/desktop/src-tauri/src/lib.rs
@@ -48,6 +48,7 @@ use notifications::NotificationType;
use png::{ColorType, Encoder};
use recording::InProgressRecording;
use relative_path::RelativePathBuf;
+
use scap::capturer::Capturer;
use scap::frame::Frame;
use scap::frame::VideoFrame;
@@ -187,33 +188,65 @@ async fn set_mic_input(state: MutableState<'_, App>, label: Option<String>) -> R
#[tauri::command]
#[specta::specta]
async fn set_camera_input(
- app_handle: AppHandle,
state: MutableState<'_, App>,
label: Option<String>,
-) -> Result<(), String> {
+) -> Result<bool, String> {
let mut app = state.write().await;
- let res = match (&label, app.camera_feed.as_ref()) {
- (Some(label), Some(camera_feed)) => camera_feed
- .lock()
- .await
- .switch_cameras(label)
- .await
- .map_err(|e| e.to_string()),
- (Some(label), None) => CameraFeed::init(label)
- .await
- .map(|feed| {
- feed.attach(app.camera_tx.clone());
- app.camera_feed = Some(Arc::new(Mutex::new(feed)));
- })
- .map_err(|e| e.to_string()),
+ match (&label, app.camera_feed.as_ref()) {
+ (Some(label), Some(camera_feed)) => {
+ // Try to switch cameras on existing feed
+ camera_feed
+ .lock()
+ .await
+ .switch_cameras(label)
+ .await
+ .map_err(|e| e.to_string())?;
+ Ok(true)
+ }
+ (Some(label), None) => {
+ let camera_tx = app.camera_tx.clone();
+ drop(app);
+
+ let init_rx = CameraFeed::init_async(label);
+
+ loop {
+ tokio::select! {
+ result = init_rx.recv_async() => {
+ match result {
+ Ok(Ok(feed)) => {
+ let mut app = state.write().await;
+ // Only attach if camera is still None
+ if app.camera_feed.is_none() {
+ feed.attach(camera_tx);
+ app.camera_feed = Some(Arc::new(Mutex::new(feed)));
+ return Ok(true);
+ } else {
+ // Camera state changed while we were initializing
+ return Ok(false);
+ }
+ }
+ Ok(Err(e)) => return Err(e.to_string()),
+ Err(_) => return Ok(false), // Channel closed
+ }
+ }
+ // Periodically check if we should abandon this initialization
+ _ = tokio::time::sleep(tokio::time::Duration::from_millis(100)) => {
+ let app = state.read().await;
+
+ if app.camera_feed.is_some() {
+ return Ok(false);
+ }
+ }
+ }
+ }
+ }
(None, _) => {
+ // User wants no camera
app.camera_feed.take();
- Ok(())
+ Ok(true)
}
- };
-
- res
+ }
}
#[derive(specta::Type, Serialize, tauri_specta::Event, Clone)]
diff --git a/apps/desktop/src/routes/(window-chrome)/(main).tsx b/apps/desktop/src/routes/(window-chrome)/(main).tsx
index 4edbcc362..ba164671e 100644
--- a/apps/desktop/src/routes/(window-chrome)/(main).tsx
+++ b/apps/desktop/src/routes/(window-chrome)/(main).tsx
@@ -409,13 +409,12 @@ function Page() {
</div>
</div>
<CameraSelect
- disabled={setCamera.isPending}
options={cameras}
value={options.cameraLabel() ?? null}
onChange={(v) => setCamera.mutate(v)}
/>
<MicrophoneSelect
- disabled={mics.isPending || setMicInput.isPending}
+ disabled={mics.isPending}
options={mics.data ?? []}
// this prevents options.micName() from suspending on initial load
value={mics.isPending ? rawOptions.micName : options.micName() ?? null}
diff --git a/apps/desktop/src/routes/camera.tsx b/apps/desktop/src/routes/camera.tsx
index c84bb734d..d0025d35a 100644
--- a/apps/desktop/src/routes/camera.tsx
+++ b/apps/desktop/src/routes/camera.tsx
@@ -66,8 +66,6 @@ function Page() {
width: number;
data: ImageData;
} | null>();
- const [isLoading, setIsLoading] = createSignal(true);
- const [error, setError] = createSignal<string | null>(null);
const [ws, isConnected] = createImageDataWS(
`ws://localhost:${cameraWsPort}`,
@@ -75,24 +73,15 @@ function Page() {
setLatestFrame(imageData);
const ctx = cameraCanvasRef?.getContext("2d");
ctx?.putImageData(imageData.data, 0, 0);
- setIsLoading(false);
}
);
- createEffect(() => {
- if (!isConnected()) {
- setIsLoading(true);
- setError("Failed to connect to the camera. Please try again.");
- } else {
- setError(null);
- }
- });
-
// Attempt to reconnect every 5 seconds if not connected
const reconnectInterval = setInterval(() => {
if (!isConnected()) {
console.log("Attempting to reconnect...");
ws.close();
+
// Create a new WebSocket connection
const newWs = createImageDataWS(
`ws://localhost:${cameraWsPort}`,
@@ -100,7 +89,6 @@ function Page() {
setLatestFrame(imageData);
const ctx = cameraCanvasRef?.getContext("2d");
ctx?.putImageData(imageData.data, 0, 0);
- setIsLoading(false);
}
);
// Update the ws reference
diff --git a/apps/desktop/src/utils/queries.ts b/apps/desktop/src/utils/queries.ts
index 3b052aee0..df4a718f0 100644
--- a/apps/desktop/src/utils/queries.ts
+++ b/apps/desktop/src/utils/queries.ts
@@ -12,6 +12,7 @@ import { commands, RecordingMode, ScreenCaptureTarget } from "./tauri";
import { createQueryInvalidate } from "./events";
import { createEventListener } from "@solid-primitives/event-listener";
import { useRecordingOptions } from "~/routes/(window-chrome)/OptionsContext";
+import { getCurrentWindow } from "@tauri-apps/api/window";
export const listWindows = queryOptions({
queryKey: ["capture", "windows"] as const,
@@ -138,9 +139,12 @@ export function createCameraMutation() {
const setCameraInput = createMutation(() => ({
mutationFn: async (label: string | null) => {
- await commands.setCameraInput(label);
setOptions("cameraLabel", label);
- await commands.showWindow("Camera");
+ if (label) {
+ await commands.showWindow("Camera");
+ getCurrentWindow().setFocus();
+ }
+ await commands.setCameraInput(label);
},
}));
diff --git a/apps/desktop/src/utils/tauri.ts b/apps/desktop/src/utils/tauri.ts
index d7b0bcaa6..bc6cff9ae 100644
--- a/apps/desktop/src/utils/tauri.ts
+++ b/apps/desktop/src/utils/tauri.ts
@@ -8,7 +8,7 @@ export const commands = {
async setMicInput(label: string | null) : Promise<null> {
return await TAURI_INVOKE("set_mic_input", { label });
},
-async setCameraInput(label: string | null) : Promise<null> {
+async setCameraInput(label: string | null) : Promise<boolean> {
return await TAURI_INVOKE("set_camera_input", { label });
},
async startRecording(inputs: StartRecordingInputs) : Promise<null> {
diff --git a/crates/media/src/feeds/camera.rs b/crates/media/src/feeds/camera.rs
index a8e34f2db..7bddd2180 100644
--- a/crates/media/src/feeds/camera.rs
+++ b/crates/media/src/feeds/camera.rs
@@ -3,9 +3,11 @@ use ffmpeg::format::Pixel;
use flume::{Receiver, Sender, TryRecvError, TrySendError};
use nokhwa::{pixel_format::RgbAFormat, utils::*, Camera};
use std::{
+ sync::Arc,
thread::{self},
time::SystemTime,
};
+use tokio::sync::Mutex;
use tracing::{debug, error, info, trace, warn};
use crate::{
@@ -66,12 +68,27 @@ impl CameraFeed {
camera_info,
video_info,
control,
- // join_handle,
};
Ok(camera_feed)
}
+ /// Initialize camera asynchronously, returning a receiver immediately.
+ /// The actual initialization happens in a background task.
+ /// Dropping the receiver cancels the initialization.
+ pub fn init_async(selected_camera: &str) -> flume::Receiver<Result<CameraFeed, MediaError>> {
+ let (tx, rx) = flume::bounded(1);
+ let selected_camera = selected_camera.to_string();
+
+ tokio::spawn(async move {
+ let result = Self::init(&selected_camera).await;
+ // Only send if receiver still exists
+ let _ = tx.send(result);
+ });
+
+ rx
+ }
+
pub fn list_cameras() -> Vec<String> {
match nokhwa::query(ApiBackend::Auto) {
Ok(cameras) => cameras