diff --git a/apps/desktop-gpui/locales/de.toml b/apps/desktop-gpui/locales/de.toml index ff53e3d096b..a94e285aa98 100644 --- a/apps/desktop-gpui/locales/de.toml +++ b/apps/desktop-gpui/locales/de.toml @@ -1209,6 +1209,10 @@ resuming = "Weiter…" saving = "Sichert…" starting = "Startet" +[controls.disconnected] +camera = "Kamera getrennt. Die Aufnahme läuft ohne Kamera-Overlay weiter." +microphone = "Mikrofon getrennt. Bis zur Wiederverbindung wird Stille aufgenommen." + [controls.marker] add = "Marker hinzufügen" @@ -1234,6 +1238,8 @@ mirror_title = "Spiegeln nicht verfügbar" [camera.issue] access_message = "Klicken Sie hier, um Cap in den Systemeinstellungen den Zugriff auf Ihre Kamera zu erlauben." access_title = "Kamerazugriff erforderlich" +disconnected_message = "Die ausgewählte Kamera sendet kein Video mehr." +disconnected_title = "Kamera getrennt" generic = "Die ausgewählte Kamera konnte nicht gestartet werden. Wählen Sie eine andere Kamera oder verbinden Sie diese erneut." invalid_format = "Diese Kamera hat kein nutzbares Aufnahmeformat gemeldet." not_found = "Diese Kamera ist nicht mehr verfügbar. Prüfen Sie, ob sie verbunden ist und in den Systemberechtigungen erlaubt ist." diff --git a/apps/desktop-gpui/locales/en.toml b/apps/desktop-gpui/locales/en.toml index 1f3b13c3be3..616f1efbd36 100644 --- a/apps/desktop-gpui/locales/en.toml +++ b/apps/desktop-gpui/locales/en.toml @@ -1211,6 +1211,10 @@ resuming = { text = "Resuming…", max_px = 73, size = 14 } saving = { text = "Saving…", max_px = 73, size = 14 } starting = { text = "Starting", max_px = 73, size = 14 } +[controls.disconnected] +camera = "Camera disconnected. Recording continues without camera overlay." +microphone = "Microphone disconnected. Silence will be used until it reconnects." + [controls.marker] add = "Add marker" @@ -1236,6 +1240,8 @@ mirror_title = "Mirror unavailable" [camera.issue] access_message = "Click to allow Cap to use your camera in System Settings." access_title = "Camera access needed" +disconnected_message = "The selected camera stopped sending video." +disconnected_title = "Camera disconnected" generic = "The selected camera could not be started. Choose another camera or reconnect this one." invalid_format = "This camera did not report a usable capture format." not_found = "This camera is no longer available. Check that it is connected and allowed by system permissions." diff --git a/apps/desktop-gpui/locales/es.toml b/apps/desktop-gpui/locales/es.toml index 73cc40ff110..98889a0c68c 100644 --- a/apps/desktop-gpui/locales/es.toml +++ b/apps/desktop-gpui/locales/es.toml @@ -1209,6 +1209,10 @@ resuming = "Continúa…" saving = "Guardar…" starting = "Iniciando" +[controls.disconnected] +camera = "Cámara desconectada. La grabación continúa sin la cámara superpuesta." +microphone = "Micrófono desconectado. Se grabará silencio hasta que se vuelva a conectar." + [controls.marker] add = "Añadir marcador" @@ -1234,6 +1238,8 @@ mirror_title = "Espejo no disponible" [camera.issue] access_message = "Haz clic para permitir que Cap use tu cámara en Ajustes del Sistema." access_title = "Se necesita acceso a la cámara" +disconnected_message = "La cámara seleccionada dejó de enviar video." +disconnected_title = "Cámara desconectada" generic = "No se pudo iniciar la cámara seleccionada. Elige otra cámara o vuelve a conectar esta." invalid_format = "Esta cámara no indicó ningún formato de captura utilizable." not_found = "Esta cámara ya no está disponible. Comprueba que esté conectada y permitida en los permisos del sistema." diff --git a/apps/desktop-gpui/locales/fr.toml b/apps/desktop-gpui/locales/fr.toml index 7092435597a..250c6097be2 100644 --- a/apps/desktop-gpui/locales/fr.toml +++ b/apps/desktop-gpui/locales/fr.toml @@ -1209,6 +1209,10 @@ resuming = "Reprise…" saving = "Arrêt…" starting = "Début" +[controls.disconnected] +camera = "Caméra déconnectée. L'enregistrement continue sans l'incrustation de la caméra." +microphone = "Micro déconnecté. Du silence sera enregistré jusqu'à sa reconnexion." + [controls.marker] add = "Ajouter un repère" @@ -1234,6 +1238,8 @@ mirror_title = "Miroir indisponible" [camera.issue] access_message = "Cliquez pour autoriser Cap à utiliser votre caméra dans Réglages Système." access_title = "Accès à la caméra requis" +disconnected_message = "La caméra sélectionnée n'envoie plus de vidéo." +disconnected_title = "Caméra déconnectée" generic = "La caméra sélectionnée n'a pas pu démarrer. Choisissez une autre caméra ou reconnectez celle-ci." invalid_format = "Cette caméra n'a signalé aucun format de capture utilisable." not_found = "Cette caméra n'est plus disponible. Vérifiez qu'elle est connectée et autorisée dans les autorisations du système." diff --git a/apps/desktop-gpui/locales/hi.toml b/apps/desktop-gpui/locales/hi.toml index 972a64d3361..f3269aa8038 100644 --- a/apps/desktop-gpui/locales/hi.toml +++ b/apps/desktop-gpui/locales/hi.toml @@ -1209,6 +1209,10 @@ resuming = "फिर शुरू…" saving = "सहेज रहा…" starting = "शुरू हो रहा" +[controls.disconnected] +camera = "कैमरा डिस्कनेक्ट हो गया। रिकॉर्डिंग कैमरा ओवरले के बिना जारी है।" +microphone = "माइक्रोफ़ोन डिस्कनेक्ट हो गया। दोबारा कनेक्ट होने तक साइलेंस रिकॉर्ड होगा।" + [controls.marker] add = "मार्कर जोड़ें" @@ -1234,6 +1238,8 @@ mirror_title = "मिरर उपलब्ध नहीं" [camera.issue] access_message = "सिस्टम सेटिंग्स में Cap को अपना कैमरा इस्तेमाल करने देने के लिए क्लिक करें।" access_title = "कैमरा एक्सेस ज़रूरी है" +disconnected_message = "चुने गए कैमरे से वीडियो आना बंद हो गया।" +disconnected_title = "कैमरा डिस्कनेक्ट हो गया" generic = "चुना गया कैमरा शुरू नहीं हो सका। कोई दूसरा कैमरा चुनें या इसे फिर से कनेक्ट करें।" invalid_format = "इस कैमरे ने कोई इस्तेमाल लायक कैप्चर फ़ॉर्मैट नहीं बताया।" not_found = "यह कैमरा अब उपलब्ध नहीं है। जाँचें कि यह कनेक्ट है और सिस्टम की अनुमतियों में इसकी अनुमति है।" diff --git a/apps/desktop-gpui/locales/ja.toml b/apps/desktop-gpui/locales/ja.toml index 1713bf64f0a..53e031a8c05 100644 --- a/apps/desktop-gpui/locales/ja.toml +++ b/apps/desktop-gpui/locales/ja.toml @@ -1209,6 +1209,10 @@ resuming = "再開中…" saving = "保存中…" starting = "開始中" +[controls.disconnected] +camera = "カメラが切断されました。カメラのオーバーレイなしで録画を続けます。" +microphone = "マイクが切断されました。再接続されるまで無音で録音します。" + [controls.marker] add = "マーカーを追加" @@ -1234,6 +1238,8 @@ mirror_title = "反転を使用できません" [camera.issue] access_message = "クリックして、システム設定でCapにカメラの使用を許可してください。" access_title = "カメラへのアクセスが必要です" +disconnected_message = "選択したカメラから映像が届かなくなりました。" +disconnected_title = "カメラが切断されました" generic = "選択したカメラを起動できませんでした。別のカメラを選ぶか、このカメラを接続し直してください。" invalid_format = "このカメラから使用可能なキャプチャフォーマットを取得できませんでした。" not_found = "このカメラは使用できなくなりました。接続されていて、システムの権限で許可されているか確認してください。" diff --git a/apps/desktop-gpui/locales/zh-CN.toml b/apps/desktop-gpui/locales/zh-CN.toml index 6b3098252b2..6a91eb5ecbe 100644 --- a/apps/desktop-gpui/locales/zh-CN.toml +++ b/apps/desktop-gpui/locales/zh-CN.toml @@ -1209,6 +1209,10 @@ resuming = "恢复中…" saving = "保存中…" starting = "正在开始" +[controls.disconnected] +camera = "摄像头已断开。录制将在没有摄像头画面的情况下继续。" +microphone = "麦克风已断开。重新连接前将录制静音。" + [controls.marker] add = "添加标记" @@ -1234,6 +1238,8 @@ mirror_title = "镜像不可用" [camera.issue] access_message = "点击以在系统设置中允许 Cap 使用你的摄像头。" access_title = "需要摄像头权限" +disconnected_message = "所选摄像头已停止发送视频。" +disconnected_title = "摄像头已断开" generic = "无法启动所选摄像头。请选择其他摄像头,或重新连接此摄像头。" invalid_format = "此摄像头未提供可用的捕获格式。" not_found = "此摄像头已不可用。请检查它是否已连接,并已在系统权限中允许。" diff --git a/apps/desktop-gpui/src/camera_window.rs b/apps/desktop-gpui/src/camera_window.rs index 86caa6ba9af..e9fc182cc92 100644 --- a/apps/desktop-gpui/src/camera_window.rs +++ b/apps/desktop-gpui/src/camera_window.rs @@ -35,11 +35,9 @@ //! Known deviations (also in the README): no 150ms opacity/translate //! transitions on the toolbar and resize brackets (no animation pass in this //! port), no `backdrop-blur-xs` behind the issue overlay (no per-element -//! backdrop blur hook in this gpui rev), no "Camera disconnected" overlay on -//! recording input loss (the Tauri `recordingEvent` InputLost seam has no -//! counterpart in this app yet), no `cursor-move` on the drag surface (gpui -//! has no 4-way move cursor; the resize handles do get their diagonal resize -//! cursors), and chrome state persists to `gpui-state.json` rather than +//! backdrop blur hook in this gpui rev), no `cursor-move` on the drag surface +//! (gpui has no 4-way move cursor; the resize handles do get their diagonal +//! resize cursors), and chrome state persists to `gpui-state.json` rather than //! `localStorage`. use std::sync::{ @@ -1093,8 +1091,12 @@ struct CameraPreviewView { camera_error: Option, effect_issue: Option, awaiting_access: bool, + /// The recording's camera was unplugged (`InputLost` in the Tauri + /// bubble, `camera.tsx:162-172`); cleared when it is back. + camera_disconnected: bool, _feeds_subscription: Subscription, _access_subscription: Subscription, + _session_subscription: Option, } impl CameraPreviewView { @@ -1147,6 +1149,19 @@ impl CameraPreviewView { cx.notify(); } }); + let session = crate::session::RecordingSession::try_global(cx); + let camera_disconnected = session + .as_ref() + .is_some_and(|session| session.read(cx).disconnected_inputs().camera); + let session_subscription = session.map(|session| { + cx.observe(&session, |this: &mut Self, session, cx| { + let disconnected = session.read(cx).disconnected_inputs().camera; + if this.camera_disconnected != disconnected { + this.camera_disconnected = disconnected; + cx.notify(); + } + }) + }); let feeds_subscription = cx.observe(&feeds, |this: &mut Self, feeds, cx| { let awaiting = awaiting_camera_access(cx); if this.awaiting_access != awaiting { @@ -1194,8 +1209,10 @@ impl CameraPreviewView { camera_error, effect_issue: None, awaiting_access, + camera_disconnected, _feeds_subscription: feeds_subscription, _access_subscription: access_subscription, + _session_subscription: session_subscription, } } @@ -1285,8 +1302,10 @@ impl Render for CameraPreviewView { let showing_frame = self.latest_frame.is_some() || self.retained.is_some(); let awaiting_access = self.awaiting_access && !showing_frame && self.camera_error.is_none(); - let has_issue = - self.camera_error.is_some() || self.effect_issue.is_some() || awaiting_access; + let has_issue = self.camera_disconnected + || self.camera_error.is_some() + || self.effect_issue.is_some() + || awaiting_access; let loading = if !showing_frame { self.loading_fade_started = None; @@ -1424,9 +1443,14 @@ impl Render for CameraPreviewView { .as_deref() .is_some_and(|error| error.contains("access is unavailable")); if let Some((title, message)) = self - .camera_error - .as_deref() - .map(camera_issue) + .camera_disconnected + .then(|| { + ( + tr::camera::issue::disconnected_title(), + tr::camera::issue::disconnected_message(), + ) + }) + .or(self.camera_error.as_deref().map(camera_issue)) .or(self.effect_issue.map(EffectIssue::text)) .or(awaiting_access.then(|| { ( diff --git a/apps/desktop-gpui/src/controls_window.rs b/apps/desktop-gpui/src/controls_window.rs index 342fdb197eb..a260a893ee4 100644 --- a/apps/desktop-gpui/src/controls_window.rs +++ b/apps/desktop-gpui/src/controls_window.rs @@ -197,6 +197,7 @@ impl ControlsWindow { session .error .clone() + .or_else(|| disconnected_issue(session.disconnected_inputs())) .or_else(|| session.input_switch_error().map(str::to_owned)) .or_else(|| { (session.paused_for_sleep && session.is_paused()) @@ -563,21 +564,22 @@ impl ControlsWindow { let has_microphone = self.has_microphone && (session.mode() == Some(RecordingMode::Instant) || Feeds::global(cx).read(cx).microphone.is_some()); + let disconnected = has_microphone && session.disconnected_inputs().microphone; self.level_bar.update(cx, |bar, cx| { bar.configure( - has_microphone && !muted, + has_microphone && !muted && !disconnected, theme.blue_9.into(), theme.gray_10.into(), cx, ); }); - let icon = if !has_microphone || muted { + let icon = if !has_microphone || muted || disconnected { "icons/mic-off.svg" } else { "icons/microphone.svg" }; - let icon_color: gpui::Hsla = if muted { + let icon_color: gpui::Hsla = if muted || disconnected { theme.red_9.into() } else if has_microphone { theme.gray_12.into() @@ -605,7 +607,7 @@ impl ControlsWindow { })) }) .child(svg().path(icon).size(px(20.)).text_color(icon_color)) - .when(has_microphone && !muted, |this| { + .when(has_microphone && !muted && !disconnected, |this| { this.child(self.level_bar.clone()) }) } @@ -1257,6 +1259,19 @@ fn recording_issue_text(error: String) -> impl IntoElement + Styled { ) } +fn disconnected_issue(disconnected: crate::session::DisconnectedInputs) -> Option { + let lines: Vec<&str> = [ + disconnected + .microphone + .then(tr::controls::disconnected::microphone), + disconnected.camera.then(tr::controls::disconnected::camera), + ] + .into_iter() + .flatten() + .collect(); + (!lines.is_empty()).then(|| lines.join("\n")) +} + fn tick_delay(live: bool, elapsed: Duration) -> Duration { if live { until_next_second(elapsed) diff --git a/apps/desktop-gpui/src/feeds.rs b/apps/desktop-gpui/src/feeds.rs index fe505d3e03e..6ba7cbe88e0 100644 --- a/apps/desktop-gpui/src/feeds.rs +++ b/apps/desktop-gpui/src/feeds.rs @@ -1327,6 +1327,24 @@ impl Feeds { cx.notify(); } + /// Opens the selected camera again on the same feed, for a camera that was + /// unplugged and is back. A feed a recording holds takes the same device + /// back without a new lock. The camera epoch stays: it is the same + /// selection, and a Linux Instant recording's camera worker checks the + /// epoch on every frame, so a new one would end its video. The input + /// watch never runs two reopens at once. + pub fn restart_camera(&mut self, cx: &mut Context) { + let Some(selection) = self.camera.clone() else { + return; + }; + if self.camera_preview_parked { + return; + } + self.camera_ready = None; + self.start_camera_preview(selection, cx); + cx.notify(); + } + /// An Instant recording moved onto `label`, opened on a feed of its own. /// Selects it (the main window persists that) and lets the app feed close /// the microphone the recording left, so the level meter only hears the diff --git a/apps/desktop-gpui/src/i18n/surface_tests.rs b/apps/desktop-gpui/src/i18n/surface_tests.rs index b9758aaaf51..0c5d223e585 100644 --- a/apps/desktop-gpui/src/i18n/surface_tests.rs +++ b/apps/desktop-gpui/src/i18n/surface_tests.rs @@ -325,6 +325,22 @@ fn main_surfaces_match_the_literals_they_replaced() { "Click to allow Cap to use your camera in System Settings.", ), (tr::camera::issue::unavailable_title(), "Camera unavailable"), + ( + tr::camera::issue::disconnected_title(), + "Camera disconnected", + ), + ( + tr::camera::issue::disconnected_message(), + "The selected camera stopped sending video.", + ), + ( + tr::controls::disconnected::microphone(), + "Microphone disconnected. Silence will be used until it reconnects.", + ), + ( + tr::controls::disconnected::camera(), + "Camera disconnected. Recording continues without camera overlay.", + ), ( tr::camera::issue::not_found(), "This camera is no longer available. Check that it is connected and allowed by system permissions.", diff --git a/apps/desktop-gpui/src/recording.rs b/apps/desktop-gpui/src/recording.rs index 35a46c615ff..f7110186390 100644 --- a/apps/desktop-gpui/src/recording.rs +++ b/apps/desktop-gpui/src/recording.rs @@ -868,6 +868,35 @@ impl ActiveRecording { } } + /// The feeds this recording opened for itself at start, when the app's + /// feed could not be locked. + pub(crate) fn owned_microphone_actor(&self) -> Option> { + self._mic_feed.as_ref().map(|feed| feed.0.clone()) + } + + pub(crate) fn owned_camera_actor(&self) -> Option> { + self._camera_feed.as_ref().map(|feed| feed.0.clone()) + } + + /// A switch moved the recording off its own start-up feed; it is no + /// longer the one to reopen. + pub(crate) fn release_owned_microphone(&mut self) { + self._mic_feed = None; + self._mic_errors = None; + } + + pub(crate) fn release_owned_camera(&mut self) { + self._camera_feed = None; + } + + pub(crate) fn switched_microphone_actor(&self) -> Option> { + self.switched_microphone + .lock() + .unwrap() + .as_ref() + .map(|switched| switched._feed.0.clone()) + } + pub(crate) fn studio_handle(&self) -> Option { match &self.handle { Handle::Studio(handle) => Some(handle.clone()), diff --git a/apps/desktop-gpui/src/session.rs b/apps/desktop-gpui/src/session.rs index c2f4f979fda..258b665cdff 100644 --- a/apps/desktop-gpui/src/session.rs +++ b/apps/desktop-gpui/src/session.rs @@ -19,7 +19,9 @@ use crate::i18n::tr; use crate::recording::{self, ActiveRecording, StartConfig}; mod input_switch; +mod input_watch; pub use input_switch::{InputKind, InputRequest}; +pub use input_watch::DisconnectedInputs; /// `Idle -> Starting -> Recording -> Stopping -> Idle`; pause is a flag on /// `Recording`, matching the `recording`/`paused` variants of the Tauri bar. @@ -487,6 +489,7 @@ pub struct RecordingSession { marker_added_at: Option, pub paused_for_sleep: bool, input_switch: input_switch::InputSwitchState, + input_watch: input_watch::InputWatchState, #[cfg(target_os = "linux")] instant_attempt: Option, #[cfg(target_os = "linux")] @@ -542,6 +545,7 @@ impl RecordingSession { marker_added_at: None, paused_for_sleep: false, input_switch: input_switch::InputSwitchState::default(), + input_watch: input_watch::InputWatchState::default(), #[cfg(target_os = "linux")] instant_attempt: None, #[cfg(target_os = "linux")] @@ -562,6 +566,11 @@ impl RecordingSession { cx.global::().0.clone() } + pub fn try_global(cx: &App) -> Option> { + cx.try_global::() + .map(|session| session.0.clone()) + } + /// True while a recording is in flight. Tolerates the global not being /// installed yet (reporting idle) so callers can gate on it from windows /// that may open before the session exists. @@ -1069,6 +1078,7 @@ impl RecordingSession { } self.monitor_storage(project_dir, cx); self.monitor_recording_failure(done, cx); + self.start_input_watch(cx); #[cfg(target_os = "linux")] if self.stop_requested { self.stop(cx); diff --git a/apps/desktop-gpui/src/session/input_switch.rs b/apps/desktop-gpui/src/session/input_switch.rs index 4c8823948ec..502be1da3c4 100644 --- a/apps/desktop-gpui/src/session/input_switch.rs +++ b/apps/desktop-gpui/src/session/input_switch.rs @@ -90,6 +90,11 @@ struct StudioSwitchOutcome { /// `Some(true)` when the recording was left paused (a resume failed), /// `Some(false)` when it runs again, `None` when the actor never answered. paused: Option, + /// The old feed was taken off the recording, so whatever it reads next + /// came through the app's feed, even if the switch then failed. + detached: bool, + /// The requested device is the one the recording reads now. + attached: bool, } impl RecordingSession { @@ -285,8 +290,9 @@ impl RecordingSession { } match result { Ok(opened) => { - if let Some(active) = &this.active { + if let Some(active) = this.active.as_mut() { active.adopt_switched_microphone(opened); + active.release_owned_microphone(); } Feeds::global(cx).update(cx, |feeds, cx| { feeds.adopt_recording_microphone(label.clone(), cx); @@ -376,9 +382,17 @@ impl RecordingSession { this.phase = Phase::Recording { paused: true }; this.input_switch.timer_frozen_at = None; } - if outcome.error.is_none() { + if outcome.attached { this.remember_input(&requested); } + if outcome.detached + && let Some(active) = this.active.as_mut() + { + match requested.kind() { + InputKind::Microphone => active.release_owned_microphone(), + InputKind::Camera => active.release_owned_camera(), + } + } this.input_switch.error = outcome.error; this.finish_input_switch(generation, cx); }) @@ -457,6 +471,8 @@ async fn studio_switch( &request.device_label(), )), paused: Some(false), + detached: false, + attached: false, }; } } @@ -472,14 +488,20 @@ async fn studio_switch( .await; let mut error = None; - if let Err(detach_error) = detached { - tracing::warn!("detaching the old input failed: {detach_error:#}"); - error = Some(tr::controls::settings::switch_failed( - &request.device_label(), - )); - } else if current(cx) { + let mut attached = false; + let detached = match detached { + Ok(()) => true, + Err(detach_error) => { + tracing::warn!("detaching the old input failed: {detach_error:#}"); + error = Some(tr::controls::settings::switch_failed( + &request.device_label(), + )); + false + } + }; + if detached && current(cx) { match attach_selection(this, cx, &handle, &request).await { - Ok(()) => {} + Ok(()) => attached = true, Err(attach_error) => { tracing::warn!( device = %request.device_label(), @@ -501,6 +523,8 @@ async fn studio_switch( return StudioSwitchOutcome { error, paused: Some(was_paused), + detached, + attached, }; } let resume = handle.clone(); @@ -508,6 +532,8 @@ async fn studio_switch( Ok(()) => StudioSwitchOutcome { error, paused: Some(false), + detached, + attached, }, Err(resume_error) => { tracing::error!("resuming after an input switch failed: {resume_error:#}"); @@ -521,6 +547,8 @@ async fn studio_switch( "{resume_error:#}. Use Stop if recording cannot continue safely." )), paused, + detached, + attached, } } } diff --git a/apps/desktop-gpui/src/session/input_watch.rs b/apps/desktop-gpui/src/session/input_watch.rs new file mode 100644 index 00000000000..cc12b983a1d --- /dev/null +++ b/apps/desktop-gpui/src/session/input_watch.rs @@ -0,0 +1,367 @@ +//! Noticing a microphone or camera unplugged mid-recording. +//! +//! The Tauri app polled the device lists once a second while a recording was +//! live (`spawn_microphone_watcher` / `spawn_camera_watcher`); so does this. +//! A missing device raises the bar's warning and the bubble's overlay while +//! the recording carries on: the microphone source fills silence and the +//! camera track simply has no new frames. When the same device is listed +//! again it is reopened on the feed the recording reads from, and the warning +//! clears once it is running. + +use std::time::Duration; + +use cap_recording::feeds::microphone; +use gpui::{Context, Task}; + +use super::{InputKind, Phase, RecordingSession}; +use crate::feeds::Feeds; + +const POLL: Duration = Duration::from_secs(1); + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct DisconnectedInputs { + pub microphone: bool, + pub camera: bool, +} + +#[derive(Default)] +pub(crate) struct InputWatchState { + pub(super) disconnected: DisconnectedInputs, + reconnecting: DisconnectedInputs, + task: Option>, +} + +#[derive(Clone, Debug, Default, PartialEq, Eq)] +struct WatchedInputs { + microphone: Option, + camera: Option, +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +struct Presence { + microphone: Option, + camera: Option, +} + +/// What a poll means: which inputs are now gone, and which came back and +/// should be reopened. An input the recording no longer uses is never +/// reported missing. +fn presence_update( + current: DisconnectedInputs, + presence: Presence, +) -> (DisconnectedInputs, DisconnectedInputs) { + let mut next = current; + let mut reopen = DisconnectedInputs::default(); + match presence.microphone { + Some(false) => next.microphone = true, + Some(true) => reopen.microphone = current.microphone, + None => next.microphone = false, + } + match presence.camera { + Some(false) => next.camera = true, + Some(true) => reopen.camera = current.camera, + None => next.camera = false, + } + (next, reopen) +} + +impl RecordingSession { + /// What the bar and bubble warn about. Nothing outside a live recording, + /// and not a microphone Instant has turned off ("No microphone" or + /// mute): it is still watched, so it is reopened if it comes back. + pub fn disconnected_inputs(&self) -> DisconnectedInputs { + if !matches!(self.phase, Phase::Recording { .. }) { + return DisconnectedInputs::default(); + } + let mut disconnected = self.input_watch.disconnected; + if self.mode() == Some(crate::recording::RecordingMode::Instant) && self.mic_muted { + disconnected.microphone = false; + } + disconnected + } + + pub(super) fn start_input_watch(&mut self, cx: &mut Context) { + self.input_watch = InputWatchState::default(); + let generation = self.recording_generation; + self.input_watch.task = Some(cx.spawn(async move |this, cx| { + loop { + cx.background_executor().timer(POLL).await; + let Ok(Some(watched)) = this.update(cx, |this, cx| { + (this.recording_generation == generation + && matches!(this.phase, Phase::Recording { .. })) + .then(|| this.watched_inputs(cx)) + }) else { + return; + }; + let polled = watched.clone(); + let presence = cx + .background_executor() + .spawn(async move { list_presence(&polled) }) + .await; + if this + .update(cx, |this, cx| { + let current = this.watched_inputs(cx); + let presence = presence_for_current(&watched, ¤t, presence); + this.apply_presence(generation, presence, cx) + }) + .is_err() + { + return; + } + } + })); + } + + fn watched_inputs(&self, cx: &gpui::App) -> WatchedInputs { + let Some(active) = self.active.as_ref() else { + return WatchedInputs::default(); + }; + let feeds = Feeds::global(cx).read(cx); + let switching = self.input_switch_pending(); + WatchedInputs { + microphone: feeds + .microphone + .clone() + .filter(|_| active.mic_mute.is_some() && switching != Some(InputKind::Microphone)), + camera: feeds + .camera + .as_ref() + .map(|camera| camera.device_id.clone()) + .filter(|_| active.started_with_camera() && switching != Some(InputKind::Camera)), + } + } + + fn apply_presence(&mut self, generation: u64, presence: Presence, cx: &mut Context) { + if generation != self.recording_generation || !matches!(self.phase, Phase::Recording { .. }) + { + return; + } + let current = self.input_watch.disconnected; + let (next, reopen) = presence_update(current, presence); + if next != current { + if next.microphone && !current.microphone { + tracing::warn!( + "recording microphone disconnected; recording continues with silence" + ); + } + if next.camera && !current.camera { + tracing::warn!("recording camera disconnected; recording continues without it"); + } + self.input_watch.disconnected = next; + cx.notify(); + } + if reopen.microphone && !self.input_watch.reconnecting.microphone { + self.reopen_microphone(generation, cx); + } + if reopen.camera && !self.input_watch.reconnecting.camera { + self.reopen_camera(generation, cx); + } + } + + /// Reopens the unplugged microphone on the feed the recording reads + /// from, which takes it back without a new lock. + fn reopen_microphone(&mut self, generation: u64, cx: &mut Context) { + let Some(label) = Feeds::global(cx).read(cx).microphone.clone() else { + return; + }; + let actor = self + .active + .as_ref() + .and_then(|active| { + active + .switched_microphone_actor() + .or_else(|| active.owned_microphone_actor()) + }) + .or_else(|| Feeds::global(cx).read(cx).mic_actor()); + let Some(actor) = actor else { + return; + }; + self.input_watch.reconnecting.microphone = true; + let settings = crate::store::RecordingDeviceSettings::for_microphone(&label); + let task = gpui_tokio::Tokio::spawn_result(cx, async move { + let ready = actor + .ask(microphone::SetInput { label, settings }) + .await + .map_err(|error| anyhow::anyhow!("{error}"))?; + ready.await.map_err(|error| anyhow::anyhow!("{error}"))?; + Ok(()) + }); + cx.spawn(async move |this, cx| { + let result = task.await; + this.update(cx, |this, cx| { + if generation != this.recording_generation { + return; + } + this.input_watch.reconnecting.microphone = false; + match result { + Ok(()) => { + tracing::info!("recording microphone reconnected"); + this.input_watch.disconnected.microphone = false; + cx.notify(); + } + Err(error) => { + tracing::warn!("reopening the recording microphone failed: {error:#}"); + } + } + }) + .ok(); + }) + .detach(); + } + + fn reopen_camera(&mut self, generation: u64, cx: &mut Context) { + if let Some(actor) = self + .active + .as_ref() + .and_then(|active| active.owned_camera_actor()) + { + let Some(camera) = Feeds::global(cx).read(cx).camera.clone() else { + return; + }; + self.input_watch.reconnecting.camera = true; + let settings = crate::store::RecordingDeviceSettings::for_camera( + &camera.device_id, + camera.model_id.as_ref(), + ); + let task = gpui_tokio::Tokio::spawn_result(cx, async move { + let ready = actor + .ask(cap_recording::feeds::camera::SetInput { + id: camera.id, + settings, + }) + .await + .map_err(|error| anyhow::anyhow!("{error}"))?; + ready.await.map_err(|error| anyhow::anyhow!("{error}"))?; + Ok(()) + }); + self.finish_camera_reopen( + generation, + async move { task.await.map_err(|e| format!("{e:#}")) }, + cx, + ); + return; + } + let ready = Feeds::global(cx).update(cx, |feeds, cx| { + feeds.restart_camera(cx); + feeds.input_readiness().camera + }); + let Some(ready) = ready else { + return; + }; + self.input_watch.reconnecting.camera = true; + self.finish_camera_reopen(generation, async move { ready.await.map(drop) }, cx); + } + + fn finish_camera_reopen( + &mut self, + generation: u64, + reopened: impl std::future::Future> + 'static, + cx: &mut Context, + ) { + cx.spawn(async move |this, cx| { + let result = reopened.await; + this.update(cx, |this, cx| { + if generation != this.recording_generation { + return; + } + this.input_watch.reconnecting.camera = false; + match result { + Ok(()) => { + tracing::info!("recording camera reconnected"); + this.input_watch.disconnected.camera = false; + cx.notify(); + } + Err(error) => tracing::warn!("reopening the recording camera failed: {error}"), + } + }) + .ok(); + }) + .detach(); + } +} + +/// A poll describes the devices watched when it started. An input switched +/// or turned off while it ran reads as unused, which clears its warning; the +/// next poll checks the new device. +fn presence_for_current( + polled: &WatchedInputs, + current: &WatchedInputs, + presence: Presence, +) -> Presence { + Presence { + microphone: presence + .microphone + .filter(|_| polled.microphone == current.microphone), + camera: presence.camera.filter(|_| polled.camera == current.camera), + } +} + +fn list_presence(watched: &WatchedInputs) -> Presence { + Presence { + microphone: watched.microphone.as_ref().map(|label| { + microphone::MicrophoneFeed::list_names() + .iter() + .any(|name| name == label) + }), + camera: watched.camera.as_ref().map(|device_id| { + cap_camera::list_cameras().any(|camera| camera.device_id() == device_id) + }), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn presence(microphone: Option, camera: Option) -> Presence { + Presence { microphone, camera } + } + + #[test] + fn a_missing_device_warns_and_its_return_asks_for_a_reopen() { + let none = DisconnectedInputs::default(); + let (gone, reopen) = presence_update(none, presence(Some(false), Some(true))); + assert_eq!( + gone, + DisconnectedInputs { + microphone: true, + camera: false + } + ); + assert_eq!(reopen, none); + + let (still_gone, reopen) = presence_update(gone, presence(Some(true), Some(true))); + assert_eq!( + still_gone, gone, + "the warning stays until the reopen succeeds" + ); + assert!(reopen.microphone && !reopen.camera); + } + + #[test] + fn a_poll_of_a_device_switched_away_from_is_discarded() { + let polled = WatchedInputs { + microphone: Some("USB Mic".into()), + camera: Some("camera-a".into()), + }; + let current = WatchedInputs { + microphone: Some("USB Mic".into()), + camera: Some("camera-b".into()), + }; + assert_eq!( + presence_for_current(&polled, ¤t, presence(Some(false), Some(false))), + presence(Some(false), None) + ); + } + + #[test] + fn an_input_the_recording_stopped_using_never_warns() { + let both = DisconnectedInputs { + microphone: true, + camera: true, + }; + let (next, reopen) = presence_update(both, presence(None, None)); + assert_eq!(next, DisconnectedInputs::default()); + assert_eq!(reopen, DisconnectedInputs::default()); + } +}