mirror of
https://codeberg.org/unspeaker/tek.git
synced 2025-12-06 11:46:41 +01:00
refactor jack ports again
This commit is contained in:
parent
c13eff95ca
commit
6c8f85ab84
16 changed files with 558 additions and 609 deletions
|
|
@ -1,24 +1,11 @@
|
|||
use crate::*;
|
||||
|
||||
pub trait HasJack {
|
||||
fn jack (&self) -> &Arc<RwLock<JackConnection>>;
|
||||
}
|
||||
|
||||
/// 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) -> &Arc<RwLock<JackConnection>> { $cb }
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/// Implement [TryFrom<&Arc<RwLock<JackConnection>>>]: create app state from wrapped JACK handle.
|
||||
#[macro_export] macro_rules! from_jack {
|
||||
(|$jack:ident|$Struct:ident$(<$($L:lifetime),*$($T:ident$(:$U:path)?),*>)? $cb:expr) => {
|
||||
impl $(<$($L),*$($T $(: $U)?),*>)? TryFrom<&Arc<RwLock<JackConnection>>> for $Struct $(<$($L),*$($T),*>)? {
|
||||
type Error = Box<dyn std::error::Error>;
|
||||
fn try_from ($jack: &Arc<RwLock<JackConnection>>) -> Usually<Self> { Ok($cb) }
|
||||
fn jack (&$self) -> &JackClient { $cb }
|
||||
}
|
||||
};
|
||||
}
|
||||
|
|
|
|||
150
jack/src/jack_client.rs
Normal file
150
jack/src/jack_client.rs
Normal file
|
|
@ -0,0 +1,150 @@
|
|||
use crate::*;
|
||||
use self::JackClientState::*;
|
||||
|
||||
/// Wraps [JackClientState] and through it [jack::Client].
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct JackClient {
|
||||
state: Arc<RwLock<JackClientState>>
|
||||
}
|
||||
impl JackClient {
|
||||
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))) })
|
||||
}
|
||||
/// 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)?)
|
||||
}
|
||||
}
|
||||
/// This is a connection which may be [Inactive], [Activating], or [Active].
|
||||
/// In the [Active] and [Inactive] states, [JackClientState::client] returns a
|
||||
/// [jack::Client], which you can use to talk to the JACK API.
|
||||
#[derive(Debug, Default)] enum JackClientState {
|
||||
/// Unused
|
||||
#[default] Inert,
|
||||
/// Before activation.
|
||||
Inactive(Client),
|
||||
/// During activation.
|
||||
Activating,
|
||||
/// 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()) },
|
||||
}
|
||||
}
|
||||
}
|
||||
/// This is a boxed realtime callback.
|
||||
pub type BoxedAudioHandler<'j> =
|
||||
Box<dyn FnMut(&Client, &ProcessScope) -> Control + Send + 'j>;
|
||||
/// This is the notification handler wrapper for a boxed realtime callback.
|
||||
pub type DynamicAudioHandler<'j> =
|
||||
ClosureProcessHandler<(), BoxedAudioHandler<'j>>;
|
||||
/// This is a boxed [JackEvent] callback.
|
||||
pub type BoxedJackEventHandler<'j> =
|
||||
Box<dyn Fn(JackEvent) + Send + Sync + 'j>;
|
||||
/// This is the notification handler wrapper for a boxed [JackEvent] callback.
|
||||
pub type DynamicNotifications<'j> =
|
||||
Notifications<BoxedJackEventHandler<'j>>;
|
||||
/// 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<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())?)
|
||||
}
|
||||
}
|
||||
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)
|
||||
}
|
||||
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)?)
|
||||
}
|
||||
}
|
||||
|
|
@ -1,136 +1,165 @@
|
|||
use crate::*;
|
||||
|
||||
/// This is a boxed realtime callback.
|
||||
pub type BoxedAudioHandler = Box<dyn FnMut(&Client, &ProcessScope) -> Control + Send>;
|
||||
|
||||
/// This is the notification handler wrapper for a boxed realtime callback.
|
||||
pub type DynamicAudioHandler = ClosureProcessHandler<(), BoxedAudioHandler>;
|
||||
|
||||
/// This is a boxed [JackEvent] callback.
|
||||
pub type BoxedJackEventHandler = Box<dyn Fn(JackEvent) + Send + Sync>;
|
||||
|
||||
/// This is the notification handler wrapper for a boxed [JackEvent] callback.
|
||||
pub type DynamicNotifications = Notifications<BoxedJackEventHandler>;
|
||||
|
||||
/// 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 = AsyncClient<DynamicNotifications, DynamicAudioHandler>;
|
||||
|
||||
/// This is a connection which may be `Inactive`, `Activating`, or `Active`.
|
||||
/// In the `Active` and `Inactive` states, its `client` method returns a
|
||||
/// [Client] which you can use to talk to the JACK API.
|
||||
#[derive(Debug, Default)]
|
||||
pub enum JackConnection {
|
||||
#[default]
|
||||
Inert,
|
||||
/// Before activation.
|
||||
Inactive(Client),
|
||||
/// During activation.
|
||||
Activating,
|
||||
/// After activation. Must not be dropped for JACK thread to persist.
|
||||
Active(DynamicAsyncClient),
|
||||
}
|
||||
|
||||
impl From<JackConnection> for Client {
|
||||
fn from (jack: JackConnection) -> Self {
|
||||
match jack {
|
||||
JackConnection::Inactive(client) => client,
|
||||
JackConnection::Inert => panic!("jack client not activated"),
|
||||
JackConnection::Activating => panic!("jack client still activating"),
|
||||
JackConnection::Active(_) => panic!("jack client already activated"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl JackConnection {
|
||||
pub fn new (name: &str) -> Usually<Self> {
|
||||
let (client, _) = Client::new(name, ClientOptions::NO_START_SERVER)?;
|
||||
Ok(Self::Inactive(client))
|
||||
}
|
||||
/// Return the internal [Client] handle that lets you call the JACK API.
|
||||
pub fn client (&self) -> &Client {
|
||||
match self {
|
||||
Self::Inert => panic!("jack client not activated"),
|
||||
Self::Inactive(ref client) => client,
|
||||
Self::Activating => panic!("jack client has not finished activation"),
|
||||
Self::Active(ref client) => client.as_client(),
|
||||
}
|
||||
}
|
||||
/// Activate a connection with an application.
|
||||
///
|
||||
/// Consume a `JackConnection::Inactive`,
|
||||
/// binding a process callback and
|
||||
/// returning a `JackConnection::Active`.
|
||||
///
|
||||
/// Needs work. Strange ownership situation between the callback
|
||||
/// and the host object.
|
||||
fn activate (
|
||||
self,
|
||||
mut cb: impl FnMut(&Arc<RwLock<Self>>, &Client, &ProcessScope) -> Control + Send + 'static,
|
||||
) -> Usually<Arc<RwLock<Self>>>
|
||||
where
|
||||
Self: Send + Sync + 'static
|
||||
{
|
||||
let client = Client::from(self);
|
||||
let state = Arc::new(RwLock::new(Self::Activating));
|
||||
let event = Box::new(move|_|{/*TODO*/}) as Box<dyn Fn(JackEvent) + Send + Sync>;
|
||||
let events = Notifications(event);
|
||||
let frame = Box::new({let state = state.clone(); move|c: &_, s: &_|cb(&state, c, s)});
|
||||
let frames = ClosureProcessHandler::new(frame as BoxedAudioHandler);
|
||||
*state.write().unwrap() = Self::Active(client.activate_async(events, frames)?);
|
||||
Ok(state)
|
||||
}
|
||||
/// Activate a connection with an application.
|
||||
///
|
||||
/// * Wrap a [JackConnection::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<JackConnection>>] that is
|
||||
/// passed to `init`, the audio engine is running.
|
||||
pub fn activate_with <T: Audio + 'static> (
|
||||
self,
|
||||
init: impl FnOnce(&Arc<RwLock<JackConnection>>)->Usually<T>
|
||||
)
|
||||
-> Usually<Arc<RwLock<T>>>
|
||||
{
|
||||
// Wrap self for multiple ownership.
|
||||
let connection = Arc::new(RwLock::new(self));
|
||||
// Run init callback. Return value is target. Target must retain clone of `connection`.
|
||||
let target = Arc::new(RwLock::new(init(&connection)?));
|
||||
// Swap the `client` from the `JackConnection::Inactive`
|
||||
// for a `JackConnection::Activating`.
|
||||
let mut client = Self::Activating;
|
||||
std::mem::swap(&mut*connection.write().unwrap(), &mut client);
|
||||
// Replace the `JackConnection::Activating` with a
|
||||
// `JackConnection::Active` wrapping the [AsyncClient]
|
||||
// returned by the activation.
|
||||
*connection.write().unwrap() = Self::Active(Client::from(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 `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
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
}) as BoxedAudioHandler),
|
||||
)?);
|
||||
Ok(target)
|
||||
}
|
||||
*connect.status.write().unwrap() = status
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
pub fn port_by_name (&self, name: &str) -> Option<Port<Unowned>> {
|
||||
self.client().port_by_name(name)
|
||||
}
|
||||
pub fn register_port <PS: PortSpec> (&self, name: &str, spec: PS) -> Usually<Port<PS>> {
|
||||
Ok(self.client().register_port(name, spec)?)
|
||||
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, }
|
||||
|
|
|
|||
|
|
@ -1,279 +1,56 @@
|
|||
use crate::*;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct JackPort<T: PortSpec> {
|
||||
/// Handle to JACK client, for receiving reconnect events.
|
||||
pub jack: Arc<RwLock<JackConnection>>,
|
||||
/// Port name
|
||||
pub name: Arc<str>,
|
||||
/// Port handle.
|
||||
pub port: Port<T>,
|
||||
/// List of ports to connect to.
|
||||
pub connect: Vec<PortConnection>
|
||||
}
|
||||
impl<T: PortSpec> JackPort<T> {
|
||||
pub fn connect_to_matching (&mut self) -> Usually<()> {
|
||||
use PortConnectionName::*;
|
||||
use PortConnectionScope::*;
|
||||
use PortConnectionStatus::*;
|
||||
for connect in self.connect.iter_mut() {
|
||||
let mut status = vec![];
|
||||
match &connect.name {
|
||||
Exact(name) => for port in self.jack.ports(None, None, PortFlags::empty()).iter() {
|
||||
if port.as_str() == &**name {
|
||||
if let Some(port) = self.jack.port_by_name(port.as_str()) {
|
||||
let port_status = Self::try_both_ways(&self.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 self.jack.ports(Some(&re), None, PortFlags::empty()).iter() {
|
||||
if let Some(port) = self.jack.port_by_name(port.as_str()) {
|
||||
let port_status = Self::try_both_ways(&self.jack, &port, &self.port);
|
||||
let name = port.name()?.into();
|
||||
status.push((port, name, port_status));
|
||||
if port_status == Connected && connect.scope == One {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
macro_rules! impl_port {
|
||||
($Name:ident $Spec:ident |$jack:ident, $name:ident|$port:expr) => {
|
||||
#[derive(Debug)] pub struct $Name {
|
||||
/// Handle to JACK client, for receiving reconnect events.
|
||||
pub jack: JackClient,
|
||||
/// Port name
|
||||
pub name: Arc<str>,
|
||||
/// Port handle.
|
||||
pub port: Port<$Spec>,
|
||||
/// List of ports to connect to.
|
||||
pub conn: Vec<PortConnection>
|
||||
}
|
||||
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])
|
||||
-> Usually<Self>
|
||||
{
|
||||
let $name = name.as_ref();
|
||||
let mut port = Self {
|
||||
jack: $jack.clone(),
|
||||
port: $port?,
|
||||
name: $name.into(),
|
||||
conn: connect.to_vec()
|
||||
};
|
||||
port.connect_to_matching()?;
|
||||
Ok(port)
|
||||
}
|
||||
connect.status = status
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn try_both_ways <A: PortSpec, B: PortSpec> (
|
||||
jack: &impl ConnectPort, port_a: &Port<A>, port_b: &Port<B>
|
||||
)
|
||||
-> PortConnectionStatus
|
||||
{
|
||||
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
|
||||
impl JackPortConnect<$Spec> for $Name {
|
||||
fn jack (&self) -> &JackClient { &self.jack }
|
||||
fn port (&self) -> &Port<$Spec> { &self.port }
|
||||
fn conn (&self) -> &[PortConnection] { self.conn.as_slice() }
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct PortConnection {
|
||||
pub name: PortConnectionName,
|
||||
pub scope: PortConnectionScope,
|
||||
pub status: Vec<(Port<Unowned>, Arc<str>, PortConnectionStatus)>,
|
||||
}
|
||||
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: vec![] }
|
||||
}
|
||||
pub fn regexp (name: impl AsRef<str>) -> Self {
|
||||
let name = PortConnectionName::RegExp(name.as_ref().into());
|
||||
Self { name, scope: PortConnectionScope::One, status: vec![] }
|
||||
}
|
||||
pub fn regexp_all (name: impl AsRef<str>) -> Self {
|
||||
let name = PortConnectionName::RegExp(name.as_ref().into());
|
||||
Self { name, scope: PortConnectionScope::All, status: 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.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, }
|
||||
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) }
|
||||
|
||||
impl<T: PortSpec> AsRef<Port<T>> for JackPort<T> {
|
||||
fn as_ref (&self) -> &Port<T> {
|
||||
&self.port
|
||||
}
|
||||
}
|
||||
impl JackPort<MidiIn> {
|
||||
pub fn new (
|
||||
jack: &Arc<RwLock<JackConnection>>, name: impl AsRef<str>, connect: &[PortConnection]
|
||||
) -> Usually<Self> {
|
||||
let mut port = JackPort {
|
||||
jack: jack.clone(),
|
||||
port: jack.midi_in(name.as_ref())?,
|
||||
name: name.as_ref().into(),
|
||||
connect: connect.to_vec()
|
||||
};
|
||||
port.connect_to_matching()?;
|
||||
Ok(port)
|
||||
}
|
||||
}
|
||||
impl JackPort<MidiOut> {
|
||||
pub fn new (
|
||||
jack: &Arc<RwLock<JackConnection>>, name: impl AsRef<str>, connect: &[PortConnection]
|
||||
) -> Usually<Self> {
|
||||
let mut port = Self {
|
||||
jack: jack.clone(),
|
||||
port: jack.midi_out(name.as_ref())?,
|
||||
name: name.as_ref().into(),
|
||||
connect: connect.to_vec()
|
||||
};
|
||||
port.connect_to_matching()?;
|
||||
Ok(port)
|
||||
}
|
||||
}
|
||||
impl JackPort<AudioIn> {
|
||||
pub fn new (
|
||||
jack: &Arc<RwLock<JackConnection>>, name: impl AsRef<str>, connect: &[PortConnection]
|
||||
) -> Usually<Self> {
|
||||
let mut port = Self {
|
||||
jack: jack.clone(),
|
||||
port: jack.audio_in(name.as_ref())?,
|
||||
name: name.as_ref().into(),
|
||||
connect: connect.to_vec()
|
||||
};
|
||||
port.connect_to_matching()?;
|
||||
Ok(port)
|
||||
}
|
||||
}
|
||||
impl JackPort<AudioOut> {
|
||||
pub fn new (
|
||||
jack: &Arc<RwLock<JackConnection>>, name: impl AsRef<str>, connect: &[PortConnection]
|
||||
) -> Usually<Self> {
|
||||
let mut port = Self {
|
||||
jack: jack.clone(),
|
||||
port: jack.audio_out(name.as_ref())?,
|
||||
name: name.as_ref().into(),
|
||||
connect: connect.to_vec()
|
||||
};
|
||||
port.connect_to_matching()?;
|
||||
Ok(port)
|
||||
}
|
||||
}
|
||||
|
||||
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 ConnectPort for JackConnection {
|
||||
fn ports (&self, re_name: Option<&str>, re_type: Option<&str>, flags: PortFlags) -> Vec<String> {
|
||||
self.client().ports(re_name, re_type, flags)
|
||||
}
|
||||
fn port_by_name (&self, name: impl AsRef<str>) -> Option<Port<Unowned>> {
|
||||
self.client().port_by_name(name.as_ref())
|
||||
}
|
||||
fn connect_ports <A: PortSpec, B: PortSpec> (&self, source: &Port<A>, target: &Port<B>)
|
||||
-> Usually<()>
|
||||
{
|
||||
Ok(self.client().connect_ports(source, target)?)
|
||||
}
|
||||
}
|
||||
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)?)
|
||||
}
|
||||
}
|
||||
|
||||
/// 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<JackConnection>>` for terse port registration in the
|
||||
/// `init` callback of [JackClient::activate_with].
|
||||
/// `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 RegisterPort for JackConnection {
|
||||
fn midi_in (&self, name: impl AsRef<str>) -> Usually<Port<MidiIn>> {
|
||||
Ok(self.client().register_port(name.as_ref(), MidiIn::default())?)
|
||||
}
|
||||
fn midi_out (&self, name: impl AsRef<str>) -> Usually<Port<MidiOut>> {
|
||||
Ok(self.client().register_port(name.as_ref(), MidiOut::default())?)
|
||||
}
|
||||
fn audio_in (&self, name: impl AsRef<str>) -> Usually<Port<AudioIn>> {
|
||||
Ok(self.client().register_port(name.as_ref(), AudioIn::default())?)
|
||||
}
|
||||
fn audio_out (&self, name: impl AsRef<str>) -> Usually<Port<AudioOut>> {
|
||||
Ok(self.client().register_port(name.as_ref(), AudioOut::default())?)
|
||||
}
|
||||
}
|
||||
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)
|
||||
|
|
|
|||
20
jack/src/jack_sync.rs
Normal file
20
jack/src/jack_sync.rs
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
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() }
|
||||
}
|
||||
|
|
@ -1,8 +1,16 @@
|
|||
#![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::*;
|
||||
|
||||
pub(crate) use std::sync::{Arc, RwLock};
|
||||
pub(crate) use std::collections::BTreeMap;
|
||||
|
||||
pub use ::jack;
|
||||
pub(crate) use ::jack::{
|
||||
pub use ::jack; pub(crate) use ::jack::{
|
||||
contrib::ClosureProcessHandler, NotificationHandler,
|
||||
Client, AsyncClient, ClientOptions, ClientStatus,
|
||||
ProcessScope, Control, Frames,
|
||||
|
|
@ -10,12 +18,6 @@ pub(crate) use ::jack::{
|
|||
Unowned, MidiIn, MidiOut, AudioIn, AudioOut,
|
||||
};
|
||||
|
||||
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_event; pub use self::jack_event::*;
|
||||
mod jack_port; pub use self::jack_port::*;
|
||||
|
||||
pub(crate) type Usually<T> = Result<T, Box<dyn std::error::Error>>;
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////////
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue