From d65eba4427017be9fac2eea56c971a7aa172af1a Mon Sep 17 00:00:00 2001 From: LastExceed Date: Wed, 4 Nov 2026 12:52:07 +0100 Subject: [PATCH 01/23] lay out basic structure --- Cargo.toml | 4 ++ src/host.rs | 4 ++ src/host/wasapi_new.rs | 141 +++++++++++++++++++++++++++++++++++++++++ src/platform.rs | 4 ++ 4 files changed, 153 insertions(+) create mode 100644 src/host/wasapi_new.rs diff --git a/Cargo.toml b/Cargo.toml index af43ca1c49..f7bd75e43c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -80,6 +80,10 @@ pulseaudio = [ "dep:portable-atomic", ] +# New WASAPI backend using WinRT +# Platform: Windows +wasapi-new = [] + # WebAssembly backend using wasm-bindgen # Enables the Web Audio API backend for browser-based audio # Required for any WebAssembly audio support diff --git a/src/host.rs b/src/host.rs index 9c8c17811e..9f4a25442f 100644 --- a/src/host.rs +++ b/src/host.rs @@ -76,6 +76,10 @@ pub(crate) mod pulseaudio; #[cfg(windows)] pub(crate) mod wasapi; +#[rustfmt::skip] +#[cfg(all(windows, feature = "wasapi-new"))] +pub(crate) mod wasapi_new; + #[cfg(all( target_arch = "wasm32", any(target_os = "emscripten", target_os = "unknown"), diff --git a/src/host/wasapi_new.rs b/src/host/wasapi_new.rs new file mode 100644 index 0000000000..1456f71933 --- /dev/null +++ b/src/host/wasapi_new.rs @@ -0,0 +1,141 @@ +use crate::traits::*; +use crate::*; +use std::fmt::{self, Debug, Display}; +use std::hash::{Hash, Hasher}; +use std::time::Duration; +use std::vec; + +type SupportedConfigs = vec::IntoIter; + +pub struct Host; + +impl Host { + #[expect( + clippy::unnecessary_wraps, + reason = "required by the `impl_platform_host` macro" + )] + pub const fn new() -> Result { + Ok(Self) + } +} + +impl HostTrait for Host { + type Devices = vec::IntoIter; + type Device = Device; + + fn is_available() -> bool { + true + } + + fn devices(&self) -> Result { + todo!() + } + + fn default_input_device(&self) -> Option { + todo!() + } + + fn default_output_device(&self) -> Option { + todo!() + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Device { +} + +impl Hash for Device { + fn hash(&self, state: &mut H) { + todo!() + } +} + +impl Display for Device { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + todo!() + } +} + +impl DeviceTrait for Device { + type SupportedInputConfigs = SupportedConfigs; + type SupportedOutputConfigs = SupportedConfigs; + type Stream = Stream; + + fn description(&self) -> Result { + todo!() + } + + fn id(&self) -> Result { + todo!() + } + + fn supported_input_configs(&self) -> Result { + todo!() + } + + fn supported_output_configs(&self) -> Result { + todo!() + } + + fn default_input_config(&self) -> Result { + todo!() + } + + fn default_output_config(&self) -> Result { + todo!() + } + + fn build_input_stream_raw( + &self, + config : StreamConfig, + format : SampleFormat, + data_cb : DataCallback, + error_cb: ErrorCallback, + _timeout: Option, + ) -> Result + where + DataCallback : FnMut(&Data, &CallbackInfo) + Send + 'static, + ErrorCallback: FnMut(Error) + Send + 'static + { + todo!() + } + + fn build_output_stream_raw( + &self, + config: StreamConfig, + format: SampleFormat, + data_cb: DataCallback, + error_cb: ErrorCallback, + _timeout: Option, + ) -> Result + where + DataCallback: FnMut(&mut Data, &CallbackInfo) + Send + 'static, + ErrorCallback: FnMut(Error) + Send + 'static, + { + todo!() + } +} + +pub struct Stream; + +impl StreamTrait for Stream { + fn start(&self) -> Result<(), Error> { + todo!() + } + + fn pause(&self) -> Result<(), Error> { + todo!() + } + + fn stop(&self, timeout: Option) -> Result<(), Error> { + todo!() + } + + fn buffer_size(&self) -> Result { + todo!() + } + + fn now(&self) -> StreamInstant { + todo!() + } +} diff --git a/src/platform.rs b/src/platform.rs index a85e0dcc89..88741b9e31 100644 --- a/src/platform.rs +++ b/src/platform.rs @@ -962,10 +962,14 @@ mod platform_impl { #[cfg(feature = "asio")] use crate::host::asio::Host as AsioHost; use crate::host::wasapi::Host as WasapiHost; + #[cfg(feature = "wasapi-new")] + use crate::host::wasapi_new::Host as WasapiNewHost; impl_platform_host!( #[cfg(feature = "asio")] Asio "ASIO" => AsioHost, Wasapi "WASAPI" => WasapiHost, + #[cfg(feature = "wasapi-new")] + WasapiNew "WASAPI_new" => WasapiNewHost, #[cfg(feature = "jack")] Jack "JACK" => JackHost, #[cfg(feature = "custom")] Custom => super::CustomHost, ); From 73b5ebe1a96139ad53e0ad4bb13ec67f4bdd9df2 Mon Sep 17 00:00:00 2001 From: LastExceed Date: Wed, 4 Nov 2026 13:31:50 +0100 Subject: [PATCH 02/23] add inner stream struct for mutability --- Cargo.toml | 4 +++- src/host/wasapi_new.rs | 46 ++++++++++++++++++++++++++++++++++++------ 2 files changed, 43 insertions(+), 7 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index f7bd75e43c..efeda4ea1f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -82,7 +82,7 @@ pulseaudio = [ # New WASAPI backend using WinRT # Platform: Windows -wasapi-new = [] +wasapi-new = ["dep:tap", "dep:parking_lot"] # WebAssembly backend using wasm-bindgen # Enables the Web Audio API backend for browser-based audio @@ -136,6 +136,8 @@ windows = { version = "0.62", features = [ audio_thread_priority = { version = "0.36", optional = true, default-features = false } asio-sys = { version = "0.5.0", path = "asio-sys", optional = true } num-traits = { version = "0.2", optional = true } +tap = { version = "1.0.1", optional = true } +parking_lot = { version = "0.13.0", optional = true } jack = { version = "0.13.5", optional = true } [target.'cfg(any(target_os = "linux", target_os = "dragonfly", target_os = "freebsd", target_os = "netbsd"))'.dependencies] diff --git a/src/host/wasapi_new.rs b/src/host/wasapi_new.rs index 1456f71933..b95c16064c 100644 --- a/src/host/wasapi_new.rs +++ b/src/host/wasapi_new.rs @@ -4,6 +4,8 @@ use std::fmt::{self, Debug, Display}; use std::hash::{Hash, Hasher}; use std::time::Duration; use std::vec; +use parking_lot::Mutex; +use tap::Pipe; type SupportedConfigs = vec::IntoIter; @@ -116,26 +118,58 @@ impl DeviceTrait for Device { } } -pub struct Stream; +pub struct Stream(Mutex); +impl From for Stream { + fn from(value: StreamInner) -> Self { + value + .pipe(Mutex::new) + .pipe(Self) + } +} impl StreamTrait for Stream { fn start(&self) -> Result<(), Error> { - todo!() + self.0.lock().start() } fn pause(&self) -> Result<(), Error> { - todo!() + self.0.lock().pause() } fn stop(&self, timeout: Option) -> Result<(), Error> { - todo!() + self.0.lock().stop(timeout) } fn buffer_size(&self) -> Result { - todo!() + self.0.lock().buffer_size() } fn now(&self) -> StreamInstant { - todo!() + self.0.lock().now() } } + +struct StreamInner { +} + +impl StreamInner { + pub fn start(&mut self) -> Result<(), Error> { + todo!() + } + + pub fn pause(&mut self) -> Result<(), Error> { + todo!() + } + + pub fn stop(&mut self, timeout: Option) -> Result<(), Error> { + todo!() + } + + pub fn buffer_size(&self) -> Result { + todo!() + } + + pub fn now(&mut self) -> StreamInstant { + todo!() + } +} \ No newline at end of file From a4b56744c0ff56101fe65f7ccaea4e2570ee432c Mon Sep 17 00:00:00 2001 From: LastExceed Date: Wed, 4 Nov 2026 14:05:25 +0100 Subject: [PATCH 03/23] implement device enumeration --- Cargo.toml | 10 ++++++- src/host/wasapi_new.rs | 13 ++++++-- src/host/wasapi_new/device.rs | 56 +++++++++++++++++++++++++++++++++++ 3 files changed, 75 insertions(+), 4 deletions(-) create mode 100644 src/host/wasapi_new/device.rs diff --git a/Cargo.toml b/Cargo.toml index efeda4ea1f..7e80fb6c34 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -82,7 +82,7 @@ pulseaudio = [ # New WASAPI backend using WinRT # Platform: Windows -wasapi-new = ["dep:tap", "dep:parking_lot"] +wasapi-new = ["dep:tap", "dep:parking_lot", "dep:wasapi", "dep:itertools"] # WebAssembly backend using wasm-bindgen # Enables the Web Audio API backend for browser-based audio @@ -108,6 +108,7 @@ wasm-bindgen = [ [dependencies] dasp_sample = "0.11" +windows-collections = "0.3.2" [dev-dependencies] anyhow = "1.0" @@ -132,7 +133,14 @@ windows = { version = "0.62", features = [ "Win32_System_Variant", "Win32_Media_Multimedia", "Win32_UI_Shell_PropertiesSystem", + "Devices_Enumeration", + "Media_Devices", + "Media_Audio", + "Media_Render", + "Media_MediaProperties" ] } +wasapi = { version = "0.27.0", optional = true } +itertools = { version = "0.15.0", optional = true } audio_thread_priority = { version = "0.36", optional = true, default-features = false } asio-sys = { version = "0.5.0", path = "asio-sys", optional = true } num-traits = { version = "0.2", optional = true } diff --git a/src/host/wasapi_new.rs b/src/host/wasapi_new.rs index b95c16064c..c509305693 100644 --- a/src/host/wasapi_new.rs +++ b/src/host/wasapi_new.rs @@ -6,6 +6,9 @@ use std::time::Duration; use std::vec; use parking_lot::Mutex; use tap::Pipe; +use windows::Devices::Enumeration::DeviceInformation; + +mod device; type SupportedConfigs = vec::IntoIter; @@ -30,20 +33,24 @@ impl HostTrait for Host { } fn devices(&self) -> Result { - todo!() + device::all()? + .into_iter() + .pipe(Ok) } fn default_input_device(&self) -> Option { - todo!() + device::default::().ok() } fn default_output_device(&self) -> Option { - todo!() + device::default::().ok() } } #[derive(Debug, Clone, PartialEq, Eq)] pub struct Device { + info: DeviceInformation, + direction: DeviceDirection, } impl Hash for Device { diff --git a/src/host/wasapi_new/device.rs b/src/host/wasapi_new/device.rs new file mode 100644 index 0000000000..6d52bf7a88 --- /dev/null +++ b/src/host/wasapi_new/device.rs @@ -0,0 +1,56 @@ +use super::Device; +use super::utils::WindowsError; +use crate::DeviceDirection; +use itertools::Itertools; +use tap::Pipe; +use windows::Devices::Enumeration::DeviceInformation; +use windows::Media::Devices::{AudioDeviceRole, MediaDevice}; +use windows_collections::IIterable; +use windows_core::HSTRING; + +fn extra_properties() -> IIterable { + todo!() +} + +pub fn all() -> Result, WindowsError> { + let extra_properties = extra_properties(); + + let capture = all_in_direction::(&extra_properties)?; + let render = all_in_direction::(&extra_properties)?; + + capture + .chain(render) + .collect_vec() + .pipe(Ok) +} + +fn all_in_direction(extra_props: &IIterable) -> Result, WindowsError> { + let fn_get_selector = + if INPUT { MediaDevice::GetAudioCaptureSelector } + else { MediaDevice::GetAudioRenderSelector }; + + DeviceInformation + ::FindAllAsyncAqsFilterAndAdditionalProperties(&fn_get_selector()?, extra_props)? + .join()? + .into_iter() + .map(|info| Device { info, direction: direction::() }) + .pipe(Ok) +} + +pub fn default() -> Result { + let extra_properties = extra_properties(); + + let fn_get_id = + if INPUT { MediaDevice::GetDefaultAudioCaptureId } + else { MediaDevice::GetDefaultAudioRenderId }; + + fn_get_id(AudioDeviceRole::Default)? + .pipe_ref(|id| DeviceInformation::CreateFromIdAsyncAdditionalProperties(id, &extra_properties))? + .join() + .map(|info| Device { info, direction: direction::() }) +} + +const fn direction() -> DeviceDirection { + if INPUT { DeviceDirection::Input } + else { DeviceDirection::Output } +} \ No newline at end of file From c7d593138989e3e0f97ef3eba8a1a4d4658b59c4 Mon Sep 17 00:00:00 2001 From: LastExceed Date: Wed, 4 Nov 2026 14:39:29 +0100 Subject: [PATCH 04/23] distinguish error types --- src/host/wasapi_new.rs | 43 +++++++++++++++++++----------------- src/host/wasapi_new/utils.rs | 2 ++ 2 files changed, 25 insertions(+), 20 deletions(-) create mode 100644 src/host/wasapi_new/utils.rs diff --git a/src/host/wasapi_new.rs b/src/host/wasapi_new.rs index c509305693..1eb7c188fd 100644 --- a/src/host/wasapi_new.rs +++ b/src/host/wasapi_new.rs @@ -8,7 +8,10 @@ use parking_lot::Mutex; use tap::Pipe; use windows::Devices::Enumeration::DeviceInformation; +use self::utils::CpalError; + mod device; +mod utils; type SupportedConfigs = vec::IntoIter; @@ -19,7 +22,7 @@ impl Host { clippy::unnecessary_wraps, reason = "required by the `impl_platform_host` macro" )] - pub const fn new() -> Result { + pub const fn new() -> Result { Ok(Self) } } @@ -32,7 +35,7 @@ impl HostTrait for Host { true } - fn devices(&self) -> Result { + fn devices(&self) -> Result { device::all()? .into_iter() .pipe(Ok) @@ -70,27 +73,27 @@ impl DeviceTrait for Device { type SupportedOutputConfigs = SupportedConfigs; type Stream = Stream; - fn description(&self) -> Result { + fn description(&self) -> Result { todo!() } - fn id(&self) -> Result { + fn id(&self) -> Result { todo!() } - fn supported_input_configs(&self) -> Result { + fn supported_input_configs(&self) -> Result { todo!() } - fn supported_output_configs(&self) -> Result { + fn supported_output_configs(&self) -> Result { todo!() } - fn default_input_config(&self) -> Result { + fn default_input_config(&self) -> Result { todo!() } - fn default_output_config(&self) -> Result { + fn default_output_config(&self) -> Result { todo!() } @@ -101,10 +104,10 @@ impl DeviceTrait for Device { data_cb : DataCallback, error_cb: ErrorCallback, _timeout: Option, - ) -> Result + ) -> Result where DataCallback : FnMut(&Data, &CallbackInfo) + Send + 'static, - ErrorCallback: FnMut(Error) + Send + 'static + ErrorCallback: FnMut(CpalError) + Send + 'static { todo!() } @@ -116,10 +119,10 @@ impl DeviceTrait for Device { data_cb: DataCallback, error_cb: ErrorCallback, _timeout: Option, - ) -> Result + ) -> Result where DataCallback: FnMut(&mut Data, &CallbackInfo) + Send + 'static, - ErrorCallback: FnMut(Error) + Send + 'static, + ErrorCallback: FnMut(CpalError) + Send + 'static, { todo!() } @@ -135,19 +138,19 @@ impl From for Stream { } } impl StreamTrait for Stream { - fn start(&self) -> Result<(), Error> { + fn start(&self) -> Result<(), CpalError> { self.0.lock().start() } - fn pause(&self) -> Result<(), Error> { + fn pause(&self) -> Result<(), CpalError> { self.0.lock().pause() } - fn stop(&self, timeout: Option) -> Result<(), Error> { + fn stop(&self, timeout: Option) -> Result<(), CpalError> { self.0.lock().stop(timeout) } - fn buffer_size(&self) -> Result { + fn buffer_size(&self) -> Result { self.0.lock().buffer_size() } @@ -160,19 +163,19 @@ struct StreamInner { } impl StreamInner { - pub fn start(&mut self) -> Result<(), Error> { + pub fn start(&mut self) -> Result<(), CpalError> { todo!() } - pub fn pause(&mut self) -> Result<(), Error> { + pub fn pause(&mut self) -> Result<(), CpalError> { todo!() } - pub fn stop(&mut self, timeout: Option) -> Result<(), Error> { + pub fn stop(&mut self, timeout: Option) -> Result<(), CpalError> { todo!() } - pub fn buffer_size(&self) -> Result { + pub fn buffer_size(&self) -> Result { todo!() } diff --git a/src/host/wasapi_new/utils.rs b/src/host/wasapi_new/utils.rs new file mode 100644 index 0000000000..874dbed88e --- /dev/null +++ b/src/host/wasapi_new/utils.rs @@ -0,0 +1,2 @@ +pub type CpalError = crate::Error; +pub type WindowsError = windows_core::Error; From 92b5ce08dcb5ca9bb98b613c1c519fa3ef1ef22b Mon Sep 17 00:00:00 2001 From: LastExceed Date: Sun, 8 Nov 2026 09:52:53 +0100 Subject: [PATCH 05/23] implement device properties --- src/host/wasapi_new.rs | 21 ++++- src/host/wasapi_new/device.rs | 141 +++++++++++++++++++++++++++++++++- 2 files changed, 156 insertions(+), 6 deletions(-) diff --git a/src/host/wasapi_new.rs b/src/host/wasapi_new.rs index 1eb7c188fd..9e4a2206c7 100644 --- a/src/host/wasapi_new.rs +++ b/src/host/wasapi_new.rs @@ -74,11 +74,28 @@ impl DeviceTrait for Device { type Stream = Stream; fn description(&self) -> Result { - todo!() + let name = self.info.Name()?.to_string_lossy(); + let reader = device::PropertyReader(self.info.Properties()?); + let (device_type, interface_type) = reader.types()?; + let mut builder = DeviceDescriptionBuilder + ::new(name.clone()) + .driver(name) + .direction(self.direction) + .device_type(device_type) + .interface_type(interface_type); + if let Some(physical_location) = reader.physical_location()? { + builder = builder.address(physical_location); + } + Ok(builder.build()) } fn id(&self) -> Result { - todo!() + self.info + .Id()? + .to_string_lossy() + .into_boxed_str() + .pipe(|id| DeviceId(HostId::WasapiNew, id)) + .pipe(Ok) } fn supported_input_configs(&self) -> Result { diff --git a/src/host/wasapi_new/device.rs b/src/host/wasapi_new/device.rs index 6d52bf7a88..0988f5be03 100644 --- a/src/host/wasapi_new/device.rs +++ b/src/host/wasapi_new/device.rs @@ -1,15 +1,28 @@ use super::Device; use super::utils::WindowsError; -use crate::DeviceDirection; +use crate::{DeviceDirection, DeviceType, InterfaceType}; use itertools::Itertools; use tap::Pipe; use windows::Devices::Enumeration::DeviceInformation; +use windows::Foundation::IPropertyValue; use windows::Media::Devices::{AudioDeviceRole, MediaDevice}; +use windows::Win32::Foundation::{PROPERTYKEY, S_OK}; +use windows::Win32::Media::Audio; +use windows::Win32::Media::Audio::*; use windows_collections::IIterable; -use windows_core::HSTRING; +use windows_collections::IMapView; +use windows_core::{Array, HSTRING, IInspectable, Interface, h}; + +pub fn to_aqs(PROPERTYKEY { fmtid, pid }: &PROPERTYKEY) -> HSTRING { + format!("{{{fmtid:?}}} {pid}").into() +} fn extra_properties() -> IIterable { - todo!() + vec![ + to_aqs(&PKEY_AudioEndpoint_FormFactor), + to_aqs(&PKEY_AudioEndpoint_JackSubType), + ] + .into() } pub fn all() -> Result, WindowsError> { @@ -53,4 +66,124 @@ pub fn default() -> Result { const fn direction() -> DeviceDirection { if INPUT { DeviceDirection::Input } else { DeviceDirection::Output } -} \ No newline at end of file +} + +const PHYSICAL_DEVICE_LOCATION: &HSTRING = h!("System.Devices.PhysicalDeviceLocation"); + +pub struct PropertyReader(pub IMapView); + +impl PropertyReader { + pub fn types(&self) -> Result<(DeviceType, InterfaceType), WindowsError> { + let form_factor = self + .0 + .Lookup(&to_aqs(&PKEY_AudioEndpoint_FormFactor))? + .cast::()? + .GetInt32()? + .pipe(EndpointFormFactor); + + let mut device_type = DeviceType ::Unknown; + let mut interface_type = InterfaceType::Unknown; + + #[deny(nonstandard_style, reason = "prevent accidental wildcards")] + #[expect(unused_qualifications, reason = "rustc bug?")] + match form_factor { + Audio::RemoteNetworkDevice => interface_type = InterfaceType::Network, + Audio::Speakers => device_type = DeviceType::Speaker, + Audio::LineLevel => interface_type = InterfaceType::Line, + Audio::Headphones => device_type = DeviceType::Headphones, + Audio::Microphone => device_type = DeviceType::Microphone, + Audio::Headset => device_type = DeviceType::Headset, + Audio::Handset => device_type = DeviceType::Handset, + Audio::UnknownDigitalPassthrough => interface_type = InterfaceType::Virtual, + Audio::SPDIF => interface_type = InterfaceType::Spdif, + Audio::DigitalAudioDisplayDevice => interface_type = InterfaceType::DisplayPort, + Audio::UnknownFormFactor => interface_type = InterfaceType::Unknown, + _ => unreachable!() + }; + + let jack_sub_type = self + .0 + .Lookup(&to_aqs(&PKEY_AudioEndpoint_JackSubType))? + .cast::()? + .GetString()? + .to_string_lossy() + .trim_matches(['{', '}']) + .try_into()?; + + use windows::Win32::Media::KernelStreaming::*; + #[deny(nonstandard_style, reason = "prevent accidental wildcards")] + match jack_sub_type { + KSNODETYPE_DISPLAYPORT_INTERFACE => interface_type = InterfaceType::DisplayPort, + + KSNODETYPE_SPDIF_INTERFACE => interface_type = InterfaceType::Spdif, + + KSNODETYPE_HDMI_INTERFACE => interface_type = InterfaceType::Hdmi, + + KSNODETYPE_AUDIO_ENGINE | + KSNODETYPE_AUDIO_LOOPBACK => interface_type = InterfaceType::Virtual, + + KSNODETYPE_BIDIRECTIONAL_UNDEFINED => interface_type = InterfaceType::Aggregate, + + KSNODETYPE_ADC | + KSNODETYPE_DAC | + KSNODETYPE_ANALOG_CONNECTOR | + KSNODETYPE_LINE_CONNECTOR | + KSNODETYPE_PHONE_LINE => interface_type = InterfaceType::Line, + + KSNODETYPE_TV_TUNER_AUDIO | + KSNODETYPE_CABLE_TUNER_AUDIO => device_type = DeviceType::Tuner, + + KSNODETYPE_SPEAKER | + KSNODETYPE_COMMUNICATION_SPEAKER | + KSNODETYPE_DESKTOP_SPEAKER | + KSNODETYPE_ROOM_SPEAKER | + KSNODETYPE_LOW_FREQUENCY_EFFECTS_SPEAKER | + KSNODETYPE_SPEAKERS_STATIC_JACK | + KSNODETYPE_SPEAKERPHONE_NO_ECHO_REDUCTION | + KSNODETYPE_ECHO_CANCELING_SPEAKERPHONE | + KSNODETYPE_ECHO_SUPPRESSING_SPEAKERPHONE | + KSNODETYPE_PHONOGRAPH => device_type = DeviceType::Speaker, + + + KSNODETYPE_MICROPHONE | + KSNODETYPE_MICROPHONE_ARRAY | + KSNODETYPE_DESKTOP_MICROPHONE | + KSNODETYPE_PERSONAL_MICROPHONE | + KSNODETYPE_PROCESSING_MICROPHONE_ARRAY | + KSNODETYPE_OMNI_DIRECTIONAL_MICROPHONE => device_type = DeviceType::Microphone, + + KSNODETYPE_DIGITAL_AUDIO_INTERFACE => device_type = DeviceType::Dock, + + KSNODETYPE_HEADPHONES => device_type = DeviceType::Headphones, + + KSNODETYPE_HEADSET | + KSNODETYPE_HEAD_MOUNTED_DISPLAY_AUDIO => device_type = DeviceType::Headset, + + KSNODETYPE_HANDSET | + KSNODETYPE_TELEPHONE | + KSNODETYPE_TELEPHONY_BIDI | + KSNODETYPE_TELEPHONY_UNDEFINED | + KSNODETYPE_DOWN_LINE_PHONE => device_type = DeviceType::Handset, + + _ => () + } + + Ok((device_type, interface_type)) + } + + pub fn physical_location(&self) -> Result, WindowsError> { + match self.0.Lookup(PHYSICAL_DEVICE_LOCATION) { + Err(error) if error.code() == S_OK => Ok(None), // https://github.com/microsoft/windows-rs/issues/4858 + + Err(error) => Err(error), + + Ok(inspectable) => { + let mut buf = Array::new(); + inspectable + .cast::()? + .GetUInt8Array(&mut buf)?; + Ok(Some(format!("{:x?}", buf.as_slice()))) + } + } + } +} From 2a1f27ea5c8e037dffbcbea1b3a34e64525f1ca5 Mon Sep 17 00:00:00 2001 From: LastExceed Date: Sun, 8 Nov 2026 10:05:09 +0100 Subject: [PATCH 06/23] implement config enumeration --- src/host/wasapi_new.rs | 122 +++++++++++++++++++++++++++++++++-- src/host/wasapi_new/utils.rs | 62 ++++++++++++++++++ 2 files changed, 177 insertions(+), 7 deletions(-) diff --git a/src/host/wasapi_new.rs b/src/host/wasapi_new.rs index 9e4a2206c7..d2b618773f 100644 --- a/src/host/wasapi_new.rs +++ b/src/host/wasapi_new.rs @@ -1,14 +1,21 @@ +use self::utils::*; +use crate::ErrorKind::{BackendError, ResourceExhausted}; use crate::traits::*; use crate::*; +use itertools::Itertools; use std::fmt::{self, Debug, Display}; use std::hash::{Hash, Hasher}; +use std::sync::Arc; use std::time::Duration; -use std::vec; +use std::{thread, vec}; use parking_lot::Mutex; use tap::Pipe; +use wasapi::{ + AudioClient, AudioClock, Device as MMDevice, DeviceEnumerator, Direction, SampleType, + ShareMode, StreamMode, WaveFormat, +}; use windows::Devices::Enumeration::DeviceInformation; - -use self::utils::CpalError; +use windows_core::Interface; mod device; mod utils; @@ -68,6 +75,107 @@ impl Display for Device { } } +impl Device { + fn mm_device(&self) -> Result { + let enumerator = DeviceEnumerator::new()?; + + self.info + .Id()? + .to_string_lossy() + .split('#') + .nth(2) + .ok_or(CpalError::with_message(BackendError, "malformed device id encountered"))? + .pipe(|id| enumerator.get_device(id))? + .pipe(Ok) + } + + fn default_config(&self) -> Result { + let mm_device = self.mm_device()?; + validate_direction::(&mm_device)?; + + mm_device + .get_iaudioclient()? + .get_mixformat()? + .try_into() + } + + fn supported_configs(&self) -> Result { + use SampleFormat::*; + + let mm_device = self.mm_device()?; + validate_direction::(&mm_device)?; + + let client = mm_device.get_iaudioclient()?; + + mm_device + .get_data_ranges()? + .into_iter() + .flat_map(move |range| + COMMON_SAMPLE_RATES + .iter() + .copied() + .skip_while(move |rate| *rate < range.min_samplerate) + .take_while(move |rate| *rate <= range.max_samplerate) + .flat_map(move |sample_rate| + (1..=range.max_channels) + .flat_map(move |channel_count| + [I8, I16, I24, I32, F32] + .into_iter() + .filter(move |format| + range + .sample_type() + .is_none_or(|ty| + (ty == SampleType::Int) + == format.is_int() + ) + ) + .map(move |format| (format, format.sample_size() * 8)) + .skip_while(move |(_format, store_bits)| range.min_bits_per_sample > *store_bits as u32) + .take_while(move |(_format, store_bits)| range.max_bits_per_sample >= *store_bits as u32) + .map(move |(format, store_bits)| WaveFormat::new( + store_bits, + format.bits_per_sample() as _, + SampleType::Int, + sample_rate as _, + channel_count as _, + None + )) + ) + ) + ) + .unique() // DataRanges can overlap + .filter_map(|waveformat| + client + .is_supported(&waveformat, ShareMode::Shared) + .map(|ret| ret.unwrap_or(waveformat)) + .ok() + ) + .unique() // `.is_supported()` might have reported the same "closest match" multiple times + .filter_map(|waveformat| SupportedStreamConfig::try_from(waveformat).ok()) // this will most likely never fail anyway + .map(|config| { + let format = config.sample_format(); + let channels = config.channels(); + let rate = config.sample_rate(); + + ((format, channels), rate) + }) + .into_group_map() + .into_iter() + .map(|((sample_format, channels), rates)| + SupportedStreamConfigRange { + channels, + min_sample_rate: rates.iter().copied().min().unwrap(), + max_sample_rate: rates.iter().copied().max().unwrap(), + buffer_size: SupportedBufferSize::default(), + sample_format, + } + ) + .collect::>() + .into_iter() + .pipe(Ok) + } +} + impl DeviceTrait for Device { type SupportedInputConfigs = SupportedConfigs; type SupportedOutputConfigs = SupportedConfigs; @@ -99,19 +207,19 @@ impl DeviceTrait for Device { } fn supported_input_configs(&self) -> Result { - todo!() + self.supported_configs::() } fn supported_output_configs(&self) -> Result { - todo!() + self.supported_configs::() } fn default_input_config(&self) -> Result { - todo!() + self.default_config::() } fn default_output_config(&self) -> Result { - todo!() + self.default_config::() } fn build_input_stream_raw( diff --git a/src/host/wasapi_new/utils.rs b/src/host/wasapi_new/utils.rs index 874dbed88e..0753236ee1 100644 --- a/src/host/wasapi_new/utils.rs +++ b/src/host/wasapi_new/utils.rs @@ -1,2 +1,64 @@ +use crate::ErrorKind::{BackendError, UnsupportedOperation}; +use crate::{DeviceDirection, SampleFormat, StreamConfig, SupportedBufferSize, SupportedStreamConfig}; +use std::alloc::{Layout, alloc_zeroed, dealloc}; +use std::fmt::Debug; +use std::mem::transmute; +use std::ops::{Deref, DerefMut}; +use std::slice; +use std::sync::atomic::{AtomicU8, Ordering}; +use std::time::Duration; +use tap::Pipe; +use wasapi::{Direction, SampleType, WaveFormat}; +use windows::Win32::Foundation::{CloseHandle, HANDLE, WAIT_EVENT, WAIT_FAILED, WAIT_OBJECT_0, WAIT_TIMEOUT}; +use windows::Win32::System::Threading::{CreateEventW, INFINITE, SetEvent, WaitForMultipleObjects, WaitForSingleObject}; + pub type CpalError = crate::Error; +pub type WasapiRsError = wasapi::WasapiError; pub type WindowsError = windows_core::Error; + +impl From for CpalError { + fn from(value: WasapiRsError) -> Self { + CpalError::with_message(BackendError, format!("{value}")) + } +} + +impl From for DeviceDirection { + fn from(value: Direction) -> Self { + match value { + Direction::Capture => DeviceDirection::Input, + Direction::Render => DeviceDirection::Output + } + } +} + +impl TryFrom for SupportedStreamConfig { + type Error = CpalError; + + fn try_from(waveformat: WaveFormat) -> Result { + SupportedStreamConfig { + channels: waveformat.get_nchannels(), + sample_rate: waveformat.get_samplespersec(), + buffer_size: SupportedBufferSize::default(), + sample_format: match waveformat.get_validbitspersample() { + 8 => SampleFormat::I8, + 16 => SampleFormat::I16, + 24 => SampleFormat::I24, + 32 if waveformat.get_subformat()? == SampleType::Float => SampleFormat::F32, + 32 => SampleFormat::I32, + _ => return Err(CpalError::with_message(BackendError, "sound server reported unexpected mix format")) + } + } + .pipe(Ok) + } +} + +pub fn validate_direction(mm_device: &wasapi::Device) -> Result<(), CpalError> { + let is_input = mm_device.get_direction() == Direction::Capture; + + // FIXME: use `bool::ok_or()` once MSRV has risen to 1.98 + if INPUT != is_input { + return Err(CpalError::with_message(UnsupportedOperation, "This device only operates in the other direction")) + } + + Ok(()) +} From ff8b545e5bcf86f82965fdeafb6ed42d99a1c1df Mon Sep 17 00:00:00 2001 From: LastExceed Date: Sun, 8 Nov 2026 10:16:52 +0100 Subject: [PATCH 07/23] implement streams --- src/host/wasapi_new.rs | 163 ++++++++++++++++++++++++-- src/host/wasapi_new/processing.rs | 157 +++++++++++++++++++++++++ src/host/wasapi_new/utils.rs | 183 ++++++++++++++++++++++++++++++ 3 files changed, 495 insertions(+), 8 deletions(-) create mode 100644 src/host/wasapi_new/processing.rs diff --git a/src/host/wasapi_new.rs b/src/host/wasapi_new.rs index d2b618773f..d4667e9bed 100644 --- a/src/host/wasapi_new.rs +++ b/src/host/wasapi_new.rs @@ -1,3 +1,4 @@ +use self::processing::FnProcess; use self::utils::*; use crate::ErrorKind::{BackendError, ResourceExhausted}; use crate::traits::*; @@ -18,6 +19,7 @@ use windows::Devices::Enumeration::DeviceInformation; use windows_core::Interface; mod device; +mod processing; mod utils; type SupportedConfigs = vec::IntoIter; @@ -174,6 +176,75 @@ impl Device { .into_iter() .pipe(Ok) } + + #[expect(clippy::too_many_arguments, reason = "3 of these only exist due to certain language features not yet being stable (see comments)")] + fn build_stream_inner( + &self, + config : StreamConfig, + sample_format : SampleFormat, + mut data_cb : DataCallback, + error_cb : ErrorCallback, + direction : Direction, // const generics when? + fn_new_processor: fn(&AudioClient) -> Result, // unique function ZSTs when? + fn_process : FnProcess // unique function ZSTs when? + ) -> Result + where + Processor : 'static, + DataCallback : Send + 'static, + ErrorCallback: FnMut(Error) + Send + 'static + { + let mm_device = self.mm_device()?; + let mut audio_client = mm_device.get_iaudioclient()?; + + let waveformat = create_waveformat(config, sample_format)?; + let period_frames = match config.buffer_size { + BufferSize::Fixed(n) => n, + BufferSize::Default => audio_client.get_shared_mode_engine_period(&waveformat)?.default + }; + + audio_client.initialize_client( + &waveformat, + direction, + StreamMode::EventsShared { autoconvert: true, buffer_duration_hns: 0 }, + None + )?; + + let processor = audio_client.pipe_ref(fn_new_processor)?.pipe(SendSync); + let audio_client = audio_client.pipe(SendSync).pipe(Arc::new); + let audio_clock = audio_client.get_audioclock()?.pipe(SendSync).pipe(Arc::new); + let buffer_event = audio_client.set_get_eventhandle()?.pipe(SendSync); + let total_frames = audio_client.get_buffer_size()?; + let mut scratch = ScratchBuffer::new(total_frames as usize * config.channels as usize, sample_format); + let stream_state = WaitableStreamState::new()?.pipe(Arc::new); + + let audio_client2 = Arc::clone(&audio_client); + let stream_state2 = Arc::clone(&stream_state); + thread::spawn(move || { + _ = processing::run_loop( + &buffer_event, + &audio_client2, + &processor, + &stream_state2, + &mut scratch, + &mut data_cb, + fn_process, + sample_format, + config.channels as _, + ) + .map_err(error_cb); + }); + + StreamInner { + total_frames, + period_frames, + audio_client, + audio_clock, + stream_state, + last_hns: u64::MIN, + } + .pipe(Stream::from) + .pipe(Ok) + } } impl DeviceTrait for Device { @@ -234,7 +305,15 @@ impl DeviceTrait for Device { DataCallback : FnMut(&Data, &CallbackInfo) + Send + 'static, ErrorCallback: FnMut(CpalError) + Send + 'static { - todo!() + self.build_stream_inner( + config, + format, + data_cb, + error_cb, + Direction::Capture, + AudioClient::get_audiocaptureclient, + processing::capture + ) } fn build_output_stream_raw( @@ -249,7 +328,15 @@ impl DeviceTrait for Device { DataCallback: FnMut(&mut Data, &CallbackInfo) + Send + 'static, ErrorCallback: FnMut(CpalError) + Send + 'static, { - todo!() + self.build_stream_inner( + config, + format, + data_cb, + error_cb, + Direction::Render, + AudioClient::get_audiorenderclient, + processing::render + ) } } @@ -285,26 +372,86 @@ impl StreamTrait for Stream { } struct StreamInner { + total_frames : u32, + period_frames: u32, + audio_client : Arc>, + audio_clock : Arc>, + stream_state : Arc, + last_hns : u64 +} + +unsafe impl Send for StreamInner {} + +impl Debug for StreamInner { + fn fmt(&self, _f: &mut fmt::Formatter<'_>) -> fmt::Result { + todo!() // https://github.com/HEnquist/wasapi-rs/pull/86 + } } impl StreamInner { pub fn start(&mut self) -> Result<(), CpalError> { - todo!() + if self.stream_state.get() == StreamState::Halted { + self.audio_client.start_stream()?; + } + + self.stream_state.set(StreamState::Running, true)?; + + Ok(()) } pub fn pause(&mut self) -> Result<(), CpalError> { - todo!() + if self.stream_state.get() != StreamState::Halted { + self.audio_client.stop_stream()?; + } + + self.stream_state.set(StreamState::Halted, true)?; + + Ok(()) } pub fn stop(&mut self, timeout: Option) -> Result<(), CpalError> { - todo!() + if self.stream_state.get() == StreamState::Halted { + return Ok(()); + } + + self.stream_state.set(StreamState::Draining, false)?; + + let wait_success = self + .stream_state + .event() + .wait_single(timeout)?; + + self.audio_client.stop_stream()?; + self.audio_client.reset_stream()?; + + // FIXME: use `bool::ok_or()` once MSRV has risen to 1.98 + if !wait_success { + return Err(CpalError::with_message(ResourceExhausted, "timeout expired")) + } + + Ok(()) } pub fn buffer_size(&self) -> Result { - todo!() + self.audio_client + .get_current_padding()? + .pipe(|padding| self.total_frames - padding + self.period_frames) + .pipe(Ok) } pub fn now(&mut self) -> StreamInstant { - todo!() + self.last_hns = self + .audio_clock + .get_position() + .map_or(u64::MIN, |(_pos, hns)| hns) + .max(self.last_hns); + + StreamInstant::from_nanos(self.last_hns * 100) } -} \ No newline at end of file +} + +impl Drop for StreamInner { + fn drop(&mut self) { + _ = self.stream_state.set(StreamState::Exit, false); + } +} diff --git a/src/host/wasapi_new/processing.rs b/src/host/wasapi_new/processing.rs new file mode 100644 index 0000000000..07724b9833 --- /dev/null +++ b/src/host/wasapi_new/processing.rs @@ -0,0 +1,157 @@ +use super::utils::StreamState::*; +use super::utils::*; +use crate::host::equilibrium::fill_equilibrium; +use crate::*; +use std::mem::MaybeUninit; +use std::time::Duration; +use tap::Pipe; +use wasapi::{AudioCaptureClient, AudioClient, AudioRenderClient, Handle}; +use windows::Win32::System::Performance::{QueryPerformanceCounter, QueryPerformanceFrequency}; + +#[expect(clippy::too_many_arguments, reason = "this is basically just the capture context of the thread spawn closure written out")] +pub fn run_loop( + buffer_event : &Handle, + audio_client : &AudioClient, + processor : &SendSync, + stream_state : &WaitableStreamState, + scratch_buf : &mut ScratchBuffer, + data_callback: &mut DataCallback, + fn_process : FnProcess, + sample_format: SampleFormat, + channel_count: usize +) -> Result<(), CpalError> { + loop { + wait_event(stream_state, buffer_event, None)?; + + #[deny(non_snake_case, reason = "prevent accidental wildcard patterns from typos")] + match stream_state.get() { + Running => fn_process( + audio_client, + processor, + data_callback, + scratch_buf, + sample_format, + channel_count + )?, + + Draining if audio_client.get_current_padding()? > 0 + => continue, + + Draining => stream_state.set(Halted, true)?, + + Halted => continue, + + Exit => break Ok(()) + } + } +} + +fn wait_event( + stream_state: &WaitableStreamState, + buffer_event: &Handle, + timeout: Option +) -> Result, WindowsError> { + let state_event = stream_state.event(); + + if stream_state.get() == Halted { + // The engine signals the buffer event even if the stream is halted + // So we need to ignore it here + return state_event + .wait_single(timeout)? + .then_some(0) + .pipe(Ok); + } + + let events = [ + buffer_event.as_handle(), + *state_event.as_raw() + ]; + + Event::wait_multiple(&events, timeout) +} + +pub type FnProcess = fn( + audio_client : &AudioClient, + processor : &Processor, + data_callback: &mut DataCallback, + scratch_buf : &mut ScratchBuffer, + sample_format: SampleFormat, + channel_count: usize +) -> Result<(), WasapiRsError>; + +pub fn capture( + _audio_client : &AudioClient, // only here to match the function signature of [`render`] + capture_client: &AudioCaptureClient, + data_callback : &mut (impl FnMut(&Data, &CallbackInfo) + Send + 'static), + scratch_buf : &mut ScratchBuffer, + sample_format : SampleFormat, + channel_count : usize +) -> Result<(), WasapiRsError> { + let (frame_count, buffer_info) = capture_client.read_from_device(scratch_buf.slice())?; + let sample_count = frame_count as usize * channel_count; + + if buffer_info.flags.silent { + fill_equilibrium(scratch_buf.slice(), sample_format); + } else if sample_format == SampleFormat::I24 { + // WASAPI stores I24 in the upper bits + scratch_buf.shift_down(sample_count); + } + + let data = unsafe { Data::from_parts(scratch_buf.ptr.cast(), sample_count, sample_format) }; + let cbi = create_cbi(buffer_info.timestamp, buffer_info.flags.data_discontinuity); + + data_callback(&data, &cbi); + + Ok(()) +} + +pub fn render( + audio_client : &AudioClient, + render_client: &AudioRenderClient, + data_callback: &mut (impl FnMut(&mut Data, &CallbackInfo) + Send + 'static), + scratch_buf : &mut ScratchBuffer, + sample_format: SampleFormat, + channel_count: usize +) -> Result<(), WasapiRsError> { + let frame_count = audio_client.get_available_space_in_frames()?; + let sample_count = frame_count as usize * channel_count; + + let mut data = unsafe { Data::from_parts(scratch_buf.ptr.cast(), sample_count, sample_format) }; + let latency = unsafe { audio_client.as_iaudioclient().GetStreamLatency() }? as u64; // https://github.com/HEnquist/wasapi-rs/pull/83 + let cbi = create_cbi(now_hns() + latency, false); + + data_callback(&mut data, &cbi); + + if sample_format == SampleFormat::I24 { + // WASAPI stores I24 in the upper bits + scratch_buf.shift_up(sample_count); + } + + render_client.write_to_device(data.bytes_mut(), None) +} + +fn create_cbi(device_hns: u64, xrun: bool) -> CallbackInfo { + CallbackInfo { + timestamp: StreamTimestamp { + callback: StreamInstant::from_nanos(now_hns() * 100), + device: StreamInstant::from_nanos(device_hns * 100) + }, + xrun + } +} + +fn now_hns() -> u64 { + let mut count = MaybeUninit::uninit(); + let mut freq = MaybeUninit::uninit(); + + let hns = unsafe { + QueryPerformanceCounter (count.as_mut_ptr()).unwrap(); // infallible since Windows XP + QueryPerformanceFrequency(freq.as_mut_ptr()).unwrap(); // infallible since Windows XP + + count.assume_init() as i128 + * 10_000_000 + / freq.assume_init() as i128 + }; + + hns as _ +} diff --git a/src/host/wasapi_new/utils.rs b/src/host/wasapi_new/utils.rs index 0753236ee1..78f26795d0 100644 --- a/src/host/wasapi_new/utils.rs +++ b/src/host/wasapi_new/utils.rs @@ -16,6 +16,152 @@ pub type CpalError = crate::Error; pub type WasapiRsError = wasapi::WasapiError; pub type WindowsError = windows_core::Error; +pub struct ScratchBuffer { + pub ptr: *mut u8, + pub layout: Layout +} + +unsafe impl Send for ScratchBuffer {} +unsafe impl Sync for ScratchBuffer {} + +impl ScratchBuffer { + pub fn new(sample_count: usize, format: SampleFormat) -> Self { + let size = sample_count * format.sample_size(); + let align = format.sample_size(); + let layout = Layout::from_size_align(size, align).unwrap(); + let ptr = unsafe { alloc_zeroed(layout) }; + + Self { ptr, layout } + } + + pub fn slice(&mut self) -> &mut [u8] { + unsafe { + slice::from_raw_parts_mut( + self.ptr, + self.layout.size() + ) + } + } + + fn slice_i32(&mut self) -> &mut [i32] { + unsafe { + slice::from_raw_parts_mut( + self.ptr.cast(), + self.layout.size() / size_of::() + ) + } + } + + pub fn shift_up(&mut self, sample_count: usize) { + for sample in &mut self.slice_i32()[..sample_count] { + *sample <<= 8; + } + } + + pub fn shift_down(&mut self, sample_count: usize) { + for sample in &mut self.slice_i32()[..sample_count] { + *sample >>= 8; + } + } +} + +impl Drop for ScratchBuffer { + fn drop(&mut self) { + unsafe { dealloc(self.ptr, self.layout) }; + } +} + +#[derive(Debug)] +pub struct Event(HANDLE); + +unsafe impl Send for Event {} +unsafe impl Sync for Event {} + +impl Event { + pub fn new() -> Result { + unsafe { CreateEventW(None, false, true, None) }.map(Self) + } + + pub const fn as_raw(&self) -> &HANDLE { + &self.0 + } + + pub fn set_signaled(&self) -> Result<(), WindowsError> { + unsafe { SetEvent(self.0) } + } + + pub fn wait_single(&self, timeout: Option) -> Result { + let millis = timeout.map_or(INFINITE, |duration| duration.as_millis() as _); + + match unsafe { WaitForSingleObject(self.0, millis) } { + WAIT_OBJECT_0 => Ok(true), + WAIT_TIMEOUT => Ok(false), + WAIT_FAILED => Err(windows_core::Error::from_thread()), + _ => unreachable!() + } + } + + pub fn wait_multiple(events: &[HANDLE], timeout: Option) -> Result, WindowsError> { + let dwmilliseconds = timeout.map_or(INFINITE, |duration| duration.as_millis() as _); + let wait_event = unsafe { WaitForMultipleObjects(events, false, dwmilliseconds) }; + + #[deny(nonstandard_style, reason = "prevent accidental wildcards")] + match wait_event { + WAIT_FAILED => Err(windows_core::Error::from_thread()), + WAIT_TIMEOUT => Ok(None), + WAIT_EVENT(i) => Ok(Some(i as _)) + } + } +} + +impl Drop for Event { + fn drop(&mut self) { + _ = unsafe { CloseHandle(self.0) }; + } +} + +#[repr(u8)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum StreamState { + Running, + Draining, + Halted, + Exit +} + +#[derive(Debug)] +pub struct WaitableStreamState { + atomic: AtomicU8, + event: Event +} + +impl WaitableStreamState { + pub fn new() -> Result { + Self { + atomic: AtomicU8::new(StreamState::Halted as _), + event: Event::new()? + } + .pipe(Ok) + } + + pub fn get(&self) -> StreamState { + unsafe { transmute(self.atomic.load(Ordering::Relaxed)) } + } + + pub fn set(&self, value: StreamState, signal: bool) -> Result<(), WindowsError> { + self.atomic.store(value as _, Ordering::Relaxed); + if signal { + self.event.set_signaled()?; + } + Ok(()) + } + + #[must_use] + pub const fn event(&self) -> &Event { + &self.event + } +} + impl From for CpalError { fn from(value: WasapiRsError) -> Self { CpalError::with_message(BackendError, format!("{value}")) @@ -62,3 +208,40 @@ pub fn validate_direction(mm_device: &wasapi::Device) -> Resu Ok(()) } + +pub fn create_waveformat(config: StreamConfig, format: SampleFormat) -> Result { + let sample_type = + if format.is_int() { SampleType::Int } + else if format.is_float() { SampleType::Float } + else { return Err(WasapiRsError::UnsupportedFormat) }; + + WaveFormat::new( + format.sample_size() * u8::BITS as usize, + format.bits_per_sample() as _, + sample_type, + config.sample_rate as _, + config.channels as _, + None + ) + .pipe(Ok) +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub struct SendSync(pub T); + +unsafe impl Send for SendSync {} +unsafe impl Sync for SendSync {} + +impl Deref for SendSync { + type Target = T; + + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +impl DerefMut for SendSync { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} From f9d6e4442747ff2922d551289296b38b269a2dbc Mon Sep 17 00:00:00 2001 From: LastExceed Date: Sun, 8 Nov 2026 10:13:22 +0100 Subject: [PATCH 08/23] add missing trait impls --- src/host/wasapi_new.rs | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/src/host/wasapi_new.rs b/src/host/wasapi_new.rs index d4667e9bed..b159c8372f 100644 --- a/src/host/wasapi_new.rs +++ b/src/host/wasapi_new.rs @@ -67,13 +67,18 @@ pub struct Device { impl Hash for Device { fn hash(&self, state: &mut H) { - todo!() + self.info.as_raw().hash(state); + self.direction.hash(state); } } impl Display for Device { fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { - todo!() + if let Ok(name) = self.info.Name() { + Display::fmt(&name, formatter) + } else { + Display::fmt("(device name lookup failed)", formatter) + } } } @@ -340,6 +345,7 @@ impl DeviceTrait for Device { } } +#[derive(Debug)] pub struct Stream(Mutex); impl From for Stream { From cdf4d4aecb6c8d3a1827b4758a0f388893f5beb9 Mon Sep 17 00:00:00 2001 From: LastExceed Date: Sun, 8 Nov 2026 09:47:31 +0100 Subject: [PATCH 09/23] update README --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index b96b319fda..2c3859359d 100644 --- a/README.md +++ b/README.md @@ -52,6 +52,7 @@ The minimum Rust version (MSRV) and minimum operating system / runtime version b | PipeWire | Linux, BSD | 1.85 | PipeWire 0.3.53 | | PulseAudio | Linux, BSD | 1.88 | — | | WASAPI / ASIO | Windows | 1.85 | Windows 10 | +| New WASAPI (`-F wasapi-new`) | Windows | 1.85 | Windows 10 | | WASM (`wasm32-unknown-unknown`) | WebAssembly | 1.85 | — | | WASM (`wasm32-unknown-emscripten`) | WebAssembly | 1.85 | Emscripten 6.0.3, wasm-bindgen 0.2.127 | | WASM (`audioworklet`) | WebAssembly | nightly | — | @@ -70,6 +71,7 @@ The `audioworklet` backend additionally requires `-Zbuild-std` with atomics supp | `pulseaudio` | Linux, BSD | PulseAudio sound server backend. Requires `libpulse-dev` (Debian/Ubuntu) or `pulseaudio-libs-devel` (Fedora). | | `realtime` | Android, Linux, Windows | Raises the audio callback thread to real-time or high-priority scheduling for lower latency. On Linux, requires `CAP_SYS_NICE`, root, or an `rtprio` limit granted via `limits.conf` or systemd, unless `realtime-dbus` is also enabled. | | `realtime-dbus` | Linux | Uses `rtkit` via D-Bus for RT scheduling on Linux desktop systems. Implies `realtime` on all platforms. Requires `libdbus-1-dev` on Linux. | +|`wasapi-new`|Windows| Rewrite of the WASAPI host, intended to replace the current one soon. | | `wasm-bindgen` | WebAssembly (`wasm32-unknown-emscripten`, `wasm32-unknown-unknown`) | Web Audio API backend for browser-based audio; required for any WebAssembly audio support. See the `webaudio` example. | See the [beep example](examples/beep.rs) for selecting the backend at runtime. From b06244f1eb0f156f359feb645b58778ce46bd9fb Mon Sep 17 00:00:00 2001 From: LastExceed Date: Sun, 8 Nov 2026 10:35:40 +0100 Subject: [PATCH 10/23] raise MSRV to 1.95 --- .github/actions/determine-msrv/action.yml | 10 +++++++++- .github/workflows/platforms.yml | 2 ++ README.md | 2 +- 3 files changed, 12 insertions(+), 2 deletions(-) diff --git a/.github/actions/determine-msrv/action.yml b/.github/actions/determine-msrv/action.yml index 41449fc874..cc4a845eba 100644 --- a/.github/actions/determine-msrv/action.yml +++ b/.github/actions/determine-msrv/action.yml @@ -16,6 +16,10 @@ inputs: description: The MSRV for Pipewire backend (optional, Linux only) required: false default: '' + wasapi-new-msrv: + description: The MSRV for the wasapi-new feature (optional, Windows only) + required: false + default: '' outputs: all-features: @@ -33,6 +37,7 @@ runs: JACK_MSRV="${{ inputs.jack-msrv }}" PULSEAUDIO_MSRV="${{ inputs.pulseaudio-msrv }}" PIPEWIRE_MSRV="${{ inputs.pipewire-msrv }}" + WASAPI_NEW_MSRV="${{ inputs.wasapi-new-msrv }}" # Use sort -V to find the maximum version VERSIONS="$PLATFORM_MSRV $JACK_MSRV" if [ -n "$PULSEAUDIO_MSRV" ]; then @@ -41,6 +46,9 @@ runs: if [ -n "$PIPEWIRE_MSRV" ]; then VERSIONS="$VERSIONS $PIPEWIRE_MSRV" fi + if [ -n "$WASAPI_NEW_MSRV" ]; then + VERSIONS="$VERSIONS $WASAPI_NEW_MSRV" + fi MAX_MSRV=$(printf '%s\n' $VERSIONS | sort -V | tail -n1) echo "all-features=$MAX_MSRV" >> $GITHUB_OUTPUT - echo "Platform MSRV: $PLATFORM_MSRV, JACK MSRV: $JACK_MSRV, PulseAudio MSRV: $PULSEAUDIO_MSRV, PIPEWIRE_MSRV: $PIPEWIRE_MSRV, Using for --all-features: $MAX_MSRV" + echo "Platform MSRV: $PLATFORM_MSRV, JACK MSRV: $JACK_MSRV, PulseAudio MSRV: $PULSEAUDIO_MSRV, PIPEWIRE_MSRV: $PIPEWIRE_MSRV, WASAPI-new MSRV: $WASAPI_NEW_MSRV, Using for --all-features: $MAX_MSRV" diff --git a/.github/workflows/platforms.yml b/.github/workflows/platforms.yml index 881b2a6e3d..560819a9ec 100644 --- a/.github/workflows/platforms.yml +++ b/.github/workflows/platforms.yml @@ -32,6 +32,7 @@ env: MSRV_PULSEAUDIO: "1.88" MSRV_WASM: "1.85" MSRV_WINDOWS: "1.85" + MSRV_WASAPI_NEW: "1.95" PACKAGES_LINUX: libasound2-dev libdbus-1-dev libjack-jackd2-dev libpipewire-0.3-dev @@ -245,6 +246,7 @@ jobs: with: platform-msrv: ${{ env.MSRV_WINDOWS }} jack-msrv: ${{ env.MSRV_JACK }} + wasapi-new-msrv: ${{ env.MSRV_WASAPI_NEW }} - name: Install Rust MSRV (${{ env.MSRV_WINDOWS }}) uses: dtolnay/rust-toolchain@master diff --git a/README.md b/README.md index 2c3859359d..0f662225c7 100644 --- a/README.md +++ b/README.md @@ -52,7 +52,7 @@ The minimum Rust version (MSRV) and minimum operating system / runtime version b | PipeWire | Linux, BSD | 1.85 | PipeWire 0.3.53 | | PulseAudio | Linux, BSD | 1.88 | — | | WASAPI / ASIO | Windows | 1.85 | Windows 10 | -| New WASAPI (`-F wasapi-new`) | Windows | 1.85 | Windows 10 | +| New WASAPI (`-F wasapi-new`) | Windows | 1.95 | Windows 10 | | WASM (`wasm32-unknown-unknown`) | WebAssembly | 1.85 | — | | WASM (`wasm32-unknown-emscripten`) | WebAssembly | 1.85 | Emscripten 6.0.3, wasm-bindgen 0.2.127 | | WASM (`audioworklet`) | WebAssembly | nightly | — | From fe98f777af156361b59aecd549403ec4ed5ddc68 Mon Sep 17 00:00:00 2001 From: LastExceed Date: Sun, 8 Nov 2026 15:05:03 +0100 Subject: [PATCH 11/23] configure default host --- src/platform.rs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/platform.rs b/src/platform.rs index 88741b9e31..97b373cd62 100644 --- a/src/platform.rs +++ b/src/platform.rs @@ -976,6 +976,12 @@ mod platform_impl { /// The default host for the current compilation target platform. pub fn default_host() -> Host { + #[cfg(feature = "wasapi-new")] + return WasapiNewHost::new() + .expect("the default host should always be available") + .into(); + + #[cfg(not(feature = "wasapi-new"))] WasapiHost::new() .expect("the default host should always be available") .into() From a99d64e1d01d7e57d829539ffce95f7636aeb9cf Mon Sep 17 00:00:00 2001 From: LastExceed Date: Sun, 8 Nov 2026 15:05:40 +0100 Subject: [PATCH 12/23] fix whitespaces --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 0f662225c7..e75718780b 100644 --- a/README.md +++ b/README.md @@ -71,7 +71,7 @@ The `audioworklet` backend additionally requires `-Zbuild-std` with atomics supp | `pulseaudio` | Linux, BSD | PulseAudio sound server backend. Requires `libpulse-dev` (Debian/Ubuntu) or `pulseaudio-libs-devel` (Fedora). | | `realtime` | Android, Linux, Windows | Raises the audio callback thread to real-time or high-priority scheduling for lower latency. On Linux, requires `CAP_SYS_NICE`, root, or an `rtprio` limit granted via `limits.conf` or systemd, unless `realtime-dbus` is also enabled. | | `realtime-dbus` | Linux | Uses `rtkit` via D-Bus for RT scheduling on Linux desktop systems. Implies `realtime` on all platforms. Requires `libdbus-1-dev` on Linux. | -|`wasapi-new`|Windows| Rewrite of the WASAPI host, intended to replace the current one soon. | +| `wasapi-new` | Windows | Rewrite of the WASAPI host, intended to replace the current one soon. | | `wasm-bindgen` | WebAssembly (`wasm32-unknown-emscripten`, `wasm32-unknown-unknown`) | Web Audio API backend for browser-based audio; required for any WebAssembly audio support. See the `webaudio` example. | See the [beep example](examples/beep.rs) for selecting the backend at runtime. From ce431d2ace069cbb8d040de0c7d116651c5d5d63 Mon Sep 17 00:00:00 2001 From: Marco Farruggio Date: Sun, 8 Nov 2026 15:30:46 +0000 Subject: [PATCH 13/23] derive Debug on StreamInner --- src/host/wasapi_new.rs | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/src/host/wasapi_new.rs b/src/host/wasapi_new.rs index b159c8372f..2048b9c493 100644 --- a/src/host/wasapi_new.rs +++ b/src/host/wasapi_new.rs @@ -377,6 +377,7 @@ impl StreamTrait for Stream { } } +#[derive(Debug)] struct StreamInner { total_frames : u32, period_frames: u32, @@ -388,12 +389,6 @@ struct StreamInner { unsafe impl Send for StreamInner {} -impl Debug for StreamInner { - fn fmt(&self, _f: &mut fmt::Formatter<'_>) -> fmt::Result { - todo!() // https://github.com/HEnquist/wasapi-rs/pull/86 - } -} - impl StreamInner { pub fn start(&mut self) -> Result<(), CpalError> { if self.stream_state.get() == StreamState::Halted { From d8fd5b76d80ddd8c5a82cc2dfca4b5b79ce5d133 Mon Sep 17 00:00:00 2001 From: Marco Farruggio Date: Sun, 8 Nov 2026 15:31:26 +0000 Subject: [PATCH 14/23] fail gracefully when spawning a thread fails, and name worker threads --- src/host/wasapi_new.rs | 42 ++++++++++++++++++++++++++++-------------- 1 file changed, 28 insertions(+), 14 deletions(-) diff --git a/src/host/wasapi_new.rs b/src/host/wasapi_new.rs index 2048b9c493..c5ceea0a1c 100644 --- a/src/host/wasapi_new.rs +++ b/src/host/wasapi_new.rs @@ -224,20 +224,34 @@ impl Device { let audio_client2 = Arc::clone(&audio_client); let stream_state2 = Arc::clone(&stream_state); - thread::spawn(move || { - _ = processing::run_loop( - &buffer_event, - &audio_client2, - &processor, - &stream_state2, - &mut scratch, - &mut data_cb, - fn_process, - sample_format, - config.channels as _, - ) - .map_err(error_cb); - }); + + let dir = match direction { + Direction::Capture => "in", + Direction::Render => "out", + }; + + thread::Builder::new() + .name(format!("cpal_wasapi_{dir}")) + .spawn(move || { + _ = processing::run_loop( + &buffer_event, + &audio_client2, + &processor, + &stream_state2, + &mut scratch, + &mut data_cb, + fn_process, + sample_format, + config.channels as _, + ) + .map_err(error_cb); + }) + .map_err(|e| { + Error::with_message( + ErrorKind::ResourceExhausted, + format!("Failed to create WASAPI {dir}put worker thread: {e}"), + ) + })?; StreamInner { total_frames, From 1a3f69a63caf1ced61c97f6890340a773d04f389 Mon Sep 17 00:00:00 2001 From: Marco Farruggio Date: Sun, 8 Nov 2026 15:33:01 +0000 Subject: [PATCH 15/23] opinionated reformatting --- src/host/wasapi_new.rs | 17 +++--- src/host/wasapi_new/device.rs | 105 ++++++++++++++++------------------ src/host/wasapi_new/utils.rs | 16 +++--- 3 files changed, 69 insertions(+), 69 deletions(-) diff --git a/src/host/wasapi_new.rs b/src/host/wasapi_new.rs index c5ceea0a1c..f31d85aa1d 100644 --- a/src/host/wasapi_new.rs +++ b/src/host/wasapi_new.rs @@ -3,12 +3,15 @@ use self::utils::*; use crate::ErrorKind::{BackendError, ResourceExhausted}; use crate::traits::*; use crate::*; +use std::{ + fmt::{self, Debug, Display}, + hash::{Hash, Hasher}, + time::Duration, + sync::Arc, + thread, + vec, +}; use itertools::Itertools; -use std::fmt::{self, Debug, Display}; -use std::hash::{Hash, Hasher}; -use std::sync::Arc; -use std::time::Duration; -use std::{thread, vec}; use parking_lot::Mutex; use tap::Pipe; use wasapi::{ @@ -18,8 +21,8 @@ use wasapi::{ use windows::Devices::Enumeration::DeviceInformation; use windows_core::Interface; -mod device; mod processing; +mod device; mod utils; type SupportedConfigs = vec::IntoIter; @@ -398,7 +401,7 @@ struct StreamInner { audio_client : Arc>, audio_clock : Arc>, stream_state : Arc, - last_hns : u64 + last_hns : u64 } unsafe impl Send for StreamInner {} diff --git a/src/host/wasapi_new/device.rs b/src/host/wasapi_new/device.rs index 0988f5be03..74a744c645 100644 --- a/src/host/wasapi_new/device.rs +++ b/src/host/wasapi_new/device.rs @@ -1,16 +1,15 @@ -use super::Device; -use super::utils::WindowsError; +use super::{Device, utils::WindowsError}; use crate::{DeviceDirection, DeviceType, InterfaceType}; use itertools::Itertools; use tap::Pipe; -use windows::Devices::Enumeration::DeviceInformation; -use windows::Foundation::IPropertyValue; -use windows::Media::Devices::{AudioDeviceRole, MediaDevice}; -use windows::Win32::Foundation::{PROPERTYKEY, S_OK}; -use windows::Win32::Media::Audio; -use windows::Win32::Media::Audio::*; -use windows_collections::IIterable; -use windows_collections::IMapView; +use windows::{ + Devices::Enumeration::DeviceInformation, + Foundation::IPropertyValue, + Media::Devices::{AudioDeviceRole, MediaDevice}, + Win32::Foundation::{PROPERTYKEY, S_OK}, + Win32::Media::Audio::{self, *}, +}; +use windows_collections::{IIterable, IMapView}; use windows_core::{Array, HSTRING, IInspectable, Interface, h}; pub fn to_aqs(PROPERTYKEY { fmtid, pid }: &PROPERTYKEY) -> HSTRING { @@ -28,7 +27,7 @@ fn extra_properties() -> IIterable { pub fn all() -> Result, WindowsError> { let extra_properties = extra_properties(); - let capture = all_in_direction::(&extra_properties)?; + let capture = all_in_direction::(&extra_properties)?; let render = all_in_direction::(&extra_properties)?; capture @@ -87,17 +86,17 @@ impl PropertyReader { #[deny(nonstandard_style, reason = "prevent accidental wildcards")] #[expect(unused_qualifications, reason = "rustc bug?")] match form_factor { + Audio::DigitalAudioDisplayDevice => interface_type = InterfaceType::DisplayPort, + Audio::UnknownDigitalPassthrough => interface_type = InterfaceType::Virtual, Audio::RemoteNetworkDevice => interface_type = InterfaceType::Network, - Audio::Speakers => device_type = DeviceType::Speaker, + Audio::UnknownFormFactor => interface_type = InterfaceType::Unknown, Audio::LineLevel => interface_type = InterfaceType::Line, + Audio::SPDIF => interface_type = InterfaceType::Spdif, Audio::Headphones => device_type = DeviceType::Headphones, Audio::Microphone => device_type = DeviceType::Microphone, + Audio::Speakers => device_type = DeviceType::Speaker, Audio::Headset => device_type = DeviceType::Headset, Audio::Handset => device_type = DeviceType::Handset, - Audio::UnknownDigitalPassthrough => interface_type = InterfaceType::Virtual, - Audio::SPDIF => interface_type = InterfaceType::Spdif, - Audio::DigitalAudioDisplayDevice => interface_type = InterfaceType::DisplayPort, - Audio::UnknownFormFactor => interface_type = InterfaceType::Unknown, _ => unreachable!() }; @@ -113,57 +112,53 @@ impl PropertyReader { use windows::Win32::Media::KernelStreaming::*; #[deny(nonstandard_style, reason = "prevent accidental wildcards")] match jack_sub_type { + KSNODETYPE_BIDIRECTIONAL_UNDEFINED => interface_type = InterfaceType::Aggregate, KSNODETYPE_DISPLAYPORT_INTERFACE => interface_type = InterfaceType::DisplayPort, - KSNODETYPE_SPDIF_INTERFACE => interface_type = InterfaceType::Spdif, - KSNODETYPE_HDMI_INTERFACE => interface_type = InterfaceType::Hdmi, - - KSNODETYPE_AUDIO_ENGINE | - KSNODETYPE_AUDIO_LOOPBACK => interface_type = InterfaceType::Virtual, - - KSNODETYPE_BIDIRECTIONAL_UNDEFINED => interface_type = InterfaceType::Aggregate, - - KSNODETYPE_ADC | - KSNODETYPE_DAC | + + KSNODETYPE_AUDIO_LOOPBACK | + KSNODETYPE_AUDIO_ENGINE => interface_type = InterfaceType::Virtual, + KSNODETYPE_ANALOG_CONNECTOR | KSNODETYPE_LINE_CONNECTOR | - KSNODETYPE_PHONE_LINE => interface_type = InterfaceType::Line, - - KSNODETYPE_TV_TUNER_AUDIO | - KSNODETYPE_CABLE_TUNER_AUDIO => device_type = DeviceType::Tuner, - - KSNODETYPE_SPEAKER | - KSNODETYPE_COMMUNICATION_SPEAKER | - KSNODETYPE_DESKTOP_SPEAKER | - KSNODETYPE_ROOM_SPEAKER | - KSNODETYPE_LOW_FREQUENCY_EFFECTS_SPEAKER | - KSNODETYPE_SPEAKERS_STATIC_JACK | - KSNODETYPE_SPEAKERPHONE_NO_ECHO_REDUCTION | - KSNODETYPE_ECHO_CANCELING_SPEAKERPHONE | - KSNODETYPE_ECHO_SUPPRESSING_SPEAKERPHONE | - KSNODETYPE_PHONOGRAPH => device_type = DeviceType::Speaker, - - - KSNODETYPE_MICROPHONE | - KSNODETYPE_MICROPHONE_ARRAY | - KSNODETYPE_DESKTOP_MICROPHONE | - KSNODETYPE_PERSONAL_MICROPHONE | - KSNODETYPE_PROCESSING_MICROPHONE_ARRAY | - KSNODETYPE_OMNI_DIRECTIONAL_MICROPHONE => device_type = DeviceType::Microphone, + KSNODETYPE_PHONE_LINE | + KSNODETYPE_ADC | + KSNODETYPE_DAC => interface_type = InterfaceType::Line, KSNODETYPE_DIGITAL_AUDIO_INTERFACE => device_type = DeviceType::Dock, - KSNODETYPE_HEADPHONES => device_type = DeviceType::Headphones, + + KSNODETYPE_TV_TUNER_AUDIO | + KSNODETYPE_CABLE_TUNER_AUDIO => device_type = DeviceType::Tuner, KSNODETYPE_HEADSET | KSNODETYPE_HEAD_MOUNTED_DISPLAY_AUDIO => device_type = DeviceType::Headset, - - KSNODETYPE_HANDSET | - KSNODETYPE_TELEPHONE | - KSNODETYPE_TELEPHONY_BIDI | + + KSNODETYPE_TELEPHONY_UNDEFINED | - KSNODETYPE_DOWN_LINE_PHONE => device_type = DeviceType::Handset, + KSNODETYPE_DOWN_LINE_PHONE | + KSNODETYPE_TELEPHONY_BIDI | + KSNODETYPE_TELEPHONE | + KSNODETYPE_HANDSET => device_type = DeviceType::Handset, + + KSNODETYPE_OMNI_DIRECTIONAL_MICROPHONE | + KSNODETYPE_PROCESSING_MICROPHONE_ARRAY | + KSNODETYPE_PERSONAL_MICROPHONE | + KSNODETYPE_DESKTOP_MICROPHONE | + KSNODETYPE_MICROPHONE_ARRAY | + KSNODETYPE_MICROPHONE => device_type = DeviceType::Microphone, + + KSNODETYPE_SPEAKERPHONE_NO_ECHO_REDUCTION | + KSNODETYPE_ECHO_SUPPRESSING_SPEAKERPHONE | + KSNODETYPE_LOW_FREQUENCY_EFFECTS_SPEAKER | + KSNODETYPE_ECHO_CANCELING_SPEAKERPHONE | + KSNODETYPE_COMMUNICATION_SPEAKER | + KSNODETYPE_SPEAKERS_STATIC_JACK | + KSNODETYPE_DESKTOP_SPEAKER | + KSNODETYPE_ROOM_SPEAKER | + KSNODETYPE_PHONOGRAPH | + KSNODETYPE_SPEAKER => device_type = DeviceType::Speaker, _ => () } diff --git a/src/host/wasapi_new/utils.rs b/src/host/wasapi_new/utils.rs index 78f26795d0..03ba8163e9 100644 --- a/src/host/wasapi_new/utils.rs +++ b/src/host/wasapi_new/utils.rs @@ -1,12 +1,14 @@ use crate::ErrorKind::{BackendError, UnsupportedOperation}; use crate::{DeviceDirection, SampleFormat, StreamConfig, SupportedBufferSize, SupportedStreamConfig}; -use std::alloc::{Layout, alloc_zeroed, dealloc}; -use std::fmt::Debug; -use std::mem::transmute; -use std::ops::{Deref, DerefMut}; -use std::slice; -use std::sync::atomic::{AtomicU8, Ordering}; -use std::time::Duration; +use std::{ + alloc::{Layout, alloc_zeroed, dealloc}, + sync::atomic::{AtomicU8, Ordering}, + ops::{Deref, DerefMut}, + time::Duration, + mem::transmute, + fmt::Debug, + slice, +}; use tap::Pipe; use wasapi::{Direction, SampleType, WaveFormat}; use windows::Win32::Foundation::{CloseHandle, HANDLE, WAIT_EVENT, WAIT_FAILED, WAIT_OBJECT_0, WAIT_TIMEOUT}; From c9cc3d09d1279f64b0b1814f5ff1cf262c3cb7e8 Mon Sep 17 00:00:00 2001 From: LastExceed Date: Tue, 10 Nov 2026 14:40:38 +0100 Subject: [PATCH 16/23] rename `to_aqs()` -> `format_aqs()` --- src/host/wasapi_new/device.rs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/host/wasapi_new/device.rs b/src/host/wasapi_new/device.rs index 74a744c645..49ceb1843b 100644 --- a/src/host/wasapi_new/device.rs +++ b/src/host/wasapi_new/device.rs @@ -12,14 +12,14 @@ use windows::{ use windows_collections::{IIterable, IMapView}; use windows_core::{Array, HSTRING, IInspectable, Interface, h}; -pub fn to_aqs(PROPERTYKEY { fmtid, pid }: &PROPERTYKEY) -> HSTRING { +pub fn format_aqs(PROPERTYKEY { fmtid, pid }: &PROPERTYKEY) -> HSTRING { format!("{{{fmtid:?}}} {pid}").into() } fn extra_properties() -> IIterable { vec![ - to_aqs(&PKEY_AudioEndpoint_FormFactor), - to_aqs(&PKEY_AudioEndpoint_JackSubType), + format_aqs(&PKEY_AudioEndpoint_FormFactor), + format_aqs(&PKEY_AudioEndpoint_JackSubType), ] .into() } @@ -75,7 +75,7 @@ impl PropertyReader { pub fn types(&self) -> Result<(DeviceType, InterfaceType), WindowsError> { let form_factor = self .0 - .Lookup(&to_aqs(&PKEY_AudioEndpoint_FormFactor))? + .Lookup(&format_aqs(&PKEY_AudioEndpoint_FormFactor))? .cast::()? .GetInt32()? .pipe(EndpointFormFactor); @@ -102,7 +102,7 @@ impl PropertyReader { let jack_sub_type = self .0 - .Lookup(&to_aqs(&PKEY_AudioEndpoint_JackSubType))? + .Lookup(&format_aqs(&PKEY_AudioEndpoint_JackSubType))? .cast::()? .GetString()? .to_string_lossy() From 438e29405b5c05a2cb9c1e5f3d9dbc20bb0830d4 Mon Sep 17 00:00:00 2001 From: LastExceed Date: Tue, 10 Nov 2026 21:55:13 +0100 Subject: [PATCH 17/23] implement auto-routed default device streams --- src/host/wasapi_new.rs | 145 ++++++++++++++++++++---------- src/host/wasapi_new/device.rs | 73 ++++++++++----- src/host/wasapi_new/processing.rs | 2 +- src/host/wasapi_new/utils.rs | 57 ++++++++---- 4 files changed, 190 insertions(+), 87 deletions(-) diff --git a/src/host/wasapi_new.rs b/src/host/wasapi_new.rs index f31d85aa1d..e6ccb3c5df 100644 --- a/src/host/wasapi_new.rs +++ b/src/host/wasapi_new.rs @@ -1,11 +1,14 @@ +use self::device::default_id; +use self::device::Kind::Specific; use self::processing::FnProcess; use self::utils::*; -use crate::ErrorKind::{BackendError, ResourceExhausted}; +use crate::ErrorKind::{BackendError, ResourceExhausted, UnsupportedOperation}; use crate::traits::*; use crate::*; +use std::borrow::Cow; use std::{ fmt::{self, Debug, Display}, - hash::{Hash, Hasher}, + hash::Hash, time::Duration, sync::Arc, thread, @@ -15,11 +18,10 @@ use itertools::Itertools; use parking_lot::Mutex; use tap::Pipe; use wasapi::{ - AudioClient, AudioClock, Device as MMDevice, DeviceEnumerator, Direction, SampleType, - ShareMode, StreamMode, WaveFormat, + AudioClient, AudioClock, DeviceEnumerator, Direction, SampleType, ShareMode, StreamMode, WaveFormat, }; use windows::Devices::Enumeration::DeviceInformation; -use windows_core::Interface; +use windows_core::HSTRING; mod processing; mod device; @@ -37,6 +39,17 @@ impl Host { pub const fn new() -> Result { Ok(Self) } + + fn default_device(&self) -> Option { + if device::current_default_id::().ok()?.is_empty() { + return None; + } + Device { + kind: device::Kind::Default, + direction: device::direction::() + } + .pipe(Some) + } } impl HostTrait for Host { @@ -54,30 +67,35 @@ impl HostTrait for Host { } fn default_input_device(&self) -> Option { - device::default::().ok() + self.default_device::() } fn default_output_device(&self) -> Option { - device::default::().ok() + self.default_device::() } } #[derive(Debug, Clone, PartialEq, Eq)] pub struct Device { - info: DeviceInformation, - direction: DeviceDirection, + kind: device::Kind, + direction: Direction, } impl Hash for Device { - fn hash(&self, state: &mut H) { - self.info.as_raw().hash(state); - self.direction.hash(state); + fn hash(&self, state: &mut H) { + self.kind.hash(state); + std::mem::discriminant(&self.direction).hash(state); } } impl Display for Device { fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { - if let Ok(name) = self.info.Name() { + let Specific(ref info) = self.kind + else { + return Display::fmt("Default", formatter); + }; + + if let Ok(name) = info.Name() { Display::fmt(&name, formatter) } else { Display::fmt("(device name lookup failed)", formatter) @@ -86,25 +104,43 @@ impl Display for Device { } impl Device { - fn mm_device(&self) -> Result { - let enumerator = DeviceEnumerator::new()?; + fn info(&self) -> Result, WindowsError> { + if let Specific(ref info) = self.kind { + return Cow::Borrowed(info).pipe(Ok); + } - self.info - .Id()? - .to_string_lossy() - .split('#') - .nth(2) - .ok_or(CpalError::with_message(BackendError, "malformed device id encountered"))? - .pipe(|id| enumerator.get_device(id))? - .pipe(Ok) + match self.direction { + Direction::Render => device::current_default_info::(), + Direction::Capture => device::current_default_info::() + } + .map(Cow::Owned) + } + + fn native_id(&self) -> Result { + match self.kind { + device::Kind::Default => default_id(self.direction), + device::Kind::Specific(ref info) => info.Id() + } + } + + fn activate(&self, timeout: Option) -> Result { + self.native_id() + .and_then(|id| activate_audio_interface(&id, timeout)) + .map(|client| AudioClient::from_iaudioclient(client, self.direction)) + } + + fn validate_direction(&self) -> Result<(), CpalError> { + if self.direction == Direction::Capture && !INPUT { + return CpalError::with_message(UnsupportedOperation, "cannot render on a capture device").pipe(Err); + } + + Ok(()) } fn default_config(&self) -> Result { - let mm_device = self.mm_device()?; - validate_direction::(&mm_device)?; + self.validate_direction::()?; - mm_device - .get_iaudioclient()? + self.activate(None)? .get_mixformat()? .try_into() } @@ -112,15 +148,19 @@ impl Device { fn supported_configs(&self) -> Result { use SampleFormat::*; - let mm_device = self.mm_device()?; - validate_direction::(&mm_device)?; + self.validate_direction::()?; + let client = self.activate(None)?; - let client = mm_device.get_iaudioclient()?; - - mm_device + self.info()? + .Id()? + .to_string_lossy() + .split('#') + .nth(2) + .ok_or(CpalError::with_message(BackendError, "malformed device id encountered"))? + .pipe(|id| DeviceEnumerator::new()?.get_device(id))? .get_data_ranges()? .into_iter() - .flat_map(move |range| + .flat_map(move |range| COMMON_SAMPLE_RATES .iter() .copied() @@ -166,7 +206,7 @@ impl Device { let format = config.sample_format(); let channels = config.channels(); let rate = config.sample_rate(); - + ((format, channels), rate) }) .into_group_map() @@ -180,7 +220,7 @@ impl Device { sample_format, } ) - .collect::>() + .collect::>() .into_iter() .pipe(Ok) } @@ -192,6 +232,7 @@ impl Device { sample_format : SampleFormat, mut data_cb : DataCallback, error_cb : ErrorCallback, + timeout : Option, direction : Direction, // const generics when? fn_new_processor: fn(&AudioClient) -> Result, // unique function ZSTs when? fn_process : FnProcess // unique function ZSTs when? @@ -201,8 +242,7 @@ impl Device { DataCallback : Send + 'static, ErrorCallback: FnMut(Error) + Send + 'static { - let mm_device = self.mm_device()?; - let mut audio_client = mm_device.get_iaudioclient()?; + let mut audio_client = self.activate(timeout)?; let waveformat = create_waveformat(config, sample_format)?; let period_frames = match config.buffer_size { @@ -227,7 +267,7 @@ impl Device { let audio_client2 = Arc::clone(&audio_client); let stream_state2 = Arc::clone(&stream_state); - + let dir = match direction { Direction::Capture => "in", Direction::Render => "out", @@ -275,23 +315,28 @@ impl DeviceTrait for Device { type Stream = Stream; fn description(&self) -> Result { - let name = self.info.Name()?.to_string_lossy(); - let reader = device::PropertyReader(self.info.Properties()?); + let info = self.info()?; + let name = info.Name()?.to_string_lossy(); + + let reader = device::PropertyReader(info.Properties()?); let (device_type, interface_type) = reader.types()?; + let mut builder = DeviceDescriptionBuilder ::new(name.clone()) .driver(name) - .direction(self.direction) + .direction(self.direction.into()) .device_type(device_type) .interface_type(interface_type); + if let Some(physical_location) = reader.physical_location()? { builder = builder.address(physical_location); } + Ok(builder.build()) } fn id(&self) -> Result { - self.info + self.info()? .Id()? .to_string_lossy() .into_boxed_str() @@ -321,7 +366,7 @@ impl DeviceTrait for Device { format : SampleFormat, data_cb : DataCallback, error_cb: ErrorCallback, - _timeout: Option, + timeout : Option, ) -> Result where DataCallback : FnMut(&Data, &CallbackInfo) + Send + 'static, @@ -332,6 +377,7 @@ impl DeviceTrait for Device { format, data_cb, error_cb, + timeout, Direction::Capture, AudioClient::get_audiocaptureclient, processing::capture @@ -344,7 +390,7 @@ impl DeviceTrait for Device { format: SampleFormat, data_cb: DataCallback, error_cb: ErrorCallback, - _timeout: Option, + timeout : Option, ) -> Result where DataCallback: FnMut(&mut Data, &CallbackInfo) + Send + 'static, @@ -355,6 +401,7 @@ impl DeviceTrait for Device { format, data_cb, error_cb, + timeout, Direction::Render, AudioClient::get_audiorenderclient, processing::render @@ -413,7 +460,7 @@ impl StreamInner { } self.stream_state.set(StreamState::Running, true)?; - + Ok(()) } @@ -423,7 +470,7 @@ impl StreamInner { } self.stream_state.set(StreamState::Halted, true)?; - + Ok(()) } @@ -438,15 +485,15 @@ impl StreamInner { .stream_state .event() .wait_single(timeout)?; - + self.audio_client.stop_stream()?; self.audio_client.reset_stream()?; - + // FIXME: use `bool::ok_or()` once MSRV has risen to 1.98 if !wait_success { return Err(CpalError::with_message(ResourceExhausted, "timeout expired")) } - + Ok(()) } diff --git a/src/host/wasapi_new/device.rs b/src/host/wasapi_new/device.rs index 49ceb1843b..6dfbe28f2d 100644 --- a/src/host/wasapi_new/device.rs +++ b/src/host/wasapi_new/device.rs @@ -1,7 +1,10 @@ use super::{Device, utils::WindowsError}; -use crate::{DeviceDirection, DeviceType, InterfaceType}; +use crate::{DeviceType, InterfaceType}; use itertools::Itertools; +use std::hash::Hash; use tap::Pipe; +use wasapi::Direction; +use windows::Win32::System::Com::{CoTaskMemFree, StringFromIID}; use windows::{ Devices::Enumeration::DeviceInformation, Foundation::IPropertyValue, @@ -12,6 +15,34 @@ use windows::{ use windows_collections::{IIterable, IMapView}; use windows_core::{Array, HSTRING, IInspectable, Interface, h}; +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Kind { + Default, + Specific(DeviceInformation) +} + +impl Hash for Kind { + fn hash(&self, state: &mut H) { + core::mem::discriminant(self).hash(state); + if let Self::Specific(info) = self { + info.as_raw().hash(state); + } + } +} + +pub fn default_id(direction: Direction) -> Result { + let guid = match direction { + Direction::Render => DEVINTERFACE_AUDIO_RENDER, + Direction::Capture => DEVINTERFACE_AUDIO_CAPTURE, + }; + unsafe { + let pwstr = StringFromIID(&guid)?; + let hstring = pwstr.to_hstring(); + CoTaskMemFree(Some(pwstr.as_ptr().cast())); + Ok(hstring) + } +} + pub fn format_aqs(PROPERTYKEY { fmtid, pid }: &PROPERTYKEY) -> HSTRING { format!("{{{fmtid:?}}} {pid}").into() } @@ -45,26 +76,28 @@ fn all_in_direction(extra_props: &IIterable) -> Resu ::FindAllAsyncAqsFilterAndAdditionalProperties(&fn_get_selector()?, extra_props)? .join()? .into_iter() - .map(|info| Device { info, direction: direction::() }) + .map(|info| Device { kind: Kind::Specific(info), direction: direction::() }) .pipe(Ok) } -pub fn default() -> Result { - let extra_properties = extra_properties(); - let fn_get_id = - if INPUT { MediaDevice::GetDefaultAudioCaptureId } - else { MediaDevice::GetDefaultAudioRenderId }; +pub fn current_default_id() -> Result { + let role = AudioDeviceRole::Default; - fn_get_id(AudioDeviceRole::Default)? - .pipe_ref(|id| DeviceInformation::CreateFromIdAsyncAdditionalProperties(id, &extra_properties))? - .join() - .map(|info| Device { info, direction: direction::() }) + if INPUT { MediaDevice::GetDefaultAudioCaptureId(role) } + else { MediaDevice::GetDefaultAudioRenderId(role) } } -const fn direction() -> DeviceDirection { - if INPUT { DeviceDirection::Input } - else { DeviceDirection::Output } +pub fn current_default_info() -> Result { + let default_device_id = current_default_id::()?; + let extra_properties = extra_properties(); + + DeviceInformation::CreateFromIdAsyncAdditionalProperties(&default_device_id, &extra_properties)?.join() +} + +pub const fn direction() -> Direction { + if INPUT { Direction::Capture } + else { Direction::Render } } const PHYSICAL_DEVICE_LOCATION: &HSTRING = h!("System.Devices.PhysicalDeviceLocation"); @@ -116,10 +149,10 @@ impl PropertyReader { KSNODETYPE_DISPLAYPORT_INTERFACE => interface_type = InterfaceType::DisplayPort, KSNODETYPE_SPDIF_INTERFACE => interface_type = InterfaceType::Spdif, KSNODETYPE_HDMI_INTERFACE => interface_type = InterfaceType::Hdmi, - + KSNODETYPE_AUDIO_LOOPBACK | KSNODETYPE_AUDIO_ENGINE => interface_type = InterfaceType::Virtual, - + KSNODETYPE_ANALOG_CONNECTOR | KSNODETYPE_LINE_CONNECTOR | KSNODETYPE_PHONE_LINE | @@ -127,21 +160,21 @@ impl PropertyReader { KSNODETYPE_DAC => interface_type = InterfaceType::Line, KSNODETYPE_DIGITAL_AUDIO_INTERFACE => device_type = DeviceType::Dock, + KSNODETYPE_HEADPHONES => device_type = DeviceType::Headphones, - + KSNODETYPE_TV_TUNER_AUDIO | KSNODETYPE_CABLE_TUNER_AUDIO => device_type = DeviceType::Tuner, KSNODETYPE_HEADSET | KSNODETYPE_HEAD_MOUNTED_DISPLAY_AUDIO => device_type = DeviceType::Headset, - - + KSNODETYPE_TELEPHONY_UNDEFINED | KSNODETYPE_DOWN_LINE_PHONE | KSNODETYPE_TELEPHONY_BIDI | KSNODETYPE_TELEPHONE | KSNODETYPE_HANDSET => device_type = DeviceType::Handset, - + KSNODETYPE_OMNI_DIRECTIONAL_MICROPHONE | KSNODETYPE_PROCESSING_MICROPHONE_ARRAY | KSNODETYPE_PERSONAL_MICROPHONE | diff --git a/src/host/wasapi_new/processing.rs b/src/host/wasapi_new/processing.rs index 07724b9833..0cf8d08220 100644 --- a/src/host/wasapi_new/processing.rs +++ b/src/host/wasapi_new/processing.rs @@ -64,7 +64,7 @@ fn wait_event( let events = [ buffer_event.as_handle(), - *state_event.as_raw() + state_event.as_raw() ]; Event::wait_multiple(&events, timeout) diff --git a/src/host/wasapi_new/utils.rs b/src/host/wasapi_new/utils.rs index 03ba8163e9..45f7150de1 100644 --- a/src/host/wasapi_new/utils.rs +++ b/src/host/wasapi_new/utils.rs @@ -1,5 +1,6 @@ -use crate::ErrorKind::{BackendError, UnsupportedOperation}; +use crate::ErrorKind::BackendError; use crate::{DeviceDirection, SampleFormat, StreamConfig, SupportedBufferSize, SupportedStreamConfig}; +use std::mem::MaybeUninit; use std::{ alloc::{Layout, alloc_zeroed, dealloc}, sync::atomic::{AtomicU8, Ordering}, @@ -10,9 +11,11 @@ use std::{ slice, }; use tap::Pipe; -use wasapi::{Direction, SampleType, WaveFormat}; -use windows::Win32::Foundation::{CloseHandle, HANDLE, WAIT_EVENT, WAIT_FAILED, WAIT_OBJECT_0, WAIT_TIMEOUT}; +use wasapi::{Direction, IAudioClient, SampleType, WaveFormat}; +use windows::Win32::Foundation::{CloseHandle, E_POINTER, HANDLE, WAIT_EVENT, WAIT_FAILED, WAIT_OBJECT_0, WAIT_TIMEOUT}; +use windows::Win32::Media::Audio::{ActivateAudioInterfaceAsync, IActivateAudioInterfaceAsyncOperation, IActivateAudioInterfaceCompletionHandler, IActivateAudioInterfaceCompletionHandler_Impl}; use windows::Win32::System::Threading::{CreateEventW, INFINITE, SetEvent, WaitForMultipleObjects, WaitForSingleObject}; +use windows_core::{Interface, PCWSTR, Param, Ref, implement}; pub type CpalError = crate::Error; pub type WasapiRsError = wasapi::WasapiError; @@ -81,11 +84,11 @@ unsafe impl Sync for Event {} impl Event { pub fn new() -> Result { - unsafe { CreateEventW(None, false, true, None) }.map(Self) + unsafe { CreateEventW(None, false, false, None) }.map(Self) } - pub const fn as_raw(&self) -> &HANDLE { - &self.0 + pub const fn as_raw(&self) -> HANDLE { + self.0 } pub fn set_signaled(&self) -> Result<(), WindowsError> { @@ -146,6 +149,7 @@ impl WaitableStreamState { .pipe(Ok) } + #[must_use] pub fn get(&self) -> StreamState { unsafe { transmute(self.atomic.load(Ordering::Relaxed)) } } @@ -200,17 +204,6 @@ impl TryFrom for SupportedStreamConfig { } } -pub fn validate_direction(mm_device: &wasapi::Device) -> Result<(), CpalError> { - let is_input = mm_device.get_direction() == Direction::Capture; - - // FIXME: use `bool::ok_or()` once MSRV has risen to 1.98 - if INPUT != is_input { - return Err(CpalError::with_message(UnsupportedOperation, "This device only operates in the other direction")) - } - - Ok(()) -} - pub fn create_waveformat(config: StreamConfig, format: SampleFormat) -> Result { let sample_type = if format.is_int() { SampleType::Int } @@ -247,3 +240,33 @@ impl DerefMut for SendSync { &mut self.0 } } + +pub fn activate_audio_interface(id: impl Param, timeout: Option) -> Result { + let event = Event::new()?; + + let operation = event + .as_raw() + .pipe(CompletionHandler) + .pipe(IActivateAudioInterfaceCompletionHandler::from) + .pipe(|handler| unsafe { ActivateAudioInterfaceAsync(id, &IAudioClient::IID, None, &handler) })?; + + event.wait_single(timeout)?; + + let mut hresult = MaybeUninit::uninit(); + let mut iunknown = MaybeUninit::uninit(); + + unsafe { + operation.GetActivateResult(hresult.as_mut_ptr(), iunknown.as_mut_ptr())?; + hresult .assume_init().ok()?; + iunknown.assume_init().ok_or(E_POINTER)?.cast() + } +} + +#[implement(IActivateAudioInterfaceCompletionHandler)] +struct CompletionHandler(HANDLE); + +impl IActivateAudioInterfaceCompletionHandler_Impl for CompletionHandler_Impl { + fn ActivateCompleted(&self, _activateoperation: Ref) -> windows_core::Result<()> { + unsafe { SetEvent(self.0) } + } +} \ No newline at end of file From 4f0b01aab8fce530983237606bf577ccacc7b1d0 Mon Sep 17 00:00:00 2001 From: LastExceed Date: Wed, 11 Nov 2026 13:16:04 +0100 Subject: [PATCH 18/23] implement thread priority --- src/host.rs | 35 +++++++++++++++++++++++++++++++++++ src/host/wasapi/stream.rs | 35 +++-------------------------------- src/host/wasapi_new.rs | 9 ++++++++- 3 files changed, 46 insertions(+), 33 deletions(-) diff --git a/src/host.rs b/src/host.rs index 9f4a25442f..b32afd84ce 100644 --- a/src/host.rs +++ b/src/host.rs @@ -456,3 +456,38 @@ pub(crate) fn stop_tracks(media_stream: &web_sys::MediaStream) { } } } + +/// Holds the MMCSS registration made by `audio_thread_priority` and reverts it on drop. +#[cfg(all(windows, feature = "realtime"))] +#[derive(Default)] +struct RtPriority(Option); + +#[cfg(all(windows, feature = "realtime"))] +impl Drop for RtPriority { + fn drop(&mut self) { + if let Some(handle) = self.0.take() { + // Nothing useful to do if reverting fails while the thread is exiting. + let _ = audio_thread_priority::demote_current_thread_from_real_time(handle); + } + } +} + +/// Attempts to elevate the current thread to real-time or high-priority scheduling. +#[cfg(all(windows, feature = "realtime"))] +fn boost_current_thread_priority( + period_frames: crate::FrameCount, + sample_rate: crate::SampleRate, +) -> Result { + use crate::ResultExt; + use windows::Win32::System::Threading; + + match audio_thread_priority::promote_current_thread_to_real_time(period_frames, sample_rate) { + Ok(handle) => Ok(RtPriority(Some(handle))), + Err(_) => unsafe { + let thread_handle = Threading::GetCurrentThread(); + Threading::SetThreadPriority(thread_handle, Threading::THREAD_PRIORITY_TIME_CRITICAL) + .map(|()| RtPriority::default()) + .context("Failed to promote audio thread to real-time priority") + }, + } +} diff --git a/src/host/wasapi/stream.rs b/src/host/wasapi/stream.rs index b62f35ee9d..a0cd35ea08 100644 --- a/src/host/wasapi/stream.rs +++ b/src/host/wasapi/stream.rs @@ -24,6 +24,9 @@ use crate::{ traits::StreamTrait, }; +#[cfg(feature = "realtime")] +use crate::host::boost_current_thread_priority; + /// Returns the current default audio endpoint for `flow`, or `None` if none exists. /// /// Used by `OnDeviceStateChanged` and `OnDeviceRemoved` to cover the edge case where the @@ -797,38 +800,6 @@ fn run_output( } } -/// Holds the MMCSS registration made by `audio_thread_priority` and reverts it on drop. -#[cfg(feature = "realtime")] -#[derive(Default)] -struct RtPriority(Option); - -#[cfg(feature = "realtime")] -impl Drop for RtPriority { - fn drop(&mut self) { - if let Some(handle) = self.0.take() { - // Nothing useful to do if reverting fails while the thread is exiting. - let _ = audio_thread_priority::demote_current_thread_from_real_time(handle); - } - } -} - -/// Attempts to elevate the current thread to real-time or high-priority scheduling. -#[cfg(feature = "realtime")] -fn boost_current_thread_priority( - period_frames: FrameCount, - sample_rate: SampleRate, -) -> Result { - match audio_thread_priority::promote_current_thread_to_real_time(period_frames, sample_rate) { - Ok(handle) => Ok(RtPriority(Some(handle))), - Err(_) => unsafe { - let thread_handle = Threading::GetCurrentThread(); - Threading::SetThreadPriority(thread_handle, Threading::THREAD_PRIORITY_TIME_CRITICAL) - .map(|()| RtPriority::default()) - .context("Failed to promote audio thread to real-time priority") - }, - } -} - fn default_device_change_error(flow: Option) -> Error { match flow.and_then(get_current_default) { None => ErrorKind::DeviceNotAvailable.into(), diff --git a/src/host/wasapi_new.rs b/src/host/wasapi_new.rs index e6ccb3c5df..bada1f5815 100644 --- a/src/host/wasapi_new.rs +++ b/src/host/wasapi_new.rs @@ -23,6 +23,9 @@ use wasapi::{ use windows::Devices::Enumeration::DeviceInformation; use windows_core::HSTRING; +#[cfg(feature = "realtime")] +use super::boost_current_thread_priority; + mod processing; mod device; mod utils; @@ -231,7 +234,7 @@ impl Device { config : StreamConfig, sample_format : SampleFormat, mut data_cb : DataCallback, - error_cb : ErrorCallback, + mut error_cb : ErrorCallback, timeout : Option, direction : Direction, // const generics when? fn_new_processor: fn(&AudioClient) -> Result, // unique function ZSTs when? @@ -276,6 +279,10 @@ impl Device { thread::Builder::new() .name(format!("cpal_wasapi_{dir}")) .spawn(move || { + #[cfg(feature = "realtime")] + let _rt_guard = boost_current_thread_priority(period_frames, config.sample_rate) + .map_err(&mut error_cb); + _ = processing::run_loop( &buffer_event, &audio_client2, From 1dbf986fe12b147d9394ecd3316f2e2ec53897f9 Mon Sep 17 00:00:00 2001 From: LastExceed Date: Wed, 11 Nov 2026 20:42:12 +0100 Subject: [PATCH 19/23] implement default device change notifications --- src/host/wasapi_new.rs | 70 +++++++++++++++---------------- src/host/wasapi_new/processing.rs | 10 +++++ src/host/wasapi_new/utils.rs | 56 ++++++++++++++++++++++++- 3 files changed, 98 insertions(+), 38 deletions(-) diff --git a/src/host/wasapi_new.rs b/src/host/wasapi_new.rs index bada1f5815..76ed6b013d 100644 --- a/src/host/wasapi_new.rs +++ b/src/host/wasapi_new.rs @@ -1,6 +1,6 @@ use self::device::default_id; use self::device::Kind::Specific; -use self::processing::FnProcess; +use self::processing::{FnNewProcessor, FnProcess, make_spawn_error}; use self::utils::*; use crate::ErrorKind::{BackendError, ResourceExhausted, UnsupportedOperation}; use crate::traits::*; @@ -228,17 +228,16 @@ impl Device { .pipe(Ok) } - #[expect(clippy::too_many_arguments, reason = "3 of these only exist due to certain language features not yet being stable (see comments)")] - fn build_stream_inner( + #[expect(clippy::too_many_arguments, reason = "the 2 fn pointers could be replaced with generics once unique function ZSTs are stabilized")] + fn build_stream_inner( &self, - config : StreamConfig, - sample_format : SampleFormat, - mut data_cb : DataCallback, - mut error_cb : ErrorCallback, - timeout : Option, - direction : Direction, // const generics when? - fn_new_processor: fn(&AudioClient) -> Result, // unique function ZSTs when? - fn_process : FnProcess // unique function ZSTs when? + config : StreamConfig, + sample_format: SampleFormat, + mut data_cb : DataCallback, + error_cb : ErrorCallback, + timeout : Option, + fn_new_proc : FnNewProcessor, + fn_process : FnProcess ) -> Result where Processor : 'static, @@ -255,34 +254,38 @@ impl Device { audio_client.initialize_client( &waveformat, - direction, + device::direction::(), StreamMode::EventsShared { autoconvert: true, buffer_duration_hns: 0 }, None )?; - let processor = audio_client.pipe_ref(fn_new_processor)?.pipe(SendSync); - let audio_client = audio_client.pipe(SendSync).pipe(Arc::new); - let audio_clock = audio_client.get_audioclock()?.pipe(SendSync).pipe(Arc::new); - let buffer_event = audio_client.set_get_eventhandle()?.pipe(SendSync); - let total_frames = audio_client.get_buffer_size()?; - let mut scratch = ScratchBuffer::new(total_frames as usize * config.channels as usize, sample_format); - let stream_state = WaitableStreamState::new()?.pipe(Arc::new); - + let processor = audio_client.pipe_ref(fn_new_proc)?.pipe(SendSync); + let audio_client = audio_client .pipe(SendSync).pipe(Arc::new); + let audio_clock = audio_client.get_audioclock()? .pipe(SendSync).pipe(Arc::new); + let buffer_event = audio_client.set_get_eventhandle()?.pipe(SendSync); + let total_frames = audio_client.get_buffer_size()?; + let sample_count = total_frames as usize * config.channels as usize; + let mut scratch = ScratchBuffer::new(sample_count, sample_format); + let stream_state = WaitableStreamState::new()? .pipe(Arc::new); + let safe_err_cb = ThreadSafeErrorCb::new(error_cb).pipe(Arc::new); + let safe_err_cb2 = Arc::clone(&safe_err_cb); let audio_client2 = Arc::clone(&audio_client); let stream_state2 = Arc::clone(&stream_state); - let dir = match direction { - Direction::Capture => "in", - Direction::Render => "out", + let monitor = match self.kind { + device::Kind::Default => Some(DefaultDeviceMonitor::::new(safe_err_cb2)?), + device::Kind::Specific(_) => None }; thread::Builder::new() - .name(format!("cpal_wasapi_{dir}")) + .name("cpal_wasapi_proc".to_owned()) .spawn(move || { + let _monitor = monitor; // RAII guard + #[cfg(feature = "realtime")] let _rt_guard = boost_current_thread_priority(period_frames, config.sample_rate) - .map_err(&mut error_cb); - + .map_err(|error| safe_err_cb.invoke(error)); + _ = processing::run_loop( &buffer_event, &audio_client2, @@ -294,14 +297,9 @@ impl Device { sample_format, config.channels as _, ) - .map_err(error_cb); + .map_err(|error| safe_err_cb.invoke(error)); }) - .map_err(|e| { - Error::with_message( - ErrorKind::ResourceExhausted, - format!("Failed to create WASAPI {dir}put worker thread: {e}"), - ) - })?; + .map_err(make_spawn_error)?; StreamInner { total_frames, @@ -379,13 +377,12 @@ impl DeviceTrait for Device { DataCallback : FnMut(&Data, &CallbackInfo) + Send + 'static, ErrorCallback: FnMut(CpalError) + Send + 'static { - self.build_stream_inner( + self.build_stream_inner::<_, _, _, true>( config, format, data_cb, error_cb, timeout, - Direction::Capture, AudioClient::get_audiocaptureclient, processing::capture ) @@ -403,13 +400,12 @@ impl DeviceTrait for Device { DataCallback: FnMut(&mut Data, &CallbackInfo) + Send + 'static, ErrorCallback: FnMut(CpalError) + Send + 'static, { - self.build_stream_inner( + self.build_stream_inner::<_, _, _, false>( config, format, data_cb, error_cb, timeout, - Direction::Render, AudioClient::get_audiorenderclient, processing::render ) diff --git a/src/host/wasapi_new/processing.rs b/src/host/wasapi_new/processing.rs index 0cf8d08220..beba8e30fe 100644 --- a/src/host/wasapi_new/processing.rs +++ b/src/host/wasapi_new/processing.rs @@ -2,6 +2,7 @@ use super::utils::StreamState::*; use super::utils::*; use crate::host::equilibrium::fill_equilibrium; use crate::*; +use std::io; use std::mem::MaybeUninit; use std::time::Duration; use tap::Pipe; @@ -70,6 +71,8 @@ fn wait_event( Event::wait_multiple(&events, timeout) } +pub type FnNewProcessor = fn(&AudioClient) -> Result; + pub type FnProcess = fn( audio_client : &AudioClient, processor : &Processor, @@ -155,3 +158,10 @@ fn now_hns() -> u64 { hns as _ } + +pub fn make_spawn_error(io_error: io::Error) -> CpalError { + Error::with_message( + ErrorKind::ResourceExhausted, + format!("Failed to spawn processing thread: {io_error:?}"), + ) +} \ No newline at end of file diff --git a/src/host/wasapi_new/utils.rs b/src/host/wasapi_new/utils.rs index 45f7150de1..b0b69da921 100644 --- a/src/host/wasapi_new/utils.rs +++ b/src/host/wasapi_new/utils.rs @@ -1,6 +1,7 @@ -use crate::ErrorKind::BackendError; +use crate::ErrorKind::{BackendError, DeviceChanged}; use crate::{DeviceDirection, SampleFormat, StreamConfig, SupportedBufferSize, SupportedStreamConfig}; use std::mem::MaybeUninit; +use std::sync::Arc; use std::{ alloc::{Layout, alloc_zeroed, dealloc}, sync::atomic::{AtomicU8, Ordering}, @@ -10,8 +11,11 @@ use std::{ fmt::Debug, slice, }; +use parking_lot::Mutex; use tap::Pipe; use wasapi::{Direction, IAudioClient, SampleType, WaveFormat}; +use windows::Foundation::TypedEventHandler; +use windows::Media::Devices::MediaDevice; use windows::Win32::Foundation::{CloseHandle, E_POINTER, HANDLE, WAIT_EVENT, WAIT_FAILED, WAIT_OBJECT_0, WAIT_TIMEOUT}; use windows::Win32::Media::Audio::{ActivateAudioInterfaceAsync, IActivateAudioInterfaceAsyncOperation, IActivateAudioInterfaceCompletionHandler, IActivateAudioInterfaceCompletionHandler_Impl}; use windows::Win32::System::Threading::{CreateEventW, INFINITE, SetEvent, WaitForMultipleObjects, WaitForSingleObject}; @@ -269,4 +273,54 @@ impl IActivateAudioInterfaceCompletionHandler_Impl for CompletionHandler_Impl { fn ActivateCompleted(&self, _activateoperation: Ref) -> windows_core::Result<()> { unsafe { SetEvent(self.0) } } +} + +pub struct ThreadSafeErrorCb(Mutex); + +impl ThreadSafeErrorCb { + pub fn new(error_cb: ErrorCb) -> Self { + error_cb + .pipe(Mutex::new) + .pipe(Self) + } + + pub fn invoke(&self, error: CpalError) { + self.0.lock()(error); + } +} + +pub struct DefaultDeviceMonitor(i64); + +impl DefaultDeviceMonitor { + pub fn new(error_cb: Arc>) -> Result { + let error = CpalError::new(DeviceChanged); + + // deduplicating this requires an infuriating amount of boilerplate + if INPUT { + let closure = move |_sender: Ref<_>, _args: Ref<_>| { + error_cb.invoke(error.clone()); + Ok(()) + }; + let handler = TypedEventHandler::new(closure); + MediaDevice::DefaultAudioCaptureDeviceChanged(&handler) + } else { + let closure = move |_sender: Ref<_>, _args: Ref<_>| { + error_cb.invoke(error.clone()); + Ok(()) + }; + let handler = TypedEventHandler::new(closure); + MediaDevice::DefaultAudioRenderDeviceChanged(&handler) + } + .map(Self) + } +} + +impl Drop for DefaultDeviceMonitor { + fn drop(&mut self) { + let fn_unregister = + if INPUT { MediaDevice::RemoveDefaultAudioRenderDeviceChanged } + else { MediaDevice::RemoveDefaultAudioCaptureDeviceChanged }; + + _ = fn_unregister(self.0); + } } \ No newline at end of file From dae40c1c4a20c2c67aeea72c8b06837ff5b10f0a Mon Sep 17 00:00:00 2001 From: LastExceed Date: Thu, 12 Nov 2026 09:54:30 +0100 Subject: [PATCH 20/23] restore thread name suffix --- src/host/wasapi_new.rs | 4 ++-- src/host/wasapi_new/processing.rs | 5 +++++ 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/src/host/wasapi_new.rs b/src/host/wasapi_new.rs index 76ed6b013d..dee46b72b5 100644 --- a/src/host/wasapi_new.rs +++ b/src/host/wasapi_new.rs @@ -1,6 +1,6 @@ use self::device::default_id; use self::device::Kind::Specific; -use self::processing::{FnNewProcessor, FnProcess, make_spawn_error}; +use self::processing::{FnNewProcessor, FnProcess, make_spawn_error, thread_name}; use self::utils::*; use crate::ErrorKind::{BackendError, ResourceExhausted, UnsupportedOperation}; use crate::traits::*; @@ -278,7 +278,7 @@ impl Device { }; thread::Builder::new() - .name("cpal_wasapi_proc".to_owned()) + .name(thread_name::().into()) .spawn(move || { let _monitor = monitor; // RAII guard diff --git a/src/host/wasapi_new/processing.rs b/src/host/wasapi_new/processing.rs index beba8e30fe..5d3c0fe191 100644 --- a/src/host/wasapi_new/processing.rs +++ b/src/host/wasapi_new/processing.rs @@ -9,6 +9,11 @@ use tap::Pipe; use wasapi::{AudioCaptureClient, AudioClient, AudioRenderClient, Handle}; use windows::Win32::System::Performance::{QueryPerformanceCounter, QueryPerformanceFrequency}; +pub const fn thread_name() -> &'static str { + if INPUT { "cpal_wasapi_in" } + else { "cpal_wasapi_out" } +} + #[expect(clippy::too_many_arguments, reason = "this is basically just the capture context of the thread spawn closure written out")] pub fn run_loop( buffer_event : &Handle, From 03feb422912caf4690adbc4d2044b8ecd1d09d23 Mon Sep 17 00:00:00 2001 From: LastExceed Date: Thu, 12 Nov 2026 10:27:49 +0100 Subject: [PATCH 21/23] include direction and error in `impl Display for Device` --- src/host/wasapi_new.rs | 26 +++++++++++++++++--------- 1 file changed, 17 insertions(+), 9 deletions(-) diff --git a/src/host/wasapi_new.rs b/src/host/wasapi_new.rs index dee46b72b5..a9f545ba0b 100644 --- a/src/host/wasapi_new.rs +++ b/src/host/wasapi_new.rs @@ -93,15 +93,23 @@ impl Hash for Device { impl Display for Device { fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { - let Specific(ref info) = self.kind - else { - return Display::fmt("Default", formatter); - }; - - if let Ok(name) = info.Name() { - Display::fmt(&name, formatter) - } else { - Display::fmt("(device name lookup failed)", formatter) + match self.kind { + device::Kind::Default => { + let is_input = self.direction == Direction::Capture; + let prefix = if is_input { "In" } else { "Out" }; + Display::fmt(prefix, formatter)?; + Display::fmt("put", formatter) + }, + device::Kind::Specific(ref info) => { + match info.Name() { + Ok(hstring) => Display::fmt(&hstring, formatter), + Err(error) => { + Display::fmt("(name lookup failed - ", formatter)?; + Display::fmt(&error, formatter)?; + Display::fmt(")", formatter) + } + } + } } } } From 4151801437b28db358e3b9e14b80552f0171be7d Mon Sep 17 00:00:00 2001 From: LastExceed Date: Thu, 19 Nov 2026 09:35:44 +0100 Subject: [PATCH 22/23] use the capability probe instead of re-inventing the wheel --- src/host/wasapi_new.rs | 51 ++++-------------------------------------- 1 file changed, 4 insertions(+), 47 deletions(-) diff --git a/src/host/wasapi_new.rs b/src/host/wasapi_new.rs index a9f545ba0b..4441fbc86d 100644 --- a/src/host/wasapi_new.rs +++ b/src/host/wasapi_new.rs @@ -18,7 +18,7 @@ use itertools::Itertools; use parking_lot::Mutex; use tap::Pipe; use wasapi::{ - AudioClient, AudioClock, DeviceEnumerator, Direction, SampleType, ShareMode, StreamMode, WaveFormat, + AudioClient, AudioClock, CapabilityProbe, DeviceEnumerator, Direction, StreamMode, }; use windows::Devices::Enumeration::DeviceInformation; use windows_core::HSTRING; @@ -157,10 +157,7 @@ impl Device { } fn supported_configs(&self) -> Result { - use SampleFormat::*; - self.validate_direction::()?; - let client = self.activate(None)?; self.info()? .Id()? @@ -169,50 +166,10 @@ impl Device { .nth(2) .ok_or(CpalError::with_message(BackendError, "malformed device id encountered"))? .pipe(|id| DeviceEnumerator::new()?.get_device(id))? - .get_data_ranges()? + .pipe_ref(CapabilityProbe::new)? + .supported_formats_all_rates() .into_iter() - .flat_map(move |range| - COMMON_SAMPLE_RATES - .iter() - .copied() - .skip_while(move |rate| *rate < range.min_samplerate) - .take_while(move |rate| *rate <= range.max_samplerate) - .flat_map(move |sample_rate| - (1..=range.max_channels) - .flat_map(move |channel_count| - [I8, I16, I24, I32, F32] - .into_iter() - .filter(move |format| - range - .sample_type() - .is_none_or(|ty| - (ty == SampleType::Int) - == format.is_int() - ) - ) - .map(move |format| (format, format.sample_size() * 8)) - .skip_while(move |(_format, store_bits)| range.min_bits_per_sample > *store_bits as u32) - .take_while(move |(_format, store_bits)| range.max_bits_per_sample >= *store_bits as u32) - .map(move |(format, store_bits)| WaveFormat::new( - store_bits, - format.bits_per_sample() as _, - SampleType::Int, - sample_rate as _, - channel_count as _, - None - )) - ) - ) - ) - .unique() // DataRanges can overlap - .filter_map(|waveformat| - client - .is_supported(&waveformat, ShareMode::Shared) - .map(|ret| ret.unwrap_or(waveformat)) - .ok() - ) - .unique() // `.is_supported()` might have reported the same "closest match" multiple times - .filter_map(|waveformat| SupportedStreamConfig::try_from(waveformat).ok()) // this will most likely never fail anyway + .filter_map(|waveformat| SupportedStreamConfig::try_from(waveformat).ok()) // conversion fails for formats which cpal cannot represent .map(|config| { let format = config.sample_format(); let channels = config.channels(); From 3ea19d82e7c2f31326ab9756aebba1d8fa059188 Mon Sep 17 00:00:00 2001 From: LastExceed Date: Thu, 19 Nov 2026 15:44:39 +0100 Subject: [PATCH 23/23] rename `wasapi-new` -> `wasapi-winrt` --- .github/actions/determine-msrv/action.yml | 12 ++++++------ .github/workflows/platforms.yml | 4 ++-- Cargo.toml | 2 +- README.md | 4 ++-- src/host.rs | 4 ++-- src/host/{wasapi_new.rs => wasapi_winrt.rs} | 2 +- src/host/{wasapi_new => wasapi_winrt}/device.rs | 0 .../{wasapi_new => wasapi_winrt}/processing.rs | 0 src/host/{wasapi_new => wasapi_winrt}/utils.rs | 0 src/platform.rs | 14 +++++++------- 10 files changed, 21 insertions(+), 21 deletions(-) rename src/host/{wasapi_new.rs => wasapi_winrt.rs} (99%) rename src/host/{wasapi_new => wasapi_winrt}/device.rs (100%) rename src/host/{wasapi_new => wasapi_winrt}/processing.rs (100%) rename src/host/{wasapi_new => wasapi_winrt}/utils.rs (100%) diff --git a/.github/actions/determine-msrv/action.yml b/.github/actions/determine-msrv/action.yml index cc4a845eba..457cee5242 100644 --- a/.github/actions/determine-msrv/action.yml +++ b/.github/actions/determine-msrv/action.yml @@ -16,8 +16,8 @@ inputs: description: The MSRV for Pipewire backend (optional, Linux only) required: false default: '' - wasapi-new-msrv: - description: The MSRV for the wasapi-new feature (optional, Windows only) + wasapi-winrt-msrv: + description: The MSRV for the wasapi-winrt feature (optional, Windows only) required: false default: '' @@ -37,7 +37,7 @@ runs: JACK_MSRV="${{ inputs.jack-msrv }}" PULSEAUDIO_MSRV="${{ inputs.pulseaudio-msrv }}" PIPEWIRE_MSRV="${{ inputs.pipewire-msrv }}" - WASAPI_NEW_MSRV="${{ inputs.wasapi-new-msrv }}" + WASAPI_WINRT_MSRV="${{ inputs.wasapi-winrt-msrv }}" # Use sort -V to find the maximum version VERSIONS="$PLATFORM_MSRV $JACK_MSRV" if [ -n "$PULSEAUDIO_MSRV" ]; then @@ -46,9 +46,9 @@ runs: if [ -n "$PIPEWIRE_MSRV" ]; then VERSIONS="$VERSIONS $PIPEWIRE_MSRV" fi - if [ -n "$WASAPI_NEW_MSRV" ]; then - VERSIONS="$VERSIONS $WASAPI_NEW_MSRV" + if [ -n "$WASAPI_WINRT_MSRV" ]; then + VERSIONS="$VERSIONS $WASAPI_WINRT_MSRV" fi MAX_MSRV=$(printf '%s\n' $VERSIONS | sort -V | tail -n1) echo "all-features=$MAX_MSRV" >> $GITHUB_OUTPUT - echo "Platform MSRV: $PLATFORM_MSRV, JACK MSRV: $JACK_MSRV, PulseAudio MSRV: $PULSEAUDIO_MSRV, PIPEWIRE_MSRV: $PIPEWIRE_MSRV, WASAPI-new MSRV: $WASAPI_NEW_MSRV, Using for --all-features: $MAX_MSRV" + echo "Platform MSRV: $PLATFORM_MSRV, JACK MSRV: $JACK_MSRV, PulseAudio MSRV: $PULSEAUDIO_MSRV, PIPEWIRE_MSRV: $PIPEWIRE_MSRV, WASAPI-winrt MSRV: $WASAPI_WINRT_MSRV, Using for --all-features: $MAX_MSRV" diff --git a/.github/workflows/platforms.yml b/.github/workflows/platforms.yml index 560819a9ec..acf94506ed 100644 --- a/.github/workflows/platforms.yml +++ b/.github/workflows/platforms.yml @@ -32,7 +32,7 @@ env: MSRV_PULSEAUDIO: "1.88" MSRV_WASM: "1.85" MSRV_WINDOWS: "1.85" - MSRV_WASAPI_NEW: "1.95" + MSRV_WASAPI_WINRT: "1.95" PACKAGES_LINUX: libasound2-dev libdbus-1-dev libjack-jackd2-dev libpipewire-0.3-dev @@ -246,7 +246,7 @@ jobs: with: platform-msrv: ${{ env.MSRV_WINDOWS }} jack-msrv: ${{ env.MSRV_JACK }} - wasapi-new-msrv: ${{ env.MSRV_WASAPI_NEW }} + wasapi-winrt-msrv: ${{ env.MSRV_WASAPI_WINRT }} - name: Install Rust MSRV (${{ env.MSRV_WINDOWS }}) uses: dtolnay/rust-toolchain@master diff --git a/Cargo.toml b/Cargo.toml index 7e80fb6c34..04eda21481 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -82,7 +82,7 @@ pulseaudio = [ # New WASAPI backend using WinRT # Platform: Windows -wasapi-new = ["dep:tap", "dep:parking_lot", "dep:wasapi", "dep:itertools"] +wasapi-winrt = ["dep:tap", "dep:parking_lot", "dep:wasapi", "dep:itertools"] # WebAssembly backend using wasm-bindgen # Enables the Web Audio API backend for browser-based audio diff --git a/README.md b/README.md index e75718780b..d57084277d 100644 --- a/README.md +++ b/README.md @@ -52,7 +52,7 @@ The minimum Rust version (MSRV) and minimum operating system / runtime version b | PipeWire | Linux, BSD | 1.85 | PipeWire 0.3.53 | | PulseAudio | Linux, BSD | 1.88 | — | | WASAPI / ASIO | Windows | 1.85 | Windows 10 | -| New WASAPI (`-F wasapi-new`) | Windows | 1.95 | Windows 10 | +| New WASAPI (`-F wasapi-winrt`) | Windows | 1.95 | Windows 10 | | WASM (`wasm32-unknown-unknown`) | WebAssembly | 1.85 | — | | WASM (`wasm32-unknown-emscripten`) | WebAssembly | 1.85 | Emscripten 6.0.3, wasm-bindgen 0.2.127 | | WASM (`audioworklet`) | WebAssembly | nightly | — | @@ -71,7 +71,7 @@ The `audioworklet` backend additionally requires `-Zbuild-std` with atomics supp | `pulseaudio` | Linux, BSD | PulseAudio sound server backend. Requires `libpulse-dev` (Debian/Ubuntu) or `pulseaudio-libs-devel` (Fedora). | | `realtime` | Android, Linux, Windows | Raises the audio callback thread to real-time or high-priority scheduling for lower latency. On Linux, requires `CAP_SYS_NICE`, root, or an `rtprio` limit granted via `limits.conf` or systemd, unless `realtime-dbus` is also enabled. | | `realtime-dbus` | Linux | Uses `rtkit` via D-Bus for RT scheduling on Linux desktop systems. Implies `realtime` on all platforms. Requires `libdbus-1-dev` on Linux. | -| `wasapi-new` | Windows | Rewrite of the WASAPI host, intended to replace the current one soon. | +| `wasapi-winrt` | Windows | Rewrite of the WASAPI host, intended to replace the current one soon. | | `wasm-bindgen` | WebAssembly (`wasm32-unknown-emscripten`, `wasm32-unknown-unknown`) | Web Audio API backend for browser-based audio; required for any WebAssembly audio support. See the `webaudio` example. | See the [beep example](examples/beep.rs) for selecting the backend at runtime. diff --git a/src/host.rs b/src/host.rs index b32afd84ce..758aae803c 100644 --- a/src/host.rs +++ b/src/host.rs @@ -77,8 +77,8 @@ pub(crate) mod pulseaudio; pub(crate) mod wasapi; #[rustfmt::skip] -#[cfg(all(windows, feature = "wasapi-new"))] -pub(crate) mod wasapi_new; +#[cfg(all(windows, feature = "wasapi-winrt"))] +pub(crate) mod wasapi_winrt; #[cfg(all( target_arch = "wasm32", diff --git a/src/host/wasapi_new.rs b/src/host/wasapi_winrt.rs similarity index 99% rename from src/host/wasapi_new.rs rename to src/host/wasapi_winrt.rs index 4441fbc86d..05c10dbb6a 100644 --- a/src/host/wasapi_new.rs +++ b/src/host/wasapi_winrt.rs @@ -310,7 +310,7 @@ impl DeviceTrait for Device { .Id()? .to_string_lossy() .into_boxed_str() - .pipe(|id| DeviceId(HostId::WasapiNew, id)) + .pipe(|id| DeviceId(HostId::WasapiWinrt, id)) .pipe(Ok) } diff --git a/src/host/wasapi_new/device.rs b/src/host/wasapi_winrt/device.rs similarity index 100% rename from src/host/wasapi_new/device.rs rename to src/host/wasapi_winrt/device.rs diff --git a/src/host/wasapi_new/processing.rs b/src/host/wasapi_winrt/processing.rs similarity index 100% rename from src/host/wasapi_new/processing.rs rename to src/host/wasapi_winrt/processing.rs diff --git a/src/host/wasapi_new/utils.rs b/src/host/wasapi_winrt/utils.rs similarity index 100% rename from src/host/wasapi_new/utils.rs rename to src/host/wasapi_winrt/utils.rs diff --git a/src/platform.rs b/src/platform.rs index 97b373cd62..710f43827c 100644 --- a/src/platform.rs +++ b/src/platform.rs @@ -962,26 +962,26 @@ mod platform_impl { #[cfg(feature = "asio")] use crate::host::asio::Host as AsioHost; use crate::host::wasapi::Host as WasapiHost; - #[cfg(feature = "wasapi-new")] - use crate::host::wasapi_new::Host as WasapiNewHost; + #[cfg(feature = "wasapi-winrt")] + use crate::host::wasapi_winrt::Host as WasapiWinrtHost; impl_platform_host!( #[cfg(feature = "asio")] Asio "ASIO" => AsioHost, Wasapi "WASAPI" => WasapiHost, - #[cfg(feature = "wasapi-new")] - WasapiNew "WASAPI_new" => WasapiNewHost, + #[cfg(feature = "wasapi-winrt")] + WasapiWinrt "WASAPI_winrt" => WasapiWinrtHost, #[cfg(feature = "jack")] Jack "JACK" => JackHost, #[cfg(feature = "custom")] Custom => super::CustomHost, ); /// The default host for the current compilation target platform. pub fn default_host() -> Host { - #[cfg(feature = "wasapi-new")] - return WasapiNewHost::new() + #[cfg(feature = "wasapi-winrt")] + return WasapiWinrtHost::new() .expect("the default host should always be available") .into(); - #[cfg(not(feature = "wasapi-new"))] + #[cfg(not(feature = "wasapi-winrt"))] WasapiHost::new() .expect("the default host should always be available") .into()