Skip to content

A personal assistant that lives on your desktop, remembers what matters, and can use your Mac for you.

TypeScript

fix(desktop): capture in the device's own format, and test the shared capture thread everywhere

Marcelitoa223f9111d22
diff --git a/apps/desktop/src-tauri/src/voice/capture_thread.rs b/apps/desktop/src-tauri/src/voice/capture_thread.rs
new file mode 100644
index 0000000..5e098be
--- /dev/null
+++ b/apps/desktop/src-tauri/src/voice/capture_thread.rs
@@ -0,0 +1,231 @@
+//! A capture that runs on a thread of its own and polls the device for packets: starting it
+//! with a bounded wait, delivering until a close, and closing it. Nothing here touches a device,
+//! so it is compiled on every platform and its tests run on all of them; the Windows
+//! microphone (`wasapi`) is what uses it.
+
+use super::{Stream, VoiceError};
+use std::sync::atomic::{AtomicBool, Ordering};
+use std::sync::{mpsc, Arc};
+use std::thread::JoinHandle;
+use std::time::Duration;
+
+/// Where the capture thread says whether the device started.
+pub(crate) type Ready = mpsc::Sender<Result<(), VoiceError>>;
+
+pub(crate) fn failed_to_start(error: impl std::fmt::Display) -> VoiceError {
+ VoiceError::Failed(format!("The microphone could not start: {error}"))
+}
+
+/// Runs `run` on the capture thread and waits up to `wait` for it to say whether the device
+/// started. The device can block inside activation or start indefinitely (Windows does), so a
+/// timeout does not wait for the thread: it closes the stream and stops listening, and the
+/// thread, once the device returns, finds nobody waiting, stops the device, and ends without
+/// capturing.
+pub(crate) fn launch(
+ run: impl FnOnce(Arc<AtomicBool>, Ready) + Send + 'static,
+ wait: Duration,
+) -> Result<CaptureStream, VoiceError> {
+ let closed = Arc::new(AtomicBool::new(false));
+ let (ready, started) = mpsc::channel();
+ let flag = closed.clone();
+ let thread = std::thread::Builder::new()
+ .name("voice-capture".into())
+ .spawn(move || run(flag, ready))
+ .map_err(failed_to_start)?;
+ let mut stream = CaptureStream { closed, thread: Some(thread) };
+ match started.recv_timeout(wait) {
+ Ok(Ok(())) => Ok(stream),
+ Ok(Err(error)) => {
+ stream.close();
+ Err(error)
+ }
+ Err(_) => {
+ stream.closed.store(true, Ordering::SeqCst);
+ drop(stream.thread.take());
+ drop(started);
+ Err(failed_to_start("the audio device did not answer"))
+ }
+ }
+}
+
+/// Delivers waiting packets, then sleeps a poll, until the stream is closed. The flag is checked
+/// before every packet, so a device that always has another one ready cannot keep the capture
+/// going after a close.
+pub(crate) fn pump<E>(
+ mut waiting: impl FnMut() -> Result<u32, E>,
+ mut read: impl FnMut() -> Result<Vec<f32>, E>,
+ closed: &AtomicBool,
+ mut deliver: impl FnMut(&[f32]),
+ poll: Duration,
+) -> Result<(), E> {
+ while !closed.load(Ordering::SeqCst) {
+ while !closed.load(Ordering::SeqCst) && waiting()? > 0 {
+ let samples = read()?;
+ if !samples.is_empty() {
+ deliver(&samples);
+ }
+ }
+ std::thread::sleep(poll);
+ }
+ Ok(())
+}
+
+/// The open capture: closing it raises the flag the thread polls and waits for the thread.
+pub(crate) struct CaptureStream {
+ closed: Arc<AtomicBool>,
+ thread: Option<JoinHandle<()>>,
+}
+
+impl Stream for CaptureStream {
+ fn close(&mut self) {
+ self.closed.store(true, Ordering::SeqCst);
+ if let Some(thread) = self.thread.take() {
+ // A failure reported from the capture thread closes the stream on that same thread
+ // (the machine discards the recording there); it is already on its way out.
+ if thread.thread().id() != std::thread::current().id() {
+ let _ = thread.join();
+ }
+ }
+ }
+}
+
+impl Drop for CaptureStream {
+ fn drop(&mut self) {
+ self.close();
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::time::Instant;
+
+ #[test]
+ fn a_close_ends_capture_even_while_packets_keep_arriving() {
+ let closed = Arc::new(AtomicBool::new(false));
+ let delivered = Arc::new(std::sync::atomic::AtomicUsize::new(0));
+ let (done, finished) = mpsc::channel();
+ let (flag, count) = (closed.clone(), delivered.clone());
+ std::thread::spawn(move || {
+ // Another packet is always ready, as when delivery keeps up with the device only just.
+ let result = pump(
+ || Ok::<u32, ()>(1),
+ || Ok(vec![0.25; 160]),
+ &flag,
+ |_| {
+ count.fetch_add(1, Ordering::SeqCst);
+ },
+ Duration::from_millis(1),
+ );
+ let _ = done.send(result);
+ });
+ let deadline = Instant::now() + Duration::from_secs(2);
+ while delivered.load(Ordering::SeqCst) < 10 {
+ assert!(Instant::now() < deadline, "packets flow");
+ std::thread::yield_now();
+ }
+ closed.store(true, Ordering::SeqCst);
+ assert_eq!(finished.recv_timeout(Duration::from_secs(2)), Ok(Ok(())), "the close ends the capture");
+ let after = delivered.load(Ordering::SeqCst);
+ std::thread::sleep(Duration::from_millis(20));
+ assert_eq!(delivered.load(Ordering::SeqCst), after, "nothing is delivered once the capture ended");
+ }
+
+ #[test]
+ fn a_device_that_never_answers_times_out_without_waiting_for_the_device() {
+ let (outcome, observed) = mpsc::channel();
+ let started = Instant::now();
+ let result = launch(
+ move |closed, ready| {
+ // The device is still activating when the wait runs out.
+ std::thread::sleep(Duration::from_millis(600));
+ let nobody_waiting = ready.send(Ok(())).is_err();
+ let _ = outcome.send((nobody_waiting, closed.load(Ordering::SeqCst)));
+ },
+ Duration::from_millis(50),
+ );
+ assert!(started.elapsed() < Duration::from_millis(400), "the timeout does not wait for the device");
+ assert_eq!(
+ result.err(),
+ Some(VoiceError::Failed("The microphone could not start: the audio device did not answer".into()))
+ );
+ assert_eq!(
+ observed.recv_timeout(Duration::from_secs(3)),
+ Ok((true, true)),
+ "the late thread finds nobody waiting and the stream closed, so it stops the device without capturing"
+ );
+ }
+
+ #[test]
+ fn a_start_failure_is_returned_once_the_thread_ended() {
+ let ended = Arc::new(AtomicBool::new(false));
+ let flag = ended.clone();
+ let result = launch(
+ move |_, ready| {
+ let _ = ready.send(Err(VoiceError::NoMicrophone));
+ std::thread::sleep(Duration::from_millis(50));
+ flag.store(true, Ordering::SeqCst);
+ },
+ Duration::from_secs(2),
+ );
+ assert_eq!(result.err(), Some(VoiceError::NoMicrophone));
+ assert!(ended.load(Ordering::SeqCst), "open waits for the failed capture thread to end");
+ }
+
+ #[test]
+ fn closing_or_dropping_waits_for_the_capture_thread_and_closing_twice_is_harmless() {
+ for drop_it in [false, true] {
+ let ended = Arc::new(AtomicBool::new(false));
+ let flag = ended.clone();
+ let mut stream = launch(
+ move |closed, ready| {
+ let _ = ready.send(Ok(()));
+ while !closed.load(Ordering::SeqCst) {
+ std::thread::sleep(Duration::from_millis(5));
+ }
+ std::thread::sleep(Duration::from_millis(30));
+ flag.store(true, Ordering::SeqCst);
+ },
+ Duration::from_secs(2),
+ )
+ .unwrap();
+ if drop_it {
+ drop(stream);
+ } else {
+ stream.close();
+ stream.close();
+ }
+ assert!(ended.load(Ordering::SeqCst), "drop={drop_it}: the thread ended before close returned");
+ }
+ }
+
+ /// A device failure while recording reports `Sink::failed` on the capture thread, and the
+ /// machine discards the recording there, closing the stream from inside the thread it joins.
+ #[test]
+ fn a_close_from_the_capture_thread_itself_ends_it_without_blocking() {
+ let (hand_over, stream_arrives) = mpsc::channel::<CaptureStream>();
+ let (closed_itself, observed) = mpsc::channel();
+ let stream = launch(
+ move |closed, ready| {
+ let _ = ready.send(Ok(()));
+ let Ok(mut stream) = stream_arrives.recv() else { return };
+ stream.close();
+ let _ = closed_itself.send(closed.load(Ordering::SeqCst));
+ drop(stream);
+ let _ = closed_itself.send(true);
+ },
+ Duration::from_secs(2),
+ )
+ .unwrap();
+ hand_over.send(stream).unwrap();
+ // Bounded, so a self-join fails the test instead of hanging the suite.
+ let wait = Duration::from_secs(2);
+ assert_eq!(observed.recv_timeout(wait), Ok(true), "close returned on the capture thread with the flag raised");
+ assert_eq!(observed.recv_timeout(wait), Ok(true), "dropping the closed stream there is harmless too");
+ assert_eq!(
+ observed.recv_timeout(wait),
+ Err(mpsc::RecvTimeoutError::Disconnected),
+ "the capture thread ended"
+ );
+ }
+}
diff --git a/apps/desktop/src-tauri/src/voice/engine.rs b/apps/desktop/src-tauri/src/voice/engine.rs
index 509ac10..d6b6bce 100644
--- a/apps/desktop/src-tauri/src/voice/engine.rs
+++ b/apps/desktop/src-tauri/src/voice/engine.rs
@@ -1,6 +1,6 @@
//! Which speech-to-text engine records (S30.5): the local Parakeet model when it is installed,
-//! else the platform's own (Apple Speech on macOS, S30.1). Linux has no platform engine, so
-//! there voice input needs the model. The choice is made on every call, so a model installed or
+//! else the platform's own (Apple Speech on macOS, S30.1). Linux and Windows have no platform
+//! engine, so there voice input needs the model. The choice is made on every call, so a model installed or
//! removed while the app runs takes effect on the next recording.
use super::model::EngineName;
diff --git a/apps/desktop/src-tauri/src/voice/mod.rs b/apps/desktop/src-tauri/src/voice/mod.rs
index 182b914..f7cb18d 100644
--- a/apps/desktop/src-tauri/src/voice/mod.rs
+++ b/apps/desktop/src-tauri/src/voice/mod.rs
@@ -13,14 +13,16 @@
//! `Voice` is the pure state machine between them (idle → starting → recording → stopping,
//! single flight, cancel, error mapping, level throttling, locale fallback), tested on every OS
//! with fakes. The objc2 bindings live in `macos`; Linux records through a command-line recorder
-//! (`pipe`) and Windows through WASAPI (`wasapi`), both with the local model; elsewhere the
-//! commands answer "unavailable".
+//! (`pipe`) and Windows through WASAPI (`wasapi`, on a `capture_thread`), both with the local
+//! model; elsewhere the commands answer "unavailable".
//!
//! SpeechAnalyzer/SpeechTranscriber (macOS 26) are Swift-only, with no Objective-C interface to
//! bind from Rust, and the app supports macOS 12.3, so `SFSpeechRecognizer` is the recognizer.
pub mod app;
pub mod audio;
+#[cfg_attr(not(windows), allow(dead_code))]
+mod capture_thread;
pub mod engine;
#[cfg(test)]
mod fake;
@@ -32,7 +34,7 @@ pub mod model;
pub mod parakeet;
#[cfg(unix)]
pub mod pipe;
-#[cfg(windows)]
+#[cfg_attr(not(windows), allow(dead_code))]
pub mod wasapi;
pub use machine::{Sink, Voice};
@@ -51,10 +53,10 @@ pub const LEVEL_EVENT: &str = "voice://level";
/// A failure while recording (permission, recognizer, interruption): `{message}`.
pub const ERROR_EVENT: &str = "voice://error";
pub const UNSUPPORTED: &str = "Voice input is available on macOS, Linux, and Windows.";
-/// Where the user turns the microphone back on. Windows asks no app: one switch covers every
-/// desktop app.
+/// Where the user turns the microphone back on. Windows asks no app: the top-level switch and
+/// the one for desktop apps both have to be on, and they cover every desktop app.
const MICROPHONE_DENIED: &str = if cfg!(windows) {
- "Microphone access is off for desktop apps. Turn it on in Settings → Privacy & security → Microphone → Let desktop apps access your microphone."
+ "Microphone access is off for desktop apps. In Settings → Privacy & security → Microphone, turn on Microphone access and Let desktop apps access your microphone."
} else {
"Microphone access is off for Gentle Dot. Turn it on in System Settings → Privacy & Security → Microphone."
};
@@ -276,7 +278,7 @@ mod tests {
#[test]
fn a_denied_microphone_points_to_this_platforms_privacy_setting() {
let expected = if cfg!(windows) {
- "Microphone access is off for desktop apps. Turn it on in Settings → Privacy & security → Microphone → Let desktop apps access your microphone."
+ "Microphone access is off for desktop apps. In Settings → Privacy & security → Microphone, turn on Microphone access and Let desktop apps access your microphone."
} else {
"Microphone access is off for Gentle Dot. Turn it on in System Settings → Privacy & Security → Microphone."
};
diff --git a/apps/desktop/src-tauri/src/voice/wasapi.rs b/apps/desktop/src-tauri/src/voice/wasapi.rs
index a997eee..8b88254 100644
--- a/apps/desktop/src-tauri/src/voice/wasapi.rs
+++ b/apps/desktop/src-tauri/src/voice/wasapi.rs
@@ -1,32 +1,26 @@
-//! The Windows microphone: the default capture endpoint through WASAPI, in shared mode. WASAPI
-//! converts the device's format to the 16 kHz mono f32 the recognizers consume
-//! (`AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM`), so the samples go to the sink as they arrive. A
-//! thread of its own owns the COM objects for the whole capture and polls for packets.
+//! The Windows microphone: the default capture endpoint through WASAPI, in shared mode and in
+//! the device's own mix format (`IAudioClient::GetMixFormat`), converted here to the 16 kHz mono
+//! f32 the recognizers consume (`format`). Forcing that format on WASAPI with
+//! `AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM` is reported to capture digital silence, without an error,
+//! on some Windows 11 endpoints (RustAudio/cpal#1200, cjpais/Handy#2141). A thread of its own
+//! (`capture_thread`) owns the COM objects for the whole capture and polls for packets.
//!
-//! Desktop apps get no microphone prompt on Windows: the system's privacy switch ("Let desktop
-//! apps access your microphone") either allows every desktop app or none, and a blocked capture
-//! fails with `E_ACCESSDENIED` when it opens.
+//! Desktop apps get no microphone prompt on Windows: the system's privacy switches ("Microphone
+//! access", and under it "Let desktop apps access your microphone") either allow every desktop
+//! app or none, and a blocked capture fails with `E_ACCESSDENIED` when it opens.
+//!
+//! Only `device` binds Win32; the rest is compiled on every platform so its tests run on all of
+//! them.
+
+#[cfg(windows)]
+mod device;
+mod format;
-use super::{audio, Authorization, Microphone, Sink, Stream, VoiceError};
-use std::sync::atomic::{AtomicBool, Ordering};
-use std::sync::{mpsc, Arc};
-use std::thread::JoinHandle;
-use std::time::Duration;
-use windows::Win32::Media::Audio::{
- eCapture, eConsole, IAudioCaptureClient, IAudioClient, IMMDeviceEnumerator, MMDeviceEnumerator,
- AUDCLNT_BUFFERFLAGS_SILENT, AUDCLNT_SHAREMODE_SHARED, AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM,
- AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY, WAVEFORMATEX,
-};
-use windows::Win32::System::Com::{CoCreateInstance, CoInitializeEx, CoUninitialize, CLSCTX_ALL, COINIT_MULTITHREADED};
+#[cfg(windows)]
+pub use device::WindowsMicrophone;
-/// `WAVE_FORMAT_IEEE_FLOAT` (mmreg.h).
-const WAVE_FORMAT_IEEE_FLOAT: u16 = 3;
-/// The shared-mode buffer, in 100 ns units: 200 ms.
-const BUFFER_DURATION: i64 = 2_000_000;
-/// How often the capture thread looks for packets; well inside the buffer.
-const POLL: Duration = Duration::from_millis(10);
-/// How long `open` waits for the capture thread to start the device.
-const OPEN_WAIT: Duration = Duration::from_secs(5);
+use super::capture_thread::failed_to_start;
+use super::VoiceError;
// HRESULTs that tell the user something they can act on.
const E_ACCESSDENIED: u32 = 0x8007_0005;
@@ -34,257 +28,18 @@ const E_ACCESSDENIED: u32 = 0x8007_0005;
const E_NOTFOUND: u32 = 0x8007_0490;
const AUDCLNT_E_DEVICE_INVALIDATED: u32 = 0x8889_0004;
-pub struct WindowsMicrophone;
-
-/// The format asked of WASAPI: `audio::SAMPLE_RATE` mono 32-bit float.
-pub(crate) fn capture_format() -> WAVEFORMATEX {
- WAVEFORMATEX {
- wFormatTag: WAVE_FORMAT_IEEE_FLOAT,
- nChannels: 1,
- nSamplesPerSec: audio::SAMPLE_RATE,
- nAvgBytesPerSec: audio::SAMPLE_RATE * 4,
- nBlockAlign: 4,
- wBitsPerSample: 32,
- cbSize: 0,
- }
-}
-
/// What a failure to open the capture means to the user.
pub(crate) fn open_error(code: u32, message: &str) -> VoiceError {
match code {
E_ACCESSDENIED => VoiceError::MicrophoneDenied,
E_NOTFOUND | AUDCLNT_E_DEVICE_INVALIDATED => VoiceError::NoMicrophone,
- _ => VoiceError::Failed(format!("The microphone could not start: {message}")),
- }
-}
-
-fn failed_to_start(error: impl std::fmt::Display) -> VoiceError {
- VoiceError::Failed(format!("The microphone could not start: {error}"))
-}
-
-impl Microphone for WindowsMicrophone {
- fn authorization(&self) -> Authorization {
- Authorization::Authorized
- }
-
- fn request_authorization(&self) -> Authorization {
- Authorization::Authorized
- }
-
- fn open(&self, sink: Sink) -> Result<Box<dyn Stream>, VoiceError> {
- let stream = launch(move |closed, ready| capture(sink, closed, ready), OPEN_WAIT)?;
- Ok(Box::new(stream))
- }
-}
-
-type Ready = mpsc::Sender<Result<(), VoiceError>>;
-
-/// Runs `run` on the capture thread and waits up to `wait` for it to say whether the device
-/// started. Windows can block inside device activation or start indefinitely, so a timeout does
-/// not wait for the thread: it closes the stream and stops listening, and the thread, once
-/// Windows returns, finds nobody waiting, stops the device, and ends without capturing.
-fn launch(run: impl FnOnce(Arc<AtomicBool>, Ready) + Send + 'static, wait: Duration) -> Result<WasapiStream, VoiceError> {
- let closed = Arc::new(AtomicBool::new(false));
- let (ready, started) = mpsc::channel();
- let flag = closed.clone();
- let thread = std::thread::Builder::new()
- .name("voice-wasapi".into())
- .spawn(move || run(flag, ready))
- .map_err(failed_to_start)?;
- let mut stream = WasapiStream { closed, thread: Some(thread) };
- match started.recv_timeout(wait) {
- Ok(Ok(())) => Ok(stream),
- Ok(Err(error)) => {
- stream.close();
- Err(error)
- }
- Err(_) => {
- stream.closed.store(true, Ordering::SeqCst);
- drop(stream.thread.take());
- drop(started);
- Err(failed_to_start("the audio device did not answer"))
- }
- }
-}
-
-/// Ends COM on the capture thread, after the COM objects it owns are released.
-struct Com;
-
-impl Drop for Com {
- fn drop(&mut self) {
- // SAFETY: built only after CoInitializeEx succeeded on this thread, and dropped on it
- // after the COM interfaces declared later in `capture` were released.
- unsafe { CoUninitialize() };
- }
-}
-
-/// Capture threads alive in this process (tests only): proves that closing ends the thread.
-#[cfg(test)]
-static CAPTURE_THREADS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
-
-#[cfg(test)]
-struct LiveCapture;
-
-#[cfg(test)]
-impl LiveCapture {
- fn new() -> Self {
- CAPTURE_THREADS.fetch_add(1, Ordering::SeqCst);
- LiveCapture
- }
-}
-
-#[cfg(test)]
-impl Drop for LiveCapture {
- fn drop(&mut self) {
- CAPTURE_THREADS.fetch_sub(1, Ordering::SeqCst);
- }
-}
-
-/// The capture thread: starts the default capture endpoint, says whether that worked, then
-/// delivers packets until the stream is closed or the device fails.
-fn capture(sink: Sink, closed: Arc<AtomicBool>, ready: Ready) {
- #[cfg(test)]
- let _live = LiveCapture::new();
- // SAFETY: initializes COM for this thread only; `Com` uninitializes it on the same thread.
- if let Err(error) = unsafe { CoInitializeEx(None, COINIT_MULTITHREADED) }.ok() {
- let _ = ready.send(Err(failed_to_start(error.message())));
- return;
- }
- let _com = Com;
- let (client, capture) = match start() {
- Ok(started) => started,
- Err(error) => {
- let _ = ready.send(Err(open_error(error.code().0 as u32, &error.message())));
- return;
- }
- };
- // `open` gave up waiting: release the device at once.
- let gave_up = ready.send(Ok(())).is_err();
- let result = if gave_up {
- Ok(())
- } else {
- // SAFETY: `capture` is a live interface created on this COM thread and used only here.
- pump(|| unsafe { capture.GetNextPacketSize() }, || read_packet(&capture), &closed, |samples| sink.audio(samples), POLL)
- };
- // SAFETY: `client` is a live interface created on this COM thread and used only here.
- unsafe {
- let _ = client.Stop();
- }
- // The device went away or failed while recording; a close is not a failure.
- if result.is_err() && !closed.load(Ordering::SeqCst) {
- sink.failed(&VoiceError::Interrupted.to_string());
- }
-}
-
-fn start() -> windows::core::Result<(IAudioClient, IAudioCaptureClient)> {
- // SAFETY: COM calls on the capture thread after CoInitializeEx; the format outlives Initialize.
- unsafe {
- let enumerator: IMMDeviceEnumerator = CoCreateInstance(&MMDeviceEnumerator, None, CLSCTX_ALL)?;
- let device = enumerator.GetDefaultAudioEndpoint(eCapture, eConsole)?;
- let client: IAudioClient = device.Activate(CLSCTX_ALL, None)?;
- let format = capture_format();
- client.Initialize(
- AUDCLNT_SHAREMODE_SHARED,
- AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM | AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY,
- BUFFER_DURATION,
- 0,
- &format,
- None,
- )?;
- let capture: IAudioCaptureClient = client.GetService()?;
- client.Start()?;
- Ok((client, capture))
- }
-}
-
-/// Delivers waiting packets, then sleeps a poll, until the stream is closed. The flag is checked
-/// before every packet, so a device that always has another one ready cannot keep the capture
-/// going after a close.
-fn pump<E>(
- mut waiting: impl FnMut() -> Result<u32, E>,
- mut read: impl FnMut() -> Result<Vec<f32>, E>,
- closed: &AtomicBool,
- mut deliver: impl FnMut(&[f32]),
- poll: Duration,
-) -> Result<(), E> {
- while !closed.load(Ordering::SeqCst) {
- while !closed.load(Ordering::SeqCst) && waiting()? > 0 {
- let samples = read()?;
- if !samples.is_empty() {
- deliver(&samples);
- }
- }
- std::thread::sleep(poll);
- }
- Ok(())
-}
-
-/// One packet, copied out before its buffer goes back to WASAPI. Each frame is one f32 (mono).
-fn read_packet(capture: &IAudioCaptureClient) -> windows::core::Result<Vec<f32>> {
- let mut data = std::ptr::null_mut();
- let mut frames = 0u32;
- let mut flags = 0u32;
- // SAFETY: valid out-pointers; the buffer stays ours until ReleaseBuffer below.
- unsafe { capture.GetBuffer(&mut data, &mut frames, &mut flags, None, None)? };
- let silent = flags & AUDCLNT_BUFFERFLAGS_SILENT.0 as u32 != 0 || data.is_null();
- let samples = if silent {
- vec![0.0; frames as usize]
- } else {
- // SAFETY: non-null, and with the 32-bit float mono format each of the `frames` frames is one
- // aligned f32 in a buffer valid until ReleaseBuffer; it is copied out before that.
- unsafe { std::slice::from_raw_parts(data as *const f32, frames as usize) }.to_vec()
- };
- // SAFETY: returns exactly the frames GetBuffer handed out; `samples` no longer borrows them.
- unsafe { capture.ReleaseBuffer(frames)? };
- Ok(samples)
-}
-
-struct WasapiStream {
- closed: Arc<AtomicBool>,
- thread: Option<JoinHandle<()>>,
-}
-
-impl Stream for WasapiStream {
- fn close(&mut self) {
- self.closed.store(true, Ordering::SeqCst);
- if let Some(thread) = self.thread.take() {
- // A failure reported from the capture thread closes the stream on that same thread
- // (the machine discards the recording there); it is already on its way out.
- if thread.thread().id() != std::thread::current().id() {
- let _ = thread.join();
- }
- }
- }
-}
-
-impl Drop for WasapiStream {
- fn drop(&mut self) {
- self.close();
+ _ => failed_to_start(message),
}
}
#[cfg(test)]
mod tests {
use super::*;
- use crate::voice::fake::{FakeClock, FakeRecognizer, Recorder};
- use crate::voice::{Voice, VoiceError};
- use std::sync::atomic::AtomicU64;
- use std::time::Instant;
-
- #[test]
- fn wasapi_converts_to_16_khz_mono_float() {
- let format = capture_format();
- let (tag, channels, rate, bytes, align, bits, extra) = (
- format.wFormatTag,
- format.nChannels,
- format.nSamplesPerSec,
- format.nAvgBytesPerSec,
- format.nBlockAlign,
- format.wBitsPerSample,
- format.cbSize,
- );
- assert_eq!((tag, channels, rate, bytes, align, bits, extra), (3, 1, 16_000, 64_000, 4, 32, 0));
- }
#[test]
fn open_failures_say_what_the_user_can_do() {
@@ -296,152 +51,4 @@ mod tests {
VoiceError::Failed("The microphone could not start: Unsupported format".into())
);
}
-
- #[test]
- fn there_is_no_prompt_for_desktop_apps() {
- assert_eq!(WindowsMicrophone.authorization(), Authorization::Authorized);
- assert_eq!(WindowsMicrophone.request_authorization(), Authorization::Authorized);
- }
-
- #[test]
- fn a_close_ends_capture_even_while_packets_keep_arriving() {
- let closed = Arc::new(AtomicBool::new(false));
- let delivered = Arc::new(std::sync::atomic::AtomicUsize::new(0));
- let (done, finished) = mpsc::channel();
- let (flag, count) = (closed.clone(), delivered.clone());
- std::thread::spawn(move || {
- // Another packet is always ready, as when delivery keeps up with the device only just.
- let result = pump(
- || Ok::<u32, ()>(1),
- || Ok(vec![0.25; 160]),
- &flag,
- |_| {
- count.fetch_add(1, Ordering::SeqCst);
- },
- Duration::from_millis(1),
- );
- let _ = done.send(result);
- });
- let deadline = Instant::now() + Duration::from_secs(2);
- while delivered.load(Ordering::SeqCst) < 10 {
- assert!(Instant::now() < deadline, "packets flow");
- std::thread::yield_now();
- }
- closed.store(true, Ordering::SeqCst);
- assert_eq!(finished.recv_timeout(Duration::from_secs(2)), Ok(Ok(())), "the close ends the capture");
- let after = delivered.load(Ordering::SeqCst);
- std::thread::sleep(Duration::from_millis(20));
- assert_eq!(delivered.load(Ordering::SeqCst), after, "nothing is delivered once the capture ended");
- }
-
- #[test]
- fn a_device_that_never_answers_times_out_without_waiting_for_windows() {
- let (outcome, observed) = mpsc::channel();
- let started = Instant::now();
- let result = launch(
- move |closed, ready| {
- // Windows is still activating the device when the wait runs out.
- std::thread::sleep(Duration::from_millis(600));
- let nobody_waiting = ready.send(Ok(())).is_err();
- let _ = outcome.send((nobody_waiting, closed.load(Ordering::SeqCst)));
- },
- Duration::from_millis(50),
- );
- assert!(started.elapsed() < Duration::from_millis(400), "the timeout does not wait for Windows");
- assert_eq!(
- result.err(),
- Some(VoiceError::Failed("The microphone could not start: the audio device did not answer".into()))
- );
- assert_eq!(
- observed.recv_timeout(Duration::from_secs(3)),
- Ok((true, true)),
- "the late thread finds nobody waiting and the stream closed, so it stops the device without capturing"
- );
- }
-
- #[test]
- fn a_start_failure_is_returned_once_the_thread_ended() {
- let ended = Arc::new(AtomicBool::new(false));
- let flag = ended.clone();
- let result = launch(
- move |_, ready| {
- let _ = ready.send(Err(VoiceError::NoMicrophone));
- std::thread::sleep(Duration::from_millis(50));
- flag.store(true, Ordering::SeqCst);
- },
- Duration::from_secs(2),
- );
- assert_eq!(result.err(), Some(VoiceError::NoMicrophone));
- assert!(ended.load(Ordering::SeqCst), "open waits for the failed capture thread to end");
- }
-
- #[test]
- fn closing_or_dropping_waits_for_the_capture_thread_and_closing_twice_is_harmless() {
- for drop_it in [false, true] {
- let ended = Arc::new(AtomicBool::new(false));
- let flag = ended.clone();
- let mut stream = launch(
- move |closed, ready| {
- let _ = ready.send(Ok(()));
- while !closed.load(Ordering::SeqCst) {
- std::thread::sleep(Duration::from_millis(5));
- }
- std::thread::sleep(Duration::from_millis(30));
- flag.store(true, Ordering::SeqCst);
- },
- Duration::from_secs(2),
- )
- .unwrap();
- if drop_it {
- drop(stream);
- } else {
- stream.close();
- stream.close();
- }
- assert!(ended.load(Ordering::SeqCst), "drop={drop_it}: the thread ended before close returned");
- }
- }
-
- /// Records the real default microphone for a moment and keeps nothing.
- #[test]
- #[ignore = "uses the real default microphone; run explicitly on a Windows machine with one"]
- fn the_default_microphone_streams_16_khz_until_stopped_and_releases_the_device() {
- let recognizer = Arc::new(FakeRecognizer::granted());
- *recognizer.final_text.lock().unwrap() = Some("done".into());
- let voice = Voice::new(Arc::new(WindowsMicrophone), recognizer.clone(), Arc::new(FakeClock(AtomicU64::new(0))));
- for round in 0..2 {
- let started = Instant::now();
- voice.start(None, Recorder::default().events()).unwrap();
- while recognizer.log.lock().unwrap().fed.len() < 8_000 {
- assert!(started.elapsed() < Duration::from_secs(5), "round {round}: half a second of audio arrives");
- std::thread::sleep(Duration::from_millis(10));
- }
- let elapsed = started.elapsed().as_secs_f64();
- let fed = recognizer.log.lock().unwrap().fed.len() as f64;
- // Converted to 16 kHz: at most what that rate delivers in the time it took.
- assert!(fed <= 16_000.0 * elapsed + 3_200.0, "round {round}: {fed} samples in {elapsed:.2} s");
- let stopping = Instant::now();
- assert_eq!(voice.stop().unwrap().text, "done");
- assert!(stopping.elapsed() < Duration::from_secs(2), "round {round}: stop releases the capture");
- recognizer.log.lock().unwrap().fed.clear();
- }
- // Shared mode allows overlapping clients, so reopening shows the device still works, not
- // that the first capture let go; the joined thread and `cancel_ends_the_capture_thread` do.
- voice.start(None, Recorder::default().events()).unwrap();
- voice.cancel().unwrap();
- }
-
- #[test]
- #[ignore = "uses the real default microphone; run explicitly on a Windows machine with one"]
- fn cancel_ends_the_capture_thread() {
- let recognizer = Arc::new(FakeRecognizer::granted());
- let voice = Voice::new(Arc::new(WindowsMicrophone), recognizer, Arc::new(FakeClock(AtomicU64::new(0))));
- let threads = || CAPTURE_THREADS.load(Ordering::SeqCst);
- let before = threads();
- voice.start(None, Recorder::default().events()).unwrap();
- assert_eq!(threads(), before + 1, "one capture thread while recording");
- voice.cancel().unwrap();
- assert_eq!(threads(), before, "cancel waits for the capture thread to end");
- assert_eq!(voice.stop(), Err(VoiceError::NotRecording));
- }
}
diff --git a/apps/desktop/src-tauri/src/voice/wasapi/device.rs b/apps/desktop/src-tauri/src/voice/wasapi/device.rs
new file mode 100644
index 0000000..049f726
--- /dev/null
+++ b/apps/desktop/src-tauri/src/voice/wasapi/device.rs
@@ -0,0 +1,260 @@
+//! The Win32 half of the Windows microphone: COM, the default capture endpoint, and its packets.
+
+use super::format::{Converter, MixFormat, WAVEFORMATEX_BYTES};
+use super::open_error;
+use crate::voice::capture_thread::{failed_to_start, launch, pump, Ready};
+use crate::voice::{Authorization, Microphone, Sink, Stream, VoiceError};
+use std::sync::atomic::{AtomicBool, Ordering};
+use std::sync::Arc;
+use std::time::Duration;
+use windows::Win32::Media::Audio::{
+ eCapture, eConsole, IAudioCaptureClient, IAudioClient, IMMDeviceEnumerator, MMDeviceEnumerator,
+ AUDCLNT_BUFFERFLAGS_SILENT, AUDCLNT_SHAREMODE_SHARED, WAVEFORMATEX,
+};
+use windows::Win32::System::Com::{
+ CoCreateInstance, CoInitializeEx, CoTaskMemFree, CoUninitialize, CLSCTX_ALL, COINIT_MULTITHREADED,
+};
+
+/// The shared-mode buffer, in 100 ns units: 200 ms.
+const BUFFER_DURATION: i64 = 2_000_000;
+/// How often the capture thread looks for packets; well inside the buffer.
+const POLL: Duration = Duration::from_millis(10);
+/// How long `open` waits for the capture thread to start the device.
+const OPEN_WAIT: Duration = Duration::from_secs(5);
+
+pub struct WindowsMicrophone;
+
+impl Microphone for WindowsMicrophone {
+ fn authorization(&self) -> Authorization {
+ Authorization::Authorized
+ }
+
+ fn request_authorization(&self) -> Authorization {
+ Authorization::Authorized
+ }
+
+ fn open(&self, sink: Sink) -> Result<Box<dyn Stream>, VoiceError> {
+ let stream = launch(move |closed, ready| capture(sink, closed, ready), OPEN_WAIT)?;
+ Ok(Box::new(stream))
+ }
+}
+
+fn windows_error(error: windows::core::Error) -> VoiceError {
+ open_error(error.code().0 as u32, &error.message())
+}
+
+/// Ends COM on the capture thread, after the COM objects it owns are released.
+struct Com;
+
+impl Drop for Com {
+ fn drop(&mut self) {
+ // SAFETY: built only after CoInitializeEx succeeded on this thread, and dropped on it
+ // after the COM interfaces declared later in `capture` were released.
+ unsafe { CoUninitialize() };
+ }
+}
+
+/// The mix format `GetMixFormat` allocated, freed with the COM allocator.
+struct MixFormatMemory(*mut WAVEFORMATEX);
+
+impl MixFormatMemory {
+ /// The `WAVEFORMATEX`, and for `WAVE_FORMAT_EXTENSIBLE` the `cbSize` bytes after it.
+ fn bytes(&self) -> &[u8] {
+ // SAFETY: GetMixFormat returned a valid WAVEFORMATEX, at least its 18 bytes, in an
+ // allocation that lives until this guard is dropped. Windows ignores `cbSize` for other
+ // tags, so only an extensible format's `cbSize` bytes are read after the header.
+ unsafe {
+ let header = std::slice::from_raw_parts(self.0 as *const u8, WAVEFORMATEX_BYTES);
+ if u16::from_le_bytes([header[0], header[1]]) != 0xFFFE {
+ return header;
+ }
+ let extra = usize::from(u16::from_le_bytes([header[16], header[17]]));
+ std::slice::from_raw_parts(self.0 as *const u8, WAVEFORMATEX_BYTES + extra)
+ }
+ }
+}
+
+impl Drop for MixFormatMemory {
+ fn drop(&mut self) {
+ // SAFETY: GetMixFormat allocated it with CoTaskMemAlloc, and nothing uses it after this.
+ unsafe { CoTaskMemFree(Some(self.0 as *const std::ffi::c_void)) };
+ }
+}
+
+/// Capture threads alive in this process (tests only): proves that closing ends the thread.
+#[cfg(test)]
+static CAPTURE_THREADS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
+
+#[cfg(test)]
+struct LiveCapture;
+
+#[cfg(test)]
+impl LiveCapture {
+ fn new() -> Self {
+ CAPTURE_THREADS.fetch_add(1, Ordering::SeqCst);
+ LiveCapture
+ }
+}
+
+#[cfg(test)]
+impl Drop for LiveCapture {
+ fn drop(&mut self) {
+ CAPTURE_THREADS.fetch_sub(1, Ordering::SeqCst);
+ }
+}
+
+/// The capture thread: starts the default capture endpoint, says whether that worked, then
+/// delivers packets until the stream is closed or the device fails.
+fn capture(sink: Sink, closed: Arc<AtomicBool>, ready: Ready) {
+ #[cfg(test)]
+ let _live = LiveCapture::new();
+ // MTA: this thread pumps no window messages, which an STA needs, and the WASAPI interfaces
+ // are free-threaded; the IAudioClient docs ask for an STA only on first use on Windows 8.
+ // SAFETY: initializes COM for this thread only; `Com` uninitializes it on the same thread.
+ if let Err(error) = unsafe { CoInitializeEx(None, COINIT_MULTITHREADED) }.ok() {
+ let _ = ready.send(Err(failed_to_start(error.message())));
+ return;
+ }
+ let _com = Com;
+ let (client, capture, format) = match start() {
+ Ok(started) => started,
+ Err(error) => {
+ let _ = ready.send(Err(error));
+ return;
+ }
+ };
+ // `open` gave up waiting: release the device at once.
+ let gave_up = ready.send(Ok(())).is_err();
+ let result = if gave_up {
+ Ok(())
+ } else {
+ let mut converter = Converter::new(format);
+ // SAFETY: `capture` is a live interface created on this COM thread and used only here.
+ pump(
+ || unsafe { capture.GetNextPacketSize() },
+ || read_packet(&capture, format, &mut converter),
+ &closed,
+ |samples| sink.audio(samples),
+ POLL,
+ )
+ };
+ // SAFETY: `client` is a live interface created on this COM thread and used only here.
+ unsafe {
+ let _ = client.Stop();
+ }
+ // The device went away or failed while recording; a close is not a failure.
+ if result.is_err() && !closed.load(Ordering::SeqCst) {
+ sink.failed(&VoiceError::Interrupted.to_string());
+ }
+}
+
+/// Opens the default capture endpoint in its own mix format and starts it.
+fn start() -> Result<(IAudioClient, IAudioCaptureClient, MixFormat), VoiceError> {
+ // SAFETY: COM calls on the capture thread after CoInitializeEx; the mix format stays
+ // allocated until after Initialize has read it.
+ unsafe {
+ let enumerator: IMMDeviceEnumerator =
+ CoCreateInstance(&MMDeviceEnumerator, None, CLSCTX_ALL).map_err(windows_error)?;
+ let device = enumerator.GetDefaultAudioEndpoint(eCapture, eConsole).map_err(windows_error)?;
+ let client: IAudioClient = device.Activate(CLSCTX_ALL, None).map_err(windows_error)?;
+ let memory = MixFormatMemory(client.GetMixFormat().map_err(windows_error)?);
+ let format = MixFormat::parse(memory.bytes())?;
+ client
+ .Initialize(AUDCLNT_SHAREMODE_SHARED, 0, BUFFER_DURATION, 0, memory.0, None)
+ .map_err(windows_error)?;
+ let capture: IAudioCaptureClient = client.GetService().map_err(windows_error)?;
+ client.Start().map_err(windows_error)?;
+ Ok((client, capture, format))
+ }
+}
+
+/// One packet, copied out and converted before its buffer goes back to WASAPI.
+fn read_packet(
+ capture: &IAudioCaptureClient,
+ format: MixFormat,
+ converter: &mut Converter,
+) -> windows::core::Result<Vec<f32>> {
+ let mut data = std::ptr::null_mut();
+ let mut frames = 0u32;
+ let mut flags = 0u32;
+ // SAFETY: valid out-pointers; the buffer stays ours until ReleaseBuffer below.
+ unsafe { capture.GetBuffer(&mut data, &mut frames, &mut flags, None, None)? };
+ let silent = flags & AUDCLNT_BUFFERFLAGS_SILENT.0 as u32 != 0 || data.is_null();
+ let samples = if silent {
+ converter.silence(frames as usize)
+ } else {
+ // SAFETY: non-null, and in the mix format the stream was initialized with, each of the
+ // `frames` frames is `block_align` bytes, valid until ReleaseBuffer; read before that.
+ let bytes = unsafe { std::slice::from_raw_parts(data as *const u8, frames as usize * format.block_align) };
+ converter.packet(bytes)
+ };
+ // SAFETY: returns exactly the frames GetBuffer handed out; `samples` no longer borrows them.
+ unsafe { capture.ReleaseBuffer(frames)? };
+ Ok(samples)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::voice::fake::{FakeClock, FakeRecognizer, Recorder};
+ use crate::voice::Voice;
+ use std::sync::atomic::AtomicU64;
+ use std::sync::Mutex;
+ use std::time::Instant;
+
+ /// The hardware tests count `CAPTURE_THREADS`, so they take turns.
+ static HARDWARE: Mutex<()> = Mutex::new(());
+
+ #[test]
+ fn there_is_no_prompt_for_desktop_apps() {
+ assert_eq!(WindowsMicrophone.authorization(), Authorization::Authorized);
+ assert_eq!(WindowsMicrophone.request_authorization(), Authorization::Authorized);
+ }
+
+ /// Records the real default microphone for a moment and keeps nothing.
+ #[test]
+ #[ignore = "uses the real default microphone; run explicitly on a Windows machine with one, \
+ with --test-threads=1 (they also take turns with each other)"]
+ fn the_default_microphone_streams_16_khz_until_stopped_and_releases_the_device() {
+ let _turn = HARDWARE.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
+ let recognizer = Arc::new(FakeRecognizer::granted());
+ *recognizer.final_text.lock().unwrap() = Some("done".into());
+ let voice = Voice::new(Arc::new(WindowsMicrophone), recognizer.clone(), Arc::new(FakeClock(AtomicU64::new(0))));
+ for round in 0..2 {
+ let started = Instant::now();
+ voice.start(None, Recorder::default().events()).unwrap();
+ while recognizer.log.lock().unwrap().fed.len() < 8_000 {
+ assert!(started.elapsed() < Duration::from_secs(5), "round {round}: half a second of audio arrives");
+ std::thread::sleep(Duration::from_millis(10));
+ }
+ let elapsed = started.elapsed().as_secs_f64();
+ let fed = recognizer.log.lock().unwrap().fed.len() as f64;
+ // Converted to 16 kHz: at most what that rate delivers in the time it took.
+ assert!(fed <= 16_000.0 * elapsed + 3_200.0, "round {round}: {fed} samples in {elapsed:.2} s");
+ let stopping = Instant::now();
+ assert_eq!(voice.stop().unwrap().text, "done");
+ assert!(stopping.elapsed() < Duration::from_secs(2), "round {round}: stop releases the capture");
+ recognizer.log.lock().unwrap().fed.clear();
+ }
+ // Shared mode allows overlapping clients, so reopening shows the device still works, not
+ // that the first capture let go; the joined thread and `cancel_ends_the_capture_thread` do.
+ voice.start(None, Recorder::default().events()).unwrap();
+ voice.cancel().unwrap();
+ }
+
+ #[test]
+ #[ignore = "uses the real default microphone; run explicitly on a Windows machine with one, \
+ with --test-threads=1 (they also take turns with each other)"]
+ fn cancel_ends_the_capture_thread() {
+ let _turn = HARDWARE.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
+ let recognizer = Arc::new(FakeRecognizer::granted());
+ let voice = Voice::new(Arc::new(WindowsMicrophone), recognizer, Arc::new(FakeClock(AtomicU64::new(0))));
+ let threads = || CAPTURE_THREADS.load(Ordering::SeqCst);
+ let before = threads();
+ voice.start(None, Recorder::default().events()).unwrap();
+ assert_eq!(threads(), before + 1, "one capture thread while recording");
+ voice.cancel().unwrap();
+ assert_eq!(threads(), before, "cancel waits for the capture thread to end");
+ assert_eq!(voice.stop(), Err(VoiceError::NotRecording));
+ }
+}
diff --git a/apps/desktop/src-tauri/src/voice/wasapi/format.rs b/apps/desktop/src-tauri/src/voice/wasapi/format.rs
new file mode 100644
index 0000000..be547ff
--- /dev/null
+++ b/apps/desktop/src-tauri/src/voice/wasapi/format.rs
@@ -0,0 +1,250 @@
+//! The device's shared-mode mix format, as `IAudioClient::GetMixFormat` reports it, and the
+//! conversion of its packets to the 16 kHz mono f32 every recognizer consumes. Parsed from the
+//! raw `WAVEFORMATEX` bytes so it is tested on every platform, without a device.
+
+use crate::voice::audio::{self, Resampler};
+use crate::voice::capture_thread::failed_to_start;
+use crate::voice::VoiceError;
+
+// Format tags (mmreg.h). An extensible format names its sample type in `SubFormat`, a GUID whose
+// first field is one of the plain tags and the rest is the same base for every one of them.
+const WAVE_FORMAT_PCM: u16 = 1;
+const WAVE_FORMAT_IEEE_FLOAT: u16 = 3;
+const WAVE_FORMAT_EXTENSIBLE: u16 = 0xFFFE;
+/// `KSDATAFORMAT_SUBTYPE_*` after its first field (`-0000-0010-8000-00aa00389b71`), in memory order.
+const SUBTYPE_BASE: [u8; 12] = [0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71];
+/// `sizeof(WAVEFORMATEX)`, and the extensible tail after it: valid bits, channel mask, SubFormat.
+pub(crate) const WAVEFORMATEX_BYTES: usize = 18;
+const EXTENSIBLE_TAIL: usize = 22;
+
+/// How one sample of one channel is stored.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub(crate) enum Sample {
+ Float32,
+ Float64,
+ /// Unsigned, centred on 128.
+ Pcm8,
+ Pcm16,
+ /// Packed in three bytes.
+ Pcm24,
+ /// Also 24-bit audio in a 32-bit container, which is left-justified, so full scale is the same.
+ Pcm32,
+}
+
+impl Sample {
+ fn bytes(self) -> usize {
+ match self {
+ Sample::Pcm8 => 1,
+ Sample::Pcm16 => 2,
+ Sample::Pcm24 => 3,
+ Sample::Float32 | Sample::Pcm32 => 4,
+ Sample::Float64 => 8,
+ }
+ }
+
+ /// One little-endian sample, `bytes()` long, scaled to -1..1.
+ fn decode(self, b: &[u8]) -> f32 {
+ match self {
+ Sample::Float32 => f32::from_le_bytes([b[0], b[1], b[2], b[3]]),
+ Sample::Float64 => f64::from_le_bytes([b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7]]) as f32,
+ Sample::Pcm8 => (f32::from(b[0]) - 128.0) / 128.0,
+ Sample::Pcm16 => f32::from(i16::from_le_bytes([b[0], b[1]])) / 32_768.0,
+ Sample::Pcm24 => (i32::from_le_bytes([0, b[0], b[1], b[2]]) >> 8) as f32 / 8_388_608.0,
+ Sample::Pcm32 => i32::from_le_bytes([b[0], b[1], b[2], b[3]]) as f32 / 2_147_483_648.0,
+ }
+ }
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub(crate) struct MixFormat {
+ pub sample: Sample,
+ pub channels: usize,
+ pub rate: u32,
+ /// Bytes per frame: one sample of every channel, interleaved.
+ pub block_align: usize,
+}
+
+impl MixFormat {
+ /// Reads a `WAVEFORMATEX` and, for `WAVE_FORMAT_EXTENSIBLE`, the `WAVEFORMATEXTENSIBLE` tail
+ /// after it: `bytes` holds the 18-byte header and then `cbSize` more.
+ pub fn parse(bytes: &[u8]) -> Result<Self, VoiceError> {
+ let unsupported = |what: String| failed_to_start(format!("the microphone's format is not supported ({what})"));
+ let u16_at = |at: usize| u16::from_le_bytes([bytes[at], bytes[at + 1]]);
+ if bytes.len() < WAVEFORMATEX_BYTES {
+ return Err(unsupported(format!("{} bytes", bytes.len())));
+ }
+ let (tag, channels, bits, block_align) = (u16_at(0), u16_at(2), u16_at(14), u16_at(12));
+ let rate = u32::from_le_bytes([bytes[4], bytes[5], bytes[6], bytes[7]]);
+ let kind = if tag == WAVE_FORMAT_EXTENSIBLE {
+ let tail = &bytes[WAVEFORMATEX_BYTES..];
+ if u16_at(16) < EXTENSIBLE_TAIL as u16 || tail.len() < EXTENSIBLE_TAIL {
+ return Err(unsupported("a truncated extensible format".into()));
+ }
+ let valid = u16::from_le_bytes([tail[0], tail[1]]);
+ if valid == 0 || valid > bits {
+ return Err(unsupported(format!("{valid} valid bits in {bits}")));
+ }
+ let subformat = &tail[6..22];
+ if subformat[4..] != SUBTYPE_BASE || subformat[2..4] != [0, 0] {
+ return Err(unsupported(format!("subformat {subformat:02x?}")));
+ }
+ u16::from_le_bytes([subformat[0], subformat[1]])
+ } else {
+ tag
+ };
+ let sample = match (kind, bits) {
+ (WAVE_FORMAT_IEEE_FLOAT, 32) => Sample::Float32,
+ (WAVE_FORMAT_IEEE_FLOAT, 64) => Sample::Float64,
+ (WAVE_FORMAT_PCM, 8) => Sample::Pcm8,
+ (WAVE_FORMAT_PCM, 16) => Sample::Pcm16,
+ (WAVE_FORMAT_PCM, 24) => Sample::Pcm24,
+ (WAVE_FORMAT_PCM, 32) => Sample::Pcm32,
+ _ => return Err(unsupported(format!("type {kind}, {bits} bits"))),
+ };
+ let (channels, block_align) = (usize::from(channels), usize::from(block_align));
+ if channels == 0 || rate == 0 || block_align != channels * sample.bytes() {
+ return Err(unsupported(format!("{channels} channels at {rate} Hz, {block_align} bytes a frame")));
+ }
+ Ok(MixFormat { sample, channels, rate, block_align })
+ }
+}
+
+/// Turns packets in the mix format into `audio::SAMPLE_RATE` mono f32, keeping the resampler's
+/// position across packets.
+pub(crate) struct Converter {
+ format: MixFormat,
+ resampler: Resampler,
+}
+
+impl Converter {
+ pub fn new(format: MixFormat) -> Self {
+ Converter { format, resampler: Resampler::new(f64::from(format.rate)) }
+ }
+
+ /// One packet of interleaved frames; a trailing partial frame is ignored.
+ pub fn packet(&mut self, data: &[u8]) -> Vec<f32> {
+ let MixFormat { sample, channels, block_align, .. } = self.format;
+ let frames = data.len() / block_align;
+ let mut split = vec![Vec::with_capacity(frames); channels];
+ for frame in data.chunks_exact(block_align) {
+ for (channel, bytes) in split.iter_mut().zip(frame.chunks_exact(sample.bytes())) {
+ channel.push(sample.decode(bytes));
+ }
+ }
+ let refs: Vec<&[f32]> = split.iter().map(Vec::as_slice).collect();
+ self.resampler.process(&audio::mono(&refs))
+ }
+
+ /// A packet WASAPI flagged silent: `frames` frames of nothing, at the device rate.
+ pub fn silence(&mut self, frames: usize) -> Vec<f32> {
+ self.resampler.process(&vec![0.0; frames])
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ /// A `WAVEFORMATEX`, with the extensible tail when `subformat` is given.
+ fn wave(tag: u16, channels: u16, rate: u32, bits: u16, subformat: Option<u16>) -> Vec<u8> {
+ let block_align = channels * bits / 8;
+ let mut bytes = Vec::new();
+ bytes.extend(tag.to_le_bytes());
+ bytes.extend(channels.to_le_bytes());
+ bytes.extend(rate.to_le_bytes());
+ bytes.extend((rate * u32::from(block_align)).to_le_bytes());
+ bytes.extend(block_align.to_le_bytes());
+ bytes.extend(bits.to_le_bytes());
+ match subformat {
+ None => bytes.extend(0u16.to_le_bytes()),
+ Some(kind) => {
+ bytes.extend(22u16.to_le_bytes());
+ bytes.extend(bits.to_le_bytes());
+ bytes.extend(0x3u32.to_le_bytes());
+ bytes.extend(u32::from(kind).to_le_bytes());
+ bytes.extend(SUBTYPE_BASE);
+ }
+ }
+ bytes
+ }
+
+ fn extensible(channels: u16, rate: u32, bits: u16, kind: u16) -> Vec<u8> {
+ wave(WAVE_FORMAT_EXTENSIBLE, channels, rate, bits, Some(kind))
+ }
+
+ #[test]
+ fn valid_bits_may_be_fewer_than_the_container_never_more() {
+ let with_valid = |valid: u16| {
+ let mut bytes = extensible(2, 48_000, 32, 1);
+ bytes[18..20].copy_from_slice(&valid.to_le_bytes());
+ MixFormat::parse(&bytes).map(|f| f.sample)
+ };
+ // 24 valid bits in a 32-bit container are left-justified, so they read as 32-bit PCM.
+ assert_eq!(with_valid(24), Ok(Sample::Pcm32));
+ assert!(with_valid(40).is_err());
+ assert!(with_valid(0).is_err());
+ }
+
+ #[test]
+ fn the_mix_format_names_its_sample_type_channels_and_rate() {
+ let parsed = |bytes: Vec<u8>| MixFormat::parse(&bytes).map(|f| (f.sample, f.channels, f.rate, f.block_align));
+ assert_eq!(parsed(extensible(2, 48_000, 32, 3)), Ok((Sample::Float32, 2, 48_000, 8)));
+ assert_eq!(parsed(extensible(2, 44_100, 16, 1)), Ok((Sample::Pcm16, 2, 44_100, 4)));
+ assert_eq!(parsed(extensible(1, 96_000, 24, 1)), Ok((Sample::Pcm24, 1, 96_000, 3)));
+ assert_eq!(parsed(extensible(4, 48_000, 32, 1)), Ok((Sample::Pcm32, 4, 48_000, 16)));
+ assert_eq!(parsed(wave(WAVE_FORMAT_IEEE_FLOAT, 1, 16_000, 32, None)), Ok((Sample::Float32, 1, 16_000, 4)));
+ assert_eq!(parsed(wave(WAVE_FORMAT_PCM, 2, 22_050, 16, None)), Ok((Sample::Pcm16, 2, 22_050, 4)));
+ }
+
+ #[test]
+ fn a_mix_format_it_cannot_read_is_an_error_not_silence() {
+ let error = |bytes: &[u8]| MixFormat::parse(bytes).unwrap_err().to_string();
+ assert!(error(&extensible(2, 48_000, 12, 1)).contains("type 1, 12 bits"));
+ let mut ac3 = extensible(2, 48_000, 16, 0x92);
+ assert!(error(&ac3).contains("type 146"));
+ ac3[30] ^= 0xff; // Not a KSDATAFORMAT_SUBTYPE GUID at all.
+ assert!(error(&ac3).contains("subformat"));
+ assert!(error(&extensible(2, 48_000, 32, 3)[..30]).contains("truncated"));
+ assert!(error(&wave(WAVE_FORMAT_PCM, 0, 48_000, 16, None)).contains("0 channels"));
+ assert!(error(&[0; 4]).starts_with("The microphone could not start: "));
+ }
+
+ #[test]
+ fn samples_of_every_type_scale_to_full_range() {
+ assert_eq!(Sample::Float32.decode(&0.5f32.to_le_bytes()), 0.5);
+ assert_eq!(Sample::Float64.decode(&(-0.25f64).to_le_bytes()), -0.25);
+ assert_eq!(Sample::Pcm8.decode(&[192]), 0.5);
+ assert_eq!(Sample::Pcm16.decode(&i16::MIN.to_le_bytes()), -1.0);
+ assert_eq!(Sample::Pcm16.decode(&16_384i16.to_le_bytes()), 0.5);
+ assert_eq!(Sample::Pcm24.decode(&[0x00, 0x00, 0xC0]), -0.5);
+ assert_eq!(Sample::Pcm24.decode(&[0x00, 0x00, 0x40]), 0.5);
+ assert_eq!(Sample::Pcm32.decode(&(1i32 << 30).to_le_bytes()), 0.5);
+ }
+
+ #[test]
+ fn a_48_khz_stereo_float_packet_becomes_16_khz_mono() {
+ let format = MixFormat::parse(&extensible(2, 48_000, 32, 3)).unwrap();
+ let mut converter = Converter::new(format);
+ // 10 ms: left at 0.5, right at -0.1, so the mix is 0.2.
+ let packet: Vec<u8> = (0..480).flat_map(|_| [0.5f32.to_le_bytes(), (-0.1f32).to_le_bytes()]).flatten().collect();
+ let out = converter.packet(&packet);
+ assert_eq!(out.len(), 160);
+ assert!(out.iter().all(|s| (s - 0.2).abs() < 1e-6), "{:?}", &out[..4]);
+ assert_eq!(converter.silence(480), vec![0.0; 160], "a silent packet keeps the timing");
+ }
+
+ #[test]
+ fn a_44_1_khz_four_channel_24_bit_packet_becomes_16_khz_mono_across_packets() {
+ let format = MixFormat::parse(&extensible(4, 44_100, 24, 1)).unwrap();
+ assert_eq!(format.block_align, 12);
+ // Two channels at half scale, two silent: the mix is a quarter.
+ let frame = [[0x00, 0x00, 0x40], [0x00, 0x00, 0x40], [0, 0, 0], [0, 0, 0]].concat();
+ let second: Vec<u8> = frame.iter().copied().cycle().take(frame.len() * 4_410).collect();
+ let mut converter = Converter::new(format);
+ let (first, rest) = second.split_at(frame.len() * 1_000);
+ let mut out = converter.packet(first);
+ out.extend(converter.packet(rest));
+ assert_eq!(out.len(), 1_600, "a tenth of a second at 16 kHz");
+ assert!(out.iter().all(|s| (s - 0.25).abs() < 1e-6));
+ }
+}