From 191b90909a390fa179649224dd3705f8c0a38a1e Mon Sep 17 00:00:00 2001 From: mitchmindtree Date: Sat, 29 Jun 2019 05:47:58 +1000 Subject: [PATCH] Make Driver type responsible for managing user callbacks --- asio-sys/src/bindings/mod.rs | 28 +++++++++++++++++++--------- src/host/asio/stream.rs | 4 ++-- 2 files changed, 21 insertions(+), 11 deletions(-) diff --git a/asio-sys/src/bindings/mod.rs b/asio-sys/src/bindings/mod.rs index a07343a..38617af 100644 --- a/asio-sys/src/bindings/mod.rs +++ b/asio-sys/src/bindings/mod.rs @@ -579,6 +579,17 @@ impl Driver { Ok(()) } + /// Adds a callback to the list of active callbacks. + /// + /// The given function receives the index of the buffer currently ready for processing. + pub fn set_callback(&self, callback: F) + where + F: 'static + FnMut(i32) + Send, + { + let mut bc = BUFFER_CALLBACK.lock().unwrap(); + bc.push(Some(BufferCallback(Box::new(callback)))); + } + /// Consumes and destroys the `Driver`, stopping the streams if they are running and releasing /// any associated resources. pub fn destroy(mut self) -> Result<(), AsioError> { @@ -597,7 +608,15 @@ impl Driver { asio_result!(ai::ASIOExit())?; ai::remove_current_driver(); } + + // Clear any existing stream callbacks. + if let Ok(mut bcs) = BUFFER_CALLBACK.lock() { + bcs.clear(); + } + + // Indicate to the self.loaded.store(false, atomic::Ordering::SeqCst); + Ok(()) } } @@ -614,15 +633,6 @@ impl Drop for Driver { unsafe impl Send for AsioStream {} -/// Adds a callback to the list of active callbacks -pub fn set_callback(callback: F) -> () -where - F: FnMut(i32) + Send, -{ - let mut bc = BUFFER_CALLBACK.lock().unwrap(); - bc.push(Some(BufferCallback(Box::new(callback)))); -} - /// Idicates the sample rate has changed /// TODO Change the sample rate when this /// is called. diff --git a/src/host/asio/stream.rs b/src/host/asio/stream.rs index c356aa9..99e9c55 100644 --- a/src/host/asio/stream.rs +++ b/src/host/asio/stream.rs @@ -225,7 +225,7 @@ impl EventLoop { // Set the input callback. // This is most performance critical part of the ASIO bindings. - sys::set_callback(move |buffer_index| unsafe { + driver.set_callback(move |buffer_index| unsafe { // If not playing return early. // TODO: Don't assume `count` is valid - we should search for the matching `StreamId`. if let Some(s) = cpal_streams.lock().unwrap().get(count) { @@ -400,7 +400,7 @@ impl EventLoop { let mut interleaved = vec![0u8; len_bytes]; let mut silence_asio_buffer = SilenceAsioBuffer::default(); - sys::set_callback(move |buffer_index| unsafe { + driver.set_callback(move |buffer_index| unsafe { // If not playing, return early. // TODO: Don't assume `count` is valid - we should search for the matching `StreamId`. if let Some(s) = cpal_streams.lock().unwrap().get(count) {