Implement BufferSize::Fixed in wasapi, and migrate wasapi to officially-supported Windows crate (#669)
I migrated to `windows-rs` in this PR since exposing the buffer size range for hardware-offloaded audio processing requires `IAudioClient2`, which isn't exposed in the `winapi` crate, and `winapi` seems to be more or less unmaintained at this point. * Basic type conversion * Make everything compile! * Fix warnings * Implement buffer sizing for wasapi * Convert tabs to spaces * Run cargo fmt * Remove winapi from Cargo.toml * Remove unused commented code from wasapi, and fix lingering TODOs * Fix compile error * Update to windows 0.37.0 * Run rustfmt * Work around rustfmt nested tuple issues * Improve readability of guid comparison code
This commit is contained in:
parent
493a0904f3
commit
417b7fff6f
5 changed files with 478 additions and 649 deletions
|
|
@ -25,7 +25,7 @@ clap = { version = "3.1", default-features = false, features = ["std"] }
|
||||||
ndk-glue = "0.6"
|
ndk-glue = "0.6"
|
||||||
|
|
||||||
[target.'cfg(target_os = "windows")'.dependencies]
|
[target.'cfg(target_os = "windows")'.dependencies]
|
||||||
winapi = { version = "0.3", features = ["audiosessiontypes", "audioclient", "coml2api", "combaseapi", "debug", "devpkey", "errhandlingapi", "handleapi", "ksmedia", "mmdeviceapi", "objbase", "profileapi", "std", "synchapi", "winbase", "winuser"] }
|
windows = { version = "0.37", features = ["Win32_Media_Audio", "Win32_Foundation", "Win32_System_Com", "Win32_Devices_Properties", "Win32_Media_KernelStreaming", "Win32_System_Com_StructuredStorage", "Win32_System_Ole", "Win32_System_Threading", "Win32_Security", "Win32_System_SystemServices", "Win32_System_WindowsProgramming", "Win32_Media_Multimedia", "Win32_UI_Shell_PropertiesSystem"]}
|
||||||
asio-sys = { version = "0.2", path = "asio-sys", optional = true }
|
asio-sys = { version = "0.2", path = "asio-sys", optional = true }
|
||||||
num-traits = { version = "0.2.6", optional = true }
|
num-traits = { version = "0.2.6", optional = true }
|
||||||
parking_lot = "0.12"
|
parking_lot = "0.12"
|
||||||
|
|
|
||||||
|
|
@ -4,9 +4,8 @@ use super::IoError;
|
||||||
use std::marker::PhantomData;
|
use std::marker::PhantomData;
|
||||||
use std::ptr;
|
use std::ptr;
|
||||||
|
|
||||||
use super::winapi::shared::winerror::{HRESULT, RPC_E_CHANGED_MODE, SUCCEEDED};
|
use windows::Win32::Foundation::RPC_E_CHANGED_MODE;
|
||||||
use super::winapi::um::combaseapi::{CoInitializeEx, CoUninitialize};
|
use windows::Win32::System::Com::{CoInitializeEx, CoUninitialize, COINIT_APARTMENTTHREADED};
|
||||||
use super::winapi::um::objbase::COINIT_APARTMENTTHREADED;
|
|
||||||
|
|
||||||
thread_local!(static COM_INITIALIZED: ComInitialized = {
|
thread_local!(static COM_INITIALIZED: ComInitialized = {
|
||||||
unsafe {
|
unsafe {
|
||||||
|
|
@ -17,14 +16,18 @@ thread_local!(static COM_INITIALIZED: ComInitialized = {
|
||||||
// That's OK though since COM ensures thread-safety/compatibility through marshalling when
|
// That's OK though since COM ensures thread-safety/compatibility through marshalling when
|
||||||
// necessary.
|
// necessary.
|
||||||
let result = CoInitializeEx(ptr::null_mut(), COINIT_APARTMENTTHREADED);
|
let result = CoInitializeEx(ptr::null_mut(), COINIT_APARTMENTTHREADED);
|
||||||
if SUCCEEDED(result) || result == RPC_E_CHANGED_MODE {
|
match result.clone().map_err(|e| e.code()) {
|
||||||
ComInitialized {
|
Ok(_) |
|
||||||
result,
|
Err(RPC_E_CHANGED_MODE) => {
|
||||||
_ptr: PhantomData,
|
ComInitialized {
|
||||||
|
result,
|
||||||
|
_ptr: PhantomData,
|
||||||
|
}
|
||||||
|
},
|
||||||
|
Err(e) => {
|
||||||
|
// COM initialization failed in another way, something is really wrong.
|
||||||
|
panic!("Failed to initialize COM: {}", IoError::from_raw_os_error(e.0));
|
||||||
}
|
}
|
||||||
} else {
|
|
||||||
// COM initialization failed in another way, something is really wrong.
|
|
||||||
panic!("Failed to initialize COM: {}", IoError::from_raw_os_error(result));
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
@ -34,7 +37,7 @@ thread_local!(static COM_INITIALIZED: ComInitialized = {
|
||||||
// We store a raw pointer because it's the only way at the moment to remove `Send`/`Sync` from the
|
// We store a raw pointer because it's the only way at the moment to remove `Send`/`Sync` from the
|
||||||
// object.
|
// object.
|
||||||
struct ComInitialized {
|
struct ComInitialized {
|
||||||
result: HRESULT,
|
result: windows::core::Result<()>,
|
||||||
_ptr: PhantomData<*mut ()>,
|
_ptr: PhantomData<*mut ()>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -43,7 +46,7 @@ impl Drop for ComInitialized {
|
||||||
fn drop(&mut self) {
|
fn drop(&mut self) {
|
||||||
// Need to avoid calling CoUninitialize() if CoInitializeEx failed since it may have
|
// Need to avoid calling CoUninitialize() if CoInitializeEx failed since it may have
|
||||||
// returned RPC_E_MODE_CHANGED - which is OK, see above.
|
// returned RPC_E_MODE_CHANGED - which is OK, see above.
|
||||||
if SUCCEEDED(self.result) {
|
if self.result.is_ok() {
|
||||||
unsafe { CoUninitialize() };
|
unsafe { CoUninitialize() };
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
File diff suppressed because it is too large
Load diff
|
|
@ -1,15 +1,13 @@
|
||||||
extern crate winapi;
|
|
||||||
|
|
||||||
pub use self::device::{
|
pub use self::device::{
|
||||||
default_input_device, default_output_device, Device, Devices, SupportedInputConfigs,
|
default_input_device, default_output_device, Device, Devices, SupportedInputConfigs,
|
||||||
SupportedOutputConfigs,
|
SupportedOutputConfigs,
|
||||||
};
|
};
|
||||||
pub use self::stream::Stream;
|
pub use self::stream::Stream;
|
||||||
use self::winapi::um::winnt::HRESULT;
|
|
||||||
use crate::traits::HostTrait;
|
use crate::traits::HostTrait;
|
||||||
use crate::BackendSpecificError;
|
use crate::BackendSpecificError;
|
||||||
use crate::DevicesError;
|
use crate::DevicesError;
|
||||||
use std::io::Error as IoError;
|
use std::io::Error as IoError;
|
||||||
|
use windows::Win32::Media::Audio;
|
||||||
|
|
||||||
mod com;
|
mod com;
|
||||||
mod device;
|
mod device;
|
||||||
|
|
@ -51,20 +49,56 @@ impl HostTrait for Host {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[inline]
|
impl From<windows::core::Error> for BackendSpecificError {
|
||||||
fn check_result(result: HRESULT) -> Result<(), IoError> {
|
fn from(error: windows::core::Error) -> Self {
|
||||||
if result < 0 {
|
BackendSpecificError {
|
||||||
Err(IoError::from_raw_os_error(result))
|
description: format!("{}", IoError::from(error)),
|
||||||
} else {
|
}
|
||||||
Ok(())
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn check_result_backend_specific(result: HRESULT) -> Result<(), BackendSpecificError> {
|
trait ErrDeviceNotAvailable: From<BackendSpecificError> {
|
||||||
match check_result(result) {
|
fn device_not_available() -> Self;
|
||||||
Ok(()) => Ok(()),
|
}
|
||||||
Err(err) => Err(BackendSpecificError {
|
|
||||||
description: format!("{}", err),
|
impl ErrDeviceNotAvailable for crate::BuildStreamError {
|
||||||
}),
|
fn device_not_available() -> Self {
|
||||||
|
Self::DeviceNotAvailable
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ErrDeviceNotAvailable for crate::SupportedStreamConfigsError {
|
||||||
|
fn device_not_available() -> Self {
|
||||||
|
Self::DeviceNotAvailable
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ErrDeviceNotAvailable for crate::DefaultStreamConfigError {
|
||||||
|
fn device_not_available() -> Self {
|
||||||
|
Self::DeviceNotAvailable
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ErrDeviceNotAvailable for crate::StreamError {
|
||||||
|
fn device_not_available() -> Self {
|
||||||
|
Self::DeviceNotAvailable
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn windows_err_to_cpal_err<E: ErrDeviceNotAvailable>(e: windows::core::Error) -> E {
|
||||||
|
windows_err_to_cpal_err_message::<E>(e, "")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn windows_err_to_cpal_err_message<E: ErrDeviceNotAvailable>(
|
||||||
|
e: windows::core::Error,
|
||||||
|
message: &str,
|
||||||
|
) -> E {
|
||||||
|
match e.code() {
|
||||||
|
Audio::AUDCLNT_E_DEVICE_INVALIDATED => E::device_not_available(),
|
||||||
|
_ => {
|
||||||
|
let description = format!("{}{}", message, e);
|
||||||
|
let err = BackendSpecificError { description };
|
||||||
|
err.into()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,11 +1,4 @@
|
||||||
use super::check_result;
|
use super::windows_err_to_cpal_err;
|
||||||
use super::winapi::shared::basetsd::{UINT32, UINT64};
|
|
||||||
use super::winapi::shared::minwindef::{BYTE, FALSE, WORD};
|
|
||||||
use super::winapi::um::audioclient::{self, AUDCLNT_E_DEVICE_INVALIDATED, AUDCLNT_S_BUFFER_EMPTY};
|
|
||||||
use super::winapi::um::handleapi;
|
|
||||||
use super::winapi::um::synchapi;
|
|
||||||
use super::winapi::um::winbase;
|
|
||||||
use super::winapi::um::winnt;
|
|
||||||
use crate::traits::StreamTrait;
|
use crate::traits::StreamTrait;
|
||||||
use crate::{
|
use crate::{
|
||||||
BackendSpecificError, Data, InputCallbackInfo, OutputCallbackInfo, PauseStreamError,
|
BackendSpecificError, Data, InputCallbackInfo, OutputCallbackInfo, PauseStreamError,
|
||||||
|
|
@ -15,6 +8,11 @@ use std::mem;
|
||||||
use std::ptr;
|
use std::ptr;
|
||||||
use std::sync::mpsc::{channel, Receiver, Sender};
|
use std::sync::mpsc::{channel, Receiver, Sender};
|
||||||
use std::thread::{self, JoinHandle};
|
use std::thread::{self, JoinHandle};
|
||||||
|
use windows::Win32::Foundation;
|
||||||
|
use windows::Win32::Media::Audio;
|
||||||
|
use windows::Win32::System::SystemServices;
|
||||||
|
use windows::Win32::System::Threading;
|
||||||
|
use windows::Win32::System::WindowsProgramming;
|
||||||
|
|
||||||
pub struct Stream {
|
pub struct Stream {
|
||||||
/// The high-priority audio processing thread calling callbacks.
|
/// The high-priority audio processing thread calling callbacks.
|
||||||
|
|
@ -30,7 +28,7 @@ pub struct Stream {
|
||||||
|
|
||||||
// This event is signalled after a new entry is added to `commands`, so that the `run()`
|
// This event is signalled after a new entry is added to `commands`, so that the `run()`
|
||||||
// method can be notified.
|
// method can be notified.
|
||||||
pending_scheduled_event: winnt::HANDLE,
|
pending_scheduled_event: Foundation::HANDLE,
|
||||||
}
|
}
|
||||||
|
|
||||||
struct RunContext {
|
struct RunContext {
|
||||||
|
|
@ -39,7 +37,7 @@ struct RunContext {
|
||||||
|
|
||||||
// Handles corresponding to the `event` field of each element of `voices`. Must always be in
|
// Handles corresponding to the `event` field of each element of `voices`. Must always be in
|
||||||
// sync with `voices`, except that the first element is always `pending_scheduled_event`.
|
// sync with `voices`, except that the first element is always `pending_scheduled_event`.
|
||||||
handles: Vec<winnt::HANDLE>,
|
handles: Vec<Foundation::HANDLE>,
|
||||||
|
|
||||||
commands: Receiver<Command>,
|
commands: Receiver<Command>,
|
||||||
}
|
}
|
||||||
|
|
@ -55,25 +53,25 @@ pub enum Command {
|
||||||
|
|
||||||
pub enum AudioClientFlow {
|
pub enum AudioClientFlow {
|
||||||
Render {
|
Render {
|
||||||
render_client: *mut audioclient::IAudioRenderClient,
|
render_client: Audio::IAudioRenderClient,
|
||||||
},
|
},
|
||||||
Capture {
|
Capture {
|
||||||
capture_client: *mut audioclient::IAudioCaptureClient,
|
capture_client: Audio::IAudioCaptureClient,
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct StreamInner {
|
pub struct StreamInner {
|
||||||
pub audio_client: *mut audioclient::IAudioClient,
|
pub audio_client: Audio::IAudioClient,
|
||||||
pub audio_clock: *mut audioclient::IAudioClock,
|
pub audio_clock: Audio::IAudioClock,
|
||||||
pub client_flow: AudioClientFlow,
|
pub client_flow: AudioClientFlow,
|
||||||
// Event that is signalled by WASAPI whenever audio data must be written.
|
// Event that is signalled by WASAPI whenever audio data must be written.
|
||||||
pub event: winnt::HANDLE,
|
pub event: Foundation::HANDLE,
|
||||||
// True if the stream is currently playing. False if paused.
|
// True if the stream is currently playing. False if paused.
|
||||||
pub playing: bool,
|
pub playing: bool,
|
||||||
// Number of frames of audio data in the underlying buffer allocated by WASAPI.
|
// Number of frames of audio data in the underlying buffer allocated by WASAPI.
|
||||||
pub max_frames_in_buffer: UINT32,
|
pub max_frames_in_buffer: u32,
|
||||||
// Number of bytes that each frame occupies.
|
// Number of bytes that each frame occupies.
|
||||||
pub bytes_per_frame: WORD,
|
pub bytes_per_frame: u16,
|
||||||
// The configuration with which the stream was created.
|
// The configuration with which the stream was created.
|
||||||
pub config: crate::StreamConfig,
|
pub config: crate::StreamConfig,
|
||||||
// The sample format with which the stream was created.
|
// The sample format with which the stream was created.
|
||||||
|
|
@ -90,8 +88,15 @@ impl Stream {
|
||||||
D: FnMut(&Data, &InputCallbackInfo) + Send + 'static,
|
D: FnMut(&Data, &InputCallbackInfo) + Send + 'static,
|
||||||
E: FnMut(StreamError) + Send + 'static,
|
E: FnMut(StreamError) + Send + 'static,
|
||||||
{
|
{
|
||||||
let pending_scheduled_event =
|
let pending_scheduled_event = unsafe {
|
||||||
unsafe { synchapi::CreateEventA(ptr::null_mut(), 0, 0, ptr::null()) };
|
Threading::CreateEventA(
|
||||||
|
ptr::null_mut(),
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
windows::core::PCSTR(ptr::null()),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
.expect("cpal: could not create input stream event");
|
||||||
let (tx, rx) = channel();
|
let (tx, rx) = channel();
|
||||||
|
|
||||||
let run_context = RunContext {
|
let run_context = RunContext {
|
||||||
|
|
@ -121,8 +126,15 @@ impl Stream {
|
||||||
D: FnMut(&mut Data, &OutputCallbackInfo) + Send + 'static,
|
D: FnMut(&mut Data, &OutputCallbackInfo) + Send + 'static,
|
||||||
E: FnMut(StreamError) + Send + 'static,
|
E: FnMut(StreamError) + Send + 'static,
|
||||||
{
|
{
|
||||||
let pending_scheduled_event =
|
let pending_scheduled_event = unsafe {
|
||||||
unsafe { synchapi::CreateEventA(ptr::null_mut(), 0, 0, ptr::null()) };
|
Threading::CreateEventA(
|
||||||
|
ptr::null_mut(),
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
windows::core::PCSTR(ptr::null()),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
.expect("cpal: could not create output stream event");
|
||||||
let (tx, rx) = channel();
|
let (tx, rx) = channel();
|
||||||
|
|
||||||
let run_context = RunContext {
|
let run_context = RunContext {
|
||||||
|
|
@ -148,8 +160,8 @@ impl Stream {
|
||||||
// Sender generally outlives receiver, unless the device gets unplugged.
|
// Sender generally outlives receiver, unless the device gets unplugged.
|
||||||
let _ = self.commands.send(command);
|
let _ = self.commands.send(command);
|
||||||
unsafe {
|
unsafe {
|
||||||
let result = synchapi::SetEvent(self.pending_scheduled_event);
|
let result = Threading::SetEvent(self.pending_scheduled_event);
|
||||||
assert_ne!(result, 0);
|
assert_ne!(result, false);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -160,7 +172,7 @@ impl Drop for Stream {
|
||||||
self.push_command(Command::Terminate);
|
self.push_command(Command::Terminate);
|
||||||
self.thread.take().unwrap().join().unwrap();
|
self.thread.take().unwrap().join().unwrap();
|
||||||
unsafe {
|
unsafe {
|
||||||
handleapi::CloseHandle(self.pending_scheduled_event);
|
Foundation::CloseHandle(self.pending_scheduled_event);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -176,24 +188,11 @@ impl StreamTrait for Stream {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Drop for AudioClientFlow {
|
|
||||||
fn drop(&mut self) {
|
|
||||||
unsafe {
|
|
||||||
match *self {
|
|
||||||
AudioClientFlow::Capture { capture_client } => (*capture_client).Release(),
|
|
||||||
AudioClientFlow::Render { render_client } => (*render_client).Release(),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Drop for StreamInner {
|
impl Drop for StreamInner {
|
||||||
#[inline]
|
#[inline]
|
||||||
fn drop(&mut self) {
|
fn drop(&mut self) {
|
||||||
unsafe {
|
unsafe {
|
||||||
(*self.audio_client).Release();
|
Foundation::CloseHandle(self.event);
|
||||||
(*self.audio_clock).Release();
|
|
||||||
handleapi::CloseHandle(self.event);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -204,25 +203,26 @@ fn process_commands(run_context: &mut RunContext) -> Result<bool, StreamError> {
|
||||||
// Process the pending commands.
|
// Process the pending commands.
|
||||||
for command in run_context.commands.try_iter() {
|
for command in run_context.commands.try_iter() {
|
||||||
match command {
|
match command {
|
||||||
Command::PlayStream => {
|
Command::PlayStream => unsafe {
|
||||||
if !run_context.stream.playing {
|
if !run_context.stream.playing {
|
||||||
let hresult = unsafe { (*run_context.stream.audio_client).Start() };
|
run_context
|
||||||
|
.stream
|
||||||
if let Err(err) = stream_error_from_hresult(hresult) {
|
.audio_client
|
||||||
return Err(err);
|
.Start()
|
||||||
}
|
.map_err(windows_err_to_cpal_err::<StreamError>)?;
|
||||||
run_context.stream.playing = true;
|
run_context.stream.playing = true;
|
||||||
}
|
}
|
||||||
}
|
},
|
||||||
Command::PauseStream => {
|
Command::PauseStream => unsafe {
|
||||||
if run_context.stream.playing {
|
if run_context.stream.playing {
|
||||||
let hresult = unsafe { (*run_context.stream.audio_client).Stop() };
|
run_context
|
||||||
if let Err(err) = stream_error_from_hresult(hresult) {
|
.stream
|
||||||
return Err(err);
|
.audio_client
|
||||||
}
|
.Stop()
|
||||||
|
.map_err(windows_err_to_cpal_err::<StreamError>)?;
|
||||||
run_context.stream.playing = false;
|
run_context.stream.playing = false;
|
||||||
}
|
}
|
||||||
}
|
},
|
||||||
Command::Terminate => {
|
Command::Terminate => {
|
||||||
return Ok(false);
|
return Ok(false);
|
||||||
}
|
}
|
||||||
|
|
@ -239,51 +239,38 @@ fn process_commands(run_context: &mut RunContext) -> Result<bool, StreamError> {
|
||||||
// This is called when the `run` thread is ready to wait for the next event. The
|
// This is called when the `run` thread is ready to wait for the next event. The
|
||||||
// next event might be some command submitted by the user (the first handle) or
|
// next event might be some command submitted by the user (the first handle) or
|
||||||
// might indicate that one of the streams is ready to deliver or receive audio.
|
// might indicate that one of the streams is ready to deliver or receive audio.
|
||||||
fn wait_for_handle_signal(handles: &[winnt::HANDLE]) -> Result<usize, BackendSpecificError> {
|
fn wait_for_handle_signal(handles: &[Foundation::HANDLE]) -> Result<usize, BackendSpecificError> {
|
||||||
debug_assert!(handles.len() <= winnt::MAXIMUM_WAIT_OBJECTS as usize);
|
debug_assert!(handles.len() <= SystemServices::MAXIMUM_WAIT_OBJECTS as usize);
|
||||||
let result = unsafe {
|
let result = unsafe {
|
||||||
synchapi::WaitForMultipleObjectsEx(
|
Threading::WaitForMultipleObjectsEx(
|
||||||
handles.len() as u32,
|
handles,
|
||||||
handles.as_ptr(),
|
false, // Don't wait for all, just wait for the first
|
||||||
FALSE, // Don't wait for all, just wait for the first
|
WindowsProgramming::INFINITE, // TODO: allow setting a timeout
|
||||||
winbase::INFINITE, // TODO: allow setting a timeout
|
false, // irrelevant parameter here
|
||||||
FALSE, // irrelevant parameter here
|
|
||||||
)
|
)
|
||||||
};
|
};
|
||||||
if result == winbase::WAIT_FAILED {
|
if result == Foundation::WAIT_FAILED.0 {
|
||||||
let err = unsafe { winapi::um::errhandlingapi::GetLastError() };
|
let err = unsafe { Foundation::GetLastError() };
|
||||||
let description = format!("`WaitForMultipleObjectsEx failed: {}", err);
|
let description = format!("`WaitForMultipleObjectsEx failed: {}", err.0);
|
||||||
let err = BackendSpecificError { description };
|
let err = BackendSpecificError { description };
|
||||||
return Err(err);
|
return Err(err);
|
||||||
}
|
}
|
||||||
// Notifying the corresponding task handler.
|
// Notifying the corresponding task handler.
|
||||||
let handle_idx = (result - winbase::WAIT_OBJECT_0) as usize;
|
let handle_idx = (result - Threading::WAIT_OBJECT_0) as usize;
|
||||||
Ok(handle_idx)
|
Ok(handle_idx)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get the number of available frames that are available for writing/reading.
|
// Get the number of available frames that are available for writing/reading.
|
||||||
fn get_available_frames(stream: &StreamInner) -> Result<u32, StreamError> {
|
fn get_available_frames(stream: &StreamInner) -> Result<u32, StreamError> {
|
||||||
unsafe {
|
unsafe {
|
||||||
let mut padding = 0u32;
|
let padding = stream
|
||||||
let hresult = (*stream.audio_client).GetCurrentPadding(&mut padding);
|
.audio_client
|
||||||
stream_error_from_hresult(hresult)?;
|
.GetCurrentPadding()
|
||||||
|
.map_err(windows_err_to_cpal_err::<StreamError>)?;
|
||||||
Ok(stream.max_frames_in_buffer - padding)
|
Ok(stream.max_frames_in_buffer - padding)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Convert the given `HRESULT` into a `StreamError` if it does indicate an error.
|
|
||||||
fn stream_error_from_hresult(hresult: winnt::HRESULT) -> Result<(), StreamError> {
|
|
||||||
if hresult == AUDCLNT_E_DEVICE_INVALIDATED {
|
|
||||||
return Err(StreamError::DeviceNotAvailable);
|
|
||||||
}
|
|
||||||
if let Err(err) = check_result(hresult) {
|
|
||||||
let description = format!("{}", err);
|
|
||||||
let err = BackendSpecificError { description };
|
|
||||||
return Err(err.into());
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn run_input(
|
fn run_input(
|
||||||
mut run_ctxt: RunContext,
|
mut run_ctxt: RunContext,
|
||||||
data_callback: &mut dyn FnMut(&Data, &InputCallbackInfo),
|
data_callback: &mut dyn FnMut(&Data, &InputCallbackInfo),
|
||||||
|
|
@ -296,7 +283,7 @@ fn run_input(
|
||||||
None => (),
|
None => (),
|
||||||
}
|
}
|
||||||
let capture_client = match run_ctxt.stream.client_flow {
|
let capture_client = match run_ctxt.stream.client_flow {
|
||||||
AudioClientFlow::Capture { capture_client } => capture_client,
|
AudioClientFlow::Capture { ref capture_client } => capture_client.clone(),
|
||||||
_ => unreachable!(),
|
_ => unreachable!(),
|
||||||
};
|
};
|
||||||
match process_input(
|
match process_input(
|
||||||
|
|
@ -323,7 +310,7 @@ fn run_output(
|
||||||
None => (),
|
None => (),
|
||||||
}
|
}
|
||||||
let render_client = match run_ctxt.stream.client_flow {
|
let render_client = match run_ctxt.stream.client_flow {
|
||||||
AudioClientFlow::Render { render_client } => render_client,
|
AudioClientFlow::Render { ref render_client } => render_client.clone(),
|
||||||
_ => unreachable!(),
|
_ => unreachable!(),
|
||||||
};
|
};
|
||||||
match process_output(
|
match process_output(
|
||||||
|
|
@ -378,26 +365,25 @@ fn process_commands_and_await_signal(
|
||||||
// The loop for processing pending input data.
|
// The loop for processing pending input data.
|
||||||
fn process_input(
|
fn process_input(
|
||||||
stream: &StreamInner,
|
stream: &StreamInner,
|
||||||
capture_client: *mut audioclient::IAudioCaptureClient,
|
capture_client: Audio::IAudioCaptureClient,
|
||||||
data_callback: &mut dyn FnMut(&Data, &InputCallbackInfo),
|
data_callback: &mut dyn FnMut(&Data, &InputCallbackInfo),
|
||||||
error_callback: &mut dyn FnMut(StreamError),
|
error_callback: &mut dyn FnMut(StreamError),
|
||||||
) -> ControlFlow {
|
) -> ControlFlow {
|
||||||
let mut frames_available = 0;
|
|
||||||
unsafe {
|
unsafe {
|
||||||
// Get the available data in the shared buffer.
|
// Get the available data in the shared buffer.
|
||||||
let mut buffer: *mut BYTE = ptr::null_mut();
|
let mut buffer: *mut u8 = ptr::null_mut();
|
||||||
let mut flags = mem::MaybeUninit::uninit();
|
let mut flags = mem::MaybeUninit::uninit();
|
||||||
loop {
|
loop {
|
||||||
let hresult = (*capture_client).GetNextPacketSize(&mut frames_available);
|
let mut frames_available = match capture_client.GetNextPacketSize() {
|
||||||
if let Err(err) = stream_error_from_hresult(hresult) {
|
Ok(0) => return ControlFlow::Continue,
|
||||||
error_callback(err);
|
Ok(f) => f,
|
||||||
return ControlFlow::Break;
|
Err(err) => {
|
||||||
}
|
error_callback(windows_err_to_cpal_err(err));
|
||||||
if frames_available == 0 {
|
return ControlFlow::Break;
|
||||||
return ControlFlow::Continue;
|
}
|
||||||
}
|
};
|
||||||
let mut qpc_position: UINT64 = 0;
|
let mut qpc_position: u64 = 0;
|
||||||
let hresult = (*capture_client).GetBuffer(
|
let result = capture_client.GetBuffer(
|
||||||
&mut buffer,
|
&mut buffer,
|
||||||
&mut frames_available,
|
&mut frames_available,
|
||||||
flags.as_mut_ptr(),
|
flags.as_mut_ptr(),
|
||||||
|
|
@ -405,12 +391,14 @@ fn process_input(
|
||||||
&mut qpc_position,
|
&mut qpc_position,
|
||||||
);
|
);
|
||||||
|
|
||||||
// TODO: Can this happen?
|
match result {
|
||||||
if hresult == AUDCLNT_S_BUFFER_EMPTY {
|
// TODO: Can this happen?
|
||||||
continue;
|
Err(e) if e.code() == Audio::AUDCLNT_S_BUFFER_EMPTY => continue,
|
||||||
} else if let Err(err) = stream_error_from_hresult(hresult) {
|
Err(e) => {
|
||||||
error_callback(err);
|
error_callback(windows_err_to_cpal_err(e));
|
||||||
return ControlFlow::Break;
|
return ControlFlow::Break;
|
||||||
|
}
|
||||||
|
Ok(_) => (),
|
||||||
}
|
}
|
||||||
|
|
||||||
debug_assert!(!buffer.is_null());
|
debug_assert!(!buffer.is_null());
|
||||||
|
|
@ -432,8 +420,10 @@ fn process_input(
|
||||||
data_callback(&data, &info);
|
data_callback(&data, &info);
|
||||||
|
|
||||||
// Release the buffer.
|
// Release the buffer.
|
||||||
let hresult = (*capture_client).ReleaseBuffer(frames_available);
|
let result = capture_client
|
||||||
if let Err(err) = stream_error_from_hresult(hresult) {
|
.ReleaseBuffer(frames_available)
|
||||||
|
.map_err(windows_err_to_cpal_err);
|
||||||
|
if let Err(err) = result {
|
||||||
error_callback(err);
|
error_callback(err);
|
||||||
return ControlFlow::Break;
|
return ControlFlow::Break;
|
||||||
}
|
}
|
||||||
|
|
@ -444,7 +434,7 @@ fn process_input(
|
||||||
// The loop for writing output data.
|
// The loop for writing output data.
|
||||||
fn process_output(
|
fn process_output(
|
||||||
stream: &StreamInner,
|
stream: &StreamInner,
|
||||||
render_client: *mut audioclient::IAudioRenderClient,
|
render_client: Audio::IAudioRenderClient,
|
||||||
data_callback: &mut dyn FnMut(&mut Data, &OutputCallbackInfo),
|
data_callback: &mut dyn FnMut(&mut Data, &OutputCallbackInfo),
|
||||||
error_callback: &mut dyn FnMut(StreamError),
|
error_callback: &mut dyn FnMut(StreamError),
|
||||||
) -> ControlFlow {
|
) -> ControlFlow {
|
||||||
|
|
@ -459,13 +449,13 @@ fn process_output(
|
||||||
};
|
};
|
||||||
|
|
||||||
unsafe {
|
unsafe {
|
||||||
let mut buffer: *mut BYTE = ptr::null_mut();
|
let buffer = match render_client.GetBuffer(frames_available) {
|
||||||
let hresult = (*render_client).GetBuffer(frames_available, &mut buffer as *mut *mut _);
|
Ok(b) => b,
|
||||||
|
Err(e) => {
|
||||||
if let Err(err) = stream_error_from_hresult(hresult) {
|
error_callback(windows_err_to_cpal_err(e));
|
||||||
error_callback(err);
|
return ControlFlow::Break;
|
||||||
return ControlFlow::Break;
|
}
|
||||||
}
|
};
|
||||||
|
|
||||||
debug_assert!(!buffer.is_null());
|
debug_assert!(!buffer.is_null());
|
||||||
|
|
||||||
|
|
@ -484,9 +474,8 @@ fn process_output(
|
||||||
let info = OutputCallbackInfo { timestamp };
|
let info = OutputCallbackInfo { timestamp };
|
||||||
data_callback(&mut data, &info);
|
data_callback(&mut data, &info);
|
||||||
|
|
||||||
let hresult = (*render_client).ReleaseBuffer(frames_available as u32, 0);
|
if let Err(err) = render_client.ReleaseBuffer(frames_available, 0) {
|
||||||
if let Err(err) = stream_error_from_hresult(hresult) {
|
error_callback(windows_err_to_cpal_err(err));
|
||||||
error_callback(err);
|
|
||||||
return ControlFlow::Break;
|
return ControlFlow::Break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -506,10 +495,14 @@ fn frames_to_duration(frames: u32, rate: crate::SampleRate) -> std::time::Durati
|
||||||
///
|
///
|
||||||
/// Uses the QPC position produced via the `GetPosition` method.
|
/// Uses the QPC position produced via the `GetPosition` method.
|
||||||
fn stream_instant(stream: &StreamInner) -> Result<crate::StreamInstant, StreamError> {
|
fn stream_instant(stream: &StreamInner) -> Result<crate::StreamInstant, StreamError> {
|
||||||
let mut position: UINT64 = 0;
|
let mut position: u64 = 0;
|
||||||
let mut qpc_position: UINT64 = 0;
|
let mut qpc_position: u64 = 0;
|
||||||
let res = unsafe { (*stream.audio_clock).GetPosition(&mut position, &mut qpc_position) };
|
unsafe {
|
||||||
stream_error_from_hresult(res)?;
|
stream
|
||||||
|
.audio_clock
|
||||||
|
.GetPosition(&mut position, &mut qpc_position)
|
||||||
|
.map_err(windows_err_to_cpal_err::<StreamError>)?;
|
||||||
|
};
|
||||||
// The `qpc_position` is in 100 nanosecond units. Convert it to nanoseconds.
|
// The `qpc_position` is in 100 nanosecond units. Convert it to nanoseconds.
|
||||||
let qpc_nanos = qpc_position as i128 * 100;
|
let qpc_nanos = qpc_position as i128 * 100;
|
||||||
let instant = crate::StreamInstant::from_nanos_i128(qpc_nanos)
|
let instant = crate::StreamInstant::from_nanos_i128(qpc_nanos)
|
||||||
|
|
@ -524,7 +517,7 @@ fn stream_instant(stream: &StreamInner) -> Result<crate::StreamInstant, StreamEr
|
||||||
/// captured.
|
/// captured.
|
||||||
fn input_timestamp(
|
fn input_timestamp(
|
||||||
stream: &StreamInner,
|
stream: &StreamInner,
|
||||||
buffer_qpc_position: UINT64,
|
buffer_qpc_position: u64,
|
||||||
) -> Result<crate::InputStreamTimestamp, StreamError> {
|
) -> Result<crate::InputStreamTimestamp, StreamError> {
|
||||||
// The `qpc_position` is in 100 nanosecond units. Convert it to nanoseconds.
|
// The `qpc_position` is in 100 nanosecond units. Convert it to nanoseconds.
|
||||||
let qpc_nanos = buffer_qpc_position as i128 * 100;
|
let qpc_nanos = buffer_qpc_position as i128 * 100;
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue