change of branch

This commit is contained in:
Tom Gowan 2018-04-22 22:07:47 +10:00 • committed by mitchmindtree
parent e0a0dc9ec7
commit 49968f4b82
24 changed files with 1371 additions and 0 deletions

View file

@ -0,0 +1,206 @@
extern crate asio_sys as sys;
use std;
pub type SupportedInputFormats = std::vec::IntoIter<SupportedFormat>;
pub type SupportedOutputFormats = std::vec::IntoIter<SupportedFormat>;
use Format;
use FormatsEnumerationError;
use DefaultFormatError;
use SupportedFormat;
use SampleFormat;
use SampleRate;
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Device{
// Calls to get a driver in memory
// require a name so I will store the
// name here as a handle to the driver
pub driver_name: String,
}
pub struct Devices{
drivers: std::vec::IntoIter<String>,
}
impl Device {
pub fn name(&self) -> String {
self.driver_name.clone()
}
// Just supporting default for now
pub fn supported_input_formats(&self) -> Result<SupportedInputFormats,
FormatsEnumerationError> {
match self.default_input_format() {
Ok(f) => Ok(vec![SupportedFormat::from(f)].into_iter()),
Err(e) => Err(FormatsEnumerationError::DeviceNotAvailable),
}
}
pub fn supported_output_formats(&self) -> Result<SupportedOutputFormats,
FormatsEnumerationError> {
match self.default_output_format() {
Ok(f) => Ok(vec![SupportedFormat::from(f)].into_iter()),
Err(e) => Err(FormatsEnumerationError::DeviceNotAvailable),
}
}
// TODO Pass errors along
pub fn default_input_format(&self) -> Result<Format, DefaultFormatError> {
let format = Format{channels: 0, sample_rate: SampleRate(0),
// TODO Not sure about how to set the data type
data_type: SampleFormat::F32};
let format = match sys::get_channels(&self.driver_name) {
Ok(channels) => {
Format{channels: channels.ins as u16,
sample_rate: format.sample_rate,
data_type: format.data_type}
},
Err(e) => {
println!("Error retrieving channels: {}", e);
format
},
};
let format = match sys::get_sample_rate(&self.driver_name) {
Ok(sample_rate) => {
Format{channels: format.channels,
sample_rate: SampleRate(sample_rate.rate),
data_type: format.data_type}
},
Err(e) => {
println!("Error retrieving sample rate: {}", e);
format
},
};
let format = match sys::get_data_type(&self.driver_name) {
Ok(data_type) => {
println!("Audio Type: {:?}", data_type);
let data_type = match data_type{
sys::AsioSampleType::ASIOSTInt16MSB => SampleFormat::I16,
sys::AsioSampleType::ASIOSTFloat32MSB => SampleFormat::F32,
sys::AsioSampleType::ASIOSTInt16LSB => SampleFormat::I16,
// TODO This should not be set to 16bit but is for testing
sys::AsioSampleType::ASIOSTInt32LSB => SampleFormat::I16,
sys::AsioSampleType::ASIOSTFloat32LSB => SampleFormat::F32,
_ => panic!("Unsupported Audio Type: {:?}", data_type),
};
Format{channels: format.channels,
sample_rate: format.sample_rate,
data_type: data_type}
},
Err(e) => {
println!("Error retrieving sample rate: {}", e);
format
},
};
Ok(format)
}
pub fn default_output_format(&self) -> Result<Format, DefaultFormatError> {
let format = Format{channels: 0, sample_rate: SampleRate(0),
// TODO Not sure about how to set the data type
data_type: SampleFormat::F32};
let format = match sys::get_channels(&self.driver_name) {
Ok(channels) => {
Format{channels: channels.outs as u16,
sample_rate: format.sample_rate,
data_type: format.data_type}
},
Err(e) => {
println!("Error retrieving channels: {}", e);
format
},
};
let format = match sys::get_sample_rate(&self.driver_name) {
Ok(sample_rate) => {
Format{channels: format.channels,
sample_rate: SampleRate(sample_rate.rate),
data_type: format.data_type}
},
Err(e) => {
println!("Error retrieving sample rate: {}", e);
format
},
};
let format = match sys::get_data_type(&self.driver_name) {
Ok(data_type) => {
let data_type = match data_type{
sys::AsioSampleType::ASIOSTInt16MSB => SampleFormat::I16,
sys::AsioSampleType::ASIOSTFloat32MSB => SampleFormat::F32,
sys::AsioSampleType::ASIOSTInt16LSB => SampleFormat::I16,
// TODO This should not be set to 16bit but is for testing
sys::AsioSampleType::ASIOSTInt32LSB => SampleFormat::I16,
sys::AsioSampleType::ASIOSTFloat32LSB => SampleFormat::F32,
_ => panic!("Unsupported Audio Type: {:?}", data_type),
};
Format{channels: format.channels,
sample_rate: format.sample_rate,
data_type: data_type}
},
Err(e) => {
println!("Error retrieving sample rate: {}", e);
format
},
};
Ok(format)
}
}
impl Default for Devices {
fn default() -> Devices {
Devices{ drivers: sys::get_driver_list().into_iter() }
}
}
impl Iterator for Devices {
type Item = Device;
fn next(&mut self) -> Option<Device> {
match self.drivers.next() {
Some(dn) => Some(Device{driver_name: dn}),
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> {
let mut driver_list = sys::get_driver_list();
match driver_list.pop() {
Some(dn) => Some(Device{ driver_name: dn }),
None => None,
}
}
pub fn default_output_device() -> Option<Device> {
let mut driver_list = sys::get_driver_list();
// TODO For build test only,
// remove if inproduction
for dn in &driver_list{
if dn == "ASIO4ALL v2"{
println!("Defaulted to ASIO4ALL **remove from production**");
return Some(Device{ driver_name: dn.clone() });
}
}
// end remove
match driver_list.pop() {
Some(dn) => Some(Device{ driver_name: dn }),
None => None,
}
}

View file

@ -0,0 +1,8 @@
extern crate asio_sys as sys;
pub use self::device::{Device, Devices, SupportedInputFormats, SupportedOutputFormats, default_input_device, default_output_device};
pub use self::stream::{InputBuffer, OutputBuffer, EventLoop, StreamId};
mod device;
mod stream;

View file

@ -0,0 +1,336 @@
extern crate asio_sys as sys;
extern crate itertools;
use std;
use Format;
use CreationError;
use StreamData;
use std::marker::PhantomData;
use super::Device;
use std::cell::Cell;
use UnknownTypeOutputBuffer;
use std::sync::{Arc, Mutex};
use std::mem;
use self::itertools::Itertools;
pub struct EventLoop {
asio_stream: Arc<Mutex<Option<sys::AsioStream>>>,
stream_count: Cell<usize>,
callbacks: Arc<Mutex<Vec<&'static mut (FnMut(StreamId, StreamData) + Send)>>>,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct StreamId(usize);
pub struct InputBuffer<'a, T: 'a> {
marker: PhantomData<&'a T>,
}
pub struct OutputBuffer<'a, T: 'a> {
buffer: &'a mut [T],
}
impl EventLoop {
pub fn new() -> EventLoop {
EventLoop {
asio_stream: Arc::new(Mutex::new(None)),
stream_count: Cell::new(0),
callbacks: Arc::new(Mutex::new(Vec::new())),
}
}
pub fn build_input_stream(
&self,
device: &Device,
format: &Format,
) -> Result<StreamId, CreationError> {
let stream_type = sys::get_data_type(&device.driver_name).expect("Couldn't load data type");
match sys::prepare_stream(&device.driver_name) {
Ok(stream) => {
{
*self.asio_stream.lock().unwrap() = Some(stream);
}
let count = self.stream_count.get();
self.stream_count.set(count + 1);
let asio_stream = self.asio_stream.clone();
let callbacks = self.callbacks.clone();
let bytes_per_channel = format.data_type.sample_size();
let num_channels = format.channels.clone();
// Get stream types
sys::set_callback(move |index| unsafe {
if let Some(ref asio_stream) = *asio_stream.lock().unwrap() {
// Number of samples needed total
let cpal_num_samples =
(asio_stream.buffer_size as usize) * num_channels as usize;
let mut callbacks = callbacks.lock().unwrap();
// Assuming only one callback, probably needs to change
match callbacks.first_mut() {
Some(callback) => {
macro_rules! try_callback {
($SampleFormat:ident,
$SampleType:ty,
$SampleTypeIdent:ident,
$AsioType:ty,
$AsioTypeIdent:ident) => {
// Buffer that is filled by cpal.
let mut cpal_buffer: Vec<$SampleType> = vec![0 as $SampleType; cpal_num_samples];
// Call in block because of mut borrow
{
}
// Function for deinterleaving because
// cpal writes to buffer interleaved
fn interleave(channels: Vec<Vec<$SampleType>>) -> Vec<$SampleType>{
let mut buffer: Vec<$SampleType> = Vec::new();
let length = channels[0].len();
for i in 0..length{
for channel in channels{
buffer.push(channel[i]);
}
}
buffer
}
// Deinter all the channels
let deinter_channels = deinterleave(&mut cpal_buffer[..],
num_channels as usize);
// For each channel write the cpal data to
// the asio buffer
// Also need to check for Endian
for (i, channel) in deinter_channels.into_iter().enumerate(){
let buff_ptr = (asio_stream
.buffer_infos[i]
.buffers[index as usize] as *mut $AsioType)
.offset(asio_stream.buffer_size as isize * i as isize);
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){
*asio_s = (*cpal_s as i64 *
::std::$AsioTypeIdent::MAX as i64 /
::std::$SampleTypeIdent::MAX as i64) as $AsioType;
}
}
let buff = InputBuffer{
buffer: &mut cpal_buffer
};
callback(
StreamId(count),
StreamData::Input{
buffer: UnknownTypeInputBuffer::$SampleFormat(
::InputBuffer{
target: Some(super::super::InputBuffer::Asio(buff))
})
}
);
};
}
// Generic over types
// TODO check for endianess
match stream_type {
sys::AsioSampleType::ASIOSTInt32LSB => {
try_callback!(I16, i16, i16, i32, i32);
}
sys::AsioSampleType::ASIOSTInt16LSB => {
try_callback!(I16, i16, i16, i16, i16);
}
sys::AsioSampleType::ASIOSTFloat32LSB => {
try_callback!(F32, f32, f32, f32, f32);
}
sys::AsioSampleType::ASIOSTFloat32LSB => {
try_callback!(F32, f32, f32, f64, f64);
}
_ => println!("unsupported format {:?}", stream_type),
}
}
None => return (),
}
}
});
Ok(StreamId(count))
}
Err(ref e) => {
println!("Error preparing stream: {}", e);
Err(CreationError::DeviceNotAvailable)
}
}
}
pub fn build_output_stream(
&self,
device: &Device,
format: &Format,
) -> Result<StreamId, CreationError> {
let stream_type = sys::get_data_type(&device.driver_name).expect("Couldn't load data type");
match sys::prepare_stream(&device.driver_name) {
Ok(stream) => {
{
*self.asio_stream.lock().unwrap() = Some(stream);
}
let count = self.stream_count.get();
self.stream_count.set(count + 1);
let asio_stream = self.asio_stream.clone();
let callbacks = self.callbacks.clone();
let bytes_per_channel = format.data_type.sample_size();
let num_channels = format.channels.clone();
// Get stream types
sys::set_callback(move |index| unsafe {
if let Some(ref asio_stream) = *asio_stream.lock().unwrap() {
// Number of samples needed total
let cpal_num_samples =
(asio_stream.buffer_size as usize) * num_channels as usize;
let mut callbacks = callbacks.lock().unwrap();
// Assuming only one callback, probably needs to change
match callbacks.first_mut() {
Some(callback) => {
macro_rules! try_callback {
($SampleFormat:ident,
$SampleType:ty,
$SampleTypeIdent:ident,
$AsioType:ty,
$AsioTypeIdent:ident) => {
// Buffer that is filled by cpal.
let mut cpal_buffer: Vec<$SampleType> = vec![0 as $SampleType; cpal_num_samples];
// Call in block because of mut borrow
{
let buff = OutputBuffer{
buffer: &mut cpal_buffer
};
callback(
StreamId(count),
StreamData::Output{
buffer: UnknownTypeOutputBuffer::$SampleFormat(
::OutputBuffer{
target: Some(super::super::OutputBuffer::Asio(buff))
})
}
);
}
// Function for deinterleaving because
// cpal writes to buffer interleaved
fn deinterleave(data_slice: &mut [$SampleType],
num_channels: usize) -> Vec<Vec<$SampleType>>{
let mut channels: Vec<Vec<$SampleType>> = Vec::new();
for i in 0..num_channels{
let mut it = data_slice.iter().skip(i).cloned();
let channel = it.step(num_channels).collect();
channels.push(channel);
}
channels
}
// Deinter all the channels
let deinter_channels = deinterleave(&mut cpal_buffer[..],
num_channels as usize);
// For each channel write the cpal data to
// the asio buffer
// Also need to check for Endian
for (i, channel) in deinter_channels.into_iter().enumerate(){
let buff_ptr = (asio_stream
.buffer_infos[i]
.buffers[index as usize] as *mut $AsioType)
.offset(asio_stream.buffer_size as isize * i as isize);
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){
*asio_s = (*cpal_s as i64 *
::std::$AsioTypeIdent::MAX as i64 /
::std::$SampleTypeIdent::MAX as i64) as $AsioType;
}
}
};
}
// Generic over types
// TODO check for endianess
match stream_type {
sys::AsioSampleType::ASIOSTInt32LSB => {
try_callback!(I16, i16, i16, i32, i32);
}
sys::AsioSampleType::ASIOSTInt16LSB => {
try_callback!(I16, i16, i16, i16, i16);
}
sys::AsioSampleType::ASIOSTFloat32LSB => {
try_callback!(F32, f32, f32, f32, f32);
}
sys::AsioSampleType::ASIOSTFloat32LSB => {
try_callback!(F32, f32, f32, f64, f64);
}
_ => println!("unsupported format {:?}", stream_type),
}
}
None => return (),
}
}
});
Ok(StreamId(count))
}
Err(ref e) => {
println!("Error preparing stream: {}", e);
Err(CreationError::DeviceNotAvailable)
}
}
}
pub fn play_stream(&self, stream: StreamId) {
sys::play();
}
pub fn pause_stream(&self, stream: StreamId) {
sys::stop();
}
pub fn destroy_stream(&self, stream_id: StreamId) {
let mut asio_stream_lock = self.asio_stream.lock().unwrap();
let old_stream = mem::replace(&mut *asio_stream_lock, None);
if let Some(old_stream) = old_stream {
sys::destroy_stream(old_stream);
}
}
pub fn run<F>(&self, mut callback: F) -> !
where
F: FnMut(StreamId, StreamData) + Send,
{
let callback: &mut (FnMut(StreamId, StreamData) + Send) = &mut callback;
self.callbacks
.lock()
.unwrap()
.push(unsafe { mem::transmute(callback) });
loop {
// Might need a sleep here to prevent the loop being
// removed in --release
}
}
}
impl<'a, T> InputBuffer<'a, T> {
pub fn buffer(&self) -> &[T] {
unimplemented!()
}
pub fn finish(self) {
unimplemented!()
}
}
impl<'a, T> OutputBuffer<'a, T> {
pub fn buffer(&mut self) -> &mut [T] {
&mut self.buffer
}
pub fn len(&self) -> usize {
self.buffer.len()
}
pub fn finish(self) {}
}