move all port connections to constructors (port: impl AsRef<str>)

This commit is contained in:
🪞👃🪞 2024-12-29 20:15:12 +01:00
parent e8b97bed37
commit 6607491f16
9 changed files with 215 additions and 129 deletions

View file

@ -45,13 +45,27 @@ pub trait Audio: Send + Sync {
}
}
pub type DynamicAsyncClient = AsyncClient<DynamicNotifications, DynamicAudioHandler>;
/// This is a boxed realtime callback.
pub type BoxedAudioHandler = Box<dyn FnMut(&Client, &ProcessScope) -> Control + Send>;
pub type DynamicAudioHandler = ClosureProcessHandler<(), BoxedAudioHandler>;
/// This is the notification handler wrapper for a boxed realtime callback.
pub type DynamicAudioHandler = ClosureProcessHandler<(), BoxedAudioHandler>;
pub type BoxedAudioHandler = Box<dyn FnMut(&Client, &ProcessScope) -> Control + Send>;
/// This is a boxed [JackEvent] callback.
pub type BoxedJackEventHandler = Box<dyn Fn(JackEvent) + Send + Sync>;
/// Wraps [Client] or [DynamicAsyncClient] in place.
/// 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)]
pub enum JackConnection {
/// Before activation.
@ -81,8 +95,11 @@ impl JackConnection {
Self::Active(ref client) => client.as_client(),
}
}
/// Bind a process callback to a `JackConnection::Inactive`,
/// consuming it and returning a `JackConnection::Active`.
/// 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.
@ -102,33 +119,48 @@ impl JackConnection {
*state.write().unwrap() = Self::Active(client.activate_async(events, frames)?);
Ok(state)
}
/// Consume a `JackConnection::Inactive`, activate a client,
/// initialize an app around it with the `init` callback,
/// then return the result of it all.
/// 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>>>
{
let client = Arc::new(RwLock::new(self));
let target = Arc::new(RwLock::new(init(&client)?));
let event = Box::new(move|_|{/*TODO*/}) as Box<dyn Fn(JackEvent) + Send + Sync>;
let events = Notifications(event);
let frame = Box::new({
let target = target.clone();
move|c: &_, s: &_|if let Ok(mut target) = target.write() {
target.process(c, s)
} else {
Control::Quit
}
});
let frames = ClosureProcessHandler::new(frame as BoxedAudioHandler);
let mut buffer = Self::Activating;
std::mem::swap(&mut*client.write().unwrap(), &mut buffer);
*client.write().unwrap() = Self::Active(Client::from(buffer).activate_async(
events,
frames,
// 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
}
}) as BoxedAudioHandler),
)?);
Ok(target)
}
@ -140,73 +172,69 @@ impl JackConnection {
}
}
/// 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].
pub trait RegisterPort {
fn midi_in (&self, name: &str) -> Usually<Port<MidiIn>>;
fn midi_out (&self, name: &str) -> Usually<Port<MidiOut>>;
fn audio_in (&self, name: &str) -> Usually<Port<AudioIn>>;
fn audio_out (&self, name: &str) -> Usually<Port<AudioOut>>;
fn connect_midi_from (&self, my_input: &Port<MidiIn>, ports: &[String]) -> Usually<()>;
fn connect_midi_to (&self, my_output: &Port<MidiOut>, ports: &[String]) -> Usually<()>;
fn connect_audio_from (&self, my_input: &Port<AudioIn>, ports: &[String]) -> Usually<()>;
fn connect_audio_to (&self, my_output: &Port<AudioOut>, ports: &[String]) -> Usually<()>;
fn midi_in (&self, name: impl AsRef<str>, connect: &[impl AsRef<str>]) -> Usually<Port<MidiIn>>;
fn midi_out (&self, name: impl AsRef<str>, connect: &[impl AsRef<str>]) -> Usually<Port<MidiOut>>;
fn audio_in (&self, name: impl AsRef<str>, connect: &[impl AsRef<str>]) -> Usually<Port<AudioIn>>;
fn audio_out (&self, name: impl AsRef<str>, connect: &[impl AsRef<str>]) -> Usually<Port<AudioOut>>;
}
impl RegisterPort for Arc<RwLock<JackConnection>> {
fn midi_in (&self, name: &str) -> Usually<Port<MidiIn>> {
Ok(self.read().unwrap().client().register_port(name, MidiIn::default())?)
}
fn midi_out (&self, name: &str) -> Usually<Port<MidiOut>> {
Ok(self.read().unwrap().client().register_port(name, MidiOut::default())?)
}
fn audio_out (&self, name: &str) -> Usually<Port<AudioOut>> {
Ok(self.read().unwrap().client().register_port(name, AudioOut::default())?)
}
fn audio_in (&self, name: &str) -> Usually<Port<AudioIn>> {
Ok(self.read().unwrap().client().register_port(name, AudioIn::default())?)
}
fn connect_midi_from (&self, input: &Port<MidiIn>, ports: &[String]) -> Usually<()> {
fn midi_in (&self, name: impl AsRef<str>, connect: &[impl AsRef<str>]) -> Usually<Port<MidiIn>> {
let jack = self.read().unwrap();
for port in ports.iter() {
if let Some(port) = jack.port_by_name(port).as_ref() {
jack.client().connect_ports(port, input)?;
let input = jack.client().register_port(name.as_ref(), MidiIn::default())?;
for port in connect.iter() {
let port = port.as_ref();
if let Some(output) = jack.port_by_name(port).as_ref() {
jack.client().connect_ports(output, &input)?;
} else {
panic!("Missing MIDI output: {port}. Use jack_lsp to list all port names.");
}
}
Ok(())
Ok(input)
}
fn connect_midi_to (&self, output: &Port<MidiOut>, ports: &[String]) -> Usually<()> {
fn midi_out (&self, name: impl AsRef<str>, connect: &[impl AsRef<str>]) -> Usually<Port<MidiOut>> {
let jack = self.read().unwrap();
for port in ports.iter() {
if let Some(port) = jack.port_by_name(port).as_ref() {
jack.client().connect_ports(output, port)?;
let output = jack.client().register_port(name.as_ref(), MidiOut::default())?;
for port in connect.iter() {
let port = port.as_ref();
if let Some(input) = jack.port_by_name(port).as_ref() {
jack.client().connect_ports(&output, input)?;
} else {
panic!("Missing MIDI input: {port}. Use jack_lsp to list all port names.");
}
}
Ok(())
Ok(output)
}
fn connect_audio_from (&self, input: &Port<AudioIn>, ports: &[String]) -> Usually<()> {
fn audio_in (&self, name: impl AsRef<str>, connect: &[impl AsRef<str>]) -> Usually<Port<AudioIn>> {
let jack = self.read().unwrap();
for port in ports.iter() {
if let Some(port) = jack.port_by_name(port).as_ref() {
jack.client().connect_ports(port, input)?;
let input = jack.client().register_port(name.as_ref(), AudioIn::default())?;
for port in connect.iter() {
let port = port.as_ref();
if let Some(output) = jack.port_by_name(port).as_ref() {
jack.client().connect_ports(output, &input)?;
} else {
panic!("Missing MIDI output: {port}. Use jack_lsp to list all port names.");
}
}
Ok(())
Ok(input)
}
fn connect_audio_to (&self, output: &Port<AudioOut>, ports: &[String]) -> Usually<()> {
fn audio_out (&self, name: impl AsRef<str>, connect: &[impl AsRef<str>]) -> Usually<Port<AudioOut>> {
let jack = self.read().unwrap();
for port in ports.iter() {
if let Some(port) = jack.port_by_name(port).as_ref() {
jack.client().connect_ports(output, port)?;
let output = jack.client().register_port(name.as_ref(), AudioOut::default())?;
for port in connect.iter() {
let port = port.as_ref();
if let Some(input) = jack.port_by_name(port).as_ref() {
jack.client().connect_ports(&output, input)?;
} else {
panic!("Missing MIDI input: {port}. Use jack_lsp to list all port names.");
}
}
Ok(())
Ok(output)
}
}
@ -225,10 +253,6 @@ pub enum JackEvent {
XRun,
}
/// Notification handler used by the [Jack] factory
/// when constructing [JackDevice]s.
pub type DynamicNotifications = Notifications<Box<dyn Fn(JackEvent) + Send + Sync>>;
/// Generic notification handler that emits [JackEvent]
pub struct Notifications<T: Fn(JackEvent) + Send>(pub T);