rewrite jack init

This commit is contained in:
🪞👃🪞 2025-01-21 22:30:53 +01:00
parent 6c8f85ab84
commit b2c9bfc0e2
19 changed files with 448 additions and 679 deletions

View file

@ -1,88 +1,89 @@
use crate::*;
use self::JackClientState::*;
/// Wraps [JackClientState] and through it [jack::Client].
#[derive(Clone, Debug, Default)]
pub struct JackClient {
state: Arc<RwLock<JackClientState>>
use ::jack::contrib::*;
use self::JackState::*;
/// Things that can provide a [jack::Client] reference.
pub trait HasJack {
/// Return the internal [jack::Client] handle
/// that lets you call the JACK API.
fn jack (&self) -> &Jack;
/// Run something with the client.
fn with_client <T> (&self, op: impl FnOnce(&Client)->T) -> T {
match &*self.jack().state.read().unwrap() {
Inert => panic!("jack client not activated"),
Inactive(ref client) => op(client),
Activating => panic!("jack client has not finished activation"),
Active(ref client) => op(client.as_client()),
}
}
fn port_by_name (&self, name: &str) -> Option<Port<Unowned>> {
self.with_client(|client|client.port_by_name(name))
}
fn register_port <PS: PortSpec + Default> (&self, name: impl AsRef<str>) -> Usually<Port<PS>> {
self.with_client(|client|Ok(client.register_port(name.as_ref(), PS::default())?))
}
fn sync_lead (&self, enable: bool, cb: impl Fn(TimebaseInfo)->Position) -> Usually<()> {
if enable {
self.with_client(|client|match client.register_timebase_callback(false, cb) {
Ok(_) => Ok(()),
Err(e) => Err(e)
})?
}
Ok(())
}
fn sync_follow (&self, enable: bool) -> Usually<()> {
// TODO: sync follow
Ok(())
}
}
impl JackClient {
impl HasJack for Jack { fn jack (&self) -> &Jack { self } }
impl HasJack for &Jack { fn jack (&self) -> &Jack { self } }
/// Wraps [JackState] and through it [jack::Client].
#[derive(Clone, Debug, Default)]
pub struct Jack {
state: Arc<RwLock<JackState>>
}
impl Jack {
pub fn new (name: &str) -> Usually<Self> {
let (client, _) = Client::new(name, ClientOptions::NO_START_SERVER)?;
Ok(Self { state: Arc::new(RwLock::new(Inactive(client))) })
Ok(Self {
state: JackState::new(Client::new(name, ClientOptions::NO_START_SERVER)?.0)
})
}
/// Return the internal [Client] handle that lets you call the JACK API.
pub fn inner (&self) -> Client {
self.state.read().unwrap().inner()
}
/// Activate a connection with an application.
///
/// Consume a `JackClient::Inactive`, binding a process callback and returning a `JackClient::Active`.
///
/// * [ ] TODO: Needs work. Strange ownership situation between the callback and the host object.
fn activate <'a: 'static> (
&'a self, mut cb: impl FnMut(JackClient, &Client, &ProcessScope) -> Control + Send + 'a
) -> Usually<Self> where Self: Send + Sync + 'a {
let client = self.inner();
let state = Arc::new(RwLock::new(Activating));
let event = Box::new(move|_|{/*TODO*/}) as Box<dyn Fn(JackEvent) + Send + Sync>;
let events = Notifications(event);
let frame = Box::new(move|c: &_, s: &_|cb(self.clone(), c, s));
let frames = ClosureProcessHandler::new(frame as BoxedAudioHandler<'a>);
*state.write().unwrap() = Active(client.activate_async(events, frames)?);
Ok(Self { state })
}
/// Activate a connection with an application.
///
/// * Wrap a [JackClient::Inactive] into [Arc<RwLock<_>>].
/// * Pass it to the `init` callback
/// * This allows user code to connect to JACK
/// * While user code retains clone of the
/// [Arc<RwLock<JackClient>>] that is
/// passed to `init`, the audio engine is running.
pub fn activate_with <'a: 'static, T> (
&self, init: impl FnOnce(&JackClient)->Usually<T>
) -> Usually<Arc<RwLock<T>>> where T: Audio + 'a {
// Run init callback. Return value is target. Target must retain clone of `connection`.
let target = Arc::new(RwLock::new(init(&self)?));
// Swap the `client` from the `JackClient::Inactive`
// for a `JackClient::Activating`.
let mut client = Activating;
std::mem::swap(&mut*self.state.write().unwrap(), &mut client);
// Replace the `JackClient::Activating` with a
// `JackClient::Active` wrapping the [AsyncClient]
// returned by the activation.
*self.state.write().unwrap() = Active(client.inner().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(move|_|{/*TODO*/}) 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 `target`'s `process` callback, which in turn
// implements audio and MIDI input and output on a realtime basis.
ClosureProcessHandler::new(Box::new({
let target = target.clone();
move|c: &_, s: &_|if let Ok(mut target) = target.write() {
target.process(c, s)
} else {
Control::Quit
}
}) as BoxedAudioHandler),
)?);
Ok(target)
}
pub fn port_by_name (&self, name: &str) -> Option<Port<Unowned>> {
self.inner().port_by_name(name)
}
pub fn register_port <PS: PortSpec> (&self, name: &str, spec: PS) -> Usually<Port<PS>> {
Ok(self.inner().register_port(name, spec)?)
pub fn run <'j: 'static, T: Audio + 'j> (
&self, cb: impl FnOnce(&Jack)->Usually<T>
) -> Usually<Arc<RwLock<T>>> {
let app = Arc::new(RwLock::new(cb(self)?));
let mut state = Activating;
std::mem::swap(&mut*self.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(move|_|{/*TODO*/}) 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<'j>),
)?;
*self.state.write().unwrap() = Active(client);
} else {
unreachable!();
}
Ok(app)
}
}
/// This is a connection which may be [Inactive], [Activating], or [Active].
/// In the [Active] and [Inactive] states, [JackClientState::client] returns a
/// 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)] enum JackClientState {
#[derive(Debug, Default)] enum JackState {
/// Unused
#[default] Inert,
/// Before activation.
@ -92,16 +93,15 @@ impl JackClient {
/// After activation. Must not be dropped for JACK thread to persist.
Active(DynamicAsyncClient<'static>),
}
impl JackClientState {
pub fn inner (&self) -> Client {
match self {
Inert => panic!("jack client not activated"),
Inactive(ref client) => unsafe { Client::from_raw(client.raw()) },
Activating => panic!("jack client has not finished activation"),
Active(ref client) => unsafe { Client::from_raw(client.as_client().raw()) },
}
}
impl JackState {
fn new (client: Client) -> Arc<RwLock<Self>> { Arc::new(RwLock::new(Self::Inactive(client))) }
}
//has_jack_client!(|self: JackState|match self {
//Inert => panic!("jack client not activated"),
//Inactive(ref client) => client,
//Activating => panic!("jack client has not finished activation"),
//Active(ref client) => client.as_client(),
//});
/// This is a boxed realtime callback.
pub type BoxedAudioHandler<'j> =
Box<dyn FnMut(&Client, &ProcessScope) -> Control + Send + 'j>;
@ -120,31 +120,26 @@ pub type DynamicNotifications<'j> =
/// and that's all it knows about them.
pub type DynamicAsyncClient<'j>
= AsyncClient<DynamicNotifications<'j>, DynamicAudioHandler<'j>>;
impl RegisterPort for JackClient {
fn midi_in (&self, name: impl AsRef<str>) -> Usually<Port<MidiIn>> {
Ok(self.inner().register_port(name.as_ref(), MidiIn::default())?)
}
fn midi_out (&self, name: impl AsRef<str>) -> Usually<Port<MidiOut>> {
Ok(self.inner().register_port(name.as_ref(), MidiOut::default())?)
}
fn audio_in (&self, name: impl AsRef<str>) -> Usually<Port<AudioIn>> {
Ok(self.inner().register_port(name.as_ref(), AudioIn::default())?)
}
fn audio_out (&self, name: impl AsRef<str>) -> Usually<Port<AudioOut>> {
Ok(self.inner().register_port(name.as_ref(), AudioOut::default())?)
/// Implement [Audio]: provide JACK callbacks.
#[macro_export] macro_rules! audio {
(|$self:ident:$Struct:ident$(<$($L:lifetime),*$($T:ident$(:$U:path)?),*>)?,$c:ident,$s:ident|$cb:expr) => {
impl $(<$($L),*$($T $(: $U)?),*>)? Audio for $Struct $(<$($L),*$($T),*>)? {
#[inline] fn process (&mut $self, $c: &Client, $s: &ProcessScope) -> Control { $cb }
}
}
}
impl ConnectPort for JackClient {
fn ports (&self, re_name: Option<&str>, re_type: Option<&str>, flags: PortFlags) -> Vec<String> {
self.inner().ports(re_name, re_type, flags)
/// Trait for thing that has a JACK process callback.
pub trait Audio: Send + Sync {
fn process (&mut self, _: &Client, _: &ProcessScope) -> Control {
Control::Continue
}
fn port_by_name (&self, name: impl AsRef<str>) -> Option<Port<Unowned>> {
self.inner().port_by_name(name.as_ref())
}
fn connect_ports <A: PortSpec, B: PortSpec> (&self, source: &Port<A>, target: &Port<B>)
-> Usually<()>
{
Ok(self.inner().connect_ports(source, target)?)
fn callback (
state: &Arc<RwLock<Self>>, client: &Client, scope: &ProcessScope
) -> Control where Self: Sized {
if let Ok(mut state) = state.write() {
state.process(client, scope)
} else {
Control::Quit
}
}
}