Update ASIO implementation for new error handling and Host API

This is currently untested and will almost certainly not build. I'm
about to move into a Windows VM to get everything running properly
again.
This commit is contained in:
mitchmindtree 2019-06-26 16:24:23 +02:00
parent 2bc9f85970
commit 09fd5562be
11 changed files with 185 additions and 129 deletions

View file

@ -0,0 +1,51 @@
#[cfg(test)]
mod tests;
use std::marker::Copy;
/// Interleave the buffer from asio to cpal
/// asio: LLLLRRRR
/// cpal: LRLRLRLR
/// More then stereo:
/// asio: 111122223333
/// cpal: 123123123123
/// cpal buffer must have a length of exactly sum( all asio channel lengths )
/// this check is ommited for performance
pub fn interleave<T>(channels: &[Vec<T>], target: &mut Vec<T>)
where
T: Copy,
{
assert!(
target.len() % channels.len() == 0,
"the length of the interleaved buffer must be a multiple of the expected number of channels"
);
assert!(!channels.is_empty());
target.clear();
let frames = channels[0].len();
target.extend((0 .. frames).flat_map(|f| channels.iter().map(move |ch| ch[f])));
}
/// Function for deinterleaving because
/// cpal writes to buffer interleaved
/// cpal: LRLRLRLR
/// asio: LLLLRRRR
/// More then stereo:
/// cpal: 123123123123
/// asio: 111122223333
pub fn deinterleave<T>(cpal_buffer: &[T], asio_channels: &mut [Vec<T>])
where
T: Copy,
{
assert!(
cpal_buffer.len() % asio_channels.len() == 0,
"the length of the interleaved buffer must be a multiple of the expected number of channels"
);
for ch in asio_channels.iter_mut() {
ch.clear();
}
let num_channels = asio_channels.len();
let mut ch = (0 .. num_channels).cycle();
for &sample in cpal_buffer.iter() {
asio_channels[ch.next().unwrap()].push(sample);
}
}

View file

@ -0,0 +1,89 @@
use super::{deinterleave, interleave};
#[test]
fn interleave_two() {
let a = vec![vec![1, 1, 1, 1], vec![2, 2, 2, 2]];
let goal = vec![1, 2, 1, 2, 1, 2, 1, 2];
let mut result = vec![0; 8];
interleave(&a[..], &mut result);
assert_eq!(goal, result);
}
#[test]
fn interleave_three() {
let a = vec![vec![1, 1, 1, 1], vec![2, 2, 2, 2], vec![3, 3, 3, 3]];
let goal = vec![1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3];
let mut result = vec![0; 12];
interleave(&a[..], &mut result);
assert_eq!(goal, result);
}
#[test]
fn interleave_none() {
let a = vec![Vec::<i32>::new()];
let goal = Vec::<i32>::new();
let mut result = Vec::<i32>::new();
interleave(&a[..], &mut result);
assert_eq!(goal, result);
}
#[test]
fn interleave_two_diff() {
let a = vec![vec![1, 2, 3, 4], vec![5, 6, 7, 8]];
let goal = vec![1, 5, 2, 6, 3, 7, 4, 8];
let mut result = vec![0; 8];
interleave(&a[..], &mut result);
assert_eq!(goal, result);
}
#[test]
fn deinterleave_two() {
let goal = vec![vec![1, 1, 1, 1], vec![2, 2, 2, 2]];
let a = vec![1, 2, 1, 2, 1, 2, 1, 2];
let mut result = vec![vec![0; 4]; 2];
deinterleave(&a[..], &mut result[..]);
assert_eq!(goal, result);
}
#[test]
fn deinterleave_three() {
let goal = vec![vec![1, 1, 1, 1], vec![2, 2, 2, 2], vec![3, 3, 3, 3]];
let a = vec![1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3];
let mut result = vec![vec![0; 4]; 3];
deinterleave(&a[..], &mut result[..]);
assert_eq!(goal, result);
}
#[test]
fn deinterleave_none() {
let goal = vec![Vec::<i32>::new()];
let a = Vec::<i32>::new();
let mut result = vec![Vec::<i32>::new()];
deinterleave(&a[..], &mut result[..]);
assert_eq!(goal, result);
}
#[test]
fn deinterleave_two_diff() {
let goal = vec![vec![1, 2, 3, 4], vec![5, 6, 7, 8]];
let a = vec![1, 5, 2, 6, 3, 7, 4, 8];
let mut result = vec![vec![0; 4]; 2];
deinterleave(&a[..], &mut result[..]);
assert_eq!(goal, result);
}

205
src/host/asio/device.rs Normal file
View file

@ -0,0 +1,205 @@
use std;
pub type SupportedInputFormats = std::vec::IntoIter<SupportedFormat>;
pub type SupportedOutputFormats = std::vec::IntoIter<SupportedFormat>;
use std::hash::{Hash, Hasher};
use DefaultFormatError;
use DeviceNameError;
use Format;
use SampleFormat;
use SampleRate;
use SupportedFormat;
use SupportedFormatsError;
use super::sys;
/// A ASIO Device
#[derive(Debug, Clone)]
pub struct Device {
/// The drivers for this device
pub drivers: sys::Drivers,
/// The name of this device
pub name: String,
}
/// All available devices
pub struct Devices {
drivers: std::vec::IntoIter<String>,
}
impl PartialEq for Device {
fn eq(&self, other: &Self) -> bool {
self.name == other.name
}
}
impl Eq for Device {}
impl Hash for Device {
fn hash<H: Hasher>(&self, state: &mut H) {
self.name.hash(state);
}
}
impl Device {
pub fn name(&self) -> Result<String, DeviceNameError> {
Ok(self.name.clone())
}
/// Gets the supported input formats.
/// TODO currently only supports the default.
/// Need to find all possible formats.
pub fn supported_input_formats(
&self,
) -> Result<SupportedInputFormats, SupportedFormatsError> {
// Retrieve the default format for the total supported channels and supported sample
// format.
let mut f = match self.default_input_format() {
Err(_) => return Err(SupportedFormatsError::DeviceNotAvailable),
Ok(f) => f,
};
// Collect a format for every combination of supported sample rate and number of channels.
let mut supported_formats = vec![];
for &rate in ::COMMON_SAMPLE_RATES {
if !self.drivers.can_sample_rate(rate.0 as u32) {
continue;
}
for channels in 1..f.channels + 1 {
f.channels = channels;
f.sample_rate = rate;
supported_formats.push(SupportedFormat::from(f.clone()));
}
}
Ok(supported_formats.into_iter())
}
/// Gets the supported output formats.
/// TODO currently only supports the default.
/// Need to find all possible formats.
pub fn supported_output_formats(
&self,
) -> Result<SupportedOutputFormats, SupportedFormatsError> {
// Retrieve the default format for the total supported channels and supported sample
// format.
let mut f = match self.default_output_format() {
Err(_) => return Err(SupportedFormatsError::DeviceNotAvailable),
Ok(f) => f,
};
// Collect a format for every combination of supported sample rate and number of channels.
let mut supported_formats = vec![];
for &rate in ::COMMON_SAMPLE_RATES {
if !self.drivers.can_sample_rate(rate.0 as u32) {
continue;
}
for channels in 1..f.channels + 1 {
f.channels = channels;
f.sample_rate = rate;
supported_formats.push(SupportedFormat::from(f.clone()));
}
}
Ok(supported_formats.into_iter())
}
/// Returns the default input format
pub fn default_input_format(&self) -> Result<Format, DefaultFormatError> {
let channels = self.drivers.get_channels().ins as u16;
let sample_rate = SampleRate(self.drivers.get_sample_rate().rate);
// Map th ASIO sample type to a CPAL sample type
match self.drivers.get_data_type() {
Ok(sys::AsioSampleType::ASIOSTInt16MSB) => Ok(SampleFormat::I16),
Ok(sys::AsioSampleType::ASIOSTInt32MSB) => Ok(SampleFormat::I16),
Ok(sys::AsioSampleType::ASIOSTFloat32MSB) => Ok(SampleFormat::F32),
Ok(sys::AsioSampleType::ASIOSTInt16LSB) => Ok(SampleFormat::I16),
Ok(sys::AsioSampleType::ASIOSTInt32LSB) => Ok(SampleFormat::I16),
Ok(sys::AsioSampleType::ASIOSTFloat32LSB) => Ok(SampleFormat::F32),
_ => Err(DefaultFormatError::StreamTypeNotSupported),
}.map(|dt| Format {
channels,
sample_rate,
data_type: dt,
})
}
/// Returns the default output format
pub fn default_output_format(&self) -> Result<Format, DefaultFormatError> {
let channels = self.drivers.get_channels().outs as u16;
let sample_rate = SampleRate(self.drivers.get_sample_rate().rate);
match self.drivers.get_data_type() {
// Map th ASIO sample type to a CPAL sample type
Ok(sys::AsioSampleType::ASIOSTInt16MSB) => Ok(SampleFormat::I16),
Ok(sys::AsioSampleType::ASIOSTFloat32MSB) => Ok(SampleFormat::F32),
Ok(sys::AsioSampleType::ASIOSTInt16LSB) => Ok(SampleFormat::I16),
Ok(sys::AsioSampleType::ASIOSTInt32LSB) => Ok(SampleFormat::I16),
Ok(sys::AsioSampleType::ASIOSTFloat32LSB) => Ok(SampleFormat::F32),
_ => Err(DefaultFormatError::StreamTypeNotSupported),
}.map(|dt| Format {
channels,
sample_rate,
data_type: dt,
})
}
}
impl Devices {
pub fn new() -> Result<Self, DevicesError> {
let driver_names = online_devices();
Ok(Devices {
drivers: driver_names.into_iter(),
})
}
}
impl Iterator for Devices {
type Item = Device;
/// Load drivers and return device
fn next(&mut self) -> Option<Device> {
match self.drivers.next() {
Some(name) => sys::Drivers::load(&name)
.or_else(|e| {
eprintln!("{}", e);
Err(e)
}).ok()
.map(|drivers| Device { drivers, name }),
None => None,
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
unimplemented!()
}
}
/// Asio doesn't have a concept of default
/// so returning first in list as default
pub fn default_input_device() -> Option<Device> {
first_device()
}
/// Asio doesn't have a concept of default
/// so returning first in list as default
pub fn default_output_device() -> Option<Device> {
first_device()
}
fn first_device() -> Option<Device> {
let mut driver_list = online_devices();
match driver_list.pop() {
Some(name) => sys::Drivers::load(&name)
.or_else(|e| {
eprintln!("{}", e);
Err(e)
}).ok()
.map(|drivers| Device { drivers, name }),
None => None,
}
}
/// Remove offline drivers
fn online_devices() -> Vec<String> {
sys::get_driver_list()
.into_iter()
.filter(|name| sys::Drivers::load(&name).is_ok())
.collect()
}

127
src/host/asio/mod.rs Normal file
View file

@ -0,0 +1,127 @@
extern crate asio_sys as sys;
use {
BuildStreamError,
DefaultFormatError,
Device as DeviceTrait,
DeviceNameError,
DevicesError,
EventLoop as EventLoopTrait,
Host as HostTrait,
PauseStreamError,
PlayStreamError,
StreamDataResult,
StreamId as StreamIdTrait,
SupportedFormatsError,
}
pub use self::device::{Device, Devices, SupportedInputFormats, SupportedOutputFormats, default_input_device, default_output_device};
pub use self::stream::{EventLoop, StreamId};
mod device;
mod stream;
mod asio_utils;
/// The host for ASIO.
#[derive(Debug)]
pub struct Host;
impl Host {
pub fn new() -> Result<Self, crate::HostUnavailable> {
unimplemented!("asio as an initialisation and termination process that needs to be impld");
//Ok(Host)
}
}
impl HostTrait for Host {
type Devices = Devices;
type Device = Device;
type EventLoop = EventLoop;
fn is_available() -> bool {
unimplemented!("check how to do this using asio-sys")
}
fn devices(&self) -> Result<Self::Devices, DevicesError> {
Devices::new()
}
fn default_input_device(&self) -> Option<Self::Device> {
default_input_device()
}
fn default_output_device(&self) -> Option<Self::Device> {
default_output_device()
}
fn event_loop(&self) -> Self::EventLoop {
EventLoop::new()
}
}
impl DeviceTrait for Device {
type SupportedInputFormats = SupportedInputFormats;
type SupportedOutputFormats = SupportedOutputFormats;
fn name(&self) -> Result<String, DeviceNameError> {
Device::name(self)
}
fn supported_input_formats(&self) -> Result<Self::SupportedInputFormats, SupportedFormatsError> {
Device::supported_input_formats(self)
}
fn supported_output_formats(&self) -> Result<Self::SupportedOutputFormats, SupportedFormatsError> {
Device::supported_output_formats(self)
}
fn default_input_format(&self) -> Result<Format, DefaultFormatError> {
Device::default_input_format(self)
}
fn default_output_format(&self) -> Result<Format, DefaultFormatError> {
Device::default_output_format(self)
}
}
impl EventLoopTrait for EventLoop {
type Device = Device;
type StreamId = StreamId;
fn build_input_stream(
&self,
device: &Self::Device,
format: &Format,
) -> Result<Self::StreamId, BuildStreamError> {
EventLoop::build_input_stream(self, device, format)
}
fn build_output_stream(
&self,
device: &Self::Device,
format: &Format,
) -> Result<Self::StreamId, BuildStreamError> {
EventLoop::build_output_stream(self, device, format)
}
fn play_stream(&self, stream: Self::StreamId) -> Result<(), PlayStreamError> {
EventLoop::play_stream(self, stream)
}
fn pause_stream(&self, stream: Self::StreamId) -> Result<(), PauseStreamError> {
EventLoop::pause_stream(self, stream)
}
fn destroy_stream(&self, stream: Self::StreamId) {
EventLoop::destroy_stream(self, stream)
}
fn run<F>(&self, callback: F) -> !
where
F: FnMut(Self::StreamId, StreamDataResult) + Send,
{
EventLoop::run(self, callback)
}
}
impl StreamIdTrait for StreamId {}

965
src/host/asio/stream.rs Normal file
View file

@ -0,0 +1,965 @@
extern crate asio_sys as sys;
extern crate num_traits;
use self::num_traits::PrimInt;
use super::asio_utils as au;
use super::Device;
use std;
use std::mem;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::Duration;
use BuildStreamError;
use Format;
use PauseStreamError;
use PlayStreamError;
use SampleFormat;
use StreamData;
use StreamDataResult;
use UnknownTypeInputBuffer;
use UnknownTypeOutputBuffer;
/// Controls all streams
pub struct EventLoop {
/// The input and output ASIO streams
asio_streams: Arc<Mutex<sys::AsioStreams>>,
/// List of all CPAL streams
cpal_streams: Arc<Mutex<Vec<Option<Stream>>>>,
/// Total stream count
stream_count: AtomicUsize,
/// The CPAL callback that the user gives to fill the buffers.
callbacks: Arc<Mutex<Option<&'static mut (FnMut(StreamId, StreamDataResult) + Send)>>>,
}
/// Id for each stream.
/// Created depending on the number they are created.
/// Starting at one! not zero.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct StreamId(usize);
/// CPAL stream.
/// This decouples the many cpal streams
/// from the single input and single output
/// ASIO streams.
/// Each stream can be playing or paused.
struct Stream {
playing: bool,
}
#[derive(Default)]
struct I16Buffer {
cpal: Vec<i16>,
channel: Vec<Vec<i16>>,
}
#[derive(Default)]
struct F32Buffer {
cpal: Vec<f32>,
channel: Vec<Vec<f32>>,
}
struct Buffers {
i16_buff: I16Buffer,
//u16_buff: U16Buffer,
f32_buff: F32Buffer,
}
enum Endian {
Little,
Big,
}
impl EventLoop {
pub fn new() -> EventLoop {
EventLoop {
asio_streams: Arc::new(Mutex::new(sys::AsioStreams {
input: None,
output: None,
})),
cpal_streams: Arc::new(Mutex::new(Vec::new())),
// This is why the Id's count from one not zero
// because at this point there is no streams
stream_count: AtomicUsize::new(0),
callbacks: Arc::new(Mutex::new(None)),
}
}
fn check_format(
&self,
drivers: &sys::Drivers,
format: &Format,
num_asio_channels: u16,
) -> Result<(), BuildStreamError> {
let Format {
channels,
sample_rate,
data_type,
} = format;
// Try and set the sample rate to what the user selected.
let sample_rate = sample_rate.0;
if sample_rate != drivers.get_sample_rate().rate {
if drivers.can_sample_rate(sample_rate) {
drivers
.set_sample_rate(sample_rate)
.expect("Unsupported sample rate");
} else {
return Err(BuildStreamError::FormatNotSupported);
}
}
// unsigned formats are not supported by asio
match data_type {
SampleFormat::I16 | SampleFormat::F32 => (),
SampleFormat::U16 => return Err(BuildStreamError::FormatNotSupported),
}
if *channels > num_asio_channels {
return Err(BuildStreamError::FormatNotSupported);
}
Ok(())
}
/// Create a new CPAL Input Stream.
/// If there is no ASIO Input Stream
/// it will be created.
fn get_input_stream(
&self,
drivers: &sys::Drivers,
format: &Format,
device: &Device,
) -> Result<usize, BuildStreamError> {
match device.default_input_format() {
Ok(f) => {
let num_asio_channels = f.channels;
self.check_format(drivers, format, num_asio_channels)
},
Err(_) => Err(BuildStreamError::FormatNotSupported),
}?;
let num_channels = format.channels as usize;
let ref mut streams = *self.asio_streams.lock().unwrap();
// Either create a stream if thers none or had back the
// size of the current one.
match streams.input {
Some(ref input) => Ok(input.buffer_size as usize),
None => {
let output = streams.output.take();
drivers
.prepare_input_stream(output, num_channels)
.map(|new_streams| {
let bs = match new_streams.input {
Some(ref inp) => inp.buffer_size as usize,
None => unreachable!(),
};
*streams = new_streams;
bs
}).map_err(|ref e| {
println!("Error preparing stream: {}", e);
BuildStreamError::DeviceNotAvailable
})
}
}
}
/// Create a new CPAL Output Stream.
/// If there is no ASIO Output Stream
/// it will be created.
fn get_output_stream(
&self,
drivers: &sys::Drivers,
format: &Format,
device: &Device,
) -> Result<usize, BuildStreamError> {
match device.default_output_format() {
Ok(f) => {
let num_asio_channels = f.channels;
self.check_format(drivers, format, num_asio_channels)
},
Err(_) => Err(BuildStreamError::FormatNotSupported),
}?;
let num_channels = format.channels as usize;
let ref mut streams = *self.asio_streams.lock().unwrap();
// Either create a stream if thers none or had back the
// size of the current one.
match streams.output {
Some(ref output) => Ok(output.buffer_size as usize),
None => {
let input = streams.input.take();
drivers
.prepare_output_stream(input, num_channels)
.map(|new_streams| {
let bs = match new_streams.output {
Some(ref out) => out.buffer_size as usize,
None => unreachable!(),
};
*streams = new_streams;
bs
}).map_err(|ref e| {
println!("Error preparing stream: {}", e);
BuildStreamError::DeviceNotAvailable
})
}
}
}
/// Builds a new cpal input stream
pub fn build_input_stream(
&self,
device: &Device,
format: &Format,
) -> Result<StreamId, BuildStreamError> {
let Device { drivers, .. } = device;
let num_channels = format.channels.clone();
let stream_type = drivers.get_data_type().expect("Couldn't load data type");
let input_stream = self.get_input_stream(&drivers, format, device);
input_stream.map(|stream_buffer_size| {
let cpal_num_samples = stream_buffer_size * num_channels as usize;
let count = self.stream_count.fetch_add(1, Ordering::SeqCst);
let asio_streams = self.asio_streams.clone();
let cpal_streams = self.cpal_streams.clone();
let callbacks = self.callbacks.clone();
let channel_len = cpal_num_samples / num_channels as usize;
// Create buffers depending on data type
// TODO the naming of cpal and channel is confusing.
// change it to:
// cpal -> interleaved
// channels -> per_channel
let mut buffers = match format.data_type {
SampleFormat::I16 => Buffers {
i16_buff: I16Buffer {
cpal: vec![0 as i16; cpal_num_samples],
channel: (0..num_channels)
.map(|_| Vec::with_capacity(channel_len))
.collect(),
},
f32_buff: F32Buffer::default(),
},
SampleFormat::F32 => Buffers {
i16_buff: I16Buffer::default(),
f32_buff: F32Buffer {
cpal: vec![0 as f32; cpal_num_samples],
channel: (0..num_channels)
.map(|_| Vec::with_capacity(channel_len))
.collect(),
},
},
_ => unimplemented!(),
};
// Set the input callback.
// This is most performance critical part of the ASIO bindings.
sys::set_callback(move |index| unsafe {
// if not playing return early
{
if let Some(s) = cpal_streams.lock().unwrap().get(count) {
if let Some(s) = s {
if !s.playing {
return ();
}
}
}
}
// Get the stream
let stream_lock = asio_streams.lock().unwrap();
let ref asio_stream = match stream_lock.input {
Some(ref asio_stream) => asio_stream,
None => return (),
};
// Get the callback
let mut callbacks = callbacks.lock().unwrap();
// Theres only a single callback because theres only one event loop
let callback = match callbacks.as_mut() {
Some(callback) => callback,
None => return (),
};
// Macro to convert sample from ASIO to CPAL type
macro_rules! convert_sample {
// floats types required different conversion
(f32,
f32,
$SampleTypeIdent:ident,
$Sample:expr
) => {
*$Sample
};
(f64,
f64,
$SampleTypeIdent:ident,
$Sample:expr
) => {
*$Sample
};
(f64,
f32,
$SampleTypeIdent:ident,
$Sample:expr
) => {
*$Sample as f32
};
(f32,
f64,
$SampleTypeIdent:ident,
$Sample:expr
) => {
*$Sample as f64
};
($AsioTypeIdent:ident,
f32,
$SampleTypeIdent:ident,
$Sample:expr
) => {
(*$Sample as f64 / ::std::$AsioTypeIdent::MAX as f64) as f32
};
($AsioTypeIdent:ident,
f64,
$SampleTypeIdent:ident,
$Sample:expr
) => {
*$Sample as f64 / ::std::$AsioTypeIdent::MAX as f64
};
(f32,
$SampleType:ty,
$SampleTypeIdent:ident,
$Sample:expr
) => {
(*$Sample as f64 * ::std::$SampleTypeIdent::MAX as f64) as $SampleType
};
(f64,
$SampleType:ty,
$SampleTypeIdent:ident,
$Sample:expr
) => {
(*$Sample as f64 * ::std::$SampleTypeIdent::MAX as f64) as $SampleType
};
($AsioTypeIdent:ident,
$SampleType:ty,
$SampleTypeIdent:ident,
$Sample:expr
) => {
(*$Sample as i64 * ::std::$SampleTypeIdent::MAX as i64
/ ::std::$AsioTypeIdent::MAX as i64) as $SampleType
};
};
// This creates gets the buffer and interleaves it.
// It allows it to be done based on the sample type.
macro_rules! try_callback {
($SampleFormat:ident,
$SampleType:ty,
$SampleTypeIdent:ident,
$AsioType:ty,
$AsioTypeIdent:ident,
$Buffers:expr,
$BuffersType:ty,
$BuffersTypeIdent:ident,
$Endianness:expr,
$ConvertEndian:expr
) => {
// For each channel write the asio buffer to
// the cpal buffer
for (i, channel) in $Buffers.channel.iter_mut().enumerate() {
let buff_ptr = asio_stream.buffer_infos[i].buffers[index as usize]
as *mut $AsioType;
let asio_buffer: &'static [$AsioType] = std::slice::from_raw_parts(
buff_ptr,
asio_stream.buffer_size as usize,
);
for asio_s in asio_buffer.iter() {
channel.push($ConvertEndian(
convert_sample!(
$AsioTypeIdent,
$SampleType,
$SampleTypeIdent,
asio_s
),
$Endianness,
));
}
}
// interleave all the channels
{
let $BuffersTypeIdent {
cpal: ref mut c_buffer,
channel: ref mut channels,
} = $Buffers;
au::interleave(&channels, c_buffer);
// Clear the per channel buffers
for c in channels.iter_mut() {
c.clear();
}
}
// Call the users callback with the buffer
callback(
StreamId(count),
Ok(StreamData::Input {
buffer: UnknownTypeInputBuffer::$SampleFormat(::InputBuffer {
buffer: &$Buffers.cpal,
}),
}),
);
};
};
// Call the right buffer handler depending on types
match stream_type {
sys::AsioSampleType::ASIOSTInt32LSB => {
try_callback!(
I16,
i16,
i16,
i32,
i32,
buffers.i16_buff,
I16Buffer,
I16Buffer,
Endian::Little,
convert_endian_from
);
}
sys::AsioSampleType::ASIOSTInt16LSB => {
try_callback!(
I16,
i16,
i16,
i16,
i16,
buffers.i16_buff,
I16Buffer,
I16Buffer,
Endian::Little,
convert_endian_from
);
}
sys::AsioSampleType::ASIOSTInt32MSB => {
try_callback!(
I16,
i16,
i16,
i32,
i32,
buffers.i16_buff,
I16Buffer,
I16Buffer,
Endian::Big,
convert_endian_from
);
}
sys::AsioSampleType::ASIOSTInt16MSB => {
try_callback!(
I16,
i16,
i16,
i16,
i16,
buffers.i16_buff,
I16Buffer,
I16Buffer,
Endian::Big,
convert_endian_from
);
}
sys::AsioSampleType::ASIOSTFloat32LSB => {
try_callback!(
F32,
f32,
f32,
f32,
f32,
buffers.f32_buff,
F32Buffer,
F32Buffer,
Endian::Little,
|a, _| a
);
}
sys::AsioSampleType::ASIOSTFloat64LSB => {
try_callback!(
F32,
f32,
f32,
f64,
f64,
buffers.f32_buff,
F32Buffer,
F32Buffer,
Endian::Little,
|a, _| a
);
}
sys::AsioSampleType::ASIOSTFloat32MSB => {
try_callback!(
F32,
f32,
f32,
f32,
f32,
buffers.f32_buff,
F32Buffer,
F32Buffer,
Endian::Big,
|a, _| a
);
}
sys::AsioSampleType::ASIOSTFloat64MSB => {
try_callback!(
F32,
f32,
f32,
f64,
f64,
buffers.f32_buff,
F32Buffer,
F32Buffer,
Endian::Big,
|a, _| a
);
}
_ => println!("unsupported format {:?}", stream_type),
}
});
// Create stream and set to paused
self.cpal_streams
.lock()
.unwrap()
.push(Some(Stream { playing: false }));
StreamId(count)
})
}
/// Create the an output cpal stream.
pub fn build_output_stream(
&self,
device: &Device,
format: &Format,
) -> Result<StreamId, BuildStreamError> {
let Device { drivers, .. } = device;
let num_channels = format.channels.clone();
let stream_type = drivers.get_data_type().expect("Couldn't load data type");
let output_stream = self.get_output_stream(&drivers, format, device);
output_stream.map(|stream_buffer_size| {
let cpal_num_samples = stream_buffer_size * num_channels as usize;
let count = self.stream_count.fetch_add(1, Ordering::SeqCst);
let asio_streams = self.asio_streams.clone();
let cpal_streams = self.cpal_streams.clone();
let callbacks = self.callbacks.clone();
let channel_len = cpal_num_samples / num_channels as usize;
// Create buffers depending on data type
let mut re_buffers = match format.data_type {
SampleFormat::I16 => Buffers {
i16_buff: I16Buffer {
cpal: vec![0 as i16; cpal_num_samples],
channel: (0..num_channels)
.map(|_| Vec::with_capacity(channel_len))
.collect(),
},
f32_buff: F32Buffer::default(),
},
SampleFormat::F32 => Buffers {
i16_buff: I16Buffer::default(),
f32_buff: F32Buffer {
cpal: vec![0 as f32; cpal_num_samples],
channel: (0..num_channels)
.map(|_| Vec::with_capacity(channel_len))
.collect(),
},
},
_ => unimplemented!(),
};
sys::set_callback(move |index| unsafe {
// if not playing return early
{
if let Some(s) = cpal_streams.lock().unwrap().get(count) {
if let Some(s) = s {
if !s.playing {
return ();
}
}
}
}
// Get the stream
let stream_lock = asio_streams.lock().unwrap();
let ref asio_stream = match stream_lock.output {
Some(ref asio_stream) => asio_stream,
None => return (),
};
// Get the callback
let mut callbacks = callbacks.lock().unwrap();
// Theres only a single callback because theres only one event loop
let callback = match callbacks.as_mut() {
Some(callback) => callback,
None => return (),
};
// Convert sample depending on the sample type
macro_rules! convert_sample {
($AsioTypeIdent:ident,
f64,
f64,
$Sample:expr
) => {
*$Sample
};
($AsioTypeIdent:ident,
f32,
f32,
$Sample:expr
) => {
*$Sample
};
($AsioTypeIdent:ident,
f64,
f32,
$Sample:expr
) => {
*$Sample as f64
};
($AsioTypeIdent:ident,
f32,
f64,
$Sample:expr
) => {
*$Sample as f32
};
($AsioTypeIdent:ident,
$AsioType:ty,
f32,
$Sample:expr
) => {
(*$Sample as f64 * ::std::$AsioTypeIdent::MAX as f64) as $AsioType
};
($AsioTypeIdent:ident,
$AsioType:ty,
f64,
$Sample:expr
) => {
(*$Sample as f64 * ::std::$AsioTypeIdent::MAX as f64) as $AsioType
};
($AsioTypeIdent:ident,
f32,
$SampleTypeIdent:ident,
$Sample:expr
) => {
(*$Sample as f64 / ::std::$SampleTypeIdent::MAX as f64) as f32
};
($AsioTypeIdent:ident,
f64,
$SampleTypeIdent:ident,
$Sample:expr
) => {
*$Sample as f64 / ::std::$SampleTypeIdent::MAX as f64
};
($AsioTypeIdent:ident,
$AsioType:ty,
$SampleTypeIdent:ident,
$Sample:expr
) => {
(*$Sample as i64 * ::std::$AsioTypeIdent::MAX as i64
/ ::std::$SampleTypeIdent::MAX as i64) as $AsioType
};
};
macro_rules! try_callback {
($SampleFormat:ident,
$SampleType:ty,
$SampleTypeIdent:ident,
$AsioType:ty,
$AsioTypeIdent:ident,
$Buffers:expr,
$BuffersType:ty,
$BuffersTypeIdent:ident,
$Endianness:expr,
$ConvertEndian:expr
) => {
let mut my_buffers = $Buffers;
{
// Wrap the cpal buffer
let buff = OutputBuffer {
buffer: &mut my_buffers.cpal,
};
// call the callback to fill the buffer with
// users data
callback(
StreamId(count),
Ok(StreamData::Output {
buffer: UnknownTypeOutputBuffer::$SampleFormat(
::OutputBuffer {
buffer: &mut my_buffers.cpal,
},
),
}),
);
}
// Deinter all the channels
{
let $BuffersTypeIdent {
cpal: ref mut c_buffer,
channel: ref mut channels,
} = my_buffers;
au::deinterleave(&c_buffer[..], channels);
}
// Silence the buffer that is about to be used.
// This checks if any other callbacks have already
// silenced this buffer. If not it will silence it
// and set the opposite buffer half to unsilenced.
let silence = match index {
0 => {
if !sys::SILENCE_FIRST.load(Ordering::SeqCst) {
sys::SILENCE_FIRST.store(true, Ordering::SeqCst);
sys::SILENCE_SECOND.store(false, Ordering::SeqCst);
true
} else {
false
}
}
1 => {
if !sys::SILENCE_SECOND.load(Ordering::SeqCst) {
sys::SILENCE_SECOND.store(true, Ordering::SeqCst);
sys::SILENCE_FIRST.store(false, Ordering::SeqCst);
true
} else {
false
}
}
_ => unreachable!(),
};
// For each channel write the cpal data to
// the asio buffer
for (i, channel) in my_buffers.channel.iter().enumerate() {
let buff_ptr = asio_stream.buffer_infos[i].buffers
[index as usize] as *mut $AsioType;
let asio_buffer: &'static mut [$AsioType] =
std::slice::from_raw_parts_mut(
buff_ptr,
asio_stream.buffer_size as usize,
);
for (asio_s, cpal_s) in asio_buffer.iter_mut().zip(channel) {
if silence {
*asio_s = 0.0 as $AsioType;
}
*asio_s += $ConvertEndian(
convert_sample!(
$AsioTypeIdent,
$AsioType,
$SampleTypeIdent,
cpal_s
),
$Endianness,
);
}
}
};
}
// Choose the buffer conversions based on the sample types
match stream_type {
sys::AsioSampleType::ASIOSTInt32LSB => {
try_callback!(
I16,
i16,
i16,
i32,
i32,
&mut re_buffers.i16_buff,
I16Buffer,
I16Buffer,
Endian::Little,
convert_endian_to
);
}
sys::AsioSampleType::ASIOSTInt16LSB => {
try_callback!(
I16,
i16,
i16,
i16,
i16,
&mut re_buffers.i16_buff,
I16Buffer,
I16Buffer,
Endian::Little,
convert_endian_to
);
}
sys::AsioSampleType::ASIOSTInt32MSB => {
try_callback!(
I16,
i16,
i16,
i32,
i32,
&mut re_buffers.i16_buff,
I16Buffer,
I16Buffer,
Endian::Big,
convert_endian_to
);
}
sys::AsioSampleType::ASIOSTInt16MSB => {
try_callback!(
I16,
i16,
i16,
i16,
i16,
&mut re_buffers.i16_buff,
I16Buffer,
I16Buffer,
Endian::Big,
convert_endian_to
);
}
sys::AsioSampleType::ASIOSTFloat32LSB => {
try_callback!(
F32,
f32,
f32,
f32,
f32,
&mut re_buffers.f32_buff,
F32Buffer,
F32Buffer,
Endian::Little,
|a, _| a
);
}
sys::AsioSampleType::ASIOSTFloat64LSB => {
try_callback!(
F32,
f32,
f32,
f64,
f64,
&mut re_buffers.f32_buff,
F32Buffer,
F32Buffer,
Endian::Little,
|a, _| a
);
}
sys::AsioSampleType::ASIOSTFloat32MSB => {
try_callback!(
F32,
f32,
f32,
f32,
f32,
&mut re_buffers.f32_buff,
F32Buffer,
F32Buffer,
Endian::Big,
|a, _| a
);
}
sys::AsioSampleType::ASIOSTFloat64MSB => {
try_callback!(
F32,
f32,
f32,
f64,
f64,
&mut re_buffers.f32_buff,
F32Buffer,
F32Buffer,
Endian::Big,
|a, _| a
);
}
_ => println!("unsupported format {:?}", stream_type),
}
});
// Create the stream paused
self.cpal_streams
.lock()
.unwrap()
.push(Some(Stream { playing: false }));
// Give the ID based on the stream count
StreamId(count)
})
}
/// Play the cpal stream for the given ID.
/// Also play The ASIO streams if they are not already.
pub fn play_stream(&self, stream_id: StreamId) -> Result<(), PlayStreamError> {
let mut streams = self.cpal_streams.lock().unwrap();
if let Some(s) = streams.get_mut(stream_id.0).expect("Bad play stream index") {
s.playing = true;
}
// Calling play when already playing is a no-op
sys::play();
}
/// Pause the cpal stream for the given ID.
/// Pause the ASIO streams if there are no CPAL streams palying.
pub fn pause_stream(&self, stream_id: StreamId) -> Result<(), PauseStreamError> {
let mut streams = self.cpal_streams.lock().unwrap();
if let Some(s) = streams
.get_mut(stream_id.0)
.expect("Bad pause stream index")
{
s.playing = false;
}
let any_playing = streams
.iter()
.any(|s| if let Some(s) = s { s.playing } else { false });
if any_playing {
sys::stop();
}
}
/// Destroy the cpal stream based on the ID.
pub fn destroy_stream(&self, stream_id: StreamId) {
let mut streams = self.cpal_streams.lock().unwrap();
streams.get_mut(stream_id.0).take();
}
/// Run the cpal callbacks
pub fn run<F>(&self, mut callback: F) -> !
where
F: FnMut(StreamId, StreamDataResult) + Send,
{
let callback: &mut (FnMut(StreamId, StreamDataResult) + Send) = &mut callback;
// Transmute needed to convince the compiler that the callback has a static lifetime
*self.callbacks.lock().unwrap() = Some(unsafe { mem::transmute(callback) });
loop {
// A sleep here to prevent the loop being
// removed in --release
thread::sleep(Duration::new(1u64, 0u32));
}
}
}
/// Clean up if event loop is dropped.
/// Currently event loop is never dropped.
impl Drop for EventLoop {
fn drop(&mut self) {
*self.asio_streams.lock().unwrap() = sys::AsioStreams {
output: None,
input: None,
};
sys::clean_up();
}
}
/// Helper function to convert to system endianness
fn convert_endian_to<T: PrimInt>(sample: T, endian: Endian) -> T {
match endian {
Endian::Big => sample.to_be(),
Endian::Little => sample.to_le(),
}
}
/// Helper function to convert from system endianness
fn convert_endian_from<T: PrimInt>(sample: T, endian: Endian) -> T {
match endian {
Endian::Big => T::from_be(sample),
Endian::Little => T::from_le(sample),
}
}

View file

@ -1,5 +1,7 @@
#[cfg(any(target_os = "linux", target_os = "freebsd"))]
pub(crate) mod alsa;
#[cfg(windows)]
pub(crate) mod asio;
#[cfg(any(target_os = "macos", target_os = "ios"))]
pub(crate) mod coreaudio;
#[cfg(target_os = "emscripten")]