Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

comments + clippy

Richie McIlroy931f3a9a7122
diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs
index 58f48cdbc..80aae9ceb 100644
--- a/apps/desktop/src-tauri/src/lib.rs
+++ b/apps/desktop/src-tauri/src/lib.rs
@@ -402,6 +402,20 @@ impl App {
}
}
+ fn microphone_settings_for_label(
+ &self,
+ label: &str,
+ ) -> Option<microphone::MicrophoneDeviceSettings> {
+ recording_settings::RecordingSettingsStore::microphone_settings_for(&self.handle, label)
+ }
+
+ fn camera_settings_for_id(
+ &self,
+ id: &DeviceOrModelID,
+ ) -> Option<feeds::camera::CameraDeviceSettings> {
+ recording_settings::RecordingSettingsStore::camera_settings_for(&self.handle, id)
+ }
+
async fn restart_mic_feed(&mut self) -> Result<(), String> {
info!("Restarting microphone feed after actor shutdown");
@@ -416,7 +430,8 @@ impl App {
.map_err(|e| e.to_string())?;
if let Some(label) = self.selected_mic_label.clone() {
- match mic_feed.ask(microphone::SetInput { label }).await {
+ let settings = self.microphone_settings_for_label(&label);
+ match mic_feed.ask(microphone::SetInput { label, settings }).await {
Ok(ready) => {
if let Err(err) = ready.await {
if matches!(err, microphone::SetInputError::DeviceNotFound) {
@@ -536,9 +551,10 @@ impl App {
async fn ensure_selected_mic_ready(&mut self) -> Result<(), String> {
if let Some(label) = self.selected_mic_label.clone() {
+ let settings = self.microphone_settings_for_label(&label);
let ready = self
.mic_feed
- .ask(feeds::microphone::SetInput { label })
+ .ask(feeds::microphone::SetInput { label, settings })
.await
.map_err(|e| e.to_string())?;
@@ -550,9 +566,13 @@ impl App {
async fn ensure_selected_camera_ready(&mut self) -> Result<(), String> {
if let Some(id) = self.selected_camera_id.clone() {
+ let settings = self.camera_settings_for_id(&id);
let ready = self
.camera_feed
- .ask(feeds::camera::SetInput { id: id.clone() })
+ .ask(feeds::camera::SetInput {
+ id: id.clone(),
+ settings,
+ })
.await
.map_err(|e| e.to_string())?;
@@ -569,7 +589,7 @@ impl App {
async fn set_mic_input(state: MutableState<'_, App>, label: Option<String>) -> Result<(), String> {
let desired_label = label;
- let (mic_feed, studio_handle, previous_label) = {
+ let (mic_feed, studio_handle, previous_label, app_handle) = {
let mut app = state.write().await;
if desired_label == app.selected_mic_label {
return Ok(());
@@ -583,7 +603,12 @@ async fn set_mic_input(state: MutableState<'_, App>, label: Option<String>) -> R
let previous_label = app.selected_mic_label.clone();
app.selected_mic_label = desired_label.clone();
- (app.mic_feed.clone(), handle, previous_label)
+ (
+ app.mic_feed.clone(),
+ handle,
+ previous_label,
+ app.handle.clone(),
+ )
};
let has_studio = studio_handle.is_some();
@@ -609,9 +634,15 @@ async fn set_mic_input(state: MutableState<'_, App>, label: Option<String>) -> R
}
}
Some(label) => {
+ let settings =
+ recording_settings::RecordingSettingsStore::microphone_settings_for(
+ &app_handle,
+ label,
+ );
mic_feed
.ask(feeds::microphone::SetInput {
label: label.clone(),
+ settings,
})
.await
.map_err(|e| e.to_string())?
@@ -746,6 +777,8 @@ async fn set_camera_input(
.map_err(|e| e.to_string())?;
}
Some(id) => {
+ let settings =
+ recording_settings::RecordingSettingsStore::camera_settings_for(&app_handle, id);
let (camera_ws_sender, native_preview_active) = {
let app = &mut *state.write().await;
app.selected_camera_id = Some(id.clone());
@@ -781,7 +814,10 @@ async fn set_camera_input(
attempts += 1;
let request = camera_feed
- .ask(feeds::camera::SetInput { id: id.clone() })
+ .ask(feeds::camera::SetInput {
+ id: id.clone(),
+ settings,
+ })
.await
.map_err(|e| e.to_string());
diff --git a/apps/desktop/src-tauri/src/recording.rs b/apps/desktop/src-tauri/src/recording.rs
index d2077f5e0..2ba78b137 100644
--- a/apps/desktop/src-tauri/src/recording.rs
+++ b/apps/desktop/src-tauri/src/recording.rs
@@ -1,5 +1,6 @@
use anyhow::anyhow;
use cap_fail::fail;
+use cap_media_info::ffmpeg_sample_format_for;
use cap_project::CursorMoveEvent;
use cap_project::cursor::SHORT_CURSOR_SHAPE_DEBOUNCE_MS;
use cap_project::{
@@ -27,6 +28,7 @@ use cap_recording::{
};
use cap_rendering::ProjectRecordingsMeta;
use cap_utils::{ensure_dir, moment_format_to_chrono, spawn_actor};
+use cpal::traits::DeviceTrait;
use futures::{FutureExt, stream};
use lazy_static::lazy_static;
use regex::Regex;
@@ -37,7 +39,7 @@ use std::borrow::Cow;
use std::error::Error as StdError;
use std::{
any::Any,
- collections::{HashMap, VecDeque},
+ collections::{BTreeSet, HashMap, VecDeque},
panic::AssertUnwindSafe,
path::{Path, PathBuf},
str::FromStr,
@@ -401,6 +403,14 @@ pub struct MicrophoneInfo {
pub name: String,
pub sample_rate: u32,
pub channels: u16,
+ pub formats: Vec<MicrophoneFormatInfo>,
+}
+
+#[derive(Debug, Clone, serde::Serialize, specta::Type)]
+#[serde(rename_all = "camelCase")]
+pub struct MicrophoneFormatInfo {
+ pub sample_rate: u32,
+ pub channels: u16,
}
#[tauri::command(async)]
@@ -416,11 +426,50 @@ pub fn get_microphone_info(name: String) -> Option<MicrophoneInfo> {
microphone::MicrophoneFeed::list()
.into_iter()
.find(|(n, _)| *n == name)
- .map(|(name, (_device, config))| MicrophoneInfo {
- name,
- sample_rate: config.sample_rate().0,
- channels: config.channels(),
+ .map(|(name, (device, config))| {
+ let formats = microphone_format_infos(&device);
+ MicrophoneInfo {
+ name,
+ sample_rate: config.sample_rate().0,
+ channels: config.channels(),
+ formats,
+ }
+ })
+}
+
+fn microphone_format_infos(device: &cpal::Device) -> Vec<MicrophoneFormatInfo> {
+ let Ok(configs) = device.supported_input_configs() else {
+ return vec![];
+ };
+ let mut formats = BTreeSet::new();
+
+ for config in configs {
+ if 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 <= sample_rate
+ && sample_rate <= config.max_sample_rate().0
+ {
+ formats.insert((sample_rate, config.channels()));
+ }
+ }
+ }
+
+ formats
+ .into_iter()
+ .map(|(sample_rate, channels)| MicrophoneFormatInfo {
+ sample_rate,
+ channels,
})
+ .collect()
}
#[tauri::command]
@@ -851,9 +900,19 @@ pub async fn start_recording(
use kameo::error::SendError;
// Initialize camera if selected but not active
- let (camera_feed_actor, selected_camera_id) = {
+ let (camera_feed_actor, selected_camera_id, selected_camera_settings) = {
let state = state_mtx.read().await;
- (state.camera_feed.clone(), state.selected_camera_id.clone())
+ let selected_camera_settings = state.selected_camera_id.as_ref().and_then(|id| {
+ crate::recording_settings::RecordingSettingsStore::camera_settings_for(
+ &state.handle,
+ id,
+ )
+ });
+ (
+ state.camera_feed.clone(),
+ state.selected_camera_id.clone(),
+ selected_camera_settings,
+ )
};
let camera_lock_result = camera_feed_actor.ask(camera::Lock).await;
@@ -867,7 +926,10 @@ pub async fn start_recording(
id
);
match camera_feed_actor
- .ask(camera::SetInput { id: id.clone() })
+ .ask(camera::SetInput {
+ id: id.clone(),
+ settings: selected_camera_settings,
+ })
.await
{
Ok(fut) => match fut.await {
diff --git a/apps/desktop/src-tauri/src/windows.rs b/apps/desktop/src-tauri/src/windows.rs
index ebd167ddb..a2e98d815 100644
--- a/apps/desktop/src-tauri/src/windows.rs
+++ b/apps/desktop/src-tauri/src/windows.rs
@@ -121,9 +121,13 @@ async fn ensure_camera_input_active(app_state: &mut App) {
if let Some(id) = app_state.selected_camera_id.clone()
&& !app_state.camera_in_use
{
+ let settings = crate::recording_settings::RecordingSettingsStore::camera_settings_for(
+ &app_state.handle,
+ &id,
+ );
match app_state
.camera_feed
- .ask(feeds::camera::SetInput { id })
+ .ask(feeds::camera::SetInput { id, settings })
.await
{
Ok(ready_future) => {
@@ -180,6 +184,8 @@ async fn restore_main_window_inputs(app: &AppHandle) {
if let Some(camera_id) = camera_to_restore {
let state = app.state::<ArcLock<App>>();
+ let settings =
+ crate::recording_settings::RecordingSettingsStore::camera_settings_for(app, &camera_id);
let (camera_feed, camera_ws_sender, native_sender) = {
let app_state = &mut *state.write().await;
@@ -212,6 +218,7 @@ async fn restore_main_window_inputs(app: &AppHandle) {
let request = camera_feed
.ask(feeds::camera::SetInput {
id: camera_id.clone(),
+ settings,
})
.await
.map_err(|e| e.to_string());
diff --git a/apps/desktop/src/utils/devices.ts b/apps/desktop/src/utils/devices.ts
index d66686bb2..52c030916 100644
--- a/apps/desktop/src/utils/devices.ts
+++ b/apps/desktop/src/utils/devices.ts
@@ -191,13 +191,10 @@ export function createStableDevicesQuery(
commands.getMicrophoneInfo(name).then((info) => {
pendingMicFetches.delete(name);
if (info) {
- const extendedInfo = info as typeof info & {
- formats?: MicrophoneFormatInfo[];
- };
const details = {
sampleRate: info.sampleRate,
channels: info.channels,
- formats: extendedInfo.formats,
+ formats: info.formats,
};
micDetailsCache[name] = details;
setMicrophones(
diff --git a/crates/recording/src/feeds/microphone.rs b/crates/recording/src/feeds/microphone.rs
index adb306499..438dba684 100644
--- a/crates/recording/src/feeds/microphone.rs
+++ b/crates/recording/src/feeds/microphone.rs
@@ -412,19 +412,29 @@ fn select_preferred_config(
settings: &MicrophoneDeviceSettings,
) -> Option<SupportedStreamConfig> {
let rate = settings.sample_rate.map(cpal::SampleRate);
-
- configs
+ let compatible_configs = configs
.iter()
- .find(|config| {
- ffmpeg_sample_format_for(config.sample_format()).is_some()
- && settings
- .channels
- .is_none_or(|channels| config.channels() == channels)
+ .filter(|config| ffmpeg_sample_format_for(config.sample_format()).is_some())
+ .collect::<Vec<_>>();
+
+ let find_config = |channels: Option<u16>, rate: Option<cpal::SampleRate>| {
+ compatible_configs.iter().find(|config| {
+ channels.is_none_or(|channels| config.channels() == channels)
&& rate.is_none_or(|rate| {
config.min_sample_rate().0 <= rate.0 && config.max_sample_rate().0 >= rate.0
})
})
- .map(|config| config.with_sample_rate(rate.unwrap_or_else(|| select_sample_rate(config))))
+ };
+
+ let config = find_config(settings.channels, rate)
+ .or_else(|| rate.and_then(|rate| find_config(None, Some(rate))))
+ .or_else(|| {
+ settings
+ .channels
+ .and_then(|channels| find_config(Some(channels), None))
+ })?;
+
+ Some(config.with_sample_rate(rate.unwrap_or_else(|| select_sample_rate(config))))
}
fn select_sample_rate(config: &SupportedStreamConfigRange) -> cpal::SampleRate {
diff --git a/crates/recording/src/output_pipeline/core.rs b/crates/recording/src/output_pipeline/core.rs
index 36b97f605..c88e8398e 100644
--- a/crates/recording/src/output_pipeline/core.rs
+++ b/crates/recording/src/output_pipeline/core.rs
@@ -1716,7 +1716,7 @@ fn resolve_pipeline_completion(
) -> anyhow::Result<()> {
match (task_result, muxer_result) {
(Err(error), _) | (_, Err(error)) => Err(error),
- (_, Ok(Ok(()))) if stop_signal.user_stopped() => Err(anyhow!(PipelineStoppedByUser)),
+ (_, Ok(Ok(()))) if stop_signal.user_stopped() => Ok(()),
(_, Ok(Ok(()))) => Ok(()),
(_, Ok(Err(error))) => Err(anyhow!("Muxer finish failed: {error:#}")),
}
@@ -3365,14 +3365,12 @@ mod tests {
}
#[test]
- fn surfaces_user_stop_after_clean_finish() {
+ fn treats_user_stop_after_clean_finish_as_success() {
let signal = PipelineStopSignal::default();
signal.mark_user_stopped();
- let error = resolve_pipeline_completion(Ok(()), Ok(Ok(())), &signal)
- .expect_err("user stop should surface as a typed pipeline completion");
-
- assert!(error.is::<PipelineStoppedByUser>());
+ resolve_pipeline_completion(Ok(()), Ok(Ok(())), &signal)
+ .expect("user stop should complete cleanly after successful finish");
}
}
diff --git a/crates/recording/src/sources/microphone.rs b/crates/recording/src/sources/microphone.rs
index 81d0bdf62..90332aeff 100644
--- a/crates/recording/src/sources/microphone.rs
+++ b/crates/recording/src/sources/microphone.rs
@@ -157,6 +157,10 @@ impl AudioSource for Microphone {
.with_channels(MICROPHONE_TARGET_CHANNELS as usize);
let is_wireless = source_info.is_wireless_transport;
let device_name = feed_lock.device_name().to_string();
+ let reconnect_settings = microphone::MicrophoneDeviceSettings {
+ sample_rate: Some(source_info.sample_rate),
+ channels: u16::try_from(source_info.channels).ok(),
+ };
let cancel = CancellationToken::new();
let (tx, rx) = flume::bounded(128);
@@ -365,7 +369,7 @@ impl AudioSource for Microphone {
let ready = match feed
.ask(microphone::SetInput {
label: name,
- settings: None,
+ settings: Some(reconnect_settings),
})
.await
{