Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

fix(voice): handle empty audio buffer in capture

Steven Enamakel722452f9a28c
diff --git a/crates/openhuman-core/src/voice/audio_capture.rs b/crates/openhuman-core/src/voice/audio_capture.rs
index b52e2f14e4..3542021eaa 100644
--- a/crates/openhuman-core/src/voice/audio_capture.rs
+++ b/crates/openhuman-core/src/voice/audio_capture.rs
@@ -76,20 +76,15 @@ impl RecordingHandle {
/// The capture error if the recording itself failed, or the module error if
/// the audio cannot be prepared. Both are strings the caller surfaces.
pub async fn stop(mut self, config: &Config) -> Result<RecordingResult, String> {
- self.stop_flag.store(true, Ordering::SeqCst);
- debug!("{LOG_PREFIX} stop signal sent");
-
#[cfg(test)]
if let Some(finalized) = self.finalized.take() {
return finalized;
}
- let raw = match self.result_rx.take() {
- Some(rx) => rx
- .await
- .map_err(|_| "recording task dropped before completing".to_string())??,
- None => return Err("recording already stopped".to_string()),
+ let Some(inner) = self.inner.take() else {
+ return Err("recording already stopped".to_string());
};
+ let raw = inner.stop().await?;
finalize(config, &raw).await
}
@@ -97,8 +92,7 @@ impl RecordingHandle {
#[cfg(test)]
pub(crate) fn from_test_result(result: Result<RecordingResult, String>) -> Self {
Self {
- stop_flag: Arc::new(AtomicBool::new(false)),
- result_rx: None,
+ inner: None,
finalized: Some(result),
}
}
@@ -165,3 +159,58 @@ async fn finalize(config: &Config, raw: &RawRecording) -> Result<RecordingResult
})
}
+/// Start recording from the default microphone.
+///
+/// Returns a `RecordingHandle` that must be `.stop().await`-ed to get
+/// the captured audio. Recording runs on a dedicated OS thread inside
+/// `tinyvoice::capture` because `cpal::Stream` is `!Send` (it must be created
+/// and dropped on the same thread).
+pub fn start_recording() -> Result<RecordingHandle, String> {
+ Ok(RecordingHandle {
+ inner: Some(tinyvoice::capture::start_recording(microphone_permission)?),
+ #[cfg(test)]
+ finalized: None,
+ })
+}
+
+/// List available input devices.
+pub fn list_input_devices() -> Result<Vec<String>, String> {
+ tinyvoice::capture::list_input_devices()
+}
+
+/// The host's microphone-permission policy for a one-shot recording.
+///
+/// Cross-platform pre-check: an undetermined state asks the OS for access (macOS
+/// may show a prompt) and re-checks; a denied state, or one still undetermined
+/// after asking, fails with the platform's explanation.
+fn microphone_permission() -> Result<(), String> {
+ use tinycomputer_accessibility::{
+ detect_microphone_permission, microphone_denied_message, request_microphone_access,
+ PermissionState,
+ };
+
+ let mic_perm = detect_microphone_permission();
+ debug!("{LOG_PREFIX} microphone permission state: {mic_perm:?}");
+
+ match mic_perm {
+ PermissionState::Unknown => {
+ info!("{LOG_PREFIX} microphone permission not yet determined — requesting access");
+ request_microphone_access();
+ // Re-check after request (macOS may have shown a prompt).
+ let updated = detect_microphone_permission();
+ debug!("{LOG_PREFIX} microphone permission after request: {updated:?}");
+ if matches!(updated, PermissionState::Denied | PermissionState::Unknown) {
+ let msg = microphone_denied_message();
+ warn!("{LOG_PREFIX} {msg}");
+ return Err(msg);
+ }
+ }
+ PermissionState::Denied => {
+ let msg = microphone_denied_message();
+ warn!("{LOG_PREFIX} {msg}");
+ return Err(msg);
+ }
+ _ => {} // Granted or Unsupported — proceed normally.
+ }
+ Ok(())
+}
diff --git a/crates/openhuman-core/src/voice/audio_capture_tests.rs b/crates/openhuman-core/src/voice/audio_capture_tests.rs
deleted file mode 100644
index 2a32c2a5e9..0000000000
--- a/crates/openhuman-core/src/voice/audio_capture_tests.rs
+++ /dev/null
@@ -1,102 +0,0 @@
-//! Tests for the capture thread.
-//!
-//! The signal processing that used to live here — downmix, resample, RMS, the
-//! silence gate, WAV framing — moved to `tinyvoice`, which carries its unit
-//! tests. What is left is the part that is genuinely this file's: converting
-//! the device's sample format, which happens in the audio callback and is the
-//! one transform that cannot move.
-
-use super::*;
-use cpal::{SampleFormat, SampleRate, SupportedBufferSize, SupportedStreamConfigRange};
-
-#[test]
-fn i16_to_f32_normalises_to_unit_range() {
- assert_eq!(i16_to_f32(&[0]), vec![0.0]);
- assert_eq!(i16_to_f32(&[16384]), vec![0.5]);
- assert_eq!(i16_to_f32(&[-32768]), vec![-1.0]);
- // Interleaved frames are converted element-wise, order preserved.
- assert_eq!(i16_to_f32(&[0, 16384, -16384]), vec![0.0, 0.5, -0.5]);
-}
-
-#[test]
-fn u16_to_f32_centers_on_midscale() {
- // Unsigned PCM is offset-binary: 32768 is silence (0.0), the endpoints map
- // to the extremes. This is the conversion the fallback path was missing.
- assert_eq!(u16_to_f32(&[32768]), vec![0.0]);
- assert_eq!(u16_to_f32(&[49152]), vec![0.5]);
- assert_eq!(u16_to_f32(&[0]), vec![-1.0]);
- assert_eq!(u16_to_f32(&[32768, 49152, 16384]), vec![0.0, 0.5, -0.5]);
-}
-
-#[test]
-fn find_best_config_prefers_target_rate_and_fewer_channels() {
- let configs = vec![
- SupportedStreamConfigRange::new(
- 2,
- SampleRate(8_000),
- SampleRate(48_000),
- SupportedBufferSize::Unknown,
- SampleFormat::F32,
- ),
- SupportedStreamConfigRange::new(
- 1,
- SampleRate(16_000),
- SampleRate(16_000),
- SupportedBufferSize::Unknown,
- SampleFormat::I16,
- ),
- ];
-
- let best = find_best_config(configs.into_iter()).expect("best config");
- assert_eq!(best.channels(), 1);
- assert_eq!(best.sample_rate(), SampleRate(TARGET_SAMPLE_RATE));
- assert_eq!(best.sample_format(), SampleFormat::I16);
-}
-
-#[test]
-fn find_best_config_falls_back_to_max_rate_when_target_missing() {
- let configs = vec![SupportedStreamConfigRange::new(
- 1,
- SampleRate(22_050),
- SampleRate(44_100),
- SupportedBufferSize::Unknown,
- SampleFormat::F32,
- )];
-
- let best = find_best_config(configs.into_iter()).expect("best config");
- assert_eq!(best.sample_rate(), SampleRate(44_100));
-}
-
-#[test]
-fn find_best_config_errors_when_empty() {
- let err = find_best_config(Vec::<SupportedStreamConfigRange>::new().into_iter())
- .expect_err("empty config list should fail");
- assert!(err.contains("no supported audio input configurations"));
-}
-
-#[test]
-fn append_capped_bounds_the_raw_buffer() {
- // The silence gate used to run inside the capture callback and drop
- // sustained silence, so an idle microphone cost almost nothing. It gates at
- // finalize now, which is too late to bound what the callback collected — so
- // the cap is what stops a recording that is started and never stopped from
- // growing without limit.
- let buffer = parking_lot::Mutex::new(Vec::new());
-
- // Fill to just under the cap.
- let chunk = vec![0.5f32; 4096];
- while buffer.lock().len() + chunk.len() <= MAX_RAW_SAMPLES {
- append_capped(&buffer, &chunk);
- }
- let before = buffer.lock().len();
- assert!(before > 0);
-
- // The chunk that crosses the line is truncated, not dropped whole: a
- // recording that hits the cap keeps its first five minutes.
- append_capped(&buffer, &vec![0.5f32; MAX_RAW_SAMPLES]);
- assert_eq!(buffer.lock().len(), MAX_RAW_SAMPLES);
-
- // Past the cap, further chunks are ignored rather than reallocating.
- append_capped(&buffer, &chunk);
- assert_eq!(buffer.lock().len(), MAX_RAW_SAMPLES);
-}