use crate::*; pub use ::jack::{*, contrib::{*, ClosureProcessHandler}}; /// Wraps [JackState] and through it [jack::Client] when connected. #[derive(Clone, Debug, Default)] pub struct Jack<'j>(Arc>>); /// Implement [Jack] constructor and methods impl<'j> Jack<'j> { /// Register new [Client] and wrap it for shared use. pub fn new_run + Audio + Send + Sync + 'static> ( name: &impl AsRef, init: impl FnOnce(Jack<'j>)->Usually ) -> Usually>> { Jack::new(name)?.run(init) } pub fn new (name: &impl AsRef) -> Usually { let client = Client::new(name.as_ref(), ClientOptions::NO_START_SERVER)?.0; Ok(Jack(Arc::new(RwLock::new(JackState::Inactive(client))))) } pub fn run + Audio + Send + Sync + 'static> (self, init: impl FnOnce(Self)->Usually) -> Usually>> { let client_state = self.0.clone(); let app: Arc> = Arc::new(RwLock::new(init(self)?)); let mut state = Activating; std::mem::swap(&mut*client_state.write().unwrap(), &mut state); if let Inactive(client) = state { let client = client.activate_async( // This is the misc notifications handler. It's a struct that wraps a [Box] // which performs type erasure on a callback that takes [JackEvent], which is // one of the available misc notifications. Notifications(Box::new({ let app = app.clone(); move|event|(&mut*app.write().unwrap()).handle(event) }) as BoxedJackEventHandler), // This is the main processing handler. It's a struct that wraps a [Box] // which performs type erasure on a callback that takes [Client] and [ProcessScope] // and passes them down to the `app`'s `process` callback, which in turn // implements audio and MIDI input and output on a realtime basis. ClosureProcessHandler::new(Box::new({ let app = app.clone(); move|c: &_, s: &_|if let Ok(mut app) = app.write() { app.process(c, s) } else { Control::Quit } }) as BoxedAudioHandler), )?; *client_state.write().unwrap() = Active(client); } else { unreachable!(); } Ok(app) } /// Run something with the client. pub fn with_client (&self, op: impl FnOnce(&Client)->T) -> T { match &*self.0.read().unwrap() { Inert => panic!("jack client not activated"), Inactive(client) => op(client), Activating => panic!("jack client has not finished activation"), Active(client) => op(client.as_client()), } } } impl<'j> HasJack<'j> for Jack<'j> { fn jack (&self) -> &Jack<'j> { self } } impl<'j> HasJack<'j> for &Jack<'j> { fn jack (&self) -> &Jack<'j> { self } } /// This is a connection which may be [Inactive], [Activating], or [Active]. /// In the [Active] and [Inactive] states, [JackState::client] returns a /// [jack::Client], which you can use to talk to the JACK API. #[derive(Debug, Default)] pub enum JackState<'j> { /// Unused #[default] Inert, /// Before activation. Inactive(Client), /// During activation. Activating, /// After activation. Must not be dropped for JACK thread to persist. Active(DynamicAsyncClient<'j>), } /// Things that can provide a [jack::Client] reference. pub trait HasJack<'j>: Send + Sync { /// Return the internal [jack::Client] handle /// that lets you call the JACK API. fn jack (&self) -> &Jack<'j>; fn with_client (&self, op: impl FnOnce(&Client)->T) -> T { self.jack().with_client(op) } fn port_by_name (&self, name: &str) -> Option> { self.with_client(|client|client.port_by_name(name)) } fn port_by_id (&self, id: u32) -> Option> { self.with_client(|c|c.port_by_id(id)) } fn register_port (&self, name: impl AsRef) -> Usually> { self.with_client(|client|Ok(client.register_port(name.as_ref(), PS::default())?)) } fn sync_lead (&self, enable: bool, callback: impl Fn(TimebaseInfo)->Position) -> Usually<()> { if enable { self.with_client(|client|match client.register_timebase_callback(false, callback) { Ok(_) => Ok(()), Err(e) => Err(e) })? } Ok(()) } fn sync_follow (&self, _enable: bool) -> Usually<()> { // TODO: sync follow Ok(()) } } /// Trait for thing that has a JACK process callback. pub trait Audio { /// Handle a JACK event. fn handle (&mut self, _event: JackEvent) {} /// Projecss a JACK chunk. fn process (&mut self, _: &Client, _: &ProcessScope) -> Control { Control::Continue } /// The JACK process callback function passed to the server. fn callback ( state: &Arc>, client: &Client, scope: &ProcessScope ) -> Control where Self: Sized { if let Ok(mut state) = state.write() { state.process(client, scope) } else { Control::Quit } } } /// Implement [Audio]: provide JACK callbacks. #[macro_export] macro_rules! audio { (| $self1:ident: $Struct:ident$(<$($L:lifetime),*$($T:ident$(:$U:path)?),*>)?,$c:ident,$s:ident |$cb:expr$(;|$self2:ident,$e:ident|$cb2:expr)?) => { impl $(<$($L),*$($T $(: $U)?),*>)? Audio for $Struct $(<$($L),*$($T),*>)? { #[inline] fn process (&mut $self1, $c: &Client, $s: &ProcessScope) -> Control { $cb } $(#[inline] fn handle (&mut $self2, $e: JackEvent) { $cb2 })? } } } /// Event enum for JACK events. #[derive(Debug, Clone, PartialEq)] pub enum JackEvent { ThreadInit, Shutdown(ClientStatus, Arc), Freewheel(bool), SampleRate(Frames), ClientRegistration(Arc, bool), PortRegistration(PortId, bool), PortRename(PortId, Arc, Arc), PortsConnected(PortId, PortId, bool), GraphReorder, XRun, } /// Generic notification handler that emits [JackEvent] pub struct Notifications(pub T); impl NotificationHandler for Notifications { fn thread_init(&self, _: &Client) { self.0(JackEvent::ThreadInit); } unsafe fn shutdown(&mut self, status: ClientStatus, reason: &str) { self.0(JackEvent::Shutdown(status, reason.into())); } fn freewheel(&mut self, _: &Client, enabled: bool) { self.0(JackEvent::Freewheel(enabled)); } fn sample_rate(&mut self, _: &Client, frames: Frames) -> Control { self.0(JackEvent::SampleRate(frames)); Control::Quit } fn client_registration(&mut self, _: &Client, name: &str, reg: bool) { self.0(JackEvent::ClientRegistration(name.into(), reg)); } fn port_registration(&mut self, _: &Client, id: PortId, reg: bool) { self.0(JackEvent::PortRegistration(id, reg)); } fn port_rename(&mut self, _: &Client, id: PortId, old: &str, new: &str) -> Control { self.0(JackEvent::PortRename(id, old.into(), new.into())); Control::Continue } fn ports_connected(&mut self, _: &Client, a: PortId, b: PortId, are: bool) { self.0(JackEvent::PortsConnected(a, b, are)); } fn graph_reorder(&mut self, _: &Client) -> Control { self.0(JackEvent::GraphReorder); Control::Continue } fn xrun(&mut self, _: &Client) -> Control { self.0(JackEvent::XRun); Control::Continue } } /// This is a running JACK [AsyncClient] with maximum type erasure. /// It has one [Box] containing a function that handles [JackEvent]s, /// and another [Box] containing a function that handles realtime IO, /// and that's all it knows about them. pub type DynamicAsyncClient<'j> = AsyncClient, DynamicAudioHandler<'j>>; /// This is the notification handler wrapper for a boxed realtime callback. pub type DynamicAudioHandler<'j> = ClosureProcessHandler<(), BoxedAudioHandler<'j>>; /// This is a boxed realtime callback. pub type BoxedAudioHandler<'j> = Box Control + Send + Sync + 'j>; /// This is the notification handler wrapper for a boxed [JackEvent] callback. pub type DynamicNotifications<'j> = Notifications>; /// This is a boxed [JackEvent] callback. pub type BoxedJackEventHandler<'j> = Box; use self::JackState::*;