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,11 +0,0 @@
use crate::*;
/// Things that can provide a [JackClient] reference.
pub trait HasJack { fn jack (&self) -> &JackClient; }
/// Implement [HasJack].
#[macro_export] macro_rules! has_jack {
(|$self:ident:$Struct:ident$(<$($L:lifetime),*$($T:ident$(:$U:path)?),*>)?|$cb:expr) => {
impl $(<$($L),*$($T $(: $U)?),*>)? HasJack for $Struct $(<$($L),*$($T),*>)? {
fn jack (&$self) -> &JackClient { $cb }
}
};
}

View file

@ -1,26 +0,0 @@
use crate::*;
/// 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 }
}
}
}
/// Trait for thing that has a JACK process callback.
pub trait Audio: Send + Sync {
fn process (&mut self, _: &Client, _: &ProcessScope) -> Control {
Control::Continue
}
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
}
}
}

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
}
}
}

View file

@ -1,165 +0,0 @@
use crate::*;
pub trait JackPortConnect<T: PortSpec> {
fn jack (&self) -> &JackClient;
fn port (&self) -> &Port<T>;
fn conn (&self) -> &[PortConnection];
fn connect_to_matching (&mut self) -> Usually<()> {
use PortConnectionName::*;
use PortConnectionScope::*;
use PortConnectionStatus::*;
let jack = self.jack();
for connect in self.conn().iter() {
let mut status = vec![];
match &connect.name {
Exact(name) => for port in jack.ports(None, None, PortFlags::empty()).iter() {
if port.as_str() == &**name {
if let Some(port) = jack.port_by_name(port.as_str()) {
let port_status = Self::try_both_ways(jack, &port, &self.port());
let name = port.name()?.into();
status.push((port, name, port_status));
if port_status == Connected {
break
}
}
}
},
RegExp(re) => for port in jack.ports(Some(&re), None, PortFlags::empty()).iter() {
if let Some(port) = jack.port_by_name(port.as_str()) {
let port_status = Self::try_both_ways(jack, &port, &self.port());
let name = port.name()?.into();
status.push((port, name, port_status));
if port_status == Connected && connect.scope == One {
break
}
}
}
}
*connect.status.write().unwrap() = status
}
Ok(())
}
fn try_both_ways <A, B> (
jack: &impl ConnectPort, port_a: &Port<A>, port_b: &Port<B>
) -> PortConnectionStatus where A: PortSpec, B: PortSpec {
if let Ok(_) = jack.connect_ports(port_a, port_b) {
PortConnectionStatus::Connected
} else if let Ok(_) = jack.connect_ports(port_b, port_a) {
PortConnectionStatus::Connected
} else {
PortConnectionStatus::Mismatch
}
}
}
#[derive(Clone, Debug)]
pub struct PortConnection {
pub name: PortConnectionName,
pub scope: PortConnectionScope,
pub status: Arc<RwLock<Vec<(Port<Unowned>, Arc<str>, PortConnectionStatus)>>>,
}
pub trait ConnectPort {
fn ports (&self, re_name: Option<&str>, re_type: Option<&str>, flags: PortFlags) -> Vec<String>;
fn port_by_name (&self, name: impl AsRef<str>) -> Option<Port<Unowned>>;
fn connect_ports <A: PortSpec, B: PortSpec> (&self, source: &Port<A>, target: &Port<B>)
-> Usually<()>;
fn connect_midi_from (&self, input: &Port<MidiIn>, ports: &[impl AsRef<str>]) -> Usually<()> {
for port in ports.iter() {
let port = port.as_ref();
if let Some(port) = self.port_by_name(port).as_ref() {
self.connect_ports(port, input)?;
} else {
panic!("Missing MIDI output: {port}. Use jack_lsp to list all port names.");
}
}
Ok(())
}
fn connect_midi_to (&self, output: &Port<MidiOut>, ports: &[impl AsRef<str>]) -> Usually<()> {
for port in ports.iter() {
let port = port.as_ref();
if let Some(port) = self.port_by_name(port).as_ref() {
self.connect_ports(output, port)?;
} else {
panic!("Missing MIDI input: {port}. Use jack_lsp to list all port names.");
}
}
Ok(())
}
fn connect_audio_from (&self, input: &Port<AudioIn>, ports: &[impl AsRef<str>]) -> Usually<()> {
for port in ports.iter() {
let port = port.as_ref();
if let Some(port) = self.port_by_name(port).as_ref() {
self.connect_ports(port, input)?;
} else {
panic!("Missing MIDI output: {port}. Use jack_lsp to list all port names.");
}
}
Ok(())
}
fn connect_audio_to (&self, output: &Port<AudioOut>, ports: &[impl AsRef<str>]) -> Usually<()> {
for port in ports.iter() {
let port = port.as_ref();
if let Some(port) = self.port_by_name(port).as_ref() {
self.connect_ports(output, port)?;
} else {
panic!("Missing MIDI input: {port}. Use jack_lsp to list all port names.");
}
}
Ok(())
}
}
impl<T: ConnectPort> ConnectPort for Arc<RwLock<T>> {
fn ports (&self, re_name: Option<&str>, re_type: Option<&str>, flags: PortFlags) -> Vec<String> {
self.read().unwrap().ports(re_name, re_type, flags)
}
fn port_by_name (&self, name: impl AsRef<str>) -> Option<Port<Unowned>> {
self.read().unwrap().port_by_name(name.as_ref())
}
fn connect_ports <A: PortSpec, B: PortSpec> (&self, source: &Port<A>, target: &Port<B>)
-> Usually<()>
{
Ok(self.read().unwrap().connect_ports(source, target)?)
}
}
impl PortConnection {
pub fn collect (exact: &[impl AsRef<str>], re: &[impl AsRef<str>], re_all: &[impl AsRef<str>])
-> Vec<Self>
{
let mut connections = vec![];
for port in exact.iter() { connections.push(Self::exact(port)) }
for port in re.iter() { connections.push(Self::regexp(port)) }
for port in re_all.iter() { connections.push(Self::regexp_all(port)) }
connections
}
/// Connect to this exact port
pub fn exact (name: impl AsRef<str>) -> Self {
let name = PortConnectionName::Exact(name.as_ref().into());
Self { name, scope: PortConnectionScope::One, status: Arc::new(RwLock::new(vec![])) }
}
pub fn regexp (name: impl AsRef<str>) -> Self {
let name = PortConnectionName::RegExp(name.as_ref().into());
Self { name, scope: PortConnectionScope::One, status: Arc::new(RwLock::new(vec![])) }
}
pub fn regexp_all (name: impl AsRef<str>) -> Self {
let name = PortConnectionName::RegExp(name.as_ref().into());
Self { name, scope: PortConnectionScope::All, status: Arc::new(RwLock::new(vec![])) }
}
pub fn info (&self) -> Arc<str> {
format!("{} {} {}", match self.scope {
PortConnectionScope::One => " ",
PortConnectionScope::All => "*",
}, match &self.name {
PortConnectionName::Exact(name) => format!("= {name}"),
PortConnectionName::RegExp(name) => format!("~ {name}"),
}, self.status.read().unwrap().len()).into()
}
}
#[derive(Clone, Debug, PartialEq)]
pub enum PortConnectionName {
/** Exact match */
Exact(Arc<str>),
/** Match regular expression */
RegExp(Arc<str>),
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum PortConnectionScope { One, All }
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum PortConnectionStatus { Missing, Disconnected, Connected, Mismatch, }

View file

@ -1,5 +1,4 @@
use crate::*
/// A [AudioComponent] bound to a JACK client and a set of ports.
pub struct JackDevice<E: Engine> {
/// The active JACK client of this device.
@ -10,7 +9,6 @@ pub struct JackDevice<E: Engine> {
/// The "real" readable/writable `Port`s are owned by the `state`.
pub ports: UnownedJackPorts,
}
impl<E: Engine> std::fmt::Debug for JackDevice<E> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("JackDevice")
@ -18,7 +16,6 @@ impl<E: Engine> std::fmt::Debug for JackDevice<E> {
.finish()
}
}
impl<E: Engine> Render for JackDevice<E> {
type Engine = E;
fn min_size(&self, to: E::Size) -> Perhaps<E::Size> {
@ -28,13 +25,11 @@ impl<E: Engine> Render for JackDevice<E> {
self.state.read().unwrap().render(to)
}
}
impl<E: Engine> Handle<E> for JackDevice<E> {
fn handle(&mut self, from: &E::Input) -> Perhaps<E::Handled> {
self.state.write().unwrap().handle(from)
}
}
impl<E: Engine> Ports for JackDevice<E> {
fn audio_ins(&self) -> Usually<Vec<&Port<Unowned>>> {
Ok(self.ports.audio_ins.values().collect())
@ -49,7 +44,6 @@ impl<E: Engine> Ports for JackDevice<E> {
Ok(self.ports.midi_outs.values().collect())
}
}
impl<E: Engine> JackDevice<E> {
/// Returns a locked mutex of the state's contents.
pub fn state(&self) -> LockResult<RwLockReadGuard<Box<dyn AudioComponent<E>>>> {
@ -84,3 +78,120 @@ impl<E: Engine> JackDevice<E> {
.connect_ports(self.audio_outs()?[index], port)?)
}
}
////////////////////////////////////////////////////////////////////////////////////
///// `JackDevice` factory. Creates JACK `Client`s, performs port registration
///// and activation, and encapsulates a `AudioComponent` into a `JackDevice`.
//pub struct Jack {
//pub client: Client,
//pub midi_ins: Vec<String>,
//pub audio_ins: Vec<String>,
//pub midi_outs: Vec<String>,
//pub audio_outs: Vec<String>,
//}
//impl Jack {
//pub fn new(name: &str) -> Usually<Self> {
//Ok(Self {
//midi_ins: vec![],
//audio_ins: vec![],
//midi_outs: vec![],
//audio_outs: vec![],
//client: Client::new(name, ClientOptions::NO_START_SERVER)?.0,
//})
//}
//pub fn run<'a: 'static, D, E>(
//self,
//state: impl FnOnce(JackPorts) -> Box<D>,
//) -> Usually<JackDevice<E>>
//where
//D: AudioComponent<E> + Sized + 'static,
//E: Engine + 'static,
//{
//let owned_ports = JackPorts {
//audio_ins: register_ports(&self.client, self.audio_ins, AudioIn::default())?,
//audio_outs: register_ports(&self.client, self.audio_outs, AudioOut::default())?,
//midi_ins: register_ports(&self.client, self.midi_ins, MidiIn::default())?,
//midi_outs: register_ports(&self.client, self.midi_outs, MidiOut::default())?,
//};
//let midi_outs = owned_ports
//.midi_outs
//.values()
//.map(|p| Ok(p.name()?))
//.collect::<Usually<Vec<_>>>()?;
//let midi_ins = owned_ports
//.midi_ins
//.values()
//.map(|p| Ok(p.name()?))
//.collect::<Usually<Vec<_>>>()?;
//let audio_outs = owned_ports
//.audio_outs
//.values()
//.map(|p| Ok(p.name()?))
//.collect::<Usually<Vec<_>>>()?;
//let audio_ins = owned_ports
//.audio_ins
//.values()
//.map(|p| Ok(p.name()?))
//.collect::<Usually<Vec<_>>>()?;
//let state = Arc::new(RwLock::new(state(owned_ports) as Box<dyn AudioComponent<E>>));
//let client = self.client.activate_async(
//Notifications(Box::new({
//let _state = state.clone();
//move |_event| {
//// FIXME: this deadlocks
////state.lock().unwrap().handle(&event).unwrap();
//}
//}) as Box<dyn Fn(JackEvent) + Send + Sync>),
//ClosureProcessHandler::new(Box::new({
//let state = state.clone();
//move |c: &Client, s: &ProcessScope| state.write().unwrap().process(c, s)
//}) as BoxedAudioHandler),
//)?;
//Ok(JackDevice {
//ports: UnownedJackPorts {
//audio_ins: query_ports(&client.as_client(), audio_ins),
//audio_outs: query_ports(&client.as_client(), audio_outs),
//midi_ins: query_ports(&client.as_client(), midi_ins),
//midi_outs: query_ports(&client.as_client(), midi_outs),
//},
//client,
//state,
//})
//}
//pub fn audio_in(mut self, name: &str) -> Self {
//self.audio_ins.push(name.to_string());
//self
//}
//pub fn audio_out(mut self, name: &str) -> Self {
//self.audio_outs.push(name.to_string());
//self
//}
//pub fn midi_in(mut self, name: &str) -> Self {
//self.midi_ins.push(name.to_string());
//self
//}
//pub fn midi_out(mut self, name: &str) -> Self {
//self.midi_outs.push(name.to_string());
//self
//}
//}
///// A UI component that may be associated with a JACK client by the `Jack` factory.
//pub trait AudioComponent<E: Engine>: Component<E> + Audio {
///// Perform type erasure for collecting heterogeneous devices.
//fn boxed(self) -> Box<dyn AudioComponent<E>>
//where
//Self: Sized + 'static,
//{
//Box::new(self)
//}
//}
///// All things that implement the required traits can be treated as `AudioComponent`.
//impl<E: Engine, W: Component<E> + Audio> AudioComponent<E> for W {}
/////////
/*
*/

View file

@ -1,5 +1,4 @@
use crate::*;
#[derive(Debug, Clone, PartialEq)]
/// Event enum for JACK events.
pub enum JackEvent {
@ -14,10 +13,8 @@ pub enum JackEvent {
GraphReorder,
XRun,
}
/// Generic notification handler that emits [JackEvent]
pub struct Notifications<T: Fn(JackEvent) + Send>(pub T);
impl<T: Fn(JackEvent) + Send> NotificationHandler for Notifications<T> {
fn thread_init(&self, _: &Client) {
self.0(JackEvent::ThreadInit);

View file

@ -1,185 +1,196 @@
use crate::*;
macro_rules! impl_port {
($Name:ident $Spec:ident |$jack:ident, $name:ident|$port:expr) => {
($Name:ident : $Spec:ident -> $Pair:ident |$jack:ident, $name:ident|$port:expr) => {
#[derive(Debug)] pub struct $Name {
/// Handle to JACK client, for receiving reconnect events.
pub jack: JackClient,
jack: Jack,
/// Port name
pub name: Arc<str>,
name: Arc<str>,
/// Port handle.
pub port: Port<$Spec>,
port: Port<$Spec>,
/// List of ports to connect to.
pub conn: Vec<PortConnection>
conn: Vec<PortConnect>
}
impl AsRef<Port<$Spec>> for $Name { fn as_ref (&self) -> &Port<$Spec> { &self.port } }
impl $Name {
pub fn new ($jack: &JackClient, name: impl AsRef<str>, connect: &[PortConnection])
pub fn name (&self) -> &str { self.name.as_ref() }
pub fn port (&self) -> &Port<$Spec> { &self.port }
pub fn port_mut (&mut self) -> &mut Port<$Spec> { &mut self.port }
pub fn new ($jack: &Jack, name: impl AsRef<str>, connect: &[PortConnect])
-> Usually<Self>
{
let $name = name.as_ref();
let mut port = Self {
jack: $jack.clone(),
port: $port?,
name: $name.into(),
conn: connect.to_vec()
};
let jack = $jack.clone();
let port = $port?;
let name = $name.into();
let conn = connect.to_vec();
let port = Self { jack, port, name, conn };
port.connect_to_matching()?;
Ok(port)
}
}
impl JackPortConnect<$Spec> for $Name {
fn jack (&self) -> &JackClient { &self.jack }
impl HasJack for $Name { fn jack (&self) -> &Jack { &self.jack } }
impl JackPort for $Name {
type Port = $Spec;
type Pair = $Pair;
fn port (&self) -> &Port<$Spec> { &self.port }
fn conn (&self) -> &[PortConnection] { self.conn.as_slice() }
}
impl JackPortConnect<&str> for $Name {
fn connect_to (&self, to: &str) -> Usually<PortConnectStatus> {
self.with_client(|c|if let Some(ref port) = c.port_by_name(to.as_ref()) {
self.connect_to(port)
} else {
Ok(Missing)
})
}
}
impl JackPortConnect<&Port<Unowned>> for $Name {
fn connect_to (&self, port: &Port<Unowned>) -> Usually<PortConnectStatus> {
self.with_client(|c|Ok(if let Ok(_) = c.connect_ports(&self.port, port) {
Connected
} else if let Ok(_) = c.connect_ports(port, &self.port) {
Connected
} else {
Mismatch
}))
}
}
impl JackPortConnect<&Port<$Pair>> for $Name {
fn connect_to (&self, port: &Port<$Pair>) -> Usually<PortConnectStatus> {
self.with_client(|c|Ok(if let Ok(_) = c.connect_ports(&self.port, port) {
Connected
} else if let Ok(_) = c.connect_ports(port, &self.port) {
Connected
} else {
Mismatch
}))
}
}
impl JackPortAutoconnect for $Name {
fn conn (&self) -> &[PortConnect] {
&self.conn
}
}
};
}
impl_port! { JackAudioIn AudioIn |jack, name|jack.audio_in(name) }
impl_port! { JackAudioOut AudioOut |jack, name|jack.audio_out(name) }
impl_port! { JackMidiIn MidiIn |jack, name|jack.midi_in(name) }
impl_port! { JackMidiOut MidiOut |jack, name|jack.midi_out(name) }
/// This is a utility trait for things that may register or connect [Port]s.
/// It contains shorthand methods to this purpose. It's implemented for
/// `Arc<RwLock<JackClient>>` for terse port registration in the
/// `init` callback of [jack::Client::activate_with].
pub trait RegisterPort {
fn midi_in (&self, name: impl AsRef<str>) -> Usually<Port<MidiIn>>;
fn midi_out (&self, name: impl AsRef<str>) -> Usually<Port<MidiOut>>;
fn audio_in (&self, name: impl AsRef<str>) -> Usually<Port<AudioIn>>;
fn audio_out (&self, name: impl AsRef<str>) -> Usually<Port<AudioOut>>;
impl_port!(JackAudioIn: AudioIn -> AudioOut |j, n|j.register_port::<AudioIn>(n));
impl_port!(JackAudioOut: AudioOut -> AudioIn |j, n|j.register_port::<AudioOut>(n));
impl_port!(JackMidiIn: MidiIn -> MidiOut |j, n|j.register_port::<MidiIn>(n));
impl_port!(JackMidiOut: MidiOut -> MidiIn |j, n|j.register_port::<MidiOut>(n));
pub trait JackPort: HasJack {
type Port: PortSpec;
type Pair: PortSpec;
fn port (&self) -> &Port<Self::Port>;
}
impl<T: RegisterPort> RegisterPort for Arc<RwLock<T>> {
fn midi_in (&self, name: impl AsRef<str>) -> Usually<Port<MidiIn>> {
self.read().unwrap().midi_in(name)
}
fn midi_out (&self, name: impl AsRef<str>) -> Usually<Port<MidiOut>> {
self.read().unwrap().midi_out(name)
}
fn audio_in (&self, name: impl AsRef<str>) -> Usually<Port<AudioIn>> {
self.read().unwrap().audio_in(name)
}
fn audio_out (&self, name: impl AsRef<str>) -> Usually<Port<AudioOut>> {
self.read().unwrap().audio_out(name)
}
pub trait JackPortConnect<T>: JackPort {
fn connect_to (&self, to: T) -> Usually<PortConnectStatus>;
}
///// Collection of JACK ports as [AudioIn]/[AudioOut]/[MidiIn]/[MidiOut].
//#[derive(Default, Debug)]
//pub struct JackPorts {
//pub audio_ins: BTreeMap<String, Port<AudioIn>>,
//pub midi_ins: BTreeMap<String, Port<MidiIn>>,
//pub audio_outs: BTreeMap<String, Port<AudioOut>>,
//pub midi_outs: BTreeMap<String, Port<MidiOut>>,
//}
///// Collection of JACK ports as [Unowned].
//#[derive(Default, Debug)]
//pub struct UnownedJackPorts {
//pub audio_ins: BTreeMap<String, Port<Unowned>>,
//pub midi_ins: BTreeMap<String, Port<Unowned>>,
//pub audio_outs: BTreeMap<String, Port<Unowned>>,
//pub midi_outs: BTreeMap<String, Port<Unowned>>,
//}
//impl JackPorts {
//pub fn clone_unowned(&self) -> UnownedJackPorts {
//let mut unowned = UnownedJackPorts::default();
//for (name, port) in self.midi_ins.iter() {
//unowned.midi_ins.insert(name.clone(), port.clone_unowned());
//}
//for (name, port) in self.midi_outs.iter() {
//unowned.midi_outs.insert(name.clone(), port.clone_unowned());
//}
//for (name, port) in self.audio_ins.iter() {
//unowned.audio_ins.insert(name.clone(), port.clone_unowned());
//}
//for (name, port) in self.audio_outs.iter() {
//unowned
//.audio_outs
//.insert(name.clone(), port.clone_unowned());
//}
//unowned
//}
//}
///// Implement the `Ports` trait.
//#[macro_export]
//macro_rules! ports {
//($T:ty $({ $(audio: {
//$(ins: |$ai_arg:ident|$ai_impl:expr,)?
//$(outs: |$ao_arg:ident|$ao_impl:expr,)?
//})? $(midi: {
//$(ins: |$mi_arg:ident|$mi_impl:expr,)?
//$(outs: |$mo_arg:ident|$mo_impl:expr,)?
//})?})?) => {
//impl Ports for $T {$(
//$(
//$(fn audio_ins <'a> (&'a self) -> Usually<Vec<&'a Port<Unowned>>> {
//let cb = |$ai_arg:&'a Self|$ai_impl;
//cb(self)
//})?
//)?
//$(
//$(fn audio_outs <'a> (&'a self) -> Usually<Vec<&'a Port<Unowned>>> {
//let cb = (|$ao_arg:&'a Self|$ao_impl);
//cb(self)
//})?
//)?
//)? $(
//$(
//$(fn midi_ins <'a> (&'a self) -> Usually<Vec<&'a Port<Unowned>>> {
//let cb = (|$mi_arg:&'a Self|$mi_impl);
//cb(self)
//})?
//)?
//$(
//$(fn midi_outs <'a> (&'a self) -> Usually<Vec<&'a Port<Unowned>>> {
//let cb = (|$mo_arg:&'a Self|$mo_impl);
//cb(self)
//})?
//)?
//)?}
//};
//}
/// Trait for things that may expose JACK ports.
pub trait Ports {
fn audio_ins(&self) -> Usually<Vec<&Port<Unowned>>> {
Ok(vec![])
pub trait JackPortAutoconnect: JackPort + for<'a>JackPortConnect<&'a Port<Unowned>> {
fn conn (&self) -> &[PortConnect];
fn ports (&self, re_name: Option<&str>, re_type: Option<&str>, flags: PortFlags) -> Vec<String> {
self.with_client(|c|c.ports(re_name, re_type, flags))
}
fn audio_outs(&self) -> Usually<Vec<&Port<Unowned>>> {
Ok(vec![])
fn port_by_name (&self, name: impl AsRef<str>) -> Option<Port<Unowned>> {
self.with_client(|c|c.port_by_name(name.as_ref()))
}
fn midi_ins(&self) -> Usually<Vec<&Port<Unowned>>> {
Ok(vec![])
fn connect_to_matching (&self) -> Usually<()> {
for connect in self.conn().iter() {
let status = match &connect.name {
Exact(name) => self.connect_exact(name),
RegExp(re) => self.connect_regexp(re),
}?;
*connect.status.write().unwrap() = status;
}
Ok(())
}
fn midi_outs(&self) -> Usually<Vec<&Port<Unowned>>> {
Ok(vec![])
}
}
fn register_ports<T: PortSpec + Copy>(
client: &Client,
names: Vec<String>,
spec: T,
) -> Usually<BTreeMap<String, Port<T>>> {
names
.into_iter()
.try_fold(BTreeMap::new(), |mut ports, name| {
let port = client.register_port(&name, spec)?;
ports.insert(name, port);
Ok(ports)
fn connect_exact (&self, name: &str) -> Usually<Vec<(Port<Unowned>, Arc<str>, PortConnectStatus)>> {
self.with_client(|c|{
let mut status = vec![];
for port in c.ports(None, None, PortFlags::empty()).iter() {
if port.as_str() == &*name {
if let Some(port) = c.port_by_name(port.as_str()) {
let port_status = self.connect_to(&port)?;
let name = port.name()?.into();
status.push((port, name, port_status));
if port_status == Connected {
break
}
}
}
}
Ok(status)
})
}
fn connect_regexp (&self, re: &str) -> Usually<Vec<(Port<Unowned>, Arc<str>, PortConnectStatus)>> {
self.with_client(|c|{
let mut status = vec![];
for port in c.ports(Some(&re), None, PortFlags::empty()).iter() {
if let Some(port) = c.port_by_name(port.as_str()) {
let port_status = self.connect_to(&port)?;
let name = port.name()?.into();
status.push((port, name, port_status));
// TODO
//if port_status == Connected && connect.scope == One {
//break
//}
}
}
Ok(status)
})
}
}
fn query_ports(client: &Client, names: Vec<String>) -> BTreeMap<String, Port<Unowned>> {
names.into_iter().fold(BTreeMap::new(), |mut ports, name| {
let port = client.port_by_name(&name).unwrap();
ports.insert(name, port);
ports
})
#[derive(Clone, Debug, PartialEq)]
pub enum PortConnectName {
/** Exact match */
Exact(Arc<str>),
/** Match regular expression */
RegExp(Arc<str>),
}
#[derive(Clone, Copy, Debug, PartialEq)] pub enum PortConnectScope {
One,
All
}
#[derive(Clone, Copy, Debug, PartialEq)] pub enum PortConnectStatus {
Missing,
Disconnected,
Connected,
Mismatch,
}
#[derive(Clone, Debug)] pub struct PortConnect {
pub name: PortConnectName,
pub scope: PortConnectScope,
pub status: Arc<RwLock<Vec<(Port<Unowned>, Arc<str>, PortConnectStatus)>>>,
}
impl PortConnect {
pub fn collect (exact: &[impl AsRef<str>], re: &[impl AsRef<str>], re_all: &[impl AsRef<str>])
-> Vec<Self>
{
let mut connections = vec![];
for port in exact.iter() { connections.push(Self::exact(port)) }
for port in re.iter() { connections.push(Self::regexp(port)) }
for port in re_all.iter() { connections.push(Self::regexp_all(port)) }
connections
}
/// Connect to this exact port
pub fn exact (name: impl AsRef<str>) -> Self {
let name = Exact(name.as_ref().into());
Self { name, scope: One, status: Arc::new(RwLock::new(vec![])) }
}
pub fn regexp (name: impl AsRef<str>) -> Self {
let name = RegExp(name.as_ref().into());
Self { name, scope: One, status: Arc::new(RwLock::new(vec![])) }
}
pub fn regexp_all (name: impl AsRef<str>) -> Self {
let name = RegExp(name.as_ref().into());
Self { name, scope: All, status: Arc::new(RwLock::new(vec![])) }
}
pub fn info (&self) -> Arc<str> {
format!("{} {} {}", match self.scope {
One => " ",
All => "*",
}, match &self.name {
Exact(name) => format!("= {name}"),
RegExp(name) => format!("~ {name}"),
}, self.status.read().unwrap().len()).into()
}
}

View file

@ -1,20 +0,0 @@
use crate::*;
use jack::contrib::*;
pub trait SyncToTransport {
fn client (&self) -> Client;
fn sync_lead (&self, enable: bool, cb: impl Fn(TimebaseInfo)->Position) -> Usually<()> {
if enable {
self.client().register_timebase_callback(false, cb)?;
}
Ok(())
}
fn sync_follow (&self, enable: bool) -> Usually<()> {
// TODO: sync follow
Ok(())
}
}
impl SyncToTransport for JackClient {
fn client (&self) -> Client { self.inner() }
}

View file

@ -1,15 +1,11 @@
#![feature(type_alias_impl_trait)]
mod has_jack; pub use self::has_jack::*;
mod jack_audio; pub use self::jack_audio::*;
mod jack_connect; pub use self::jack_connect::*;
mod jack_client; pub use self::jack_client::*;
mod jack_event; pub use self::jack_event::*;
mod jack_port; pub use self::jack_port::*;
mod jack_sync; pub use self::jack_sync::*;
mod jack_client; pub use self::jack_client::*;
mod jack_event; pub use self::jack_event::*;
mod jack_port; pub use self::jack_port::*;
pub(crate) use PortConnectName::*;
pub(crate) use PortConnectScope::*;
pub(crate) use PortConnectStatus::*;
pub(crate) use std::sync::{Arc, RwLock};
pub(crate) use std::collections::BTreeMap;
pub use ::jack; pub(crate) use ::jack::{
contrib::ClosureProcessHandler, NotificationHandler,
Client, AsyncClient, ClientOptions, ClientStatus,
@ -17,123 +13,4 @@ pub use ::jack; pub(crate) use ::jack::{
Port, PortId, PortSpec, PortFlags,
Unowned, MidiIn, MidiOut, AudioIn, AudioOut,
};
pub(crate) type Usually<T> = Result<T, Box<dyn std::error::Error>>;
////////////////////////////////////////////////////////////////////////////////////
///// `JackDevice` factory. Creates JACK `Client`s, performs port registration
///// and activation, and encapsulates a `AudioComponent` into a `JackDevice`.
//pub struct Jack {
//pub client: Client,
//pub midi_ins: Vec<String>,
//pub audio_ins: Vec<String>,
//pub midi_outs: Vec<String>,
//pub audio_outs: Vec<String>,
//}
//impl Jack {
//pub fn new(name: &str) -> Usually<Self> {
//Ok(Self {
//midi_ins: vec![],
//audio_ins: vec![],
//midi_outs: vec![],
//audio_outs: vec![],
//client: Client::new(name, ClientOptions::NO_START_SERVER)?.0,
//})
//}
//pub fn run<'a: 'static, D, E>(
//self,
//state: impl FnOnce(JackPorts) -> Box<D>,
//) -> Usually<JackDevice<E>>
//where
//D: AudioComponent<E> + Sized + 'static,
//E: Engine + 'static,
//{
//let owned_ports = JackPorts {
//audio_ins: register_ports(&self.client, self.audio_ins, AudioIn::default())?,
//audio_outs: register_ports(&self.client, self.audio_outs, AudioOut::default())?,
//midi_ins: register_ports(&self.client, self.midi_ins, MidiIn::default())?,
//midi_outs: register_ports(&self.client, self.midi_outs, MidiOut::default())?,
//};
//let midi_outs = owned_ports
//.midi_outs
//.values()
//.map(|p| Ok(p.name()?))
//.collect::<Usually<Vec<_>>>()?;
//let midi_ins = owned_ports
//.midi_ins
//.values()
//.map(|p| Ok(p.name()?))
//.collect::<Usually<Vec<_>>>()?;
//let audio_outs = owned_ports
//.audio_outs
//.values()
//.map(|p| Ok(p.name()?))
//.collect::<Usually<Vec<_>>>()?;
//let audio_ins = owned_ports
//.audio_ins
//.values()
//.map(|p| Ok(p.name()?))
//.collect::<Usually<Vec<_>>>()?;
//let state = Arc::new(RwLock::new(state(owned_ports) as Box<dyn AudioComponent<E>>));
//let client = self.client.activate_async(
//Notifications(Box::new({
//let _state = state.clone();
//move |_event| {
//// FIXME: this deadlocks
////state.lock().unwrap().handle(&event).unwrap();
//}
//}) as Box<dyn Fn(JackEvent) + Send + Sync>),
//ClosureProcessHandler::new(Box::new({
//let state = state.clone();
//move |c: &Client, s: &ProcessScope| state.write().unwrap().process(c, s)
//}) as BoxedAudioHandler),
//)?;
//Ok(JackDevice {
//ports: UnownedJackPorts {
//audio_ins: query_ports(&client.as_client(), audio_ins),
//audio_outs: query_ports(&client.as_client(), audio_outs),
//midi_ins: query_ports(&client.as_client(), midi_ins),
//midi_outs: query_ports(&client.as_client(), midi_outs),
//},
//client,
//state,
//})
//}
//pub fn audio_in(mut self, name: &str) -> Self {
//self.audio_ins.push(name.to_string());
//self
//}
//pub fn audio_out(mut self, name: &str) -> Self {
//self.audio_outs.push(name.to_string());
//self
//}
//pub fn midi_in(mut self, name: &str) -> Self {
//self.midi_ins.push(name.to_string());
//self
//}
//pub fn midi_out(mut self, name: &str) -> Self {
//self.midi_outs.push(name.to_string());
//self
//}
//}
///// A UI component that may be associated with a JACK client by the `Jack` factory.
//pub trait AudioComponent<E: Engine>: Component<E> + Audio {
///// Perform type erasure for collecting heterogeneous devices.
//fn boxed(self) -> Box<dyn AudioComponent<E>>
//where
//Self: Sized + 'static,
//{
//Box::new(self)
//}
//}
///// All things that implement the required traits can be treated as `AudioComponent`.
//impl<E: Engine, W: Component<E> + Audio> AudioComponent<E> for W {}
/////////
/*
*/