Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
fix: apply saved GPUI device formats with readiness checks
Richie McIlroy1c5342901129
diff --git a/apps/desktop-gpui/Cargo.lock b/apps/desktop-gpui/Cargo.lockindex d69344d54..e5faa7c8a 100644--- a/apps/desktop-gpui/Cargo.lock+++ b/apps/desktop-gpui/Cargo.lock@@ -1543,6 +1543,7 @@ dependencies = ["cap-editor","cap-enc-ffmpeg","cap-export",+ "cap-media-info","cap-project","cap-recording","cap-rendering",diff --git a/apps/desktop-gpui/Cargo.toml b/apps/desktop-gpui/Cargo.tomlindex 58ae0c10e..82319835a 100644--- a/apps/desktop-gpui/Cargo.toml+++ b/apps/desktop-gpui/Cargo.toml@@ -50,6 +50,7 @@ cpal = { git = "https://github.com/CapSoftware/cpal", rev = "6013cb5f8bd3" }# The actual recording engine -- the same studio/instant actors the Tauri app# drives. Drags in the ffmpeg encode stack; that is the point.cap-recording = { path = "../../crates/recording" }+cap-media-info = { path = "../../crates/media-info" }cap-enc-ffmpeg = { path = "../../crates/enc-ffmpeg" }# Already in the tree through cap-recording; direct so the camera draw bench# can construct `NativeCameraFrame.timestamp` for its synthetic frames.diff --git a/apps/desktop-gpui/src/app_windows.rs b/apps/desktop-gpui/src/app_windows.rsindex 6f1a45ba8..2ea1c7a70 100644--- a/apps/desktop-gpui/src/app_windows.rs+++ b/apps/desktop-gpui/src/app_windows.rs@@ -5426,6 +5426,8 @@ mod tests {},microphone: None,camera: None,+ device_settings: crate::store::RecordingDeviceSettings::default(),+ input_readiness: crate::feeds::InputReadiness::default(),system_audio: false,excluded_windows: Vec::new(),camera_feed: None,diff --git a/apps/desktop-gpui/src/deeplink.rs b/apps/desktop-gpui/src/deeplink.rsindex b92aa6f5f..28efcbc3d 100644--- a/apps/desktop-gpui/src/deeplink.rs+++ b/apps/desktop-gpui/src/deeplink.rs@@ -360,10 +360,7 @@ impl DeepLinkAction {let permit = main.update(cx, |view, _, cx| view.prepare_deep_link_start(cx)).map_err(|_| "The recording window is unavailable".to_string())??;- let selection = camera.clone().map(|id| SelectedCamera {- label: camera_label(&id),- id,- });+ let selection = camera.clone().map(camera_selection);if !permit.is_current(cx) {let _ = main.update(cx, |view, _, _| view.finish_deep_link_start(&permit));return Err("Recording preparation is no longer current".into());@@ -383,11 +380,16 @@ impl DeepLinkAction {let _ = main.update(cx, |view, _, _| view.finish_deep_link_start(&permit));return;}- let (camera_feed, mic_feed) = {+ let (camera_feed, mic_feed, input_readiness, device_settings) = {let feeds = Feeds::global(cx);feeds.update(cx, |feeds, cx| feeds.resume_camera_preview(cx));let feeds = feeds.read(cx);- (feeds.camera_actor(), feeds.mic_actor())+ (+ feeds.camera_actor(),+ feeds.mic_actor(),+ feeds.input_readiness(),+ feeds.requested_device_settings(),+ )};if main.update(cx, |view, _, cx| {@@ -395,6 +397,8 @@ impl DeepLinkAction {recording::StartConfig {mode,target: capture_target,+ device_settings,+ input_readiness,microphone: mic_label,camera,system_audio: capture_system_audio,@@ -469,10 +473,7 @@ impl DeepLinkAction {// signals with no consumer in this app.#[cfg(debug_assertions)]DeepLinkAction::OpenCamera { camera } => {- let selection = SelectedCamera {- label: camera_label(&camera),- id: camera,- };+ let selection = camera_selection(camera);Feeds::global(cx).update(cx, |feeds, cx| feeds.set_camera(Some(selection), cx));Ok(())}@@ -556,22 +557,35 @@ impl DeepLinkAction {}}-/// The display label for a deep-linked camera id. The Tauri action carries no-/// label (its command takes the bare `DeviceOrModelID`); this app's-/// [`SelectedCamera`] wants one for the pickers, so it is resolved against the-/// same enumeration `devices.rs` lists from, falling back to the raw device id-/// for a device that is not currently attached.-fn camera_label(id: &DeviceOrModelID) -> String {- cap_camera::list_cameras()- .find(|info| match id {- DeviceOrModelID::DeviceID(device_id) => info.device_id() == device_id.as_str(),- DeviceOrModelID::ModelID(model) => info.model_id() == Some(model),- })- .map(|info| info.display_name().to_string())- .unwrap_or_else(|| match id {- DeviceOrModelID::DeviceID(device_id) => device_id.clone(),- DeviceOrModelID::ModelID(_) => "Camera".to_string(),- })+fn camera_selection(id: DeviceOrModelID) -> SelectedCamera {+ let info = cap_camera::list_cameras().find(|info| match &id {+ DeviceOrModelID::DeviceID(device) => info.device_id() == device,+ DeviceOrModelID::ModelID(model) => info.model_id() == Some(model),+ });+ SelectedCamera {+ device_id: info+ .as_ref()+ .map(|info| info.device_id().to_string())+ .unwrap_or_else(|| match &id {+ DeviceOrModelID::DeviceID(device) => device.clone(),+ DeviceOrModelID::ModelID(_) => String::new(),+ }),+ model_id: info+ .as_ref()+ .and_then(|info| info.model_id().cloned())+ .or_else(|| match &id {+ DeviceOrModelID::ModelID(model) => Some(model.clone()),+ DeviceOrModelID::DeviceID(_) => None,+ }),+ label: info+ .as_ref()+ .map(|info| info.display_name().to_string())+ .unwrap_or_else(|| match &id {+ DeviceOrModelID::DeviceID(device) => device.clone(),+ DeviceOrModelID::ModelID(_) => "Camera".to_string(),+ }),+ id,+ }}#[cfg(test)]diff --git a/apps/desktop-gpui/src/devices.rs b/apps/desktop-gpui/src/devices.rsindex 064108127..3d967566f 100644--- a/apps/desktop-gpui/src/devices.rs+++ b/apps/desktop-gpui/src/devices.rs@@ -18,6 +18,7 @@ pub struct CameraOption {/// Highest-resolution format the device advertises, shown as the row's/// subtitle. `None` when the device reports no formats.pub best_format: Option<CameraFormat>,+ pub formats: Vec<CameraFormat>,}#[derive(Debug, Clone, Copy, PartialEq)]@@ -28,6 +29,14 @@ pub struct CameraFormat {}impl CameraFormat {+ pub fn settings(self) -> cap_recording::feeds::camera::CameraDeviceSettings {+ cap_recording::feeds::camera::CameraDeviceSettings {+ width: Some(self.width),+ height: Some(self.height),+ frame_rate: Some(self.frame_rate),+ }+ }+/// Matches the web UI: `1920×1080 @ 30fps`.pub fn describe(&self) -> String {format!(@@ -167,28 +176,37 @@ impl TargetSnapshot {fn list_cameras() -> Vec<CameraOption> {cap_camera::list_cameras().map(|camera| {- // Highest resolution first, then highest frame rate at that- // resolution -- the same ordering the web UI's `bestFormat` uses.- let best_format = camera.formats().and_then(|formats| {- formats- .into_iter()- .max_by(|a, b| {- (a.width() * a.height())- .cmp(&(b.width() * b.height()))- .then(a.frame_rate().total_cmp(&b.frame_rate()))- })- .map(|format| CameraFormat {- width: format.width(),- height: format.height(),- frame_rate: format.frame_rate(),- })+ let mut formats = camera+ .formats()+ .unwrap_or_default()+ .into_iter()+ .map(|format| CameraFormat {+ width: format.width(),+ height: format.height(),+ frame_rate: format.frame_rate(),+ })+ .collect::<Vec<_>>();+ let mut seen = std::collections::HashSet::new();+ formats.retain(|format| {+ seen.insert((+ format.width,+ format.height,+ format.frame_rate.round() as u32,+ ))});+ formats.sort_by(|a, b| {+ (b.width * b.height)+ .cmp(&(a.width * a.height))+ .then(b.frame_rate.total_cmp(&a.frame_rate))+ });+ let best_format = formats.first().copied();CameraOption {device_id: camera.device_id().to_string(),model_id: camera.model_id().cloned(),label: camera.display_name().to_string(),best_format,+ formats,}}).collect()@@ -235,6 +253,45 @@ fn list_microphones() -> Vec<MicrophoneOption> {mics}+pub fn microphone_formats(+ name: &str,+) -> Result<Vec<cap_recording::feeds::microphone::MicrophoneDeviceSettings>, String> {+ let devices = cap_recording::feeds::microphone::MicrophoneFeed::list();+ let (device, _) = devices+ .get(name)+ .ok_or_else(|| format!("Microphone '{name}' is no longer available"))?;+ let configs = device+ .supported_input_configs()+ .map_err(|error| format!("Could not read microphone formats: {error}"))?;+ let mut formats = std::collections::BTreeSet::new();+ for config in configs {+ if cap_media_info::ffmpeg_sample_format_for(config.sample_format()).is_none() {+ continue;+ }+ for sample_rate in [+ config.min_sample_rate().0,+ 44_100,+ 48_000,+ 96_000,+ config.max_sample_rate().0,+ ] {+ if (config.min_sample_rate().0..=config.max_sample_rate().0).contains(&sample_rate) {+ formats.insert((sample_rate, config.channels()));+ }+ }+ }+ Ok(formats+ .into_iter()+ .rev()+ .map(+ |(sample_rate, channels)| cap_recording::feeds::microphone::MicrophoneDeviceSettings {+ sample_rate: Some(sample_rate),+ channels: Some(channels),+ },+ )+ .collect())+}+/// `Window::get_topmost_at_cursor`, minus this process's own windows: the/// same level-≤5 filter and descending-level (stable, so front-to-back within/// a level) pick, transcribed from `scap-targets/src/platform/macos.rs`, withdiff --git a/apps/desktop-gpui/src/feeds.rs b/apps/desktop-gpui/src/feeds.rsindex 5c1329043..3822268c7 100644--- a/apps/desktop-gpui/src/feeds.rs+++ b/apps/desktop-gpui/src/feeds.rs@@ -23,11 +23,42 @@ use cap_recording::feeds::{camera::{self, CameraFeed},microphone::{self, MicrophoneFeed, MicrophoneSamples},};+use futures_util::{+ FutureExt as _,+ future::{BoxFuture, Shared},+};use gpui::{App, AppContext as _, Context, Entity, Global};use kameo::{Actor as _, actor::ActorRef};pub use cap_recording::feeds::camera::DeviceOrModelID;+pub type InputReady =+ Shared<BoxFuture<'static, Result<crate::store::RecordingDeviceSettings, String>>>;++#[derive(Clone, Default)]+pub struct InputReadiness {+ pub camera: Option<InputReady>,+ pub microphone: Option<InputReady>,+}++fn owned_input_readiness(+ input: impl std::future::Future<Output = Result<crate::store::RecordingDeviceSettings, String>>+ + Send+ + 'static,+ current_epoch: Arc<AtomicU64>,+ epoch: u64,+) -> InputReady {+ async move {+ let result = input.await;+ if current_epoch.load(Ordering::Acquire) != epoch {+ return Err("Device selection changed before it was ready".to_string());+ }+ result+ }+ .boxed()+ .shared()+}+use crate::app_windows;#[cfg(target_os = "macos")]@@ -62,6 +93,23 @@ async fn camera_input_operation<T>(operation.await.map(Some)}+fn configuration_result(+ current_epoch: u64,+ epoch: u64,+ pending: bool,+ error: Option<&str>,+) -> Option<Result<(), String>> {+ if current_epoch != epoch {+ Some(Err(+ "Device selection changed before the format was applied".into(),+ ))+ } else if pending {+ None+ } else {+ Some(error.map_or(Ok(()), |error| Err(error.to_string())))+ }+}+/// How the pickers map dB to a 0..1 bar: `DeviceListPanel` in `index.tsx`/// (`DB_SCALE = 40`, inverted, square-rooted). 1 = silence, 0 = full scale --/// the overlay's `right` offset, kept in the same orientation as the web app.@@ -588,7 +636,18 @@ pub struct Feeds {camera_actor: Option<ActorRef<CameraFeed>>,camera_preview_sender: Option<flume::Sender<PreviewCameraFrame>>,camera_input_gate: Arc<tokio::sync::Mutex<()>>,+ mic_input_gate: Arc<tokio::sync::Mutex<()>>,+ mic_input_epoch: Arc<AtomicU64>,mic_actor: Option<ActorRef<MicrophoneFeed>>,+ camera_settings: Option<camera::CameraDeviceSettings>,+ microphone_settings: Option<microphone::MicrophoneDeviceSettings>,+ applied_settings: crate::store::RecordingDeviceSettings,+ camera_input_pending: bool,+ mic_input_pending: bool,+ mic_input_released: bool,+ microphone_error: Option<String>,+ camera_ready: Option<InputReady>,+ microphone_ready: Option<InputReady>,/// Selected camera; `Some` while the preview window should exist.pub camera: Option<SelectedCamera>,/// Selected microphone name.@@ -625,6 +684,8 @@ pub struct Feeds {pub struct SelectedCamera {pub id: DeviceOrModelID,pub label: String,+ pub device_id: String,+ pub model_id: Option<cap_camera::ModelID>,}struct FeedsGlobal(Entity<Feeds>);@@ -636,7 +697,18 @@ impl Feeds {camera_actor: None,camera_preview_sender: None,camera_input_gate: Arc::new(tokio::sync::Mutex::new(())),+ mic_input_gate: Arc::new(tokio::sync::Mutex::new(())),+ mic_input_epoch: Arc::new(AtomicU64::new(0)),mic_actor: None,+ camera_settings: None,+ microphone_settings: None,+ applied_settings: crate::store::RecordingDeviceSettings::default(),+ camera_input_pending: false,+ mic_input_pending: false,+ mic_input_released: false,+ microphone_error: None,+ camera_ready: None,+ microphone_ready: None,camera: None,microphone: None,mic_level_db: -96.0,@@ -698,6 +770,30 @@ impl Feeds {self.mic_actor.clone().filter(|actor| actor.is_alive())}+ pub fn input_readiness(&self) -> InputReadiness {+ InputReadiness {+ camera: self+ .camera_ready+ .clone()+ .filter(|_| self.camera_actor().is_some()),+ microphone: self+ .microphone_ready+ .clone()+ .filter(|_| self.mic_actor().is_some()),+ }+ }++ pub fn applied_device_settings(&self) -> crate::store::RecordingDeviceSettings {+ self.applied_settings+ }++ pub fn requested_device_settings(&self) -> crate::store::RecordingDeviceSettings {+ crate::store::RecordingDeviceSettings {+ camera: self.camera_settings,+ microphone: self.microphone_settings,+ }+ }+#[cfg(target_os = "linux")]pub(crate) fn set_camera_preview_rendering(&self, enabled: bool) -> bool {self.camera_preview_active.swap(enabled, Ordering::AcqRel)@@ -720,13 +816,35 @@ impl Feeds {/// Select (or deselect) the camera. Opens/closes the preview window and/// points the app-scoped feed at the device.pub fn set_camera(&mut self, selection: Option<SelectedCamera>, cx: &mut Context<Self>) {- if self.camera == selection {- return;+ let settings = selection.as_ref().and_then(|selection| {+ crate::store::RecordingDeviceSettings::for_camera(+ &selection.device_id,+ selection.model_id.as_ref(),+ )+ });+ self.set_camera_with_settings(selection, settings, cx);+ }++ pub fn set_camera_with_settings(+ &mut self,+ selection: Option<SelectedCamera>,+ settings: Option<camera::CameraDeviceSettings>,+ cx: &mut Context<Self>,+ ) -> u64 {+ if self.camera == selection+ && self.camera_settings == settings+ && self.camera_error.is_none()+ {+ return self.camera_epoch;}self.camera_epoch += 1;self.camera_input_epoch.store(self.camera_epoch, Ordering::Release);self.camera = selection.clone();+ self.camera_ready = None;+ self.camera_settings = settings;+ self.applied_settings.camera = None;+ self.camera_input_pending = false;self.camera_error = None;cx.notify();@@ -740,6 +858,25 @@ impl Feeds {cx.defer(app_windows::close_camera_window);}}+ self.camera_epoch+ }++ pub fn camera_configuration_result(&self, epoch: u64) -> Option<Result<(), String>> {+ configuration_result(+ self.camera_epoch,+ epoch,+ self.camera_input_pending,+ self.camera_error.as_deref(),+ )+ }++ pub fn microphone_configuration_result(&self, epoch: u64) -> Option<Result<(), String>> {+ configuration_result(+ self.mic_epoch,+ epoch,+ self.mic_input_pending,+ self.microphone_error.as_deref(),+ )}pub fn park_camera_preview(&mut self, cx: &mut Context<Self>) {@@ -748,6 +885,8 @@ impl Feeds {}self.camera_preview_parked = true;+ self.applied_settings.camera = None;+ self.camera_input_pending = false;self.camera_epoch += 1;self.camera_input_epoch.store(self.camera_epoch, Ordering::Release);@@ -784,11 +923,15 @@ impl Feeds {fn start_camera_preview(&mut self, selection: SelectedCamera, cx: &mut Context<Self>) {self.camera_error = None;+ self.camera_input_pending = true;+ self.applied_settings.camera = None;let epoch = self.camera_epoch;+ let settings = self.camera_settings;let actor = self.ensure_camera_actor(cx);let sender = self.camera_preview_sender.clone();let gate = self.camera_input_gate.clone();let current_epoch = self.camera_input_epoch.clone();+ let readiness_epoch = current_epoch.clone();let set = gpui_tokio::Tokio::spawn(cx, async move {let ready = camera_input_operation(&gate, ¤t_epoch, epoch, async {let sender = sender@@ -798,29 +941,46 @@ impl Feeds {actor.ask(camera::SetInput {id: selection.id,- settings: None,+ settings,}).await.map_err(|error| error.to_string())}).await?;- if let Some(ready) = ready {- ready.await.map_err(|error| error.to_string())?;- }- Ok::<_, String>(())+ let camera = if let Some(ready) = ready {+ let (_, info) = ready.await.map_err(|error| error.to_string())?;+ Some(camera::CameraDeviceSettings {+ width: Some(info.width),+ height: Some(info.height),+ frame_rate: Some(info.frame_rate.0 as f32 / info.frame_rate.1 as f32),+ })+ } else {+ None+ };+ Ok::<_, String>(crate::store::RecordingDeviceSettings {+ camera,+ microphone: None,+ })});+ let ready = owned_input_readiness(+ async move { set.await.unwrap_or_else(|error| Err(error.to_string())) },+ readiness_epoch,+ epoch,+ );+ self.camera_ready = Some(ready.clone());cx.spawn(async move |this, cx| {- let result = match set.await {- Ok(result) => result.map(|_| ()),- Err(error) => Err(error.to_string()),- };+ let result = ready.await;this.update(cx, |this, cx| {if this.camera_epoch != epoch {return;}- if let Err(error) = result {- tracing::error!("camera input failed: {error}");- this.camera_error = Some(error);+ this.camera_input_pending = false;+ match result {+ Ok(settings) => this.applied_settings.camera = settings.camera,+ Err(error) => {+ tracing::error!("camera input failed: {error}");+ this.camera_error = Some(error);+ }}cx.notify();})@@ -855,44 +1015,98 @@ impl Feeds {/// Select (or deselect) the microphone. The feed keeps running between/// recordings so the pickers and bar have a live level.pub fn set_microphone(&mut self, label: Option<String>, cx: &mut Context<Self>) {- if self.microphone == label {- return;+ let settings = label+ .as_deref()+ .and_then(crate::store::RecordingDeviceSettings::for_microphone);+ self.set_microphone_with_settings(label, settings, cx);+ }++ pub fn set_microphone_with_settings(+ &mut self,+ label: Option<String>,+ settings: Option<microphone::MicrophoneDeviceSettings>,+ cx: &mut Context<Self>,+ ) -> u64 {+ if self.microphone == label+ && self.microphone_settings == settings+ && !self.mic_input_released+ && self.microphone_error.is_none()+ {+ return self.mic_epoch;}self.mic_epoch += 1;+ self.mic_input_epoch+ .store(self.mic_epoch, Ordering::Release);self.microphone = label.clone();+ self.microphone_settings = settings;+ self.applied_settings.microphone = None;+ self.microphone_error = None;+ self.mic_input_pending = label.is_some();+ self.mic_input_released = false;self.mic_level_db = -96.0;- cx.notify();-+ let epoch = self.mic_epoch;let actor = self.ensure_mic_actor(cx);- match label {- Some(label) => {- gpui_tokio::Tokio::spawn(cx, async move {- match actor- .ask(microphone::SetInput {- label: label.clone(),- settings: None,- })+ let gate = self.mic_input_gate.clone();+ let current_epoch = self.mic_input_epoch.clone();+ let readiness_epoch = current_epoch.clone();+ let task = gpui_tokio::Tokio::spawn(cx, async move {+ let ready = camera_input_operation(&gate, ¤t_epoch, epoch, async {+ if let Some(label) = label {+ actor+ .ask(microphone::SetInput { label, settings }).await- {- Ok(ready) => {- if let Err(error) = ready.await {- tracing::warn!("microphone '{label}' failed to open: {error}");- }- }- Err(error) => {- tracing::warn!("microphone '{label}' set-input failed: {error}")- }- }- })- .detach();- }- None => {- gpui_tokio::Tokio::spawn(cx, async move {- let _ = actor.ask(microphone::RemoveInput).await;+ .map(Some)+ .map_err(|error| error.to_string())+ } else {+ actor+ .ask(microphone::RemoveInput)+ .await+ .map(|()| None)+ .map_err(|error| error.to_string())+ }+ })+ .await?;+ let microphone = if let Some(Some(ready)) = ready {+ let config = ready.await.map_err(|error| error.to_string())?;+ Some(microphone::MicrophoneDeviceSettings {+ sample_rate: Some(config.sample_rate().0),+ channels: Some(config.channels()),})- .detach();- }- }+ } else {+ None+ };+ Ok::<_, String>(crate::store::RecordingDeviceSettings {+ camera: None,+ microphone,+ })+ });+ let ready = owned_input_readiness(+ async move { task.await.unwrap_or_else(|error| Err(error.to_string())) },+ readiness_epoch,+ epoch,+ );+ self.microphone_ready = Some(ready.clone());+ cx.spawn(async move |this, cx| {+ let result = ready.await;+ this.update(cx, |this, cx| {+ if this.mic_epoch != epoch {+ return;+ }+ this.mic_input_pending = false;+ match result {+ Ok(settings) => this.applied_settings.microphone = settings.microphone,+ Err(error) => {+ tracing::warn!("microphone input failed: {error}");+ this.microphone_error = Some(error);+ }+ }+ cx.notify();+ })+ .ok();+ })+ .detach();+ cx.notify();+ epoch}/// Drop the live camera and microphone inputs without forgetting what was@@ -905,9 +1119,26 @@ impl Feeds {/// chosen -- so neither does this: only the hardware is released.pub fn release_inputs(&mut self, cx: &mut Context<Self>) {self.park_camera_preview(cx);+ self.mic_epoch += 1;+ self.mic_input_epoch+ .store(self.mic_epoch, Ordering::Release);+ self.mic_input_pending = false;+ self.mic_input_released = true;+ self.applied_settings.microphone = None;+ self.microphone_ready = None;if let Some(actor) = self.mic_actor.clone() {+ let gate = self.mic_input_gate.clone();+ let current_epoch = self.mic_input_epoch.clone();+ let epoch = self.mic_epoch;gpui_tokio::Tokio::spawn(cx, async move {- if let Err(error) = actor.ask(microphone::RemoveInput).await {+ if let Err(error) = camera_input_operation(&gate, ¤t_epoch, epoch, async {+ actor+ .ask(microphone::RemoveInput)+ .await+ .map_err(|error| error.to_string())+ })+ .await+ {tracing::warn!("releasing the microphone feed: {error}");}})@@ -1194,6 +1425,85 @@ fn db_fs(samples: &MicrophoneSamples) -> f64 {mod tests {use super::*;+ #[tokio::test]+ async fn same_device_format_change_discards_queued_previous_configuration() {+ let gate = tokio::sync::Mutex::new(());+ let current = AtomicU64::new(1);+ let guard = gate.lock().await;+ let first = camera_input_operation(&gate, ¤t, 1, async {+ Ok((+ "same-device",+ camera::CameraDeviceSettings {+ width: Some(1280),+ height: Some(720),+ frame_rate: Some(30.),+ },+ ))+ });+ tokio::pin!(first);+ assert!(futures_util::poll!(&mut first).is_pending());+ current.store(2, Ordering::Release);+ let second = camera_input_operation(&gate, ¤t, 2, async {+ Ok((+ "same-device",+ camera::CameraDeviceSettings {+ width: Some(1920),+ height: Some(1080),+ frame_rate: Some(60.),+ },+ ))+ });+ tokio::pin!(second);+ assert!(futures_util::poll!(&mut second).is_pending());+ drop(guard);+ assert_eq!(first.await.unwrap(), None);+ let (device, settings) = second.await.unwrap().unwrap();+ assert_eq!(device, "same-device");+ assert_eq!(settings.width, Some(1920));+ assert_eq!(settings.frame_rate, Some(60.));+ assert!(configuration_result(2, 1, false, None).unwrap().is_err());+ }++ #[tokio::test]+ async fn input_readiness_rejects_late_ack_for_preview_and_recording_waiters() {+ let current = Arc::new(AtomicU64::new(7));+ let (send, receive) = tokio::sync::oneshot::channel();+ let ready = owned_input_readiness(+ async move { receive.await.map_err(|error| error.to_string()) },+ current.clone(),+ 7,+ );+ let mut recording_waiter = ready.clone();+ assert!(futures_util::poll!(&mut recording_waiter).is_pending());+ current.store(8, Ordering::Release);+ send.send(crate::store::RecordingDeviceSettings::default())+ .unwrap();+ assert!(ready.await.unwrap_err().contains("selection changed"));+ assert!(recording_waiter.await.is_err());+ let applied = crate::store::RecordingDeviceSettings {+ camera: Some(camera::CameraDeviceSettings {+ width: Some(1280),+ height: Some(720),+ frame_rate: Some(29.97),+ }),+ microphone: None,+ };+ let ready = owned_input_readiness(async move { Ok(applied) }, current, 8);+ assert_eq!(ready.clone().await.unwrap(), applied);+ assert_eq!(ready.await.unwrap(), applied);+ }++ #[test]+ fn input_configuration_status_never_reports_pending_or_failed_as_ready() {+ assert_eq!(configuration_result(3, 3, true, None), None);+ assert_eq!(+ configuration_result(3, 3, false, Some("unavailable")),+ Some(Err("unavailable".into()))+ );+ assert_eq!(configuration_result(3, 3, false, None), Some(Ok(())));+ assert!(configuration_result(4, 3, false, None).unwrap().is_err());+ }+#[tokio::test]async fn camera_preview_subscription_survives_removal_and_reattaches_once() {let actor = CameraFeed::spawn(CameraFeed::default());diff --git a/apps/desktop-gpui/src/main_window.rs b/apps/desktop-gpui/src/main_window.rsindex 314b44da3..1e2caff18 100644--- a/apps/desktop-gpui/src/main_window.rs+++ b/apps/desktop-gpui/src/main_window.rs@@ -62,6 +62,7 @@ fn remembered_camera(id: &recording::DeviceOrModelID, cameras: &[CameraOption])},label: "Camera".to_string(),best_format: None,+ formats: Vec::new(),})}@@ -226,6 +227,86 @@ pub enum DeviceMenu {Microphone,}+#[derive(Clone, Debug, PartialEq)]+enum DeviceFormatTarget {+ Camera(CameraOption),+ Microphone(String),+}++#[derive(Clone, Copy, Debug, PartialEq)]+enum DeviceFormat {+ Camera(cap_recording::feeds::camera::CameraDeviceSettings),+ Microphone(cap_recording::feeds::microphone::MicrophoneDeviceSettings),+}++impl DeviceFormat {+ fn label(self) -> String {+ match self {+ Self::Camera(settings) => {+ match (settings.width, settings.height, settings.frame_rate) {+ (Some(width), Some(height), Some(rate)) => {+ format!("{width}×{height} @ {rate:.0}fps")+ }+ _ => "Default".into(),+ }+ }+ Self::Microphone(settings) => match (settings.sample_rate, settings.channels) {+ (Some(rate), Some(channels)) => {+ let channels = match channels {+ 1 => "Mono".into(),+ 2 => "Stereo".into(),+ count => format!("{count} channels"),+ };+ format!("{}kHz {channels}", rate as f32 / 1000.)+ }+ _ => "Default".into(),+ },+ }+ }+}++struct PendingDeviceFormat {+ target: DeviceFormatTarget,+ format: DeviceFormat,+ epoch: u64,+}++fn complete_format_request(+ pending: &mut Option<PendingDeviceFormat>,+ result: Option<Result<(), String>>,+ still_owned: bool,+ save: impl FnOnce(&DeviceFormatTarget, DeviceFormat) -> bool,+) -> Option<Result<DeviceFormat, String>> {+ let result = result?;+ let pending = pending.take()?;+ if !still_owned {+ return None;+ }+ Some(result.and_then(|()| {+ if save(&pending.target, pending.format) {+ Ok(pending.format)+ } else {+ Err("Could not save the device format preference. Try again.".to_string())+ }+ }))+}++fn save_device_format(target: &DeviceFormatTarget, format: DeviceFormat) -> bool {+ match (target, format) {+ (DeviceFormatTarget::Camera(camera), DeviceFormat::Camera(settings)) => {+ crate::store::set_camera_device_settings(+ &camera.device_id,+ camera.model_id.as_ref(),+ settings,+ )+ }+ (DeviceFormatTarget::Microphone(name), DeviceFormat::Microphone(settings)) => {+ crate::store::set_microphone_device_settings(name, settings)+ }+ _ => false,+ }+}+impl DeviceMenu {fn title(self) -> &'static str {match self {@@ -414,6 +495,12 @@ pub struct MainWindow {microphone: Option<MicrophoneOption>,pending_device_restore: crate::store::RecordingInputSettings,device_restore_suspended: bool,+ device_format_target: Option<DeviceFormatTarget>,+ device_formats: Option<Result<Vec<DeviceFormat>, String>>,+ device_format_value: Option<DeviceFormat>,+ device_format_generation: u64,+ device_format_pending: Option<PendingDeviceFormat>,+ device_format_notice: Option<String>,system_audio: bool,/// Which display/window is selected for each split target.selected_display: Option<DisplayOption>,@@ -587,10 +674,20 @@ impl MainWindow {tracing::warn!("Could not save the selected microphone");}}+ let format_result =+ this.device_format_pending+ .as_ref()+ .and_then(|pending| match pending.format {+ DeviceFormat::Camera(_) => feeds.camera_configuration_result(pending.epoch),+ DeviceFormat::Microphone(_) => {+ feeds.microphone_configuration_result(pending.epoch)+ }+ });if camera_changed || microphone_changed || matches!(this.panel, Some(Panel::Device(_))){cx.notify();}+ this.finish_device_format_change(format_result, cx);}).detach();@@ -620,6 +717,12 @@ impl MainWindow {microphone: None,pending_device_restore: crate::store::RecordingInputSettings::load(),device_restore_suspended: false,+ device_format_target: None,+ device_formats: None,+ device_format_value: None,+ device_format_generation: 0,+ device_format_pending: None,+ device_format_notice: None,system_audio: false,selected_display: None,selected_window: None,@@ -1881,15 +1984,22 @@ impl MainWindow {return;}- let (camera_feed, mic_feed) = {+ let (camera_feed, mic_feed, input_readiness, device_settings) = {let feeds = Feeds::global(cx);feeds.update(cx, |feeds, cx| feeds.resume_camera_preview(cx));let feeds = feeds.read(cx);- (feeds.camera_actor(), feeds.mic_actor())+ (+ feeds.camera_actor(),+ feeds.mic_actor(),+ feeds.input_readiness(),+ feeds.requested_device_settings(),+ )};let config = recording::StartConfig {mode,target,+ device_settings,+ input_readiness,microphone: self.microphone.as_ref().map(|mic| mic.name.clone()),camera: self.camera_id.clone(),system_audio: self.system_audio,@@ -1909,6 +2019,7 @@ impl MainWindow {cx: &mut Context<Self>,) {if self.enumerating+ || self.device_format_pending.is_some()|| self.pending_device_restore.camera_id.is_some()|| self.pending_device_restore.microphone_name.is_some(){@@ -1948,6 +2059,9 @@ impl MainWindow {&mut self,cx: &mut Context<Self>,) -> Result<RecordingStartPermit, String> {+ if self.device_format_pending.is_some() {+ return Err("Wait for the device format change to finish before recording".into());+ }let permit = RecordingStartPermit::prepare(self.session.read(cx).phase,app_windows::clean_capture_owned(cx),@@ -1967,12 +2081,15 @@ impl MainWindow {}pub(crate) fn is_preparing_recording(&self) -> bool {- self.checking_storage || self.deep_link_start.is_some()+ self.checking_storage+ || self.deep_link_start.is_some()+ || self.device_format_pending.is_some()}fn device_changes_allowed(&self, cx: &gpui::App) -> bool {self.session.read(cx).phase == Phase::Idle&& !self.is_preparing_recording()+ && !self.device_restore_suspended&& !app_windows::clean_capture_owned(cx)}@@ -2210,6 +2327,7 @@ impl MainWindow {pub(crate) fn suspend_device_restore(&mut self) {self.device_restore_suspended = true;+ self.device_format_pending = None;}pub(crate) fn resume_device_restore(&mut self, cx: &mut Context<Self>) {@@ -2266,6 +2384,8 @@ impl MainWindow {.map(|(camera, id)| feeds::SelectedCamera {id: id.clone(),label: camera.label.clone(),+ device_id: camera.device_id.clone(),+ model_id: camera.model_id.clone(),});self.camera_id = id;self.camera = camera;@@ -3193,6 +3313,17 @@ impl MainWindow {.child("Recording Modes").into_any_element(),Panel::Library(kind) => self.render_library_header(kind, cx).into_any_element(),+ Panel::Device(_) if self.device_format_target.is_some() => div()+ .flex_1()+ .min_w_0()+ .truncate()+ .text_size(px(12.))+ .text_color(theme.gray_11)+ .child(match self.device_format_target.as_ref().unwrap() {+ DeviceFormatTarget::Camera(camera) => camera.label.clone(),+ DeviceFormatTarget::Microphone(name) => name.clone(),+ })+ .into_any_element(),Panel::Device(_) | Panel::Target(_) => {self.render_search_field(panel, cx).into_any_element()}@@ -3239,7 +3370,7 @@ impl MainWindow {.child("Back"),).hover(|style| style.bg(theme.body_hover_fill(4)))- .on_click(cx.listener(|this, _, _window, cx| this.close_panel(cx))),+ .on_click(cx.listener(|this, _, _window, cx| this.back_panel(cx))),).child(header_trailing),)@@ -3268,6 +3399,9 @@ impl MainWindow {}fn close_panel(&mut self, cx: &mut Context<Self>) {+ self.device_format_target = None;+ self.device_formats = None;+ self.device_format_generation += 1;self.panel = None;self.search.clear();self.search_input@@ -3280,6 +3414,16 @@ impl MainWindow {cx.notify();}+ fn back_panel(&mut self, cx: &mut Context<Self>) {+ if self.device_format_target.take().is_some() {+ self.device_formats = None;+ self.device_format_generation += 1;+ cx.notify();+ } else {+ self.close_panel(cx);+ }+ }+pub(crate) fn show_recorder(&mut self, cx: &mut Context<Self>) {if self.panel.is_some() {self.close_panel(cx);@@ -3291,7 +3435,7 @@ impl MainWindow {self.dismiss_microphone_warning(cx);} else if self.panel.is_some() {if self.search.is_empty() {- self.close_panel(cx);+ self.back_panel(cx);} else {self.clear_search(cx);}@@ -3305,6 +3449,9 @@ impl MainWindow {}pub fn open_panel(&mut self, panel: Panel, window: &mut Window, cx: &mut Context<Self>) {+ self.device_format_target = None;+ self.device_formats = None;+ self.device_format_generation += 1;self.panel = Some(panel);self.search.clear();self.search_input@@ -4242,6 +4389,9 @@ impl MainWindow {}fn render_device_list(&self, menu: DeviceMenu, cx: &mut Context<Self>) -> gpui::Div {+ if self.device_format_target.is_some() {+ return self.render_device_formats(menu, cx);+ }let theme = self.theme;let list = div().flex().flex_col().gap(px(4.)).w_full();@@ -4304,22 +4454,45 @@ impl MainWindow {let chosen = camera.clone();rows.push(- self.render_device_list_row(- SharedString::from(format!("camera-{}", camera.device_id)),- menu.icon(),- camera.label.clone(),- camera.best_format.map(|format| format.describe()),- selected,- None,- cx.listener(move |this, _, _window, cx| {- if !this.device_changes_allowed(cx) {- return;- }- this.set_camera_selection(Some(chosen.clone()), cx);- this.close_panel(cx);- }),- )- .into_any_element(),+ div()+ .flex()+ .flex_row()+ .gap(px(4.))+ .w_full()+ .child(+ self.render_device_list_row(+ SharedString::from(format!("camera-{}", camera.device_id)),+ menu.icon(),+ camera.label.clone(),+ if selected {+ Feeds::global(cx)+ .read(cx)+ .applied_device_settings()+ .camera+ .map(|settings| DeviceFormat::Camera(settings).label())+ } else {+ camera.best_format.map(|format| {+ format!("Available: {}", format.describe())+ })+ },+ selected,+ None,+ cx.listener(move |this, _, _window, cx| {+ if !this.device_changes_allowed(cx) {+ return;+ }+ this.set_camera_selection(Some(chosen.clone()), cx);+ this.close_panel(cx);+ }),+ )+ .flex_1()+ .min_w_0(),+ )+ .child(self.render_device_format_button(+ DeviceFormatTarget::Camera(camera.clone()),+ cx,+ ))+ .into_any_element(),);}}@@ -4338,24 +4511,48 @@ impl MainWindow {let chosen = mic.clone();rows.push(- self.render_device_list_row(- SharedString::from(format!("mic-{}", mic.name)),- menu.icon(),- mic.name.clone(),- mic.describe(),- selected,- selected.then(|| {- feeds::picker_level(Feeds::global(cx).read(cx).mic_level_db)- }),- cx.listener(move |this, _, _window, cx| {- if !this.device_changes_allowed(cx) {- return;- }- this.set_microphone_selection(Some(chosen.clone()), cx);- this.close_panel(cx);- }),- )- .into_any_element(),+ div()+ .flex()+ .flex_row()+ .gap(px(4.))+ .w_full()+ .child(+ self.render_device_list_row(+ SharedString::from(format!("mic-{}", mic.name)),+ menu.icon(),+ mic.name.clone(),+ if selected {+ Feeds::global(cx)+ .read(cx)+ .applied_device_settings()+ .microphone+ .map(|settings| {+ DeviceFormat::Microphone(settings).label()+ })+ } else {+ mic.describe()+ .map(|description| format!("Available: {description}"))+ },+ selected,+ selected.then(|| {+ feeds::picker_level(Feeds::global(cx).read(cx).mic_level_db)+ }),+ cx.listener(move |this, _, _window, cx| {+ if !this.device_changes_allowed(cx) {+ return;+ }+ this.set_microphone_selection(Some(chosen.clone()), cx);+ this.close_panel(cx);+ }),+ )+ .flex_1()+ .min_w_0(),+ )+ .child(self.render_device_format_button(+ DeviceFormatTarget::Microphone(mic.name.clone()),+ cx,+ ))+ .into_any_element(),);}}@@ -4368,6 +4565,274 @@ impl MainWindow {list.children(rows)}+ fn open_device_formats(&mut self, target: DeviceFormatTarget, cx: &mut Context<Self>) {+ if !self.device_changes_allowed(cx) {+ return;+ }+ self.device_format_generation += 1;+ let generation = self.device_format_generation;+ self.device_format_value = Some(match &target {+ DeviceFormatTarget::Camera(camera) => DeviceFormat::Camera(+ crate::store::RecordingDeviceSettings::for_camera(+ &camera.device_id,+ camera.model_id.as_ref(),+ )+ .unwrap_or_default(),+ ),+ DeviceFormatTarget::Microphone(name) => DeviceFormat::Microphone(+ crate::store::RecordingDeviceSettings::for_microphone(name).unwrap_or_default(),+ ),+ });+ self.device_format_target = Some(target.clone());+ self.device_format_notice = None;+ self.device_formats = match &target {+ DeviceFormatTarget::Camera(camera) => Some(Ok(std::iter::once(DeviceFormat::Camera(+ Default::default(),+ ))+ .chain(+ camera+ .formats+ .iter()+ .map(|format| DeviceFormat::Camera(format.settings())),+ )+ .collect())),+ DeviceFormatTarget::Microphone(_) => None,+ };+ if let DeviceFormatTarget::Microphone(name) = target {+ cx.spawn(async move |this, cx| {+ let formats = cx+ .background_executor()+ .spawn(async move {+ devices::microphone_formats(&name).map(|formats| {+ std::iter::once(DeviceFormat::Microphone(Default::default()))+ .chain(formats.into_iter().map(DeviceFormat::Microphone))+ .collect()+ })+ })+ .await;+ this.update(cx, |this, cx| {+ if this.device_format_generation != generation+ || this.device_format_target.is_none()+ {+ return;+ }+ this.device_formats = Some(formats);+ cx.notify();+ })+ .ok();+ })+ .detach();+ }+ cx.notify();+ }++ fn device_format_target_selected(&self, target: &DeviceFormatTarget) -> bool {+ match target {+ DeviceFormatTarget::Camera(camera) => self+ .camera+ .as_ref()+ .is_some_and(|selected| selected.device_id == camera.device_id),+ DeviceFormatTarget::Microphone(name) => self+ .microphone+ .as_ref()+ .is_some_and(|selected| selected.name == *name),+ }+ }++ fn choose_device_format(&mut self, format: DeviceFormat, cx: &mut Context<Self>) {+ if !self.device_changes_allowed(cx) {+ return;+ }+ let Some(target) = self.device_format_target.clone() else {+ return;+ };+ if !self+ .device_formats+ .as_ref()+ .and_then(|formats| formats.as_ref().ok())+ .is_some_and(|formats| formats.contains(&format))+ {+ return;+ }+ self.device_format_notice = None;+ if !self.device_format_target_selected(&target) {+ self.complete_device_format_save(&target, format, cx);+ return;+ }+ let feeds = Feeds::global(cx);+ let epoch = feeds.update(cx, |feeds, cx| match format {+ DeviceFormat::Camera(settings) => {+ feeds.set_camera_with_settings(feeds.camera.clone(), Some(settings), cx)+ }+ DeviceFormat::Microphone(settings) => {+ feeds.set_microphone_with_settings(feeds.microphone.clone(), Some(settings), cx)+ }+ });+ self.device_format_pending = Some(PendingDeviceFormat {+ target,+ format,+ epoch,+ });+ let result = match format {+ DeviceFormat::Camera(_) => feeds.read(cx).camera_configuration_result(epoch),+ DeviceFormat::Microphone(_) => feeds.read(cx).microphone_configuration_result(epoch),+ };+ self.finish_device_format_change(result, cx);+ cx.notify();+ }++ fn finish_device_format_change(+ &mut self,+ result: Option<Result<(), String>>,+ cx: &mut Context<Self>,+ ) {+ let still_owned = !self.device_restore_suspended+ && self.session.read(cx).phase == Phase::Idle+ && self+ .device_format_pending+ .as_ref()+ .is_some_and(|pending| self.device_format_target_selected(&pending.target));+ let Some(result) = complete_format_request(+ &mut self.device_format_pending,+ result,+ still_owned,+ save_device_format,+ ) else {+ return;+ };+ match result {+ Ok(format) => {+ self.device_format_value = Some(format);+ self.device_format_notice = None;+ }+ Err(error) => {+ self.device_format_notice = Some(error.clone());+ self.session.update(cx, |session, cx| {+ session.error = Some(format!("Could not apply device format: {error}"));+ cx.notify();+ });+ }+ }+ cx.notify();+ }++ fn complete_device_format_save(+ &mut self,+ target: &DeviceFormatTarget,+ format: DeviceFormat,+ cx: &mut Context<Self>,+ ) {+ if save_device_format(target, format) {+ self.device_format_value = Some(format);+ self.device_format_notice = None;+ } else {+ let error = "Could not save the device format preference. Try again.".to_string();+ self.device_format_notice = Some(error.clone());+ self.session.update(cx, |session, cx| {+ session.error = Some(error);+ cx.notify();+ });+ }+ cx.notify();+ }++ fn render_device_formats(&self, menu: DeviceMenu, cx: &mut Context<Self>) -> gpui::Div {+ let theme = self.theme;+ let applied = self+ .device_format_target+ .as_ref()+ .filter(|target| self.device_format_target_selected(target))+ .and_then(|target| {+ let settings = Feeds::global(cx).read(cx).applied_device_settings();+ match target {+ DeviceFormatTarget::Camera(_) => settings.camera.map(DeviceFormat::Camera),+ DeviceFormatTarget::Microphone(_) => {+ settings.microphone.map(DeviceFormat::Microphone)+ }+ }+ });+ let list = div()+ .flex()+ .flex_col()+ .gap(px(4.))+ .w_full()+ .child(+ div()+ .text_size(px(12.))+ .text_color(theme.gray_11)+ .pb(px(8.))+ .child("Preferred format"),+ )+ .when_some(applied, |list, format| {+ list.child(+ div()+ .text_size(px(12.))+ .text_color(theme.gray_11)+ .pb(px(8.))+ .child(format!("Current: {}", format.label())),+ )+ });+ let list = match &self.device_formats {+ None => list.child(self.render_empty_state("Loading formats...")),+ Some(Err(error)) => list.child(self.render_empty_state(error.clone())),+ Some(Ok(formats)) => {+ list.children(formats.iter().enumerate().map(|(index, format)| {+ let format = *format;+ self.render_device_list_row(+ SharedString::from(format!("device-format-{index}")),+ menu.icon(),+ format.label(),+ None,+ self.device_format_value == Some(format),+ None,+ cx.listener(move |this, _, _, cx| this.choose_device_format(format, cx)),+ )+ }))+ }+ };+ list.when(self.device_format_pending.is_some(), |list| {+ list.child(self.render_empty_state("Applying format..."))+ })+ .when_some(self.device_format_notice.as_ref(), |list, notice| {+ list.child(self.render_empty_state(notice.clone()))+ })+ }++ fn render_device_format_button(+ &self,+ target: DeviceFormatTarget,+ cx: &mut Context<Self>,+ ) -> gpui::Stateful<gpui::Div> {+ let enabled = self.device_changes_allowed(cx);+ let name = match &target {+ DeviceFormatTarget::Camera(camera) => format!("camera-format-{}", camera.device_id),+ DeviceFormatTarget::Microphone(name) => format!("mic-format-{name}"),+ };+ div()+ .id(SharedString::from(name))+ .flex()+ .items_center()+ .justify_center()+ .w(px(32.))+ .flex_shrink_0()+ .rounded(px(6.))+ .when(enabled, |button| {+ button+ .cursor_pointer()+ .hover(|style| style.bg(self.theme.body_hover_fill(4)))+ })+ .when(!enabled, |button| button.opacity(0.45))+ .child(+ svg()+ .path("icons/settings-2.svg")+ .size(px(16.))+ .text_color(self.theme.gray_11),+ )+ .on_click(+ cx.listener(move |this, _, _, cx| this.open_device_formats(target.clone(), cx)),+ )+ }+/// The width one target card gets, computed rather than flexed.////// Two columns inside `render_body`'s `px-[13px]` and the panel body's@@ -4660,13 +5125,13 @@ impl MainWindow {)}- fn render_empty_state(&self, message: &'static str) -> gpui::AnyElement {+ fn render_empty_state(&self, message: impl Into<SharedString>) -> gpui::AnyElement {div().py(px(24.)).w_full().text_size(px(14.)).text_color(self.theme.gray_11)- .child(message)+ .child(message.into()).into_any_element()}@@ -5864,6 +6329,7 @@ mod remembered_device_tests {model_id: model.map(|model| cap_camera::ModelID::try_from(model.to_string()).unwrap()),label: format!("Camera {device}"),best_format: None,+ formats: Vec::new(),}}@@ -5943,6 +6409,84 @@ mod remembered_device_tests {}}+#[cfg(test)]+mod device_format_tests {+ use super::*;++ fn pending() -> Option<PendingDeviceFormat> {+ Some(PendingDeviceFormat {+ target: DeviceFormatTarget::Microphone("Desk".into()),+ format: DeviceFormat::Microphone(+ cap_recording::feeds::microphone::MicrophoneDeviceSettings {+ sample_rate: Some(48_000),+ channels: Some(1),+ },+ ),+ epoch: 7,+ })+ }++ #[test]+ fn format_preference_is_saved_once_after_readiness_not_while_pending() {+ let mut request = pending();+ let mut writes = Vec::new();+ assert!(+ complete_format_request(&mut request, None, true, |_, _| panic!(+ "pending input cannot save"+ ))+ .is_none()+ );+ assert!(request.is_some());+ let result = complete_format_request(&mut request, Some(Ok(())), true, |target, format| {+ writes.push((target.clone(), format));+ true+ })+ .unwrap()+ .unwrap();+ assert!(request.is_none());+ assert_eq!(+ writes,+ vec![(DeviceFormatTarget::Microphone("Desk".into()), result)]+ );+ assert!(+ complete_format_request(&mut request, Some(Ok(())), true, |_, _| panic!(+ "duplicate acknowledgement cannot save"+ ))+ .is_none()+ );+ }++ #[test]+ fn failed_or_unowned_format_acknowledgements_do_not_save() {+ for (result, owned) in [+ (Err("input disconnected".into()), true),+ (Ok(()), false),+ (Err("selection changed".into()), false),+ ] {+ let mut request = pending();+ let completion = complete_format_request(&mut request, Some(result), owned, |_, _| {+ panic!("failed or stale input cannot save")+ });+ assert!(request.is_none());+ if owned {+ assert!(completion.unwrap().is_err());+ } else {+ assert!(completion.is_none());+ }+ }+ }++ #[test]+ fn format_save_error_does_not_report_success() {+ let mut request = pending();+ let error = complete_format_request(&mut request, Some(Ok(())), true, |_, _| false)+ .unwrap()+ .unwrap_err();+ assert!(error.contains("Could not save"));+ assert!(request.is_none());+ }+}+#[cfg(test)]mod recording_start_permit_tests {use super::*;diff --git a/apps/desktop-gpui/src/recording.rs b/apps/desktop-gpui/src/recording.rsindex 9a3973a92..939506091 100644--- a/apps/desktop-gpui/src/recording.rs+++ b/apps/desktop-gpui/src/recording.rs@@ -40,6 +40,8 @@ pub struct StartConfig {/// Microphone by name -- the identity `MicrophoneFeed` keys on.pub microphone: Option<String>,pub camera: Option<DeviceOrModelID>,+ pub device_settings: crate::store::RecordingDeviceSettings,+ pub input_readiness: crate::feeds::InputReadiness,pub system_audio: bool,/// Our own windows (the recording controls bar; the camera bubble in studio/// mode), excluded from capture the way the Tauri app excludes them.@@ -1686,6 +1688,17 @@ async fn start_attempt_with_upload(tracing::info!(dir = %project_dir.display(), "starting recording");+ if config.camera.is_some()+ && let Some(ready) = &config.input_readiness.camera+ {+ ready.clone().await.map_err(anyhow::Error::msg)?;+ }+ if config.microphone.is_some()+ && let Some(ready) = &config.input_readiness.microphone+ {+ ready.clone().await.map_err(anyhow::Error::msg)?;+ }+let (mic_feed, mic_lock, mic_errors) = match (&config.mic_feed, &config.microphone) {(Some(actor), Some(label)) => match actor.ask(microphone::Lock).await {Ok(lock) => {@@ -1698,14 +1711,15 @@ async fn start_attempt_with_upload(}Err(error) => {tracing::warn!("app mic feed lock failed ({error}), spawning one for '{label}'");- let (feed, lock, error_rx) = setup_microphone(label)- .await- .with_context(|| format!("Selected microphone '{label}' is unavailable"))?;+ let (feed, lock, error_rx) =+ setup_microphone(label, config.device_settings.microphone)+ .await+ .with_context(|| format!("Selected microphone '{label}' is unavailable"))?;(Some(feed), Some(lock), Some(error_rx))}},(None, Some(label)) => {- let (feed, lock, error_rx) = setup_microphone(label)+ let (feed, lock, error_rx) = setup_microphone(label, config.device_settings.microphone).await.with_context(|| format!("Selected microphone '{label}' is unavailable"))?;(Some(feed), Some(lock), Some(error_rx))@@ -1731,12 +1745,12 @@ async fn start_attempt_with_upload(}Err(error) => {tracing::warn!("app camera feed lock failed ({error}), spawning one");- let (feed, lock) = setup_camera(id).await?;+ let (feed, lock) = setup_camera(id, config.device_settings.camera).await?;(Some(feed), Some(Arc::new(lock)))}}} else {- let (feed, lock) = setup_camera(id).await?;+ let (feed, lock) = setup_camera(id, config.device_settings.camera).await?;(Some(feed), Some(Arc::new(lock)))}}@@ -1995,6 +2009,7 @@ fn resolve_excluded_window_ids(async fn setup_camera(id: &DeviceOrModelID,+ settings: Option<camera::CameraDeviceSettings>,) -> anyhow::Result<(ActorRef<CameraFeed>,cap_recording::feeds::camera::CameraFeedLock,@@ -2003,7 +2018,7 @@ async fn setup_camera(let ready = feed.ask(camera::SetInput {id: id.clone(),- settings: None,+ settings,}).await.map_err(|e| anyhow!("camera setup: {e}"))?;@@ -2017,6 +2032,7 @@ async fn setup_camera(async fn setup_microphone(label: &str,+ settings: Option<microphone::MicrophoneDeviceSettings>,) -> anyhow::Result<(ActorRef<MicrophoneFeed>,Arc<cap_recording::feeds::microphone::MicrophoneFeedLock>,@@ -2027,7 +2043,7 @@ async fn setup_microphone(let ready = feed.ask(microphone::SetInput {label: label.to_string(),- settings: None,+ settings,}).await.map_err(|e| anyhow!("setup: {e}"))?;diff --git a/apps/desktop-gpui/src/store.rs b/apps/desktop-gpui/src/store.rsindex ee2d47afc..e79449e27 100644--- a/apps/desktop-gpui/src/store.rs+++ b/apps/desktop-gpui/src/store.rs@@ -935,6 +935,97 @@ pub const RECORDING_START_SAFETY: &str = "recording_start_safety";/// the section the tray's Select Mode submenu reads and writes.pub const RECORDING_SETTINGS: &str = "recording_settings";+#[derive(Clone, Copy, Debug, Default, PartialEq)]+pub struct RecordingDeviceSettings {+ pub camera: Option<cap_recording::feeds::camera::CameraDeviceSettings>,+ pub microphone: Option<cap_recording::feeds::microphone::MicrophoneDeviceSettings>,+}++impl RecordingDeviceSettings {+ pub fn for_camera(+ device_id: &str,+ model_id: Option<&cap_camera::ModelID>,+ ) -> Option<cap_recording::feeds::camera::CameraDeviceSettings> {+ let settings = store_section(RECORDING_SETTINGS);+ let formats = settings.get("cameraDeviceSettings")?;+ std::iter::once(format!("device:{device_id}"))+ .chain(model_id.map(|model| format!("model:{model}")))+ .find_map(|key| {+ formats+ .get(key)+ .cloned()+ .and_then(|value| serde_json::from_value(value).ok())+ })+ }++ pub fn for_microphone(+ name: &str,+ ) -> Option<cap_recording::feeds::microphone::MicrophoneDeviceSettings> {+ store_section(RECORDING_SETTINGS)+ .get("microphoneDeviceSettings")?+ .get(name)+ .cloned()+ .and_then(|value| serde_json::from_value(value).ok())+ }+}++pub fn set_camera_device_settings(+ device_id: &str,+ model_id: Option<&cap_camera::ModelID>,+ settings: cap_recording::feeds::camera::CameraDeviceSettings,+) -> bool {+ let keys = std::iter::once(format!("device:{device_id}"))+ .chain(model_id.map(|model| format!("model:{model}")));+ set_device_format_settings("cameraDeviceSettings", keys, settings)+}++pub fn set_microphone_device_settings(+ name: &str,+ settings: cap_recording::feeds::microphone::MicrophoneDeviceSettings,+) -> bool {+ set_device_format_settings("microphoneDeviceSettings", [name.to_string()], settings)+}++fn set_device_format_settings(+ map_key: &str,+ keys: impl IntoIterator<Item = String>,+ settings: impl serde::Serialize,+) -> bool {+ let Ok(Value::Object(fields)) = serde_json::to_value(settings) else {+ return false;+ };+ let path = tauri_store_path();+ let Some(mut store) = read_store(&path) else {+ return false;+ };+ let section = store+ .entry(RECORDING_SETTINGS.to_string())+ .or_insert_with(|| Value::Object(Map::new()));+ let Some(section) = section.as_object_mut() else {+ return false;+ };+ let map = section+ .entry(map_key.to_string())+ .or_insert_with(|| Value::Object(Map::new()));+ let Some(map) = map.as_object_mut() else {+ return false;+ };+ for key in keys {+ let entry = map.entry(key).or_insert_with(|| Value::Object(Map::new()));+ let Some(entry) = entry.as_object_mut() else {+ return false;+ };+ for (key, value) in &fields {+ if value.is_null() {+ entry.remove(key);+ } else {+ entry.insert(key.clone(), value.clone());+ }+ }+ }+ write_store(&path, &Value::Object(store))+}+#[derive(Clone, Debug, Default, PartialEq)]pub struct RecordingInputSettings {pub camera_id: Option<cap_recording::feeds::camera::DeviceOrModelID>,@@ -1763,6 +1854,99 @@ mod tests {}}+ #[test]+ fn device_format_preferences_use_tauri_keys_and_preserve_other_fields() {+ use cap_recording::feeds::{+ camera::CameraDeviceSettings, microphone::MicrophoneDeviceSettings,+ };+ let store = TempStore::new(+ "device-format-preferences",+ Some(+ r#"{"recording_settings":{"mode":"studio","cameraDeviceSettings":{"device:camera-1":{"width":1280,"height":720,"frameRate":30,"future":7},"model:vendor:product":{"frameRate":60},"device:other":{"width":640}},"microphoneDeviceSettings":{"Desk":{"sampleRate":48000,"channels":1,"future":9},"Other":{"channels":2}},"future":{"keep":true}},"unrelated":{"keep":true}}"#,+ ),+ );+ let before = store.read();+ let model = cap_camera::ModelID::try_from("vendor:product".to_string()).unwrap();+ let snapshot = RecordingDeviceSettings {+ camera: RecordingDeviceSettings::for_camera("camera-1", Some(&model)),+ microphone: RecordingDeviceSettings::for_microphone("Desk"),+ };+ assert_eq!(snapshot.camera.unwrap().frame_rate, Some(30.));+ assert_eq!(+ RecordingDeviceSettings::for_camera("replugged", Some(&model))+ .unwrap()+ .frame_rate,+ Some(60.)+ );+ let camera = CameraDeviceSettings {+ width: Some(1920),+ height: Some(1080),+ frame_rate: Some(30.),+ };+ assert!(set_camera_device_settings("camera-1", Some(&model), camera));+ assert!(set_microphone_device_settings(+ "Desk",+ MicrophoneDeviceSettings {+ sample_rate: Some(44100),+ channels: Some(2)+ }+ ));+ assert_eq!(+ RecordingDeviceSettings::for_camera("camera-1", Some(&model)),+ Some(camera)+ );+ assert_eq!(+ RecordingDeviceSettings::for_camera("replugged", Some(&model)),+ Some(camera)+ );+ assert_eq!(snapshot.camera.unwrap().width, Some(1280));+ assert_eq!(snapshot.microphone.unwrap().sample_rate, Some(48000));+ let after = store.read();+ assert_eq!(+ after[RECORDING_SETTINGS]["cameraDeviceSettings"]["device:camera-1"]["future"],+ 7+ );+ assert_eq!(+ after[RECORDING_SETTINGS]["microphoneDeviceSettings"]["Desk"]["future"],+ 9+ );+ assert_eq!(+ after[RECORDING_SETTINGS]["cameraDeviceSettings"]["device:other"],+ before[RECORDING_SETTINGS]["cameraDeviceSettings"]["device:other"]+ );+ assert_eq!(+ after[RECORDING_SETTINGS]["microphoneDeviceSettings"]["Other"],+ before[RECORDING_SETTINGS]["microphoneDeviceSettings"]["Other"]+ );+ assert_eq!(after["unrelated"], before["unrelated"]);+ assert_eq!(+ after[RECORDING_SETTINGS]["future"],+ before[RECORDING_SETTINGS]["future"]+ );+ assert!(set_camera_device_settings(+ "camera-1",+ Some(&model),+ CameraDeviceSettings::default()+ ));+ assert!(+ store.read()[RECORDING_SETTINGS]["cameraDeviceSettings"]["device:camera-1"]+ .get("frameRate")+ .is_none()+ );+ assert_eq!(+ store.read()[RECORDING_SETTINGS]["cameraDeviceSettings"]["device:camera-1"]["future"],+ 7+ );+ }++ #[test]+ fn device_format_save_failure_does_not_replace_unreadable_preferences() {+ let store = TempStore::new("device-format-invalid-store", Some("{broken"));+ let before = std::fs::read(&store.path).unwrap();+ assert!(!set_microphone_device_settings("Desk", Default::default()));+ assert_eq!(std::fs::read(&store.path).unwrap(), before);+ }+#[test]fn recording_inputs_round_trip_without_replacing_unknown_settings() {use cap_recording::feeds::camera::DeviceOrModelID;