Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

Improve robustness of camera, exit, and websocket handling

Richie McIlroy3e50b0783db1
diff --git a/apps/desktop/src-tauri/src/camera.rs b/apps/desktop/src-tauri/src/camera.rs
index 3c5ae5d4e..fdd319907 100644
--- a/apps/desktop/src-tauri/src/camera.rs
+++ b/apps/desktop/src-tauri/src/camera.rs
@@ -227,7 +227,7 @@ impl CameraPreviewManager {
})
.ok();
- let rt = Runtime::new().expect("Failed to get Tokio runtime!");
+ let rt = Runtime::new().context("Failed to create camera preview runtime")?;
let (shutdown_complete_tx, shutdown_complete_rx) = oneshot::channel();
self.preview = Some(InitializedCameraPreview {
@@ -252,7 +252,7 @@ impl CameraPreviewManager {
})
.ok();
- let _ = rt.block_on(drop_rx);
+ let _ = rt.block_on(tokio::time::timeout(Duration::from_millis(250), drop_rx));
shutdown_complete_tx.send(()).ok();
info!("DONE");
@@ -819,7 +819,7 @@ impl Renderer {
async fn cleanup_for_shutdown(&mut self, window: &WebviewWindow) {
info!("Camera preview shutdown requested. Cleaning up...");
- let _ = self.device.poll(wgpu::PollType::Wait);
+ let _ = self.device.poll(wgpu::PollType::Poll);
drop(std::mem::take(&mut self.texture));
self.aspect_ratio = Cached::default();
@@ -832,11 +832,11 @@ impl Renderer {
let _ = drop_tx.send(());
})
.ok();
- let _ = drop_rx.await;
+ let _ = tokio::time::timeout(Duration::from_millis(250), drop_rx).await;
self.device.destroy();
- tokio::time::sleep(Duration::from_millis(200)).await;
+ tokio::time::sleep(Duration::from_millis(50)).await;
}
fn reconfigure_gpu_surface(&mut self, window_width: u32, window_height: u32) {
diff --git a/apps/desktop/src-tauri/src/camera_legacy.rs b/apps/desktop/src-tauri/src/camera_legacy.rs
index 096635a56..3d016dad9 100644
--- a/apps/desktop/src-tauri/src/camera_legacy.rs
+++ b/apps/desktop/src-tauri/src/camera_legacy.rs
@@ -28,22 +28,19 @@ pub async fn create_camera_preview_ws() -> (Sender<FFmpegVideoFrame>, u16, Cance
converter
}
_ => {
- &mut converter
- .insert((
- frame.format(),
- ffmpeg::software::scaling::Context::get(
- frame.format(),
- frame.width(),
- frame.height(),
- Pixel::RGBA,
- 1280,
- (1280.0 / (frame.width() as f64 / frame.height() as f64))
- as u32,
- ffmpeg::software::scaling::flag::Flags::FAST_BILINEAR,
- )
- .unwrap(),
- ))
- .1
+ let Ok(new_converter) = ffmpeg::software::scaling::Context::get(
+ frame.format(),
+ frame.width(),
+ frame.height(),
+ Pixel::RGBA,
+ 1280,
+ (1280.0 / (frame.width() as f64 / frame.height() as f64)) as u32,
+ ffmpeg::software::scaling::flag::Flags::FAST_BILINEAR,
+ ) else {
+ continue;
+ };
+
+ &mut converter.insert((frame.format(), new_converter)).1
}
};
@@ -53,7 +50,9 @@ pub async fn create_camera_preview_ws() -> (Sender<FFmpegVideoFrame>, u16, Cance
converter.output().height,
);
- converter.run(&frame, &mut new_frame).unwrap();
+ if converter.run(&frame, &mut new_frame).is_err() {
+ continue;
+ }
frame = new_frame;
}
diff --git a/apps/desktop/src-tauri/src/deeplink_actions.rs b/apps/desktop/src-tauri/src/deeplink_actions.rs
index fce75b4a8..a11702848 100644
--- a/apps/desktop/src-tauri/src/deeplink_actions.rs
+++ b/apps/desktop/src-tauri/src/deeplink_actions.rs
@@ -82,9 +82,10 @@ impl TryFrom<&Url> for DeepLinkAction {
fn try_from(url: &Url) -> Result<Self, Self::Error> {
#[cfg(target_os = "macos")]
if url.scheme() == "file" {
- return Ok(Self::OpenEditor {
- project_path: url.to_file_path().unwrap(),
- });
+ return url
+ .to_file_path()
+ .map(|project_path| Self::OpenEditor { project_path })
+ .map_err(|_| ActionParseFromUrlError::Invalid);
}
match url.domain() {
diff --git a/apps/desktop/src-tauri/src/editor_window.rs b/apps/desktop/src-tauri/src/editor_window.rs
index f47d3f43a..e85b90077 100644
--- a/apps/desktop/src-tauri/src/editor_window.rs
+++ b/apps/desktop/src-tauri/src/editor_window.rs
@@ -159,10 +159,16 @@ impl<'de, R: Runtime> CommandArg<'de, R> for WindowEditorInstance {
) -> Result<Self, tauri::ipc::InvokeError> {
let window = Window::from_command(command)?;
- let instances = window.state::<EditorInstances>();
+ let Some(instances) = window.try_state::<EditorInstances>() else {
+ return Err("editor instance registry unavailable".into());
+ };
let instance = futures::executor::block_on(instances.0.read());
- Ok(Self(instance.get(window.label()).cloned().unwrap()))
+ let Some(instance) = instance.get(window.label()).cloned() else {
+ return Err("editor instance unavailable".into());
+ };
+
+ Ok(Self(instance))
}
}
diff --git a/apps/desktop/src-tauri/src/frame_ws.rs b/apps/desktop/src-tauri/src/frame_ws.rs
index f60cd8caa..fd97e96f1 100644
--- a/apps/desktop/src-tauri/src/frame_ws.rs
+++ b/apps/desktop/src-tauri/src/frame_ws.rs
@@ -1,5 +1,6 @@
use std::sync::atomic::{AtomicU32, AtomicU64, Ordering};
use std::time::Instant;
+use std::time::{SystemTime, UNIX_EPOCH};
use tokio::sync::{broadcast, watch};
use tokio_util::sync::CancellationToken;
@@ -179,7 +180,10 @@ pub async fn create_watch_frame_ws(
Ok(()) => {
TOTAL_BYTES_SENT.fetch_add(packed_len as u64, Ordering::Relaxed);
TOTAL_FRAMES_SENT.fetch_add(1, Ordering::Relaxed);
- let now_ms = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_millis() as u64;
+ let now_ms = SystemTime::now()
+ .duration_since(UNIX_EPOCH)
+ .map(|duration| duration.as_millis() as u64)
+ .unwrap_or_default();
let last_log = LAST_LOG_TIME.load(Ordering::Relaxed);
if now_ms - last_log > 2000 {
LAST_LOG_TIME.store(now_ms, Ordering::Relaxed);
@@ -214,12 +218,24 @@ pub async fn create_watch_frame_ws(
.route("/", get(ws_handler))
.with_state(frame_rx);
- let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
- let port = listener.local_addr().unwrap().port();
- tracing::info!("WebSocket server listening on port {}", port);
-
let cancel_token = CancellationToken::new();
let cancel_token_child = cancel_token.child_token();
+ let listener = match tokio::net::TcpListener::bind("127.0.0.1:0").await {
+ Ok(listener) => listener,
+ Err(err) => {
+ tracing::error!("Failed to bind watch frame websocket listener: {err}");
+ return (0, cancel_token_child);
+ }
+ };
+ let port = match listener.local_addr() {
+ Ok(addr) => addr.port(),
+ Err(err) => {
+ tracing::error!("Failed to read watch frame websocket listener address: {err}");
+ return (0, cancel_token_child);
+ }
+ };
+ tracing::info!("WebSocket server listening on port {}", port);
+
tokio::spawn(async move {
let server = axum::serve(listener, router.into_make_service());
tokio::select! {
@@ -314,12 +330,24 @@ pub async fn create_frame_ws(frame_tx: broadcast::Sender<WSFrame>) -> (u16, Canc
.route("/", get(ws_handler))
.with_state(frame_tx);
- let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
- let port = listener.local_addr().unwrap().port();
- tracing::info!("WebSocket server listening on port {}", port);
-
let cancel_token = CancellationToken::new();
let cancel_token_child = cancel_token.child_token();
+ let listener = match tokio::net::TcpListener::bind("127.0.0.1:0").await {
+ Ok(listener) => listener,
+ Err(err) => {
+ tracing::error!("Failed to bind frame websocket listener: {err}");
+ return (0, cancel_token_child);
+ }
+ };
+ let port = match listener.local_addr() {
+ Ok(addr) => addr.port(),
+ Err(err) => {
+ tracing::error!("Failed to read frame websocket listener address: {err}");
+ return (0, cancel_token_child);
+ }
+ };
+ tracing::info!("WebSocket server listening on port {}", port);
+
tokio::spawn(async move {
let server = axum::serve(listener, router.into_make_service());
tokio::select! {
diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs
index 7497f352d..303f7425a 100644
--- a/apps/desktop/src-tauri/src/lib.rs
+++ b/apps/desktop/src-tauri/src/lib.rs
@@ -156,6 +156,44 @@ impl AppExitState {
}
}
+const APP_EXIT_STEP_TIMEOUT: Duration = Duration::from_millis(750);
+const APP_EXIT_CAMERA_SHUTDOWN_TIMEOUT: Duration = Duration::from_millis(1200);
+const APP_EXIT_TOTAL_TIMEOUT: Duration = Duration::from_secs(3);
+const APP_EXIT_FORCE_TIMEOUT: Duration = Duration::from_secs(8);
+
+async fn await_exit_step<T, E, F>(name: &'static str, timeout: Duration, fut: F) -> Option<T>
+where
+ E: std::fmt::Display,
+ F: Future<Output = Result<T, E>>,
+{
+ match tokio::time::timeout(timeout, fut).await {
+ Ok(Ok(value)) => Some(value),
+ Ok(Err(err)) => {
+ warn!(step = name, error = %err, "Exit cleanup step failed");
+ None
+ }
+ Err(_) => {
+ warn!(
+ step = name,
+ timeout_ms = timeout.as_millis(),
+ "Exit cleanup step timed out"
+ );
+ None
+ }
+ }
+}
+
+fn spawn_exit_watchdog() {
+ std::thread::spawn(move || {
+ std::thread::sleep(APP_EXIT_FORCE_TIMEOUT);
+ error!(
+ timeout_ms = APP_EXIT_FORCE_TIMEOUT.as_millis(),
+ "Forcing process exit after shutdown deadline"
+ );
+ std::process::exit(0);
+ });
+}
+
fn now_millis() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
@@ -1016,8 +1054,16 @@ async fn cleanup_app_resources_for_exit(app: &AppHandle) {
)
};
- let _ = mic_feed.ask(microphone::RemoveInput).await;
- let _ = camera_feed.ask(feeds::camera::RemoveInput).await;
+ let _ = await_exit_step(
+ "remove_microphone_input",
+ APP_EXIT_STEP_TIMEOUT,
+ async move { mic_feed.ask(microphone::RemoveInput).await },
+ )
+ .await;
+ let _ = await_exit_step("remove_camera_input", APP_EXIT_STEP_TIMEOUT, async move {
+ camera_feed.ask(feeds::camera::RemoveInput).await
+ })
+ .await;
#[cfg(target_os = "macos")]
{
@@ -1028,7 +1074,12 @@ async fn cleanup_app_resources_for_exit(app: &AppHandle) {
}
if let Some(rx) = camera_shutdown {
- let _ = tokio::time::timeout(Duration::from_secs(2), rx).await;
+ let _ = await_exit_step(
+ "camera_preview_shutdown",
+ APP_EXIT_CAMERA_SHUTDOWN_TIMEOUT,
+ rx,
+ )
+ .await;
}
}
@@ -1037,7 +1088,18 @@ pub async fn request_app_exit(app: AppHandle) {
return;
}
- cleanup_app_resources_for_exit(&app).await;
+ spawn_exit_watchdog();
+
+ if tokio::time::timeout(APP_EXIT_TOTAL_TIMEOUT, cleanup_app_resources_for_exit(&app))
+ .await
+ .is_err()
+ {
+ error!(
+ timeout_ms = APP_EXIT_TOTAL_TIMEOUT.as_millis(),
+ "Timed out while cleaning up app resources for exit"
+ );
+ }
+
app.exit(0);
}
@@ -3394,7 +3456,9 @@ pub async fn run(recording_logging_handle: LoggingHandle, logs_dir: PathBuf) {
audio_meter::spawn_event_emitter(app.clone(), mic_samples_rx);
- tray::create_tray(&app).unwrap();
+ if let Err(err) = tray::create_tray(&app) {
+ error!("Failed to create tray: {err}");
+ }
RequestStartRecording::listen_any_spawn(&app, async |event, app| {
let settings = RecordingSettingsStore::get(&app)
@@ -3492,13 +3556,7 @@ pub async fn run(recording_logging_handle: LoggingHandle, logs_dir: PathBuf) {
let _ = camera_window.hide();
}
- for (id, overlay_window) in app.webview_windows() {
- if let Ok(CapWindowId::TargetSelectOverlay { .. }) =
- CapWindowId::from_str(&id)
- {
- let _ = overlay_window.hide();
- }
- }
+ close_target_select_overlays(app);
let app = app.clone();
tokio::spawn(async move {
@@ -3532,13 +3590,7 @@ pub async fn run(recording_logging_handle: LoggingHandle, logs_dir: PathBuf) {
CapWindowId::Main => {
let app = app.clone();
- for (id, window) in app.webview_windows() {
- if let Ok(CapWindowId::TargetSelectOverlay { .. }) =
- CapWindowId::from_str(&id)
- {
- let _ = window.hide();
- }
- }
+ close_target_select_overlays(&app);
if let Some(camera) = CapWindowId::Camera.get(&app) {
let _ = camera.hide();
@@ -3777,16 +3829,18 @@ pub async fn run(recording_logging_handle: LoggingHandle, logs_dir: PathBuf) {
});
}
tauri::RunEvent::Exit => {
+ if !_handle.state::<AppExitState>().begin() {
+ return;
+ }
+
let handle = _handle.clone();
- let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
- let _ = tauri::async_runtime::block_on(async {
- tokio::time::timeout(
- Duration::from_secs(2),
- cleanup_app_resources_for_exit(&handle),
- )
- .await
- });
- }));
+ tokio::spawn(async move {
+ let _ = tokio::time::timeout(
+ Duration::from_secs(2),
+ cleanup_app_resources_for_exit(&handle),
+ )
+ .await;
+ });
}
_ => {}
});
@@ -3817,6 +3871,17 @@ fn restore_main_windows_if_no_editors(app: &AppHandle) {
}
}
+fn close_target_select_overlays(app: &AppHandle) {
+ let focus_manager = app.state::<target_select_overlay::WindowFocusManager>();
+
+ for (label, window) in app.webview_windows() {
+ if let Ok(CapWindowId::TargetSelectOverlay { display_id }) = CapWindowId::from_str(&label) {
+ let _ = window.hide();
+ focus_manager.destroy(&display_id, app.global_shortcut());
+ }
+ }
+}
+
#[cfg(target_os = "windows")]
fn reopen_main_window(app: &AppHandle) {
if let Some(main) = CapWindowId::Main.get(app) {
diff --git a/apps/desktop/src-tauri/src/permissions.rs b/apps/desktop/src-tauri/src/permissions.rs
index b926a6081..e4cb26a5b 100644
--- a/apps/desktop/src-tauri/src/permissions.rs
+++ b/apps/desktop/src-tauri/src/permissions.rs
@@ -28,35 +28,37 @@ pub fn open_permission_settings(_permission: OSPermission) {
{
use std::process::Command;
- let mut process = match _permission {
+ let process = match _permission {
OSPermission::ScreenRecording => Command::new("open")
.arg(
"x-apple.systempreferences:com.apple.preference.security?Privacy_ScreenCapture",
)
- .spawn()
- .expect("Failed to open Screen Recording settings"),
+ .spawn(),
OSPermission::Camera => Command::new("open")
.arg("x-apple.systempreferences:com.apple.preference.security?Privacy_Camera")
- .spawn()
- .expect("Failed to open Camera settings"),
+ .spawn(),
OSPermission::Microphone => Command::new("open")
.arg("x-apple.systempreferences:com.apple.preference.security?Privacy_Microphone")
- .spawn()
- .expect("Failed to open Microphone settings"),
+ .spawn(),
OSPermission::Accessibility => Command::new("open")
.arg(
"x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility",
)
- .spawn()
- .expect("Failed to open Accessibility settings"),
+ .spawn(),
};
- // https://doc.rust-lang.org/stable/std/process/struct.Child.html#warning
- tokio::spawn(async move {
- let _ = process.wait().map_err(|err| {
- tracing::error!("Error waiting for accessibility child process: {err}")
- });
- });
+ match process {
+ Ok(mut process) => {
+ tokio::spawn(async move {
+ let _ = process.wait().map_err(|err| {
+ tracing::error!("Error waiting for permission settings process: {err}")
+ });
+ });
+ }
+ Err(err) => {
+ tracing::error!("Failed to open permission settings: {err}");
+ }
+ }
}
}
@@ -153,12 +155,14 @@ pub fn do_permissions_check(_initial_check: bool) -> OSPermissionsCheck {
use cidre::av::{AuthorizationStatus, CaptureDevice, MediaType};
fn check_av_permission(media_type: &'static MediaType) -> OSPermissionStatus {
- let status = CaptureDevice::authorization_status_for_media_type(media_type).unwrap();
-
- match status {
- AuthorizationStatus::NotDetermined => OSPermissionStatus::Empty,
- AuthorizationStatus::Authorized => OSPermissionStatus::Granted,
- _ => OSPermissionStatus::Denied,
+ match CaptureDevice::authorization_status_for_media_type(media_type) {
+ Ok(AuthorizationStatus::NotDetermined) => OSPermissionStatus::Empty,
+ Ok(AuthorizationStatus::Authorized) => OSPermissionStatus::Granted,
+ Ok(_) => OSPermissionStatus::Denied,
+ Err(err) => {
+ tracing::error!("Failed to query AV permission status: {err}");
+ OSPermissionStatus::Denied
+ }
}
}
diff --git a/apps/desktop/src-tauri/src/platform/macos/sc_shareable_content.rs b/apps/desktop/src-tauri/src/platform/macos/sc_shareable_content.rs
index 03ff5b95b..8bc5eebe7 100644
--- a/apps/desktop/src-tauri/src/platform/macos/sc_shareable_content.rs
+++ b/apps/desktop/src-tauri/src/platform/macos/sc_shareable_content.rs
@@ -1,7 +1,7 @@
use cidre::{arc, ns, sc};
use std::sync::{Arc, OnceLock, RwLock};
use tokio::sync::{Mutex, Notify};
-use tracing::trace;
+use tracing::{error, trace};
#[derive(Default)]
struct CacheState {
@@ -56,12 +56,10 @@ async fn prewarm_shareable_content_inner(force_refresh: bool) -> Result<(), arc:
};
warmup.notify.notified().await;
- warmup
- .result
- .lock()
- .await
- .clone()
- .expect("ScreenCaptureKit warmup task missing result")
+ warmup.result.lock().await.clone().unwrap_or_else(|| {
+ error!("ScreenCaptureKit warmup task finished without a result");
+ Ok(())
+ })
}
pub async fn get_shareable_content()
diff --git a/apps/desktop/src-tauri/src/screenshot_editor.rs b/apps/desktop/src-tauri/src/screenshot_editor.rs
index dfaa09d7f..1e539dd44 100644
--- a/apps/desktop/src-tauri/src/screenshot_editor.rs
+++ b/apps/desktop/src-tauri/src/screenshot_editor.rs
@@ -101,6 +101,9 @@ impl ScreenshotEditorInstances {
Entry::Vacant(entry) => {
let (frame_tx, frame_rx) = watch::channel(None);
let (ws_port, ws_shutdown_token) = create_watch_frame_ws(frame_rx).await;
+ if ws_port == 0 {
+ return Err("Failed to start screenshot editor frame websocket".to_string());
+ }
let (data, width, height) = {
let key = path
diff --git a/apps/desktop/src-tauri/src/target_select_overlay.rs b/apps/desktop/src-tauri/src/target_select_overlay.rs
index e4d8a3832..f01151016 100644
--- a/apps/desktop/src-tauri/src/target_select_overlay.rs
+++ b/apps/desktop/src-tauri/src/target_select_overlay.rs
@@ -410,6 +410,7 @@ pub struct WindowFocusManager {
impl WindowFocusManager {
pub fn spawn(&self, id: &DisplayId, window: WebviewWindow) {
+ let display_id = id.clone();
let mut tasks = self.tasks.lock().unwrap_or_else(PoisonError::into_inner);
tasks.insert(
id.to_string(),
@@ -431,11 +432,15 @@ impl WindowFocusManager {
if main_window_was_seen && !main_window_available && !settings_window_available
{
window.hide().ok();
+ app.state::<WindowFocusManager>()
+ .finish(&display_id, app.global_shortcut());
break;
}
#[cfg(windows)]
- if let Some(cap_main) = cap_main {
+ if window.is_visible().unwrap_or(false)
+ && let Some(cap_main) = cap_main
+ {
let should_refocus = cap_main.is_focused().ok().unwrap_or_default()
|| window.is_focused().unwrap_or_default();
@@ -450,17 +455,11 @@ impl WindowFocusManager {
);
}
- /// Called when a specific overlay window is destroyed to cleanup it's resources
- pub fn destroy<R: tauri::Runtime>(&self, id: &DisplayId, global_shortcut: &GlobalShortcut<R>) {
+ fn finish<R: tauri::Runtime>(&self, id: &DisplayId, global_shortcut: &GlobalShortcut<R>) {
let mut tasks = self.tasks.lock().unwrap_or_else(PoisonError::into_inner);
- if let Some(task) = tasks.remove(&id.to_string()) {
- task.abort();
- }
+ tasks.remove(&id.to_string());
- // When all overlay windows are closed cleanup shared resources.
if tasks.is_empty() {
- // Unregister keyboard shortcut
- // This messes with other applications if we don't remove it.
global_shortcut
.unregister("Escape")
.map_err(|err| {
@@ -468,7 +467,6 @@ impl WindowFocusManager {
})
.ok();
- // Shutdown the cursor tracking task
if let Some(task) = self
.task
.lock()
@@ -479,4 +477,15 @@ impl WindowFocusManager {
}
}
}
+
+ /// Called when a specific overlay window is destroyed to cleanup it's resources
+ pub fn destroy<R: tauri::Runtime>(&self, id: &DisplayId, global_shortcut: &GlobalShortcut<R>) {
+ let mut tasks = self.tasks.lock().unwrap_or_else(PoisonError::into_inner);
+ if let Some(task) = tasks.remove(&id.to_string()) {
+ task.abort();
+ }
+ drop(tasks);
+
+ self.finish(id, global_shortcut);
+ }
}
diff --git a/apps/web/actions/video/retry-processing.ts b/apps/web/actions/video/retry-processing.ts
index 18df09624..5f82a46d6 100644
--- a/apps/web/actions/video/retry-processing.ts
+++ b/apps/web/actions/video/retry-processing.ts
@@ -5,8 +5,7 @@ import { getCurrentUser } from "@cap/database/auth/session";
import { videos, videoUploads } from "@cap/database/schema";
import type { Video } from "@cap/web-domain";
import { eq } from "drizzle-orm";
-import { start } from "workflow/api";
-import { processVideoWorkflow } from "@/workflows/process-video";
+import { startVideoProcessingWorkflow } from "@/lib/video-processing";
export async function retryVideoProcessing({
videoId,
@@ -32,25 +31,14 @@ export async function retryVideoProcessing({
if (!upload) throw new Error("No upload record found");
if (!upload.rawFileKey) throw new Error("No raw file key found for retry");
- await db()
- .update(videoUploads)
- .set({
- phase: "processing",
- processingProgress: 0,
- processingMessage: "Retrying video processing...",
- processingError: null,
- updatedAt: new Date(),
- })
- .where(eq(videoUploads.videoId, videoId));
-
- await start(processVideoWorkflow, [
- {
- videoId,
- userId: user.id,
- rawFileKey: upload.rawFileKey,
- bucketId: video.bucket ?? null,
- },
- ]);
+ await startVideoProcessingWorkflow({
+ videoId,
+ userId: user.id,
+ rawFileKey: upload.rawFileKey,
+ bucketId: video.bucket ?? null,
+ processingMessage: "Retrying video processing...",
+ startFailureMessage: "Video processing could not restart.",
+ });
return { success: true };
}
diff --git a/apps/web/actions/video/trigger-processing.ts b/apps/web/actions/video/trigger-processing.ts
index 5f7d6f267..476e4cf4d 100644
--- a/apps/web/actions/video/trigger-processing.ts
+++ b/apps/web/actions/video/trigger-processing.ts
@@ -5,8 +5,7 @@ import { getCurrentUser } from "@cap/database/auth/session";
import { videos, videoUploads } from "@cap/database/schema";
import type { Video } from "@cap/web-domain";
import { eq } from "drizzle-orm";
-import { start } from "workflow/api";
-import { processVideoWorkflow } from "@/workflows/process-video";
+import { startVideoProcessingWorkflow } from "@/lib/video-processing";
export async function triggerVideoProcessing({
videoId,
@@ -28,25 +27,14 @@ export async function triggerVideoProcessing({
if (!video) throw new Error("Video not found");
if (video.ownerId !== user.id) throw new Error("Unauthorized");
- await db()
- .update(videoUploads)
- .set({
- phase: "processing",
- processingProgress: 0,
- processingMessage: "Starting video processing...",
- rawFileKey,
- updatedAt: new Date(),
- })
- .where(eq(videoUploads.videoId, videoId));
-
- await start(processVideoWorkflow, [
- {
- videoId,
- userId: user.id,
- rawFileKey,
- bucketId,
- },
- ]);
+ await startVideoProcessingWorkflow({
+ videoId,
+ userId: user.id,
+ rawFileKey,
+ bucketId,
+ processingMessage: "Starting video processing...",
+ startFailureMessage: "Video processing could not start.",
+ });
return { success: true };
}
diff --git a/apps/web/lib/video-processing.ts b/apps/web/lib/video-processing.ts
new file mode 100644
index 000000000..68276c75b
--- /dev/null
+++ b/apps/web/lib/video-processing.ts
@@ -0,0 +1,121 @@
+import { db } from "@cap/database";
+import { videoUploads } from "@cap/database/schema";
+import type { S3Bucket, Video } from "@cap/web-domain";
+import { and, eq, ne } from "drizzle-orm";
+import { start } from "workflow/api";
+import { processVideoWorkflow } from "@/workflows/process-video";
+
+export type VideoProcessingStartStatus = "started" | "already-processing";
+
+const getAffectedRows = (result: unknown) =>
+ (result as { affectedRows?: number } | undefined)?.affectedRows ?? 0;
+
+export async function setVideoProcessingError(
+ videoId: Video.VideoId,
+ processingMessage: string,
+ error: unknown,
+): Promise<void> {
+ await db()
+ .update(videoUploads)
+ .set({
+ phase: "error",
+ processingProgress: 0,
+ processingMessage,
+ processingError: error instanceof Error ? error.message : String(error),
+ updatedAt: new Date(),
+ })
+ .where(eq(videoUploads.videoId, videoId));
+}
+
+export async function transitionVideoToProcessing({
+ videoId,
+ rawFileKey,
+ processingMessage,
+ mode,
+}: {
+ videoId: Video.VideoId;
+ rawFileKey: string;
+ processingMessage: string;
+ mode?: "singlepart" | "multipart";
+}): Promise<VideoProcessingStartStatus> {
+ const result = await db()
+ .update(videoUploads)
+ .set({
+ ...(mode ? { mode } : {}),
+ phase: "processing",
+ processingProgress: 0,
+ processingMessage,
+ processingError: null,
+ rawFileKey,
+ updatedAt: new Date(),
+ })
+ .where(
+ and(
+ eq(videoUploads.videoId, videoId),
+ ne(videoUploads.phase, "processing"),
+ ),
+ );
+
+ if (getAffectedRows(result) > 0) {
+ return "started";
+ }
+
+ const [upload] = await db()
+ .select()
+ .from(videoUploads)
+ .where(eq(videoUploads.videoId, videoId));
+
+ if (!upload) {
+ throw new Error("No upload record found");
+ }
+
+ if (upload.phase === "processing") {
+ return "already-processing";
+ }
+
+ throw new Error("Failed to transition upload to processing");
+}
+
+export async function startVideoProcessingWorkflow({
+ videoId,
+ userId,
+ rawFileKey,
+ bucketId,
+ processingMessage,
+ startFailureMessage,
+ mode,
+}: {
+ videoId: Video.VideoId;
+ userId: string;
+ rawFileKey: string;
+ bucketId: string | null;
+ processingMessage: string;
+ startFailureMessage: string;
+ mode?: "singlepart" | "multipart";
+}): Promise<VideoProcessingStartStatus> {
+ const status = await transitionVideoToProcessing({
+ videoId,
+ rawFileKey,
+ processingMessage,
+ mode,
+ });
+
+ if (status === "already-processing") {
+ return status;
+ }
+
+ try {
+ await start(processVideoWorkflow, [
+ {
+ videoId,
+ userId,
+ rawFileKey,
+ bucketId: bucketId as S3Bucket.S3BucketId | null,
+ },
+ ]);
+ return "started";
+ } catch (error) {
+ await setVideoProcessingError(videoId, startFailureMessage, error);
+ throw error;
+ }
+}
diff --git a/crates/camera/src/macos.rs b/crates/camera/src/macos.rs
index d934a8b64..4245b38cb 100644
--- a/crates/camera/src/macos.rs
+++ b/crates/camera/src/macos.rs
@@ -115,17 +115,26 @@ 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;
session.configure(|s| {
if s.can_add_input(&input) {
s.add_input(&input);
+ added_input = true;
} else {
- panic!("can't add input");
+ return;
}
s.add_output(&output);
});
+ if !added_input {
+ return Err(AVFoundationError::Message(
+ "Failed to add camera input to AVFoundation session".to_string(),
+ )
+ .into());
+ }
+
output.set_sample_buf_delegate(Some(delegate.as_ref()), Some(&queue));
// The device config must stay locked while running starts,
@@ -169,6 +178,8 @@ pub enum AVFoundationError {
Static(&'static cidre::ns::Error),
#[error("{0}")]
Retained(cidre::arc::R<cidre::ns::Error>),
+ #[error("{0}")]
+ Message(String),
}
impl From<&'static cidre::ns::Error> for AVFoundationError {
@@ -190,6 +201,7 @@ impl Deref for AVFoundationError {
match self {
AVFoundationError::Static(err) => err,
AVFoundationError::Retained(err) => err,
+ AVFoundationError::Message(_) => unreachable!(),
}
}
}
@@ -199,6 +211,7 @@ impl Debug for AVFoundationError {
match self {
AVFoundationError::Static(err) => write!(f, "{err}"),
AVFoundationError::Retained(err) => write!(f, "{err}"),
+ AVFoundationError::Message(err) => write!(f, "{err}"),
}
}
}