RFC: Rework the API [WIP] (#165)

* Rework the API to not use futures anymore

* Add some comments

* Update the MacOS backend

* Restore the null implementation

* Add an emscripten backend

* Remove erroneously added feature

* Fix to_f32 formula

* [WIP] Alsa backend

* Alsa backend compiling

* Working ALSA backend

* Fix tests

* Move WASAPI endpoint to endpoint module

* Fix WASAPI warnings

* Rework the WASAPI backend

* Check overflows for voice ID

* Add comments and minor fixes to WASAPI backend

* Add a changelog
This commit is contained in:
tomaka 2017-10-18 20:24:05 +02:00 • committed by GitHub
parent 4b019243c2
commit 6ae01f437c
13 changed files with 1472 additions and 1447 deletions

414
src/wasapi/endpoint.rs Normal file
View file

@ -0,0 +1,414 @@
use std::ffi::OsString;
use std::io::Error as IoError;
use std::mem;
use std::option::IntoIter as OptionIntoIter;
use std::os::windows::ffi::OsStringExt;
use std::ptr;
use std::slice;
use std::sync::{Arc, Mutex, MutexGuard};
use ChannelPosition;
use Format;
use FormatsEnumerationError;
use SampleFormat;
use SamplesRate;
use super::check_result;
use super::com;
use super::ole32;
use super::winapi;
pub type SupportedFormatsIterator = OptionIntoIter<Format>;
/// Wrapper because of that stupid decision to remove `Send` and `Sync` from raw pointers.
#[derive(Copy, Clone)]
struct IAudioClientWrapper(*mut winapi::IAudioClient);
unsafe impl Send for IAudioClientWrapper {
}
unsafe impl Sync for IAudioClientWrapper {
}
/// An opaque type that identifies an end point.
pub struct Endpoint {
device: *mut winapi::IMMDevice,
/// We cache an uninitialized `IAudioClient` so that we can call functions from it without
/// having to create/destroy audio clients all the time.
future_audio_client: Arc<Mutex<Option<IAudioClientWrapper>>>, // TODO: add NonZero around the ptr
}
unsafe impl Send for Endpoint {
}
unsafe impl Sync for Endpoint {
}
impl Endpoint {
// TODO: this function returns a GUID of the endpoin
// instead it should use the property store and return the friendly name
pub fn name(&self) -> String {
unsafe {
let mut name_ptr = mem::uninitialized();
// can only fail if wrong params or out of memory
check_result((*self.device).GetId(&mut name_ptr)).unwrap();
// finding the length of the name
let mut len = 0;
while *name_ptr.offset(len) != 0 {
len += 1;
}
// building a slice containing the name
let name_slice = slice::from_raw_parts(name_ptr, len as usize);
// and turning it into a string
let name_string: OsString = OsStringExt::from_wide(name_slice);
ole32::CoTaskMemFree(name_ptr as *mut _);
name_string.into_string().unwrap()
}
}
#[inline]
fn from_immdevice(device: *mut winapi::IMMDevice) -> Endpoint {
Endpoint {
device: device,
future_audio_client: Arc::new(Mutex::new(None)),
}
}
/// Ensures that `future_audio_client` contains a `Some` and returns a locked mutex to it.
fn ensure_future_audio_client(&self)
-> Result<MutexGuard<Option<IAudioClientWrapper>>, IoError> {
let mut lock = self.future_audio_client.lock().unwrap();
if lock.is_some() {
return Ok(lock);
}
let audio_client: *mut winapi::IAudioClient = unsafe {
let mut audio_client = mem::uninitialized();
let hresult = (*self.device).Activate(&winapi::IID_IAudioClient,
winapi::CLSCTX_ALL,
ptr::null_mut(),
&mut audio_client);
// can fail if the device has been disconnected since we enumerated it, or if
// the device doesn't support playback for some reason
check_result(hresult)?;
assert!(!audio_client.is_null());
audio_client as *mut _
};
*lock = Some(IAudioClientWrapper(audio_client));
Ok(lock)
}
/// Returns an uninitialized `IAudioClient`.
#[inline]
pub(crate) fn build_audioclient(&self) -> Result<*mut winapi::IAudioClient, IoError> {
let mut lock = self.ensure_future_audio_client()?;
let client = lock.unwrap().0;
*lock = None;
Ok(client)
}
pub fn supported_formats(
&self)
-> Result<SupportedFormatsIterator, FormatsEnumerationError> {
// We always create voices in shared mode, therefore all samples go through an audio
// processor to mix them together.
// However there is no way to query the list of all formats that are supported by the
// audio processor, but one format is guaranteed to be supported, the one returned by
// `GetMixFormat`.
// initializing COM because we call `CoTaskMemFree`
com::com_initialized();
let lock = match self.ensure_future_audio_client() {
Err(ref e) if e.raw_os_error() == Some(winapi::AUDCLNT_E_DEVICE_INVALIDATED) =>
return Err(FormatsEnumerationError::DeviceNotAvailable),
e => e.unwrap(),
};
let client = lock.unwrap().0;
unsafe {
let mut format_ptr = mem::uninitialized();
match check_result((*client).GetMixFormat(&mut format_ptr)) {
Err(ref e) if e.raw_os_error() == Some(winapi::AUDCLNT_E_DEVICE_INVALIDATED) => {
return Err(FormatsEnumerationError::DeviceNotAvailable);
},
Err(e) => panic!("{:?}", e),
Ok(()) => (),
};
let format = {
let (channels, data_type) = match (*format_ptr).wFormatTag {
winapi::WAVE_FORMAT_PCM => {
(vec![ChannelPosition::FrontLeft, ChannelPosition::FrontRight],
SampleFormat::I16)
},
winapi::WAVE_FORMAT_EXTENSIBLE => {
let format_ptr = format_ptr as *const winapi::WAVEFORMATEXTENSIBLE;
let channels = {
let mut channels = Vec::new();
let mask = (*format_ptr).dwChannelMask;
if (mask & winapi::SPEAKER_FRONT_LEFT) != 0 {
channels.push(ChannelPosition::FrontLeft);
}
if (mask & winapi::SPEAKER_FRONT_RIGHT) != 0 {
channels.push(ChannelPosition::FrontRight);
}
if (mask & winapi::SPEAKER_FRONT_CENTER) != 0 {
channels.push(ChannelPosition::FrontCenter);
}
if (mask & winapi::SPEAKER_LOW_FREQUENCY) != 0 {
channels.push(ChannelPosition::LowFrequency);
}
if (mask & winapi::SPEAKER_BACK_LEFT) != 0 {
channels.push(ChannelPosition::BackLeft);
}
if (mask & winapi::SPEAKER_BACK_RIGHT) != 0 {
channels.push(ChannelPosition::BackRight);
}
if (mask & winapi::SPEAKER_FRONT_LEFT_OF_CENTER) != 0 {
channels.push(ChannelPosition::FrontLeftOfCenter);
}
if (mask & winapi::SPEAKER_FRONT_RIGHT_OF_CENTER) != 0 {
channels.push(ChannelPosition::FrontRightOfCenter);
}
if (mask & winapi::SPEAKER_BACK_CENTER) != 0 {
channels.push(ChannelPosition::BackCenter);
}
if (mask & winapi::SPEAKER_SIDE_LEFT) != 0 {
channels.push(ChannelPosition::SideLeft);
}
if (mask & winapi::SPEAKER_SIDE_RIGHT) != 0 {
channels.push(ChannelPosition::SideRight);
}
if (mask & winapi::SPEAKER_TOP_CENTER) != 0 {
channels.push(ChannelPosition::TopCenter);
}
if (mask & winapi::SPEAKER_TOP_FRONT_LEFT) != 0 {
channels.push(ChannelPosition::TopFrontLeft);
}
if (mask & winapi::SPEAKER_TOP_FRONT_CENTER) != 0 {
channels.push(ChannelPosition::TopFrontCenter);
}
if (mask & winapi::SPEAKER_TOP_FRONT_RIGHT) != 0 {
channels.push(ChannelPosition::TopFrontRight);
}
if (mask & winapi::SPEAKER_TOP_BACK_LEFT) != 0 {
channels.push(ChannelPosition::TopBackLeft);
}
if (mask & winapi::SPEAKER_TOP_BACK_CENTER) != 0 {
channels.push(ChannelPosition::TopBackCenter);
}
if (mask & winapi::SPEAKER_TOP_BACK_RIGHT) != 0 {
channels.push(ChannelPosition::TopBackRight);
}
assert_eq!((*format_ptr).Format.nChannels as usize, channels.len());
channels
};
let format = {
fn cmp_guid(a: &winapi::GUID, b: &winapi::GUID) -> bool {
a.Data1 == b.Data1 && a.Data2 == b.Data2 && a.Data3 == b.Data3 &&
a.Data4 == b.Data4
}
if cmp_guid(&(*format_ptr).SubFormat,
&winapi::KSDATAFORMAT_SUBTYPE_IEEE_FLOAT)
{
SampleFormat::F32
} else if cmp_guid(&(*format_ptr).SubFormat,
&winapi::KSDATAFORMAT_SUBTYPE_PCM)
{
SampleFormat::I16
} else {
panic!("Unknown SubFormat GUID returned by GetMixFormat: {:?}",
(*format_ptr).SubFormat)
}
};
(channels, format)
},
f => panic!("Unknown data format returned by GetMixFormat: {:?}", f),
};
Format {
channels: channels,
samples_rate: SamplesRate((*format_ptr).nSamplesPerSec),
data_type: data_type,
}
};
ole32::CoTaskMemFree(format_ptr as *mut _);
Ok(Some(format).into_iter())
}
}
}
impl PartialEq for Endpoint {
#[inline]
fn eq(&self, other: &Endpoint) -> bool {
self.device == other.device
}
}
impl Eq for Endpoint {
}
impl Clone for Endpoint {
#[inline]
fn clone(&self) -> Endpoint {
unsafe {
(*self.device).AddRef();
}
Endpoint {
device: self.device,
future_audio_client: self.future_audio_client.clone(),
}
}
}
impl Drop for Endpoint {
#[inline]
fn drop(&mut self) {
unsafe {
(*self.device).Release();
}
if let Some(client) = self.future_audio_client.lock().unwrap().take() {
unsafe {
(*client.0).Release();
}
}
}
}
lazy_static! {
static ref ENUMERATOR: Enumerator = {
// COM initialization is thread local, but we only need to have COM initialized in the
// thread we create the objects in
com::com_initialized();
// building the devices enumerator object
unsafe {
let mut enumerator: *mut winapi::IMMDeviceEnumerator = mem::uninitialized();
let hresult = ole32::CoCreateInstance(&winapi::CLSID_MMDeviceEnumerator,
ptr::null_mut(), winapi::CLSCTX_ALL,
&winapi::IID_IMMDeviceEnumerator,
&mut enumerator
as *mut *mut winapi::IMMDeviceEnumerator
as *mut _);
check_result(hresult).unwrap();
Enumerator(enumerator)
}
};
}
/// RAII object around `winapi::IMMDeviceEnumerator`.
struct Enumerator(*mut winapi::IMMDeviceEnumerator);
unsafe impl Send for Enumerator {
}
unsafe impl Sync for Enumerator {
}
impl Drop for Enumerator {
#[inline]
fn drop(&mut self) {
unsafe {
(*self.0).Release();
}
}
}
/// WASAPI implementation for `EndpointsIterator`.
pub struct EndpointsIterator {
collection: *mut winapi::IMMDeviceCollection,
total_count: u32,
next_item: u32,
}
unsafe impl Send for EndpointsIterator {
}
unsafe impl Sync for EndpointsIterator {
}
impl Drop for EndpointsIterator {
#[inline]
fn drop(&mut self) {
unsafe {
(*self.collection).Release();
}
}
}
impl Default for EndpointsIterator {
fn default() -> EndpointsIterator {
unsafe {
let mut collection: *mut winapi::IMMDeviceCollection = mem::uninitialized();
// can fail because of wrong parameters (should never happen) or out of memory
check_result((*ENUMERATOR.0).EnumAudioEndpoints(winapi::eRender,
winapi::DEVICE_STATE_ACTIVE,
&mut collection))
.unwrap();
let mut count = mem::uninitialized();
// can fail if the parameter is null, which should never happen
check_result((*collection).GetCount(&mut count)).unwrap();
EndpointsIterator {
collection: collection,
total_count: count,
next_item: 0,
}
}
}
}
impl Iterator for EndpointsIterator {
type Item = Endpoint;
fn next(&mut self) -> Option<Endpoint> {
if self.next_item >= self.total_count {
return None;
}
unsafe {
let mut device = mem::uninitialized();
// can fail if out of range, which we just checked above
check_result((*self.collection).Item(self.next_item, &mut device)).unwrap();
self.next_item += 1;
Some(Endpoint::from_immdevice(device))
}
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
let num = self.total_count - self.next_item;
let num = num as usize;
(num, Some(num))
}
}
pub fn default_endpoint() -> Option<Endpoint> {
unsafe {
let mut device = mem::uninitialized();
let hres = (*ENUMERATOR.0)
.GetDefaultAudioEndpoint(winapi::eRender, winapi::eConsole, &mut device);
if let Err(_err) = check_result(hres) {
return None; // TODO: check specifically for `E_NOTFOUND`, and panic otherwise
}
Some(Endpoint::from_immdevice(device))
}
}

View file

@ -1,133 +0,0 @@
use super::Endpoint;
use super::check_result;
use super::com;
use super::ole32;
use super::winapi;
use std::mem;
use std::ptr;
lazy_static! {
static ref ENUMERATOR: Enumerator = {
// COM initialization is thread local, but we only need to have COM initialized in the
// thread we create the objects in
com::com_initialized();
// building the devices enumerator object
unsafe {
let mut enumerator: *mut winapi::IMMDeviceEnumerator = mem::uninitialized();
let hresult = ole32::CoCreateInstance(&winapi::CLSID_MMDeviceEnumerator,
ptr::null_mut(), winapi::CLSCTX_ALL,
&winapi::IID_IMMDeviceEnumerator,
&mut enumerator
as *mut *mut winapi::IMMDeviceEnumerator
as *mut _);
check_result(hresult).unwrap();
Enumerator(enumerator)
}
};
}
/// RAII object around `winapi::IMMDeviceEnumerator`.
struct Enumerator(*mut winapi::IMMDeviceEnumerator);
unsafe impl Send for Enumerator {
}
unsafe impl Sync for Enumerator {
}
impl Drop for Enumerator {
#[inline]
fn drop(&mut self) {
unsafe {
(*self.0).Release();
}
}
}
/// WASAPI implementation for `EndpointsIterator`.
pub struct EndpointsIterator {
collection: *mut winapi::IMMDeviceCollection,
total_count: u32,
next_item: u32,
}
unsafe impl Send for EndpointsIterator {
}
unsafe impl Sync for EndpointsIterator {
}
impl Drop for EndpointsIterator {
#[inline]
fn drop(&mut self) {
unsafe {
(*self.collection).Release();
}
}
}
impl Default for EndpointsIterator {
fn default() -> EndpointsIterator {
unsafe {
let mut collection: *mut winapi::IMMDeviceCollection = mem::uninitialized();
// can fail because of wrong parameters (should never happen) or out of memory
check_result((*ENUMERATOR.0).EnumAudioEndpoints(winapi::eRender,
winapi::DEVICE_STATE_ACTIVE,
&mut collection))
.unwrap();
let mut count = mem::uninitialized();
// can fail if the parameter is null, which should never happen
check_result((*collection).GetCount(&mut count)).unwrap();
EndpointsIterator {
collection: collection,
total_count: count,
next_item: 0,
}
}
}
}
impl Iterator for EndpointsIterator {
type Item = Endpoint;
fn next(&mut self) -> Option<Endpoint> {
if self.next_item >= self.total_count {
return None;
}
unsafe {
let mut device = mem::uninitialized();
// can fail if out of range, which we just checked above
check_result((*self.collection).Item(self.next_item, &mut device)).unwrap();
self.next_item += 1;
Some(Endpoint::from_immdevice(device))
}
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
let num = self.total_count - self.next_item;
let num = num as usize;
(num, Some(num))
}
}
pub fn default_endpoint() -> Option<Endpoint> {
unsafe {
let mut device = mem::uninitialized();
let hres = (*ENUMERATOR.0)
.GetDefaultAudioEndpoint(winapi::eRender, winapi::eConsole, &mut device);
if let Err(_err) = check_result(hres) {
return None; // TODO: check specifically for `E_NOTFOUND`, and panic otherwise
}
Some(Endpoint::from_immdevice(device))
}
}

View file

@ -2,28 +2,13 @@ extern crate winapi;
extern crate ole32;
extern crate kernel32;
use std::ffi::OsString;
use std::io::Error as IoError;
use std::mem;
use std::os::windows::ffi::OsStringExt;
use std::ptr;
use std::slice;
use std::sync::{Arc, Mutex, MutexGuard};
use ChannelPosition;
use Format;
use FormatsEnumerationError;
use SampleFormat;
use SamplesRate;
pub use self::enumerate::{EndpointsIterator, default_endpoint};
pub use self::voice::{Buffer, EventLoop, SamplesStream, Voice};
pub use std::option::IntoIter as OptionIntoIter;
pub type SupportedFormatsIterator = OptionIntoIter<Format>;
pub use self::endpoint::{Endpoint, EndpointsIterator, default_endpoint, SupportedFormatsIterator};
pub use self::voice::{Buffer, EventLoop, VoiceId};
mod com;
mod enumerate;
mod endpoint;
mod voice;
#[inline]
@ -34,272 +19,3 @@ fn check_result(result: winapi::HRESULT) -> Result<(), IoError> {
Ok(())
}
}
/// Wrapper because of that stupid decision to remove `Send` and `Sync` from raw pointers.
#[derive(Copy, Clone)]
struct IAudioClientWrapper(*mut winapi::IAudioClient);
unsafe impl Send for IAudioClientWrapper {
}
unsafe impl Sync for IAudioClientWrapper {
}
/// An opaque type that identifies an end point.
pub struct Endpoint {
device: *mut winapi::IMMDevice,
/// We cache an uninitialized `IAudioClient` so that we can call functions from it without
/// having to create/destroy audio clients all the time.
future_audio_client: Arc<Mutex<Option<IAudioClientWrapper>>>, // TODO: add NonZero around the ptr
}
unsafe impl Send for Endpoint {
}
unsafe impl Sync for Endpoint {
}
impl Endpoint {
// TODO: this function returns a GUID of the endpoin
// instead it should use the property store and return the friendly name
pub fn name(&self) -> String {
unsafe {
let mut name_ptr = mem::uninitialized();
// can only fail if wrong params or out of memory
check_result((*self.device).GetId(&mut name_ptr)).unwrap();
// finding the length of the name
let mut len = 0;
while *name_ptr.offset(len) != 0 {
len += 1;
}
// building a slice containing the name
let name_slice = slice::from_raw_parts(name_ptr, len as usize);
// and turning it into a string
let name_string: OsString = OsStringExt::from_wide(name_slice);
ole32::CoTaskMemFree(name_ptr as *mut _);
name_string.into_string().unwrap()
}
}
#[inline]
fn from_immdevice(device: *mut winapi::IMMDevice) -> Endpoint {
Endpoint {
device: device,
future_audio_client: Arc::new(Mutex::new(None)),
}
}
/// Ensures that `future_audio_client` contains a `Some` and returns a locked mutex to it.
fn ensure_future_audio_client(&self)
-> Result<MutexGuard<Option<IAudioClientWrapper>>, IoError> {
let mut lock = self.future_audio_client.lock().unwrap();
if lock.is_some() {
return Ok(lock);
}
let audio_client: *mut winapi::IAudioClient = unsafe {
let mut audio_client = mem::uninitialized();
let hresult = (*self.device).Activate(&winapi::IID_IAudioClient,
winapi::CLSCTX_ALL,
ptr::null_mut(),
&mut audio_client);
// can fail if the device has been disconnected since we enumerated it, or if
// the device doesn't support playback for some reason
check_result(hresult)?;
assert!(!audio_client.is_null());
audio_client as *mut _
};
*lock = Some(IAudioClientWrapper(audio_client));
Ok(lock)
}
/// Returns an uninitialized `IAudioClient`.
#[inline]
fn build_audioclient(&self) -> Result<*mut winapi::IAudioClient, IoError> {
let mut lock = self.ensure_future_audio_client()?;
let client = lock.unwrap().0;
*lock = None;
Ok(client)
}
pub fn supported_formats(
&self)
-> Result<SupportedFormatsIterator, FormatsEnumerationError> {
// We always create voices in shared mode, therefore all samples go through an audio
// processor to mix them together.
// However there is no way to query the list of all formats that are supported by the
// audio processor, but one format is guaranteed to be supported, the one returned by
// `GetMixFormat`.
// initializing COM because we call `CoTaskMemFree`
com::com_initialized();
let lock = match self.ensure_future_audio_client() {
Err(ref e) if e.raw_os_error() == Some(winapi::AUDCLNT_E_DEVICE_INVALIDATED) =>
return Err(FormatsEnumerationError::DeviceNotAvailable),
e => e.unwrap(),
};
let client = lock.unwrap().0;
unsafe {
let mut format_ptr = mem::uninitialized();
match check_result((*client).GetMixFormat(&mut format_ptr)) {
Err(ref e) if e.raw_os_error() == Some(winapi::AUDCLNT_E_DEVICE_INVALIDATED) => {
return Err(FormatsEnumerationError::DeviceNotAvailable);
},
Err(e) => panic!("{:?}", e),
Ok(()) => (),
};
let format = {
let (channels, data_type) = match (*format_ptr).wFormatTag {
winapi::WAVE_FORMAT_PCM => {
(vec![ChannelPosition::FrontLeft, ChannelPosition::FrontRight],
SampleFormat::I16)
},
winapi::WAVE_FORMAT_EXTENSIBLE => {
let format_ptr = format_ptr as *const winapi::WAVEFORMATEXTENSIBLE;
let channels = {
let mut channels = Vec::new();
let mask = (*format_ptr).dwChannelMask;
if (mask & winapi::SPEAKER_FRONT_LEFT) != 0 {
channels.push(ChannelPosition::FrontLeft);
}
if (mask & winapi::SPEAKER_FRONT_RIGHT) != 0 {
channels.push(ChannelPosition::FrontRight);
}
if (mask & winapi::SPEAKER_FRONT_CENTER) != 0 {
channels.push(ChannelPosition::FrontCenter);
}
if (mask & winapi::SPEAKER_LOW_FREQUENCY) != 0 {
channels.push(ChannelPosition::LowFrequency);
}
if (mask & winapi::SPEAKER_BACK_LEFT) != 0 {
channels.push(ChannelPosition::BackLeft);
}
if (mask & winapi::SPEAKER_BACK_RIGHT) != 0 {
channels.push(ChannelPosition::BackRight);
}
if (mask & winapi::SPEAKER_FRONT_LEFT_OF_CENTER) != 0 {
channels.push(ChannelPosition::FrontLeftOfCenter);
}
if (mask & winapi::SPEAKER_FRONT_RIGHT_OF_CENTER) != 0 {
channels.push(ChannelPosition::FrontRightOfCenter);
}
if (mask & winapi::SPEAKER_BACK_CENTER) != 0 {
channels.push(ChannelPosition::BackCenter);
}
if (mask & winapi::SPEAKER_SIDE_LEFT) != 0 {
channels.push(ChannelPosition::SideLeft);
}
if (mask & winapi::SPEAKER_SIDE_RIGHT) != 0 {
channels.push(ChannelPosition::SideRight);
}
if (mask & winapi::SPEAKER_TOP_CENTER) != 0 {
channels.push(ChannelPosition::TopCenter);
}
if (mask & winapi::SPEAKER_TOP_FRONT_LEFT) != 0 {
channels.push(ChannelPosition::TopFrontLeft);
}
if (mask & winapi::SPEAKER_TOP_FRONT_CENTER) != 0 {
channels.push(ChannelPosition::TopFrontCenter);
}
if (mask & winapi::SPEAKER_TOP_FRONT_RIGHT) != 0 {
channels.push(ChannelPosition::TopFrontRight);
}
if (mask & winapi::SPEAKER_TOP_BACK_LEFT) != 0 {
channels.push(ChannelPosition::TopBackLeft);
}
if (mask & winapi::SPEAKER_TOP_BACK_CENTER) != 0 {
channels.push(ChannelPosition::TopBackCenter);
}
if (mask & winapi::SPEAKER_TOP_BACK_RIGHT) != 0 {
channels.push(ChannelPosition::TopBackRight);
}
assert_eq!((*format_ptr).Format.nChannels as usize, channels.len());
channels
};
let format = {
fn cmp_guid(a: &winapi::GUID, b: &winapi::GUID) -> bool {
a.Data1 == b.Data1 && a.Data2 == b.Data2 && a.Data3 == b.Data3 &&
a.Data4 == b.Data4
}
if cmp_guid(&(*format_ptr).SubFormat,
&winapi::KSDATAFORMAT_SUBTYPE_IEEE_FLOAT)
{
SampleFormat::F32
} else if cmp_guid(&(*format_ptr).SubFormat,
&winapi::KSDATAFORMAT_SUBTYPE_PCM)
{
SampleFormat::I16
} else {
panic!("Unknown SubFormat GUID returned by GetMixFormat: {:?}",
(*format_ptr).SubFormat)
}
};
(channels, format)
},
f => panic!("Unknown data format returned by GetMixFormat: {:?}", f),
};
Format {
channels: channels,
samples_rate: SamplesRate((*format_ptr).nSamplesPerSec),
data_type: data_type,
}
};
ole32::CoTaskMemFree(format_ptr as *mut _);
Ok(Some(format).into_iter())
}
}
}
impl PartialEq for Endpoint {
#[inline]
fn eq(&self, other: &Endpoint) -> bool {
self.device == other.device
}
}
impl Eq for Endpoint {
}
impl Clone for Endpoint {
#[inline]
fn clone(&self) -> Endpoint {
unsafe {
(*self.device).AddRef();
}
Endpoint {
device: self.device,
future_audio_client: self.future_audio_client.clone(),
}
}
}
impl Drop for Endpoint {
#[inline]
fn drop(&mut self) {
unsafe {
(*self.device).Release();
}
if let Some(client) = self.future_audio_client.lock().unwrap().take() {
unsafe {
(*client.0).Release();
}
}
}
}

View file

@ -6,19 +6,15 @@ use super::kernel32;
use super::ole32;
use super::winapi;
use std::iter;
use std::marker::PhantomData;
use std::mem;
use std::ptr;
use std::slice;
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering;
use std::sync::Arc;
use std::sync::Mutex;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering;
use futures::Async;
use futures::Poll;
use futures::stream::Stream;
use futures::task;
use futures::task::Task;
use ChannelPosition;
use CreationError;
@ -27,45 +23,56 @@ use SampleFormat;
use UnknownTypeBuffer;
pub struct EventLoop {
inner: Arc<EventLoopInner>,
}
// Data used by the `run()` function implementation. The mutex is kept lock permanently by
// `run()`. This ensures that two `run()` invocations can't run at the same time, and also
// means that we shouldn't try to lock this field from anywhere else but `run()`.
run_context: Mutex<RunContext>,
unsafe impl Send for EventLoop {
}
unsafe impl Sync for EventLoop {
}
// Identifier of the next voice to create. Each new voice increases this counter. If the
// counter overflows, there's a panic.
// TODO: use AtomicU64 instead
next_voice_id: AtomicUsize,
struct EventLoopInner {
// List of handles that are currently being polled or that are going to be polled. This mutex
// is locked for as long as the event loop is running.
//
// In the `EventLoopScheduled`, the first handle in the list of handles is always
// `pending_scheduled_event`. This means that the length of `handles` is always 1 + the length
// of `task_handles`.
// FIXME: no way to remove elements from that list?
scheduled: Mutex<EventLoopScheduled>,
// Commands processed by the `run()` method that is currently running.
// `pending_scheduled_event` must be signalled whenever a command is added here, so that it
// will get picked up.
// TODO: use a lock-free container
commands: Mutex<Vec<Command>>,
// Since the above mutex is locked most of the time, we add new handles to this list instead.
// After a new element is added to this list, you should notify `pending_scheduled_event`
// so that they get transferred to `scheduled`.
//
// The length of `handles` and `task_handles` should always be equal.
pending_scheduled: Mutex<EventLoopScheduled>,
// This event is signalled after elements have been added to `pending_scheduled` in order to
// notify that they should be picked up.
// This event is signalled after a new entry is added to `commands`, so that the `run()`
// method can be notified.
pending_scheduled_event: winapi::HANDLE,
}
struct EventLoopScheduled {
// List of handles that correspond to voices.
// They are linked to `task_handles`, but we store them separately in order to easily call
// `WaitForMultipleObjectsEx` on the array without having to perform any conversion.
handles: Vec<winapi::HANDLE>,
struct RunContext {
// Voices that have been created in this event loop.
voices: Vec<VoiceInner>,
// List of task handles corresponding to `handles`. The second element is used to signal
// the voice that it has been signaled.
task_handles: Vec<(Task, Arc<AtomicBool>)>,
// 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`.
handles: Vec<winapi::HANDLE>,
}
enum Command {
NewVoice(VoiceInner),
DestroyVoice(VoiceId),
Play(VoiceId),
Pause(VoiceId),
}
struct VoiceInner {
id: VoiceId,
audio_client: *mut winapi::IAudioClient,
render_client: *mut winapi::IAudioRenderClient,
// Event that is signalled by WASAPI whenever audio data must be written.
event: winapi::HANDLE,
// True if the voice is currently playing. False if paused.
playing: bool,
// Number of frames of audio data in the underlying buffer allocated by WASAPI.
max_frames_in_buffer: winapi::UINT32,
// Number of bytes that each frame occupies.
bytes_per_frame: winapi::WORD,
}
impl EventLoop {
@ -74,103 +81,18 @@ impl EventLoop {
unsafe { kernel32::CreateEventA(ptr::null_mut(), 0, 0, ptr::null()) };
EventLoop {
inner: Arc::new(EventLoopInner {
pending_scheduled_event: pending_scheduled_event,
scheduled: Mutex::new(EventLoopScheduled {
handles: vec![pending_scheduled_event],
task_handles: vec![],
}),
pending_scheduled: Mutex::new(EventLoopScheduled {
handles: vec![],
task_handles: vec![],
}),
}),
pending_scheduled_event: pending_scheduled_event,
run_context: Mutex::new(RunContext {
voices: Vec::new(),
handles: vec![pending_scheduled_event],
}),
next_voice_id: AtomicUsize::new(0),
commands: Mutex::new(Vec::new()),
}
}
pub fn run(&self) {
unsafe {
let mut scheduled = self.inner.scheduled.lock().unwrap();
loop {
debug_assert!(scheduled.handles.len() == 1 + scheduled.task_handles.len());
// Creating a voice checks for the MAXIMUM_WAIT_OBJECTS limit.
// FIXME: this is not the case ^
debug_assert!(scheduled.handles.len() <= winapi::MAXIMUM_WAIT_OBJECTS as usize);
// Wait for any of the handles to be signalled, which means that the corresponding
// sound needs a buffer.
let result = kernel32::WaitForMultipleObjectsEx(scheduled.handles.len() as u32,
scheduled.handles.as_ptr(),
winapi::FALSE,
winapi::INFINITE, /* TODO: allow setting a timeout */
winapi::FALSE /* irrelevant parameter here */);
// Notifying the corresponding task handler.
assert!(result >= winapi::WAIT_OBJECT_0);
let handle_id = (result - winapi::WAIT_OBJECT_0) as usize;
if handle_id == 0 {
// The `pending_scheduled_event` handle has been notified, which means that we
// should pick up the content of `pending_scheduled`.
let mut pending = self.inner.pending_scheduled.lock().unwrap();
scheduled.handles.append(&mut pending.handles);
scheduled.task_handles.append(&mut pending.task_handles);
} else {
scheduled.handles.remove(handle_id);
let (task_handle, ready) = scheduled.task_handles.remove(handle_id - 1);
ready.store(true, Ordering::Relaxed);
task_handle.unpark();
}
}
}
}
}
impl Drop for EventLoop {
#[inline]
fn drop(&mut self) {
unsafe {
kernel32::CloseHandle(self.inner.pending_scheduled_event);
}
}
}
pub struct Voice {
inner: Arc<Mutex<VoiceInner>>,
playing: bool,
}
pub struct SamplesStream {
event_loop: Arc<EventLoopInner>,
inner: Arc<Mutex<VoiceInner>>,
// The event that is signalled whenever a buffer is ready to be submitted to the voice.
event: winapi::HANDLE, // TODO: not deleted
max_frames_in_buffer: winapi::UINT32,
bytes_per_frame: winapi::WORD,
ready: Arc<AtomicBool>,
}
unsafe impl Send for SamplesStream {
}
unsafe impl Sync for SamplesStream {
}
struct VoiceInner {
audio_client: *mut winapi::IAudioClient,
render_client: *mut winapi::IAudioRenderClient,
}
unsafe impl Send for Voice {
}
unsafe impl Sync for Voice {
}
impl Voice {
pub fn new(end_point: &Endpoint, format: &Format, event_loop: &EventLoop)
-> Result<(Voice, SamplesStream), CreationError> {
pub fn build_voice(&self, end_point: &Endpoint, format: &Format)
-> Result<VoiceId, CreationError> {
unsafe {
// Making sure that COM is initialized.
// It's not actually sure that this is required, but when in doubt do it.
@ -305,169 +227,218 @@ impl Voice {
&mut *render_client
};
// Everything went fine.
let inner = Arc::new(Mutex::new(VoiceInner {
audio_client: audio_client,
render_client: render_client,
}));
let new_voice_id = VoiceId(self.next_voice_id.fetch_add(1, Ordering::Relaxed));
assert_ne!(new_voice_id.0, usize::max_value()); // check for overflows
let voice = Voice {
inner: inner.clone(),
playing: false,
// Once we built the `VoiceInner`, we add a command that will be picked up by the
// `run()` method and added to the `RunContext`.
{
let inner = VoiceInner {
id: new_voice_id.clone(),
audio_client: audio_client,
render_client: render_client,
event: event,
playing: false,
max_frames_in_buffer: max_frames_in_buffer,
bytes_per_frame: format.nBlockAlign,
};
self.commands.lock().unwrap().push(Command::NewVoice(inner));
let result = kernel32::SetEvent(self.pending_scheduled_event);
assert!(result != 0);
};
let samples_stream = SamplesStream {
event_loop: event_loop.inner.clone(),
inner: inner,
event: event,
max_frames_in_buffer: max_frames_in_buffer,
bytes_per_frame: format.nBlockAlign,
ready: Arc::new(AtomicBool::new(false)),
};
Ok((voice, samples_stream))
Ok(new_voice_id)
}
}
#[inline]
pub fn play(&mut self) {
if !self.playing {
let mut inner = self.inner.lock().unwrap();
unsafe {
let hresult = (*inner.audio_client).Start();
check_result(hresult).unwrap();
}
}
self.playing = true;
}
#[inline]
pub fn pause(&mut self) {
if self.playing {
let mut inner = self.inner.lock().unwrap();
unsafe {
let hresult = (*inner.audio_client).Stop();
check_result(hresult).unwrap();
}
}
self.playing = false;
}
}
impl SamplesStream {
#[inline]
fn schedule(&mut self) {
let mut pending = self.event_loop.pending_scheduled.lock().unwrap();
pending.handles.push(self.event);
pending
.task_handles
.push((task::park(), self.ready.clone()));
drop(pending);
let result = unsafe { kernel32::SetEvent(self.event_loop.pending_scheduled_event) };
assert!(result != 0);
}
}
impl Stream for SamplesStream {
type Item = UnknownTypeBuffer;
type Error = ();
fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> {
pub fn destroy_voice(&self, voice_id: VoiceId) {
unsafe {
if self.ready.swap(false, Ordering::Relaxed) == false {
// Despite its name this function does not block, because we pass `0`.
let result = kernel32::WaitForSingleObject(self.event, 0);
self.commands.lock().unwrap().push(Command::DestroyVoice(voice_id));
let result = kernel32::SetEvent(self.pending_scheduled_event);
assert!(result != 0);
}
}
// Park the task and returning if the event is not ready.
match result {
winapi::WAIT_OBJECT_0 => (),
winapi::WAIT_TIMEOUT => {
self.schedule();
return Ok(Async::NotReady);
},
_ => unreachable!(),
};
}
#[inline]
pub fn run<F>(&self, mut callback: F) -> !
where F: FnMut(VoiceId, UnknownTypeBuffer)
{
self.run_inner(&mut callback);
}
// If we reach here, that means we're ready to accept new samples.
fn run_inner(&self, callback: &mut FnMut(VoiceId, UnknownTypeBuffer)) -> ! {
unsafe {
// We keep `run_context` locked forever, which guarantees that two invocations of
// `run()` cannot run simultaneously.
let mut run_context = self.run_context.lock().unwrap();
let poll = {
let mut inner = self.inner.lock().unwrap();
loop {
// Process the pending commands.
let mut commands_lock = self.commands.lock().unwrap();
for command in commands_lock.drain(..) {
match command {
Command::NewVoice(voice_inner) => {
let event = voice_inner.event;
run_context.voices.push(voice_inner);
run_context.handles.push(event);
},
Command::DestroyVoice(voice_id) => {
match run_context.voices.iter().position(|v| v.id == voice_id) {
None => continue,
Some(p) => {
run_context.handles.remove(p + 1);
run_context.voices.remove(p);
},
}
},
Command::Play(voice_id) => {
if let Some(v) = run_context.voices.get_mut(voice_id.0) {
if !v.playing {
let hresult = (*v.audio_client).Start();
check_result(hresult).unwrap();
v.playing = true;
}
}
},
Command::Pause(voice_id) => {
if let Some(v) = run_context.voices.get_mut(voice_id.0) {
if v.playing {
let hresult = (*v.audio_client).Stop();
check_result(hresult).unwrap();
v.playing = true;
}
}
},
}
}
drop(commands_lock);
// Obtaining the number of frames that are available to be written.
let frames_available = {
let mut padding = mem::uninitialized();
let hresult = (*inner.audio_client).GetCurrentPadding(&mut padding);
check_result(hresult).unwrap();
self.max_frames_in_buffer - padding
};
// Wait for any of the handles to be signalled, which means that the corresponding
// sound needs a buffer.
debug_assert!(run_context.handles.len() <= winapi::MAXIMUM_WAIT_OBJECTS as usize);
let result = kernel32::WaitForMultipleObjectsEx(run_context.handles.len() as u32,
run_context.handles.as_ptr(),
winapi::FALSE,
winapi::INFINITE, /* TODO: allow setting a timeout */
winapi::FALSE /* irrelevant parameter here */);
if frames_available == 0 {
Ok(Async::NotReady)
} else {
// Notifying the corresponding task handler.
debug_assert!(result >= winapi::WAIT_OBJECT_0);
let handle_id = (result - winapi::WAIT_OBJECT_0) as usize;
// If `handle_id` is 0, then it's `pending_scheduled_event` that was signalled in
// order for us to pick up the pending commands.
// Otherwise, a voice needs data.
if handle_id >= 1 {
let voice = &mut run_context.voices[handle_id - 1];
let voice_id = voice.id.clone();
// Obtaining the number of frames that are available to be written.
let frames_available = {
let mut padding = mem::uninitialized();
let hresult = (*voice.audio_client).GetCurrentPadding(&mut padding);
check_result(hresult).unwrap();
voice.max_frames_in_buffer - padding
};
if frames_available == 0 {
// TODO: can this happen?
continue;
}
// Obtaining a pointer to the buffer.
let (buffer_data, buffer_len) = {
let mut buffer: *mut winapi::BYTE = mem::uninitialized();
let hresult = (*inner.render_client)
let hresult = (*voice.render_client)
.GetBuffer(frames_available, &mut buffer as *mut *mut _);
check_result(hresult).unwrap(); // FIXME: can return `AUDCLNT_E_DEVICE_INVALIDATED`
debug_assert!(!buffer.is_null());
(buffer as *mut _,
frames_available as usize * self.bytes_per_frame as usize /
mem::size_of::<f32>()) // FIXME: correct size
frames_available as usize * voice.bytes_per_frame as usize /
mem::size_of::<f32>()) // FIXME: correct size when not f32
};
let buffer = Buffer {
voice: self.inner.clone(),
voice: voice,
buffer_data: buffer_data,
buffer_len: buffer_len,
frames: frames_available,
marker: PhantomData,
};
Ok(Async::Ready(Some(UnknownTypeBuffer::F32(::Buffer {
target: Some(buffer),
})))) // FIXME: not necessarily F32
let buffer = UnknownTypeBuffer::F32(::Buffer { target: Some(buffer) }); // FIXME: not always f32
callback(voice_id, buffer);
}
};
if let Ok(Async::NotReady) = poll {
self.schedule();
}
}
}
poll
#[inline]
pub fn play(&self, voice: VoiceId) {
unsafe {
self.commands.lock().unwrap().push(Command::Play(voice));
let result = kernel32::SetEvent(self.pending_scheduled_event);
assert!(result != 0);
}
}
#[inline]
pub fn pause(&self, voice: VoiceId) {
unsafe {
self.commands.lock().unwrap().push(Command::Pause(voice));
let result = kernel32::SetEvent(self.pending_scheduled_event);
assert!(result != 0);
}
}
}
impl Drop for EventLoop {
#[inline]
fn drop(&mut self) {
unsafe {
kernel32::CloseHandle(self.pending_scheduled_event);
}
}
}
unsafe impl Send for EventLoop {
}
unsafe impl Sync for EventLoop {
}
// The content of a voice ID is a number that was fetched from `next_voice_id`.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct VoiceId(usize);
impl Drop for VoiceInner {
#[inline]
fn drop(&mut self) {
unsafe {
(*self.render_client).Release();
(*self.audio_client).Release();
kernel32::CloseHandle(self.event);
}
}
}
pub struct Buffer<T> {
voice: Arc<Mutex<VoiceInner>>,
pub struct Buffer<'a, T: 'a> {
voice: &'a mut VoiceInner,
buffer_data: *mut T,
buffer_len: usize,
frames: winapi::UINT32,
marker: PhantomData<&'a mut [T]>,
}
unsafe impl<T> Send for Buffer<T> {
unsafe impl<'a, T> Send for Buffer<'a, T> {
}
impl<T> Buffer<T> {
impl<'a, T> Buffer<'a, T> {
#[inline]
pub fn buffer(&mut self) -> &mut [T] {
unsafe { slice::from_raw_parts_mut(self.buffer_data, self.buffer_len) }
@ -481,10 +452,9 @@ impl<T> Buffer<T> {
#[inline]
pub fn finish(self) {
unsafe {
let mut inner = self.voice.lock().unwrap();
let hresult = (*inner.render_client).ReleaseBuffer(self.frames as u32, 0);
let hresult = (*self.voice.render_client).ReleaseBuffer(self.frames as u32, 0);
match check_result(hresult) {
// ignoring the error that is produced if the device has been disconnected
// Ignoring the error that is produced if the device has been disconnected.
Err(ref e) if e.raw_os_error() == Some(winapi::AUDCLNT_E_DEVICE_INVALIDATED) => (),
e => e.unwrap(),
};
@ -492,6 +462,7 @@ impl<T> Buffer<T> {
}
}
// Turns a `Format` into a `WAVEFORMATEXTENSIBLE`.
fn format_to_waveformatextensible(format: &Format)
-> Result<winapi::WAVEFORMATEXTENSIBLE, CreationError> {
Ok(winapi::WAVEFORMATEXTENSIBLE {
@ -505,10 +476,10 @@ fn format_to_waveformatextensible(format: &Format)
nSamplesPerSec: format.samples_rate.0 as winapi::DWORD,
nAvgBytesPerSec: format.channels.len() as winapi::DWORD *
format.samples_rate.0 as winapi::DWORD *
format.data_type.get_sample_size() as winapi::DWORD,
format.data_type.sample_size() as winapi::DWORD,
nBlockAlign: format.channels.len() as winapi::WORD *
format.data_type.get_sample_size() as winapi::WORD,
wBitsPerSample: 8 * format.data_type.get_sample_size() as winapi::WORD,
format.data_type.sample_size() as winapi::WORD,
wBitsPerSample: 8 * format.data_type.sample_size() as winapi::WORD,
cbSize: match format.data_type {
SampleFormat::I16 => 0,
SampleFormat::F32 => (mem::size_of::<winapi::WAVEFORMATEXTENSIBLE>() -
@ -517,7 +488,7 @@ fn format_to_waveformatextensible(format: &Format)
SampleFormat::U16 => return Err(CreationError::FormatNotSupported),
},
},
Samples: 8 * format.data_type.get_sample_size() as winapi::WORD,
Samples: 8 * format.data_type.sample_size() as winapi::WORD,
dwChannelMask: {
let mut mask = 0;
for &channel in format.channels.iter() {