Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

Refactor microphone stream spawning logic

Richie McIlroy89db344290e0
diff --git a/crates/recording/src/feeds/microphone.rs b/crates/recording/src/feeds/microphone.rs
index 4700fa162..98d0e07ea 100644
--- a/crates/recording/src/feeds/microphone.rs
+++ b/crates/recording/src/feeds/microphone.rs
@@ -125,6 +125,139 @@ impl MicrophoneFeed {
device_map
}
+
+ fn spawn_input_stream(
+ params: StreamSpawnParams,
+ ) -> (
+ BoxFuture<'static, Result<(SupportedStreamConfig, Option<u32>), SetInputError>>,
+ SyncSender<()>,
+ ) {
+ let StreamSpawnParams {
+ id,
+ label,
+ device,
+ config,
+ stream_config,
+ buffer_size_frames,
+ sample_format,
+ actor_ref,
+ error_sender,
+ log_action,
+ } = params;
+
+ let (ready_tx, ready_rx) = oneshot::channel::<Result<Option<u32>, SetInputError>>();
+ let (done_tx, done_rx) = mpsc::sync_channel(0);
+
+ let ready = {
+ let config_for_ready = config.clone();
+ ready_rx
+ .map(move |v| {
+ let config = config_for_ready.clone();
+ v.map_err(|_| SetInputError::BuildStreamCrashed)
+ .and_then(|inner| inner)
+ .map(|buffer_size| (config, buffer_size))
+ })
+ .boxed()
+ };
+
+ std::thread::spawn({
+ let stream_config = stream_config.clone();
+ let config = config.clone();
+ let actor_ref = actor_ref.clone();
+ let error_sender = error_sender.clone();
+ move || {
+ let device_name_for_log = device.name().ok();
+
+ if let Some(ref name) = device_name_for_log {
+ info!("Device '{}' available configs:", name);
+ for config in device.supported_input_configs().into_iter().flatten() {
+ info!(
+ " Format: {:?}, Min rate: {}, Max rate: {}, Sample size: {}",
+ config.sample_format(),
+ config.min_sample_rate().0,
+ config.max_sample_rate().0,
+ config.sample_format().sample_size()
+ );
+ }
+ }
+
+ let buffer_size_description = match &stream_config.buffer_size {
+ BufferSize::Default => "default".to_string(),
+ BufferSize::Fixed(frames) => format!(
+ "{} frames (~{:.1}ms)",
+ frames,
+ (*frames as f64 / config.sample_rate().0 as f64) * 1000.0
+ ),
+ };
+
+ info!(
+ "🎀 {} stream (id {}, label '{}') for '{:?}' with config: rate={}, channels={}, format={:?}, buffer_size={}",
+ log_action.verb(),
+ id,
+ label,
+ device_name_for_log,
+ config.sample_rate().0,
+ config.channels(),
+ sample_format,
+ buffer_size_description
+ );
+
+ let stream = match device.build_input_stream_raw(
+ &stream_config,
+ sample_format,
+ {
+ let actor_ref = actor_ref.clone();
+ let mut callback_count = 0u64;
+ move |data, info| {
+ if callback_count == 0 {
+ info!(
+ "🎀 First audio callback - data size: {} bytes, format: {:?}",
+ data.bytes().len(),
+ data.sample_format()
+ );
+ }
+ callback_count += 1;
+
+ let _ = actor_ref
+ .tell(MicrophoneSamples {
+ data: data.bytes().to_vec(),
+ format: data.sample_format(),
+ info: info.clone(),
+ timestamp: Timestamp::from_cpal(info.timestamp().capture),
+ })
+ .try_send();
+ }
+ },
+ move |e| {
+ error!("Microphone stream error: {e}");
+
+ let _ = error_sender.send(e).is_err();
+ },
+ None,
+ ) {
+ Ok(stream) => stream,
+ Err(e) => {
+ let _ = ready_tx.send(Err(SetInputError::BuildStream(e.to_string())));
+ return;
+ }
+ };
+
+ if let Err(e) = stream.play() {
+ let _ = ready_tx.send(Err(SetInputError::PlayStream(e.to_string())));
+ return;
+ }
+
+ let _ = ready_tx.send(Ok(buffer_size_frames));
+
+ match done_rx.recv() {
+ Ok(_) => info!("Microphone actor shut down, ending stream"),
+ Err(_) => info!("Microphone actor unreachable, ending stream"),
+ }
+ }
+ });
+
+ (ready, done_tx)
+ }
}
fn get_usable_device(device: Device) -> Option<(String, Device, SupportedStreamConfig)> {
@@ -302,6 +435,34 @@ struct InputConnectFailed {
struct Unlock;
+#[derive(Clone, Copy)]
+enum StreamLogAction {
+ Build,
+ Rebuild,
+}
+
+impl StreamLogAction {
+ fn verb(&self) -> &'static str {
+ match self {
+ Self::Build => "Building",
+ Self::Rebuild => "Rebuilding",
+ }
+ }
+}
+
+struct StreamSpawnParams {
+ id: u32,
+ label: String,
+ device: Device,
+ config: SupportedStreamConfig,
+ stream_config: cpal::StreamConfig,
+ buffer_size_frames: Option<u32>,
+ sample_format: SampleFormat,
+ actor_ref: ActorRef<MicrophoneFeed>,
+ error_sender: flume::Sender<StreamError>,
+ log_action: StreamLogAction,
+}
+
// Impls
#[derive(Debug, Clone, Copy, thiserror::Error)]
@@ -343,22 +504,20 @@ impl Message<SetInput> for MicrophoneFeed {
let sample_format = config.sample_format();
let (stream_config, buffer_size_frames) = stream_config_with_latency(&config);
- let (ready_tx, ready_rx) = oneshot::channel::<Result<Option<u32>, SetInputError>>();
- let (done_tx, done_rx) = mpsc::sync_channel(0);
-
let actor_ref = ctx.actor_ref();
- let ready = {
- let config_for_ready = config.clone();
- ready_rx
- .map(move |v| {
- let config = config_for_ready.clone();
- v.map_err(|_| SetInputError::BuildStreamCrashed)
- .and_then(|inner| inner)
- .map(|buffer_size| (config, buffer_size))
- })
- .shared()
- };
- let error_sender = self.error_sender.clone();
+ let (ready_future, done_tx) = Self::spawn_input_stream(StreamSpawnParams {
+ id,
+ label: label.clone(),
+ device,
+ config,
+ stream_config,
+ buffer_size_frames,
+ sample_format,
+ actor_ref: actor_ref.clone(),
+ error_sender: self.error_sender.clone(),
+ log_action: StreamLogAction::Build,
+ });
+ let ready = ready_future.shared();
state.connecting = Some(ConnectingState {
id,
@@ -383,100 +542,10 @@ impl Message<SetInput> for MicrophoneFeed {
},
});
- std::thread::spawn({
- let config = config.clone();
- let stream_config = stream_config.clone();
- let device_name_for_log = device.name().ok();
- move || {
- if let Some(ref name) = device_name_for_log {
- info!("Device '{}' available configs:", name);
- for config in device.supported_input_configs().into_iter().flatten() {
- info!(
- " Format: {:?}, Min rate: {}, Max rate: {}, Sample size: {}",
- config.sample_format(),
- config.min_sample_rate().0,
- config.max_sample_rate().0,
- config.sample_format().sample_size()
- );
- }
- }
-
- let buffer_size_description = match &stream_config.buffer_size {
- BufferSize::Default => "default".to_string(),
- BufferSize::Fixed(frames) => format!(
- "{} frames (~{:.1}ms)",
- frames,
- (*frames as f64 / config.sample_rate().0 as f64) * 1000.0
- ),
- };
-
- info!(
- "🎀 Building stream for '{:?}' with config: rate={}, channels={}, format={:?}, buffer_size={}",
- device_name_for_log,
- config.sample_rate().0,
- config.channels(),
- sample_format,
- buffer_size_description
- );
-
- let stream = match device.build_input_stream_raw(
- &stream_config,
- sample_format,
- {
- let actor_ref = actor_ref.clone();
- let mut callback_count = 0u64;
- move |data, info| {
- if callback_count == 0 {
- info!(
- "🎀 First audio callback - data size: {} bytes, format: {:?}",
- data.bytes().len(),
- data.sample_format()
- );
- }
- callback_count += 1;
-
- let _ = actor_ref
- .tell(MicrophoneSamples {
- data: data.bytes().to_vec(),
- format: data.sample_format(),
- info: info.clone(),
- timestamp: Timestamp::from_cpal(info.timestamp().capture),
- })
- .try_send();
- }
- },
- move |e| {
- error!("Microphone stream error: {e}");
-
- let _ = error_sender.send(e).is_err();
- },
- None,
- ) {
- Ok(stream) => stream,
- Err(e) => {
- let _ = ready_tx.send(Err(SetInputError::BuildStream(e.to_string())));
- return;
- }
- };
-
- if let Err(e) = stream.play() {
- let _ = ready_tx.send(Err(SetInputError::PlayStream(e.to_string())));
- return;
- }
-
- let _ = ready_tx.send(Ok(buffer_size_frames));
-
- match done_rx.recv() {
- Ok(_) => info!("Microphone actor shut down, ending stream"),
- Err(_) => info!("Microphone actor unreachable, ending stream"),
- }
- }
- });
-
tokio::spawn({
let ready = ready.clone();
- let actor = ctx.actor_ref();
- let done_tx = done_tx;
+ let actor = actor_ref.clone();
+ let done_tx = done_tx.clone();
let label = label.clone();
async move {
match ready.await {
@@ -498,9 +567,12 @@ impl Message<SetInput> for MicrophoneFeed {
}
});
- let ready_for_return = ready.clone().map(|result| result.map(|(config, _)| config));
+ let ready_for_return = ready
+ .clone()
+ .map(|result| result.map(|(config, _)| config))
+ .boxed();
- Ok(ready_for_return.boxed())
+ Ok(ready_for_return)
}
State::Locked { inner } => {
if inner.label != msg.label {
@@ -515,120 +587,29 @@ impl Message<SetInput> for MicrophoneFeed {
let sample_format = config.sample_format();
let (stream_config, buffer_size_frames) = stream_config_with_latency(&config);
- let (ready_tx, ready_rx) = oneshot::channel::<Result<Option<u32>, SetInputError>>();
- let (done_tx, done_rx) = mpsc::sync_channel(0);
-
- let actor_ref = ctx.actor_ref();
- let ready = {
- let config_for_ready = config.clone();
- ready_rx
- .map(move |v| {
- let config = config_for_ready.clone();
- v.map_err(|_| SetInputError::BuildStreamCrashed)
- .and_then(|inner| inner)
- .map(|buffer_size| (config, buffer_size))
- })
- .shared()
- };
- let error_sender = self.error_sender.clone();
-
let new_id = self.input_id_counter;
self.input_id_counter += 1;
let _ = inner.done_tx.send(());
- std::thread::spawn({
- let config = config.clone();
- let stream_config = stream_config.clone();
- let device_name_for_log = device.name().ok();
- move || {
- if let Some(ref name) = device_name_for_log {
- info!("Device '{}' available configs:", name);
- for config in device.supported_input_configs().into_iter().flatten() {
- info!(
- " Format: {:?}, Min rate: {}, Max rate: {}, Sample size: {}",
- config.sample_format(),
- config.min_sample_rate().0,
- config.max_sample_rate().0,
- config.sample_format().sample_size()
- );
- }
- }
-
- let buffer_size_description = match &stream_config.buffer_size {
- BufferSize::Default => "default".to_string(),
- BufferSize::Fixed(frames) => format!(
- "{} frames (~{:.1}ms)",
- frames,
- (*frames as f64 / config.sample_rate().0 as f64) * 1000.0
- ),
- };
-
- info!(
- "🎀 Rebuilding stream for '{:?}' with config: rate={}, channels={}, format={:?}, buffer_size={}",
- device_name_for_log,
- config.sample_rate().0,
- config.channels(),
- sample_format,
- buffer_size_description
- );
-
- let stream = match device.build_input_stream_raw(
- &stream_config,
- sample_format,
- {
- let actor_ref = actor_ref.clone();
- let mut callback_count = 0u64;
- move |data, info| {
- if callback_count == 0 {
- info!(
- "🎀 First audio callback - data size: {} bytes, format: {:?}",
- data.bytes().len(),
- data.sample_format()
- );
- }
- callback_count += 1;
-
- let _ = actor_ref
- .tell(MicrophoneSamples {
- data: data.bytes().to_vec(),
- format: data.sample_format(),
- info: info.clone(),
- timestamp: Timestamp::from_cpal(info.timestamp().capture),
- })
- .try_send();
- }
- },
- move |e| {
- error!("Microphone stream error: {e}");
- let _ = error_sender.send(e).is_err();
- },
- None,
- ) {
- Ok(stream) => stream,
- Err(e) => {
- let _ = ready_tx.send(Err(SetInputError::BuildStream(e.to_string())));
- return;
- }
- };
-
- if let Err(e) = stream.play() {
- let _ = ready_tx.send(Err(SetInputError::PlayStream(e.to_string())));
- return;
- }
-
- let _ = ready_tx.send(Ok(buffer_size_frames));
-
- match done_rx.recv() {
- Ok(_) => info!("Microphone actor shut down, ending stream"),
- Err(_) => info!("Microphone actor unreachable, ending stream"),
- }
- }
+ let actor_ref = ctx.actor_ref();
+ let (ready_future, done_tx) = Self::spawn_input_stream(StreamSpawnParams {
+ id: new_id,
+ label: label.clone(),
+ device,
+ config,
+ stream_config,
+ buffer_size_frames,
+ sample_format,
+ actor_ref: actor_ref.clone(),
+ error_sender: self.error_sender.clone(),
+ log_action: StreamLogAction::Rebuild,
});
+ let ready = ready_future.shared();
tokio::spawn({
let ready = ready.clone();
- let actor = ctx.actor_ref();
+ let actor = actor_ref;
let done_tx = done_tx.clone();
let label = label.clone();
async move {
@@ -646,9 +627,9 @@ impl Message<SetInput> for MicrophoneFeed {
}
});
- let ready_for_return = ready.clone().map(|result| result.map(|(config, _)| config));
+ let ready_for_return = ready.map(|result| result.map(|(config, _)| config)).boxed();
- Ok(ready_for_return.boxed())
+ Ok(ready_for_return)
}
}
}