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,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()
}
}