Skip to content

Commit

Permalink
Cleaned up asio-sys (#831)
Browse files Browse the repository at this point in the history
- Fixed clippy warnings
- Removed once_cell
  • Loading branch information
jesnor authored Feb 10, 2024
1 parent bbb58ab commit 52c7a9d
Show file tree
Hide file tree
Showing 6 changed files with 34 additions and 33 deletions.
1 change: 0 additions & 1 deletion asio-sys/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,5 @@ cc = "1.0.83"
parse_cfg = "4.1.1"

[dependencies]
once_cell = "1.12"
num-derive = "0.4"
num-traits = "0.2"
3 changes: 2 additions & 1 deletion asio-sys/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ fn create_lib(cpal_asio_dir: &Path) {

// Gathers cpp files from directories
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 {
Err(e) => {
println!("error: {}", e);
Expand Down Expand Up @@ -209,6 +209,7 @@ fn create_bindings(cpal_asio_dir: &PathBuf) {
.allowlist_function("ASIOGetChannelInfo")
.allowlist_function("ASIOGetBufferSize")
.allowlist_function("ASIOGetSamplePosition")
.allowlist_function("ASIOOutputReady")
.allowlist_function("get_sample_rate")
.allowlist_function("set_sample_rate")
.allowlist_function("can_sample_rate")
Expand Down
1 change: 1 addition & 0 deletions asio-sys/src/bindings/asio_import.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,6 @@
#![allow(non_camel_case_types)]
#![allow(non_snake_case)]
#![allow(dead_code)]
#![allow(clippy::missing_safety_doc)]

include!(concat!(env!("OUT_DIR"), "/asio_bindings.rs"));
5 changes: 2 additions & 3 deletions asio-sys/src/bindings/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,15 +43,14 @@ impl fmt::Display for LoadDriverError {
LoadDriverError::LoadDriverFailed => {
write!(
f,
"{}",
"ASIO `loadDriver` function returned `false` indicating failure"
)
}
LoadDriverError::InitializationFailed(ref err) => {
write!(f, "{}", err)
write!(f, "{err}")
}
LoadDriverError::DriverAlreadyExists => {
write!(f, "{}", "ASIO only supports loading one driver at a time")
write!(f, "ASIO only supports loading one driver at a time")
}
}
}
Expand Down
52 changes: 29 additions & 23 deletions asio-sys/src/bindings/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,19 +4,22 @@ pub mod errors;

use self::errors::{AsioError, AsioErrorWrapper, LoadDriverError};
use num_traits::FromPrimitive;
use once_cell::sync::Lazy;
use std::ffi::CStr;
use std::ffi::CString;

use std::ffi::{CStr, CString};
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
use self::asio_import as ai;

/// A handle to the ASIO API.
///
/// There should only be one instance of this type at any point in time.
#[derive(Debug)]
#[derive(Debug, Default)]
pub struct Asio {
// Keeps track of whether or not a driver is already loaded.
//
Expand Down Expand Up @@ -307,18 +310,15 @@ pub struct CallbackId(usize);
///
/// This is required because of how ASIO calls the `buffer_switch` function with no data
/// parameters.
///
/// Options are used so that when a callback is removed we don't change the Vec indices.
///
/// The indices are how we match a callback with a stream.
static BUFFER_CALLBACK: Lazy<Mutex<Vec<(CallbackId, BufferCallback)>>> =
Lazy::new(|| Mutex::new(Vec::new()));
static BUFFER_CALLBACK: Mutex<Vec<(CallbackId, BufferCallback)>> = Mutex::new(Vec::new());

/// Indicates that ASIOOutputReady should be called
static CALL_OUTPUT_READY: AtomicBool = AtomicBool::new(false);

impl Asio {
/// Initialise the ASIO API.
pub fn new() -> Self {
let loaded_driver = Mutex::new(Weak::new());
Asio { loaded_driver }
Self::default()
}

/// Returns the name for each available driver.
Expand All @@ -334,7 +334,7 @@ impl Asio {
let mut driver_names: [[c_char; MAX_DRIVER_NAME_LEN]; MAX_DRIVERS] =
[[0; MAX_DRIVER_NAME_LEN]; MAX_DRIVERS];
// 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[..]) {
*ptr = (*name).as_mut_ptr();
}
Expand Down Expand Up @@ -525,6 +525,11 @@ impl Driver {
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.
if let DriverState::Running = *state {
state.stop()?;
Expand Down Expand Up @@ -628,9 +633,7 @@ impl Driver {
buffer_size: Option<i32>,
) -> Result<AsioStreams, AsioError> {
let input_buffer_infos = prepare_buffer_infos(true, num_channels);
let output_buffer_infos = output
.map(|output| output.buffer_infos)
.unwrap_or_else(Vec::new);
let output_buffer_infos = output.map(|output| output.buffer_infos).unwrap_or_default();
self.create_streams(input_buffer_infos, output_buffer_infos, buffer_size)
}

Expand All @@ -653,9 +656,7 @@ impl Driver {
num_channels: usize,
buffer_size: Option<i32>,
) -> Result<AsioStreams, AsioError> {
let input_buffer_infos = input
.map(|input| input.buffer_infos)
.unwrap_or_else(Vec::new);
let input_buffer_infos = input.map(|input| input.buffer_infos).unwrap_or_default();
let output_buffer_infos = prepare_buffer_infos(false, num_channels);
self.create_streams(input_buffer_infos, output_buffer_infos, buffer_size)
}
Expand Down Expand Up @@ -903,7 +904,7 @@ fn _channel_name_to_utf8(bytes: &[c_char]) -> std::borrow::Cow<str> {
/// Indicates the stream sample rate has changed.
///
/// 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);
}

Expand Down Expand Up @@ -1002,6 +1003,11 @@ extern "C" fn buffer_switch_time_info(
for &mut (_, ref mut bc) in bcs.iter_mut() {
bc.run(&callback_info);
}

if CALL_OUTPUT_READY.load(Ordering::Acquire) {
unsafe { ai::ASIOOutputReady() };
}

time
}

Expand All @@ -1010,7 +1016,7 @@ extern "C" fn buffer_switch_time_info(
/// Here we run the callback for each stream.
///
/// `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.
// This is an attempt at matching the behaviour in `hostsample.cpp` from the SDK.
let mut time = unsafe {
Expand Down Expand Up @@ -1041,7 +1047,7 @@ extern "C" fn buffer_switch(double_buffer_index: c_long, direct_process: c_long)
// kSampleRateChanged = 1 << 4,
// kClockSourceChanged = 1 << 5
// } AsioTimeInfoFlags;
.0 as i32;
.0;
}
time
};
Expand Down
5 changes: 0 additions & 5 deletions asio-sys/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,7 @@
#![allow(non_camel_case_types)]

#[allow(unused_imports)]
extern crate once_cell;

#[allow(unused_imports)]
#[macro_use]
extern crate num_derive;
#[allow(unused_imports)]
extern crate num_traits;

#[cfg(asio)]
Expand Down

0 comments on commit 52c7a9d

Please sign in to comment.