Skip to content

armgit / Handy

Public Imported from GitHub
0

A free, open source, and extensible speech-to-text application that works completely offline.

fix: recover microphone stream after the capture worker dies (#1838)

asjad-vyroa4348beb18ab
diff --git a/src-tauri/src/audio_toolkit/audio/recorder.rs b/src-tauri/src/audio_toolkit/audio/recorder.rs
index 82297cb6..9077bf1c 100644
--- a/src-tauri/src/audio_toolkit/audio/recorder.rs
+++ b/src-tauri/src/audio_toolkit/audio/recorder.rs
@@ -138,7 +138,14 @@ impl AudioRecorder {
pub fn open(&mut self, device: Option<Device>) -> Result<(), Box<dyn std::error::Error>> {
if self.worker_handle.is_some() {
- return Ok(()); // already open
+ if !self.is_capture_worker_dead() {
+ return Ok(()); // already open
+ }
+ // The worker exited on its own (see `is_capture_worker_dead`). Reap
+ // it so we rebuild the stream below instead of handing the caller
+ // back a recorder whose channels are already closed.
+ log::warn!("Capture worker exited; rebuilding microphone stream");
+ let _ = self.close();
}
let (sample_tx, sample_rx) = mpsc::channel::<AudioChunk>();
@@ -331,6 +338,20 @@ impl AudioRecorder {
Ok(resp_rx.recv()?) // wait for the samples
}
+ /// True once the capture worker has exited without anyone calling `close`.
+ ///
+ /// `run_consumer` is driven entirely by the sample channel, so when cpal
+ /// tears the stream down mid-session (device unplugged, USB/Bluetooth
+ /// dropout) `sample_rx.recv()` returns `Err`, the loop ends and the worker
+ /// thread finishes. `cmd_tx` and `worker_handle` are still populated at
+ /// that point, so the recorder looks open from the outside while every
+ /// command sent to it fails on a closed channel.
+ pub fn is_capture_worker_dead(&self) -> bool {
+ self.worker_handle
+ .as_ref()
+ .is_some_and(|handle| handle.is_finished())
+ }
+
pub fn close(&mut self) -> Result<(), Box<dyn std::error::Error>> {
if let Some(tx) = self.cmd_tx.take() {
let _ = tx.send(Cmd::Shutdown);
@@ -472,7 +493,16 @@ pub fn is_no_input_device_error(error_message: &str) -> bool {
#[cfg(test)]
mod tests {
- use super::{is_microphone_access_denied, is_no_input_device_error};
+ use super::{is_microphone_access_denied, is_no_input_device_error, AudioRecorder};
+
+ #[test]
+ fn unopened_recorder_is_not_reported_dead() {
+ // No worker has been spawned yet, so there is nothing to reap. Guards
+ // against inverting the "no worker" case, which would make every first
+ // open() take the rebuild path.
+ let recorder = AudioRecorder::new().expect("recorder");
+ assert!(!recorder.is_capture_worker_dead());
+ }
#[test]
fn detects_access_is_denied() {
diff --git a/src-tauri/src/managers/audio.rs b/src-tauri/src/managers/audio.rs
index dc8ef9f1..ca599be0 100644
--- a/src-tauri/src/managers/audio.rs
+++ b/src-tauri/src/managers/audio.rs
@@ -10,7 +10,7 @@ use crate::helpers::clamshell;
use crate::managers::transcription::StreamRouter;
use crate::settings::{get_settings, AppSettings};
use crate::utils;
-use log::{debug, error, info, warn};
+use log::{debug, error, info, trace, warn};
use std::path::Path;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
@@ -518,8 +518,46 @@ impl AudioRecordingManager {
pub fn start_microphone_stream(&self) -> Result<(), anyhow::Error> {
let mut open_flag = self.is_open.lock().unwrap();
if *open_flag {
- debug!("Microphone stream already active");
- return Ok(());
+ // `is_open` only records that we opened a stream at some point, not
+ // that one is still running. If the capture worker has since exited
+ // (mic unplugged mid-session, USB dropout), returning Ok here hands
+ // the caller a dead recorder: it captures nothing, then fails in
+ // stop() on the closed channel, and stays wedged until the
+ // on-demand close timeout eventually resets the manager.
+ let worker_dead = self
+ .recorder
+ .lock()
+ .unwrap()
+ .as_ref()
+ .is_some_and(|rec| rec.is_capture_worker_dead());
+
+ if !worker_dead {
+ // trace, not debug: with the aliveness check in
+ // try_start_recording this now fires on every keypress in
+ // always-on mode.
+ trace!("Microphone stream already active");
+ return Ok(());
+ }
+
+ warn!("Microphone stream is no longer running (device disconnected?); reopening");
+
+ // Torn down inline rather than via stop_microphone_stream(), which
+ // takes the `is_open` lock we are already holding.
+ {
+ let mut mute_guard = self.mute_state.lock().unwrap();
+ if mute_guard.did_mute {
+ restore_mute(mute_guard.prev_muted);
+ mute_guard.did_mute = false;
+ }
+ }
+ if let Some(rec) = self.recorder.lock().unwrap().as_mut() {
+ // Skipping rec.stop() here: the worker is gone, so the command
+ // would only fail on the closed channel.
+ let _ = rec.close();
+ }
+ *self.is_recording.lock().unwrap() = false;
+ *open_flag = false;
+ // Fall through and open a fresh stream.
}
let start_time = Instant::now();
@@ -645,15 +683,18 @@ impl AudioRecordingManager {
let mut state = self.state.lock().unwrap();
if let RecordingState::Idle = *state {
- // Ensure microphone is open in on-demand mode
- if matches!(*self.mode.lock().unwrap(), MicrophoneMode::OnDemand) {
- // Cancel any pending lazy close
- self.close_generation.fetch_add(1, Ordering::SeqCst);
- if let Err(e) = self.start_microphone_stream() {
- let msg = format!("{e}");
- error!("Failed to open microphone stream: {msg}");
- return Err(msg);
- }
+ // Cancel any pending lazy close (no-op in always-on mode, where
+ // closes are never scheduled).
+ self.close_generation.fetch_add(1, Ordering::SeqCst);
+ // Opens the stream in on-demand mode. In always-on mode the stream
+ // is normally already open and this is a cheap aliveness check —
+ // but if the capture worker died (device disconnect), it rebuilds
+ // the stream instead of leaving every subsequent start wedged on
+ // "Recorder not available".
+ if let Err(e) = self.start_microphone_stream() {
+ let msg = format!("{e}");
+ error!("Failed to open microphone stream: {msg}");
+ return Err(msg);
}
if let Some(rec) = self.recorder.lock().unwrap().as_ref() {