Cleaned up asio-sys (#831)

- Fixed clippy warnings
- Removed once_cell
This commit is contained in:
Jesper Nordenberg 2024-02-10 18:40:19 +01:00 • committed by GitHub
parent bbb58ab767
commit 52c7a9d680
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
6 changed files with 34 additions and 33 deletions

View file

@ -16,6 +16,5 @@ cc = "1.0.83"
parse_cfg = "4.1.1" parse_cfg = "4.1.1"
[dependencies] [dependencies]
once_cell = "1.12"
num-derive = "0.4" num-derive = "0.4"
num-traits = "0.2" num-traits = "0.2"

View file

@ -91,7 +91,7 @@ fn create_lib(cpal_asio_dir: &Path) {
// Gathers cpp files from directories // Gathers cpp files from directories
let walk_a_dir = |dir_to_walk, paths: &mut Vec<PathBuf>| { let walk_a_dir = |dir_to_walk, paths: &mut Vec<PathBuf>| {
for entry in WalkDir::new(&dir_to_walk).max_depth(1) { for entry in WalkDir::new(dir_to_walk).max_depth(1) {
let entry = match entry { let entry = match entry {
Err(e) => { Err(e) => {
println!("error: {}", e); println!("error: {}", e);
@ -209,6 +209,7 @@ fn create_bindings(cpal_asio_dir: &PathBuf) {
.allowlist_function("ASIOGetChannelInfo") .allowlist_function("ASIOGetChannelInfo")
.allowlist_function("ASIOGetBufferSize") .allowlist_function("ASIOGetBufferSize")
.allowlist_function("ASIOGetSamplePosition") .allowlist_function("ASIOGetSamplePosition")
.allowlist_function("ASIOOutputReady")
.allowlist_function("get_sample_rate") .allowlist_function("get_sample_rate")
.allowlist_function("set_sample_rate") .allowlist_function("set_sample_rate")
.allowlist_function("can_sample_rate") .allowlist_function("can_sample_rate")

View file

@ -2,5 +2,6 @@
#![allow(non_camel_case_types)] #![allow(non_camel_case_types)]
#![allow(non_snake_case)] #![allow(non_snake_case)]
#![allow(dead_code)] #![allow(dead_code)]
#![allow(clippy::missing_safety_doc)]
include!(concat!(env!("OUT_DIR"), "/asio_bindings.rs")); include!(concat!(env!("OUT_DIR"), "/asio_bindings.rs"));

View file

@ -43,15 +43,14 @@ impl fmt::Display for LoadDriverError {
LoadDriverError::LoadDriverFailed => { LoadDriverError::LoadDriverFailed => {
write!( write!(
f, f,
"{}",
"ASIO `loadDriver` function returned `false` indicating failure" "ASIO `loadDriver` function returned `false` indicating failure"
) )
} }
LoadDriverError::InitializationFailed(ref err) => { LoadDriverError::InitializationFailed(ref err) => {
write!(f, "{}", err) write!(f, "{err}")
} }
LoadDriverError::DriverAlreadyExists => { LoadDriverError::DriverAlreadyExists => {
write!(f, "{}", "ASIO only supports loading one driver at a time") write!(f, "ASIO only supports loading one driver at a time")
} }
} }
} }

View file

@ -4,11 +4,14 @@ pub mod errors;
use self::errors::{AsioError, AsioErrorWrapper, LoadDriverError}; use self::errors::{AsioError, AsioErrorWrapper, LoadDriverError};
use num_traits::FromPrimitive; use num_traits::FromPrimitive;
use once_cell::sync::Lazy;
use std::ffi::CStr; use std::ffi::{CStr, CString};
use std::ffi::CString;
use std::os::raw::{c_char, c_double, c_long, c_void}; use std::os::raw::{c_char, c_double, c_long, c_void};
use std::sync::{Arc, Mutex, MutexGuard, Weak}; use std::ptr::null_mut;
use std::sync::{
atomic::{AtomicBool, Ordering},
Arc, Mutex, MutexGuard, Weak,
};
// Bindings import // Bindings import
use self::asio_import as ai; use self::asio_import as ai;
@ -16,7 +19,7 @@ use self::asio_import as ai;
/// A handle to the ASIO API. /// A handle to the ASIO API.
/// ///
/// There should only be one instance of this type at any point in time. /// There should only be one instance of this type at any point in time.
#[derive(Debug)] #[derive(Debug, Default)]
pub struct Asio { pub struct Asio {
// Keeps track of whether or not a driver is already loaded. // Keeps track of whether or not a driver is already loaded.
// //
@ -307,18 +310,15 @@ pub struct CallbackId(usize);
/// ///
/// This is required because of how ASIO calls the `buffer_switch` function with no data /// This is required because of how ASIO calls the `buffer_switch` function with no data
/// parameters. /// parameters.
/// static BUFFER_CALLBACK: Mutex<Vec<(CallbackId, BufferCallback)>> = Mutex::new(Vec::new());
/// Options are used so that when a callback is removed we don't change the Vec indices.
/// /// Indicates that ASIOOutputReady should be called
/// The indices are how we match a callback with a stream. static CALL_OUTPUT_READY: AtomicBool = AtomicBool::new(false);
static BUFFER_CALLBACK: Lazy<Mutex<Vec<(CallbackId, BufferCallback)>>> =
Lazy::new(|| Mutex::new(Vec::new()));
impl Asio { impl Asio {
/// Initialise the ASIO API. /// Initialise the ASIO API.
pub fn new() -> Self { pub fn new() -> Self {
let loaded_driver = Mutex::new(Weak::new()); Self::default()
Asio { loaded_driver }
} }
/// Returns the name for each available driver. /// Returns the name for each available driver.
@ -334,7 +334,7 @@ impl Asio {
let mut driver_names: [[c_char; MAX_DRIVER_NAME_LEN]; MAX_DRIVERS] = let mut driver_names: [[c_char; MAX_DRIVER_NAME_LEN]; MAX_DRIVERS] =
[[0; MAX_DRIVER_NAME_LEN]; MAX_DRIVERS]; [[0; MAX_DRIVER_NAME_LEN]; MAX_DRIVERS];
// Pointer to each driver name. // Pointer to each driver name.
let mut driver_name_ptrs: [*mut i8; MAX_DRIVERS] = [0 as *mut i8; MAX_DRIVERS]; let mut driver_name_ptrs: [*mut i8; MAX_DRIVERS] = [null_mut(); MAX_DRIVERS];
for (ptr, name) in driver_name_ptrs.iter_mut().zip(&mut driver_names[..]) { for (ptr, name) in driver_name_ptrs.iter_mut().zip(&mut driver_names[..]) {
*ptr = (*name).as_mut_ptr(); *ptr = (*name).as_mut_ptr();
} }
@ -525,6 +525,11 @@ impl Driver {
None => buffer_sizes.pref, None => buffer_sizes.pref,
}; };
CALL_OUTPUT_READY.store(
asio_result!(unsafe { ai::ASIOOutputReady() }).is_ok(),
Ordering::Release,
);
// Ensure the driver is in the `Initialized` state. // Ensure the driver is in the `Initialized` state.
if let DriverState::Running = *state { if let DriverState::Running = *state {
state.stop()?; state.stop()?;
@ -628,9 +633,7 @@ impl Driver {
buffer_size: Option<i32>, buffer_size: Option<i32>,
) -> Result<AsioStreams, AsioError> { ) -> Result<AsioStreams, AsioError> {
let input_buffer_infos = prepare_buffer_infos(true, num_channels); let input_buffer_infos = prepare_buffer_infos(true, num_channels);
let output_buffer_infos = output let output_buffer_infos = output.map(|output| output.buffer_infos).unwrap_or_default();
.map(|output| output.buffer_infos)
.unwrap_or_else(Vec::new);
self.create_streams(input_buffer_infos, output_buffer_infos, buffer_size) self.create_streams(input_buffer_infos, output_buffer_infos, buffer_size)
} }
@ -653,9 +656,7 @@ impl Driver {
num_channels: usize, num_channels: usize,
buffer_size: Option<i32>, buffer_size: Option<i32>,
) -> Result<AsioStreams, AsioError> { ) -> Result<AsioStreams, AsioError> {
let input_buffer_infos = input let input_buffer_infos = input.map(|input| input.buffer_infos).unwrap_or_default();
.map(|input| input.buffer_infos)
.unwrap_or_else(Vec::new);
let output_buffer_infos = prepare_buffer_infos(false, num_channels); let output_buffer_infos = prepare_buffer_infos(false, num_channels);
self.create_streams(input_buffer_infos, output_buffer_infos, buffer_size) self.create_streams(input_buffer_infos, output_buffer_infos, buffer_size)
} }
@ -903,7 +904,7 @@ fn _channel_name_to_utf8(bytes: &[c_char]) -> std::borrow::Cow<str> {
/// Indicates the stream sample rate has changed. /// Indicates the stream sample rate has changed.
/// ///
/// TODO: Provide some way of allowing CPAL to handle this. /// TODO: Provide some way of allowing CPAL to handle this.
extern "C" fn sample_rate_did_change(s_rate: c_double) -> () { extern "C" fn sample_rate_did_change(s_rate: c_double) {
eprintln!("unhandled sample rate change to {}", s_rate); eprintln!("unhandled sample rate change to {}", s_rate);
} }
@ -1002,6 +1003,11 @@ extern "C" fn buffer_switch_time_info(
for &mut (_, ref mut bc) in bcs.iter_mut() { for &mut (_, ref mut bc) in bcs.iter_mut() {
bc.run(&callback_info); bc.run(&callback_info);
} }
if CALL_OUTPUT_READY.load(Ordering::Acquire) {
unsafe { ai::ASIOOutputReady() };
}
time time
} }
@ -1010,7 +1016,7 @@ extern "C" fn buffer_switch_time_info(
/// Here we run the callback for each stream. /// Here we run the callback for each stream.
/// ///
/// `double_buffer_index` is either `0` or `1` indicating which buffer to fill. /// `double_buffer_index` is either `0` or `1` indicating which buffer to fill.
extern "C" fn buffer_switch(double_buffer_index: c_long, direct_process: c_long) -> () { extern "C" fn buffer_switch(double_buffer_index: c_long, direct_process: c_long) {
// Emulate the time info provided by the `buffer_switch_time_info` callback. // Emulate the time info provided by the `buffer_switch_time_info` callback.
// This is an attempt at matching the behaviour in `hostsample.cpp` from the SDK. // This is an attempt at matching the behaviour in `hostsample.cpp` from the SDK.
let mut time = unsafe { let mut time = unsafe {
@ -1041,7 +1047,7 @@ extern "C" fn buffer_switch(double_buffer_index: c_long, direct_process: c_long)
// kSampleRateChanged = 1 << 4, // kSampleRateChanged = 1 << 4,
// kClockSourceChanged = 1 << 5 // kClockSourceChanged = 1 << 5
// } AsioTimeInfoFlags; // } AsioTimeInfoFlags;
.0 as i32; .0;
} }
time time
}; };

View file

@ -1,12 +1,7 @@
#![allow(non_camel_case_types)] #![allow(non_camel_case_types)]
#[allow(unused_imports)]
extern crate once_cell;
#[allow(unused_imports)]
#[macro_use] #[macro_use]
extern crate num_derive; extern crate num_derive;
#[allow(unused_imports)]
extern crate num_traits; extern crate num_traits;
#[cfg(asio)] #[cfg(asio)]