diff --git a/.github/actions/determine-msrv/action.yml b/.github/actions/determine-msrv/action.yml index 41449fc874..457cee5242 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-winrt-msrv: + description: The MSRV for the wasapi-winrt 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_WINRT_MSRV="${{ inputs.wasapi-winrt-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_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, 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 881b2a6e3d..acf94506ed 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_WINRT: "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-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 af43ca1c49..04eda21481 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -80,6 +80,10 @@ pulseaudio = [ "dep:portable-atomic", ] +# New WASAPI backend using WinRT +# Platform: Windows +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 # Required for any WebAssembly audio support @@ -104,6 +108,7 @@ wasm-bindgen = [ [dependencies] dasp_sample = "0.11" +windows-collections = "0.3.2" [dev-dependencies] anyhow = "1.0" @@ -128,10 +133,19 @@ 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 } +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/README.md b/README.md index b96b319fda..d57084277d 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-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 | — | @@ -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-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 9c8c17811e..758aae803c 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-winrt"))] +pub(crate) mod wasapi_winrt; + #[cfg(all( target_arch = "wasm32", any(target_os = "emscripten", target_os = "unknown"), @@ -452,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_winrt.rs b/src/host/wasapi_winrt.rs new file mode 100644 index 0000000000..05c10dbb6a --- /dev/null +++ b/src/host/wasapi_winrt.rs @@ -0,0 +1,490 @@ +use self::device::default_id; +use self::device::Kind::Specific; +use self::processing::{FnNewProcessor, FnProcess, make_spawn_error, thread_name}; +use self::utils::*; +use crate::ErrorKind::{BackendError, ResourceExhausted, UnsupportedOperation}; +use crate::traits::*; +use crate::*; +use std::borrow::Cow; +use std::{ + fmt::{self, Debug, Display}, + hash::Hash, + time::Duration, + sync::Arc, + thread, + vec, +}; +use itertools::Itertools; +use parking_lot::Mutex; +use tap::Pipe; +use wasapi::{ + AudioClient, AudioClock, CapabilityProbe, DeviceEnumerator, Direction, StreamMode, +}; +use windows::Devices::Enumeration::DeviceInformation; +use windows_core::HSTRING; + +#[cfg(feature = "realtime")] +use super::boost_current_thread_priority; + +mod processing; +mod device; +mod utils; + +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) + } + + 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 { + type Devices = vec::IntoIter; + type Device = Device; + + fn is_available() -> bool { + true + } + + fn devices(&self) -> Result { + device::all()? + .into_iter() + .pipe(Ok) + } + + fn default_input_device(&self) -> Option { + self.default_device::() + } + + fn default_output_device(&self) -> Option { + self.default_device::() + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Device { + kind: device::Kind, + direction: Direction, +} + +impl Hash for Device { + 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 { + 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) + } + } + } + } + } +} + +impl Device { + fn info(&self) -> Result, WindowsError> { + if let Specific(ref info) = self.kind { + return Cow::Borrowed(info).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 { + self.validate_direction::()?; + + self.activate(None)? + .get_mixformat()? + .try_into() + } + + fn supported_configs(&self) -> Result { + self.validate_direction::()?; + + 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))? + .pipe_ref(CapabilityProbe::new)? + .supported_formats_all_rates() + .into_iter() + .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(); + 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) + } + + #[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, + error_cb : ErrorCallback, + timeout : Option, + fn_new_proc : FnNewProcessor, + fn_process : FnProcess + ) -> Result + where + Processor : 'static, + DataCallback : Send + 'static, + ErrorCallback: FnMut(Error) + Send + 'static + { + let mut audio_client = self.activate(timeout)?; + + 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, + device::direction::(), + StreamMode::EventsShared { autoconvert: true, buffer_duration_hns: 0 }, + None + )?; + + 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 monitor = match self.kind { + device::Kind::Default => Some(DefaultDeviceMonitor::::new(safe_err_cb2)?), + device::Kind::Specific(_) => None + }; + + thread::Builder::new() + .name(thread_name::().into()) + .spawn(move || { + let _monitor = monitor; // RAII guard + + #[cfg(feature = "realtime")] + let _rt_guard = boost_current_thread_priority(period_frames, config.sample_rate) + .map_err(|error| safe_err_cb.invoke(error)); + + _ = 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| safe_err_cb.invoke(error)); + }) + .map_err(make_spawn_error)?; + + StreamInner { + total_frames, + period_frames, + audio_client, + audio_clock, + stream_state, + last_hns: u64::MIN, + } + .pipe(Stream::from) + .pipe(Ok) + } +} + +impl DeviceTrait for Device { + type SupportedInputConfigs = SupportedConfigs; + type SupportedOutputConfigs = SupportedConfigs; + type Stream = Stream; + + fn description(&self) -> Result { + 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.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()? + .Id()? + .to_string_lossy() + .into_boxed_str() + .pipe(|id| DeviceId(HostId::WasapiWinrt, id)) + .pipe(Ok) + } + + fn supported_input_configs(&self) -> Result { + self.supported_configs::() + } + + fn supported_output_configs(&self) -> Result { + self.supported_configs::() + } + + fn default_input_config(&self) -> Result { + self.default_config::() + } + + fn default_output_config(&self) -> Result { + self.default_config::() + } + + 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(CpalError) + Send + 'static + { + self.build_stream_inner::<_, _, _, true>( + config, + format, + data_cb, + error_cb, + timeout, + AudioClient::get_audiocaptureclient, + processing::capture + ) + } + + 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(CpalError) + Send + 'static, + { + self.build_stream_inner::<_, _, _, false>( + config, + format, + data_cb, + error_cb, + timeout, + AudioClient::get_audiorenderclient, + processing::render + ) + } +} + +#[derive(Debug)] +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<(), CpalError> { + self.0.lock().start() + } + + fn pause(&self) -> Result<(), CpalError> { + self.0.lock().pause() + } + + fn stop(&self, timeout: Option) -> Result<(), CpalError> { + self.0.lock().stop(timeout) + } + + fn buffer_size(&self) -> Result { + self.0.lock().buffer_size() + } + + fn now(&self) -> StreamInstant { + self.0.lock().now() + } +} + +#[derive(Debug)] +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 StreamInner { + pub fn start(&mut self) -> Result<(), CpalError> { + 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> { + 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> { + 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 { + self.audio_client + .get_current_padding()? + .pipe(|padding| self.total_frames - padding + self.period_frames) + .pipe(Ok) + } + + pub fn now(&mut self) -> StreamInstant { + 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) + } +} + +impl Drop for StreamInner { + fn drop(&mut self) { + _ = self.stream_state.set(StreamState::Exit, false); + } +} diff --git a/src/host/wasapi_winrt/device.rs b/src/host/wasapi_winrt/device.rs new file mode 100644 index 0000000000..6dfbe28f2d --- /dev/null +++ b/src/host/wasapi_winrt/device.rs @@ -0,0 +1,217 @@ +use super::{Device, utils::WindowsError}; +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, + 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}; + +#[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() +} + +fn extra_properties() -> IIterable { + vec![ + format_aqs(&PKEY_AudioEndpoint_FormFactor), + format_aqs(&PKEY_AudioEndpoint_JackSubType), + ] + .into() +} + +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 { kind: Kind::Specific(info), direction: direction::() }) + .pipe(Ok) +} + + +pub fn current_default_id() -> Result { + let role = AudioDeviceRole::Default; + + if INPUT { MediaDevice::GetDefaultAudioCaptureId(role) } + else { MediaDevice::GetDefaultAudioRenderId(role) } +} + +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"); + +pub struct PropertyReader(pub IMapView); + +impl PropertyReader { + pub fn types(&self) -> Result<(DeviceType, InterfaceType), WindowsError> { + let form_factor = self + .0 + .Lookup(&format_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::DigitalAudioDisplayDevice => interface_type = InterfaceType::DisplayPort, + Audio::UnknownDigitalPassthrough => interface_type = InterfaceType::Virtual, + Audio::RemoteNetworkDevice => interface_type = InterfaceType::Network, + 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, + _ => unreachable!() + }; + + let jack_sub_type = self + .0 + .Lookup(&format_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_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_LOOPBACK | + KSNODETYPE_AUDIO_ENGINE => interface_type = InterfaceType::Virtual, + + KSNODETYPE_ANALOG_CONNECTOR | + KSNODETYPE_LINE_CONNECTOR | + 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_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 | + 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, + + _ => () + } + + 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()))) + } + } + } +} diff --git a/src/host/wasapi_winrt/processing.rs b/src/host/wasapi_winrt/processing.rs new file mode 100644 index 0000000000..5d3c0fe191 --- /dev/null +++ b/src/host/wasapi_winrt/processing.rs @@ -0,0 +1,172 @@ +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; +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, + 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 FnNewProcessor = fn(&AudioClient) -> Result; + +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 _ +} + +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_winrt/utils.rs b/src/host/wasapi_winrt/utils.rs new file mode 100644 index 0000000000..b0b69da921 --- /dev/null +++ b/src/host/wasapi_winrt/utils.rs @@ -0,0 +1,326 @@ +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}, + ops::{Deref, DerefMut}, + time::Duration, + mem::transmute, + 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}; +use windows_core::{Interface, PCWSTR, Param, Ref, implement}; + +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, false, 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) + } + + #[must_use] + 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}")) + } +} + +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 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 + } +} + +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) } + } +} + +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 diff --git a/src/platform.rs b/src/platform.rs index a85e0dcc89..710f43827c 100644 --- a/src/platform.rs +++ b/src/platform.rs @@ -962,16 +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-winrt")] + use crate::host::wasapi_winrt::Host as WasapiWinrtHost; impl_platform_host!( #[cfg(feature = "asio")] Asio "ASIO" => AsioHost, Wasapi "WASAPI" => WasapiHost, + #[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-winrt")] + return WasapiWinrtHost::new() + .expect("the default host should always be available") + .into(); + + #[cfg(not(feature = "wasapi-winrt"))] WasapiHost::new() .expect("the default host should always be available") .into()