mirror of
https://codeberg.org/unspeaker/tek.git
synced 2025-12-07 12:16:42 +01:00
wip: port: make device
This commit is contained in:
parent
447638ee71
commit
cb7e4f7a95
31 changed files with 602 additions and 865 deletions
|
|
@ -1,2 +0,0 @@
|
|||
mod audio_in; pub use self::audio_in::*;
|
||||
mod audio_out; pub use self::audio_out::*;
|
||||
|
|
@ -1,86 +0,0 @@
|
|||
use crate::*;
|
||||
|
||||
//impl_port!(AudioInput: AudioOut -> AudioIn |j, n|j.register_port::<AudioOut>(n));
|
||||
|
||||
#[derive(Debug)] pub struct AudioInput<'j> {
|
||||
/// Handle to JACK client, for receiving reconnect events.
|
||||
jack: Jack<'j>,
|
||||
/// Port name
|
||||
name: Arc<str>,
|
||||
/// Port handle.
|
||||
port: Port<AudioOut>,
|
||||
/// List of ports to connect to.
|
||||
connections: Vec<PortConnect>
|
||||
}
|
||||
impl<'j> AsRef<Port<AudioOut>> for AudioInput<'j> {
|
||||
fn as_ref (&self) -> &Port<AudioOut> { &self.port }
|
||||
}
|
||||
impl<'j> AudioInput<'j> {
|
||||
pub fn new (jack: &Jack, name: impl AsRef<str>, connect: &[PortConnect])
|
||||
-> Usually<Self>
|
||||
{
|
||||
let port = Self {
|
||||
port: jack.register_port::<AudioIn>(name.as_ref())?,
|
||||
jack,
|
||||
name: name.into(),
|
||||
connections: connect.to_vec()
|
||||
};
|
||||
port.connect_to_matching()?;
|
||||
Ok(port)
|
||||
}
|
||||
pub fn name (&self) -> &Arc<str> { &self.name }
|
||||
pub fn port (&self) -> &Port<AudioOut> { &self.port }
|
||||
pub fn port_mut (&mut self) -> &mut Port<AudioOut> { &mut self.port }
|
||||
pub fn into_port (self) -> Port<AudioOut> { self.port }
|
||||
pub fn close (self) -> Usually<()> {
|
||||
let Self { jack, port, .. } = self;
|
||||
Ok(jack.with_client(|client|client.unregister_port(port))?)
|
||||
}
|
||||
}
|
||||
impl<'j> HasJack<'j> for AudioInput<'j> {
|
||||
fn jack (&self) -> &'j Jack<'j> { &self.jack }
|
||||
}
|
||||
impl<'j> JackPort<'j> for AudioInput<'j> {
|
||||
type Port = AudioIn;
|
||||
type Pair = AudioOut;
|
||||
fn port (&self) -> &Port<AudioOut> { &self.port }
|
||||
}
|
||||
//impl<'j, T: AsRef<str>> ConnectTo<'j, T> for AudioInput<'j> {
|
||||
//fn connect_to (&self, to: &T) -> 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)
|
||||
//})
|
||||
//}
|
||||
//}
|
||||
connect_to!(<'j>|self: AudioInput<'j>, port: &str|{
|
||||
self.with_client(|c|if let Some(ref port) = c.port_by_name(port.as_ref()) {
|
||||
self.connect_to(port)
|
||||
} else {
|
||||
Ok(Missing)
|
||||
})
|
||||
});
|
||||
connect_to!(<'j>|self: AudioInput<'j>, port: Port<AudioOut>|{
|
||||
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
|
||||
}))
|
||||
});
|
||||
connect_to!(<'j>|self: AudioInput<'j>, port: Port<Unowned>|{
|
||||
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<'j> ConnectAuto<'j> for AudioInput<'j> {
|
||||
fn connections (&self) -> &[PortConnect] {
|
||||
&self.connections
|
||||
}
|
||||
}
|
||||
|
|
@ -1,77 +0,0 @@
|
|||
use crate::*;
|
||||
|
||||
//impl_port!(AudioOutput: AudioOut -> AudioIn |j, n|j.register_port::<AudioOut>(n));
|
||||
|
||||
#[derive(Debug)] pub struct AudioOutput<'j> {
|
||||
/// Handle to JACK client, for receiving reconnect events.
|
||||
jack: Jack<'j>,
|
||||
/// Port name
|
||||
name: Arc<str>,
|
||||
/// Port handle.
|
||||
port: Port<AudioOut>,
|
||||
/// List of ports to connect to.
|
||||
connections: Vec<PortConnect>
|
||||
}
|
||||
impl<'j> AsRef<Port<AudioOut>> for AudioOutput<'j> {
|
||||
fn as_ref (&self) -> &Port<AudioOut> { &self.port }
|
||||
}
|
||||
impl<'j> AudioOutput<'j> {
|
||||
pub fn new (jack: &Jack, name: impl AsRef<str>, connect: &[PortConnect])
|
||||
-> Usually<Self>
|
||||
{
|
||||
let port = Self {
|
||||
port: jack.register_port::<AudioOut>(name.as_ref())?,
|
||||
jack,
|
||||
name: name.into(),
|
||||
connections: connect.to_vec()
|
||||
};
|
||||
port.connect_to_matching()?;
|
||||
Ok(port)
|
||||
}
|
||||
pub fn name (&self) -> &Arc<str> { &self.name }
|
||||
pub fn port (&self) -> &Port<AudioOut> { &self.port }
|
||||
pub fn port_mut (&mut self) -> &mut Port<AudioOut> { &mut self.port }
|
||||
pub fn into_port (self) -> Port<AudioOut> { self.port }
|
||||
pub fn close (self) -> Usually<()> {
|
||||
let Self { jack, port, .. } = self;
|
||||
Ok(jack.with_client(|client|client.unregister_port(port))?)
|
||||
}
|
||||
}
|
||||
impl<'j> HasJack<'j> for AudioOutput<'j> {
|
||||
fn jack (&self) -> &'j Jack<'j> { &self.jack }
|
||||
}
|
||||
impl<'j> JackPort<'j> for AudioOutput<'j> {
|
||||
type Port = AudioOut;
|
||||
type Pair = AudioIn;
|
||||
fn port (&self) -> &Port<AudioOut> { &self.port }
|
||||
}
|
||||
connect_to!(<'j>|self: AudioOutput<'j>, port: &str|{
|
||||
self.with_client(|c|if let Some(ref port) = c.port_by_name(port.as_ref()) {
|
||||
self.connect_to(port)
|
||||
} else {
|
||||
Ok(Missing)
|
||||
})
|
||||
});
|
||||
connect_to!(<'j>|self: AudioOutput<'j>, port: Port<AudioIn>|{
|
||||
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
|
||||
}))
|
||||
});
|
||||
connect_to!(<'j>|self: AudioOutput<'j>, port: Port<Unowned>|{
|
||||
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<'j> ConnectAuto<'j> for AudioOutput<'j> {
|
||||
fn connections (&self) -> &[PortConnect] {
|
||||
&self.connections
|
||||
}
|
||||
}
|
||||
|
|
@ -1,18 +1,225 @@
|
|||
use crate::*;
|
||||
pub use ::jack::{*, contrib::{*, ClosureProcessHandler}};
|
||||
//contrib::ClosureProcessHandler,
|
||||
//NotificationHandler,
|
||||
//Client, AsyncClient, ClientOptions, ClientStatus,
|
||||
//ProcessScope, Control, Frames,
|
||||
//Port, PortId, PortSpec, PortFlags,
|
||||
//Unowned, MidiIn, MidiOut, AudioIn, AudioOut,
|
||||
//};
|
||||
|
||||
pub(crate) use ConnectName::*;
|
||||
pub(crate) use ConnectScope::*;
|
||||
pub(crate) use ConnectStatus::*;
|
||||
pub(crate) use std::sync::{Arc, RwLock};
|
||||
/// Trait for thing that has a JACK process callback.
|
||||
pub trait Audio {
|
||||
fn handle (&mut self, _event: JackEvent) {}
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
mod jack_client; pub use self::jack_client::*;
|
||||
mod jack_device; pub use self::jack_device::*;
|
||||
mod jack_handler; pub use self::jack_handler::*;
|
||||
mod jack_port; pub use self::jack_port::*;
|
||||
/// Implement [Audio]: provide JACK callbacks.
|
||||
#[macro_export] macro_rules! audio {
|
||||
(|
|
||||
$self1:ident:
|
||||
$Struct:ident$(<$($L:lifetime),*$($T:ident$(:$U:path)?),*>)?,$c:ident,$s:ident
|
||||
|$cb:expr$(;|$self2:ident,$e:ident|$cb2:expr)?) => {
|
||||
impl $(<$($L),*$($T $(: $U)?),*>)? Audio for $Struct $(<$($L),*$($T),*>)? {
|
||||
#[inline] fn process (&mut $self1, $c: &Client, $s: &ProcessScope) -> Control { $cb }
|
||||
$(#[inline] fn handle (&mut $self2, $e: JackEvent) { $cb2 })?
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Event enum for JACK events.
|
||||
#[derive(Debug, Clone, PartialEq)] pub enum JackEvent {
|
||||
ThreadInit,
|
||||
Shutdown(ClientStatus, Arc<str>),
|
||||
Freewheel(bool),
|
||||
SampleRate(Frames),
|
||||
ClientRegistration(Arc<str>, bool),
|
||||
PortRegistration(PortId, bool),
|
||||
PortRename(PortId, Arc<str>, Arc<str>),
|
||||
PortsConnected(PortId, PortId, bool),
|
||||
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);
|
||||
}
|
||||
unsafe fn shutdown(&mut self, status: ClientStatus, reason: &str) {
|
||||
self.0(JackEvent::Shutdown(status, reason.into()));
|
||||
}
|
||||
fn freewheel(&mut self, _: &Client, enabled: bool) {
|
||||
self.0(JackEvent::Freewheel(enabled));
|
||||
}
|
||||
fn sample_rate(&mut self, _: &Client, frames: Frames) -> Control {
|
||||
self.0(JackEvent::SampleRate(frames));
|
||||
Control::Quit
|
||||
}
|
||||
fn client_registration(&mut self, _: &Client, name: &str, reg: bool) {
|
||||
self.0(JackEvent::ClientRegistration(name.into(), reg));
|
||||
}
|
||||
fn port_registration(&mut self, _: &Client, id: PortId, reg: bool) {
|
||||
self.0(JackEvent::PortRegistration(id, reg));
|
||||
}
|
||||
fn port_rename(&mut self, _: &Client, id: PortId, old: &str, new: &str) -> Control {
|
||||
self.0(JackEvent::PortRename(id, old.into(), new.into()));
|
||||
Control::Continue
|
||||
}
|
||||
fn ports_connected(&mut self, _: &Client, a: PortId, b: PortId, are: bool) {
|
||||
self.0(JackEvent::PortsConnected(a, b, are));
|
||||
}
|
||||
fn graph_reorder(&mut self, _: &Client) -> Control {
|
||||
self.0(JackEvent::GraphReorder);
|
||||
Control::Continue
|
||||
}
|
||||
fn xrun(&mut self, _: &Client) -> Control {
|
||||
self.0(JackEvent::XRun);
|
||||
Control::Continue
|
||||
}
|
||||
}
|
||||
|
||||
/// 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>>;
|
||||
/// This is the notification handler wrapper for a boxed realtime callback.
|
||||
pub type DynamicAudioHandler<'j> =
|
||||
ClosureProcessHandler<(), BoxedAudioHandler<'j>>;
|
||||
/// This is a boxed realtime callback.
|
||||
pub type BoxedAudioHandler<'j> =
|
||||
Box<dyn FnMut(&Client, &ProcessScope) -> Control + Send + Sync + 'j>;
|
||||
/// This is the notification handler wrapper for a boxed [JackEvent] callback.
|
||||
pub type DynamicNotifications<'j> =
|
||||
Notifications<BoxedJackEventHandler<'j>>;
|
||||
/// This is a boxed [JackEvent] callback.
|
||||
pub type BoxedJackEventHandler<'j> =
|
||||
Box<dyn Fn(JackEvent) + Send + Sync + 'j>;
|
||||
use self::JackState::*;
|
||||
|
||||
impl<'j, T: Has<Jack<'j>>> HasJack<'j> for T {
|
||||
fn jack (&self) -> &Jack<'j> { self.get() }
|
||||
}
|
||||
impl<'j> HasJack<'j> for Jack<'j> {
|
||||
fn jack (&self) -> &Jack<'j> { self }
|
||||
}
|
||||
impl<'j> HasJack<'j> for &Jack<'j> {
|
||||
fn jack (&self) -> &Jack<'j> { self }
|
||||
}
|
||||
|
||||
/// Things that can provide a [jack::Client] reference.
|
||||
pub trait HasJack<'j> {
|
||||
/// Return the internal [jack::Client] handle
|
||||
/// that lets you call the JACK API.
|
||||
fn jack (&self) -> &Jack<'j>;
|
||||
/// Run the JACK thread.
|
||||
fn run <T: Audio + Send + Sync + 'static> (
|
||||
&self, callback: impl FnOnce(&Jack)->Usually<T>
|
||||
) -> Usually<Arc<RwLock<T>>> {
|
||||
let jack = self.jack();
|
||||
let app = Arc::new(RwLock::new(callback(jack)?));
|
||||
let mut state = Activating;
|
||||
std::mem::swap(&mut*jack.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({
|
||||
let app = app.clone();
|
||||
move|event|app.write().unwrap().handle(event)
|
||||
}) 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),
|
||||
)?;
|
||||
*jack.state.write().unwrap() = Active(client);
|
||||
} else {
|
||||
unreachable!();
|
||||
}
|
||||
Ok(app)
|
||||
}
|
||||
/// 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 port_by_id (&self, id: u32) -> Option<Port<Unowned>> {
|
||||
self.with_client(|c|c.port_by_id(id))
|
||||
}
|
||||
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, callback: impl Fn(TimebaseInfo)->Position) -> Usually<()> {
|
||||
if enable {
|
||||
self.with_client(|client|match client.register_timebase_callback(false, callback) {
|
||||
Ok(_) => Ok(()),
|
||||
Err(e) => Err(e)
|
||||
})?
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn sync_follow (&self, _enable: bool) -> Usually<()> {
|
||||
// TODO: sync follow
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Wraps [JackState] and through it [jack::Client].
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct Jack<'j> {
|
||||
pub state: Arc<RwLock<JackState<'j>>>
|
||||
}
|
||||
|
||||
impl<'j> Jack<'j> {
|
||||
pub fn new (name: &str) -> Usually<Self> {
|
||||
Ok(Self {
|
||||
state: JackState::new(Client::new(name, ClientOptions::NO_START_SERVER)?.0)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// This is a connection which may be [Inactive], [Activating], or [Active].
|
||||
/// 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)]
|
||||
pub enum JackState<'j> {
|
||||
/// Unused
|
||||
#[default] Inert,
|
||||
/// Before activation.
|
||||
Inactive(Client),
|
||||
/// During activation.
|
||||
Activating,
|
||||
/// After activation. Must not be dropped for JACK thread to persist.
|
||||
Active(DynamicAsyncClient<'j>),
|
||||
}
|
||||
|
||||
impl<'j> JackState<'j> {
|
||||
fn new (client: Client) -> Arc<RwLock<Self>> {
|
||||
Arc::new(RwLock::new(Self::Inactive(client)))
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,122 +0,0 @@
|
|||
use crate::*;
|
||||
use super::*;
|
||||
use self::JackState::*;
|
||||
|
||||
impl<'j, T: Has<Jack<'j>>> HasJack<'j> for T {
|
||||
fn jack (&'j self) -> &'j Jack<'j> { self.get() }
|
||||
}
|
||||
impl<'j> HasJack<'j> for Jack<'j> {
|
||||
fn jack (&'j self) -> &'j Jack<'j> { self }
|
||||
}
|
||||
impl<'j> HasJack<'j> for &Jack<'j> {
|
||||
fn jack (&'j self) -> &'j Jack<'j> { self }
|
||||
}
|
||||
|
||||
/// Things that can provide a [jack::Client] reference.
|
||||
pub trait HasJack<'j> {
|
||||
/// Return the internal [jack::Client] handle
|
||||
/// that lets you call the JACK API.
|
||||
fn jack (&'j self) -> &'j Jack<'j>;
|
||||
/// Run the JACK thread.
|
||||
fn run <T: Audio + Send + Sync + 'j> (
|
||||
&self, cb: impl FnOnce(&Jack)->Usually<T>
|
||||
) -> Usually<Arc<RwLock<T>>> {
|
||||
let jack = self.jack();
|
||||
let app = Arc::new(RwLock::new(cb(jack)?));
|
||||
let mut state = Activating;
|
||||
std::mem::swap(&mut*jack.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({
|
||||
let app = app.clone();
|
||||
move|event|app.write().unwrap().handle(event)
|
||||
}) as BoxedJackEventHandler<'j>),
|
||||
// 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),
|
||||
)?;
|
||||
*jack.state.write().unwrap() = Active(client);
|
||||
} else {
|
||||
unreachable!();
|
||||
}
|
||||
Ok(app)
|
||||
}
|
||||
/// 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 port_by_id (&self, id: u32) -> Option<Port<Unowned>> {
|
||||
self.with_client(|c|c.port_by_id(id))
|
||||
}
|
||||
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(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Wraps [JackState] and through it [jack::Client].
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct Jack<'j> {
|
||||
pub state: Arc<RwLock<JackState<'j>>>
|
||||
}
|
||||
|
||||
impl<'j> Jack<'j> {
|
||||
pub fn new (name: &str) -> Usually<Self> {
|
||||
Ok(Self {
|
||||
state: JackState::new(Client::new(name, ClientOptions::NO_START_SERVER)?.0)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// This is a connection which may be [Inactive], [Activating], or [Active].
|
||||
/// 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)]
|
||||
pub enum JackState<'j> {
|
||||
/// Unused
|
||||
#[default] Inert,
|
||||
/// Before activation.
|
||||
Inactive(Client),
|
||||
/// During activation.
|
||||
Activating,
|
||||
/// After activation. Must not be dropped for JACK thread to persist.
|
||||
Active(DynamicAsyncClient<'j>),
|
||||
}
|
||||
|
||||
impl<'j> JackState<'j> {
|
||||
fn new (client: Client) -> Arc<RwLock<Self>> {
|
||||
Arc::new(RwLock::new(Self::Inactive(client)))
|
||||
}
|
||||
}
|
||||
|
|
@ -1,86 +0,0 @@
|
|||
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.
|
||||
//pub client: DynamicAsyncClient,
|
||||
///// The device state, encapsulated for sharing between threads.
|
||||
//pub state: Arc<RwLock<Box<dyn AudioComponent<E>>>>,
|
||||
///// Unowned copies of the device's JACK ports, for connecting to the device.
|
||||
///// 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")
|
||||
//.field("ports", &self.ports)
|
||||
//.finish()
|
||||
//}
|
||||
//}
|
||||
|
||||
//impl<E: Engine> Render for JackDevice<E> {
|
||||
//type Engine = E;
|
||||
//fn min_size(&self, to: E::Size) -> Perhaps<E::Size> {
|
||||
//self.state.read().unwrap().layout(to)
|
||||
//}
|
||||
//fn render(&self, to: &mut E::Output) -> Usually<()> {
|
||||
//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())
|
||||
//}
|
||||
//fn audio_outs (&self) -> Usually<Vec<&Port<Unowned>>> {
|
||||
//Ok(self.ports.audio_outs.values().collect())
|
||||
//}
|
||||
//fn midi_ins (&self) -> Usually<Vec<&Port<Unowned>>> {
|
||||
//Ok(self.ports.midi_ins.values().collect())
|
||||
//}
|
||||
//fn midi_outs (&self) -> Usually<Vec<&Port<Unowned>>> {
|
||||
//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>>>> {
|
||||
//self.state.read()
|
||||
//}
|
||||
///// Returns a locked mutex of the state's contents.
|
||||
//pub fn state_mut(&self) -> LockResult<RwLockWriteGuard<Box<dyn AudioComponent<E>>>> {
|
||||
//self.state.write()
|
||||
//}
|
||||
//pub fn connect_midi_in(&self, index: usize, port: &Port<Unowned>) -> Usually<()> {
|
||||
//Ok(self
|
||||
//.client
|
||||
//.as_client()
|
||||
//.connect_ports(port, self.midi_ins()?[index])?)
|
||||
//}
|
||||
//pub fn connect_midi_out(&self, index: usize, port: &Port<Unowned>) -> Usually<()> {
|
||||
//Ok(self
|
||||
//.client
|
||||
//.as_client()
|
||||
//.connect_ports(self.midi_outs()?[index], port)?)
|
||||
//}
|
||||
//pub fn connect_audio_in(&self, index: usize, port: &Port<Unowned>) -> Usually<()> {
|
||||
//Ok(self
|
||||
//.client
|
||||
//.as_client()
|
||||
//.connect_ports(port, self.audio_ins()?[index])?)
|
||||
//}
|
||||
//pub fn connect_audio_out(&self, index: usize, port: &Port<Unowned>) -> Usually<()> {
|
||||
//Ok(self
|
||||
//.client
|
||||
//.as_client()
|
||||
//.connect_ports(self.audio_outs()?[index], port)?)
|
||||
//}
|
||||
//}
|
||||
|
|
@ -1,105 +0,0 @@
|
|||
use crate::*;
|
||||
use super::*;
|
||||
|
||||
/// Trait for thing that has a JACK process callback.
|
||||
pub trait Audio {
|
||||
fn handle (&mut self, _event: JackEvent) {}
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Implement [Audio]: provide JACK callbacks.
|
||||
#[macro_export] macro_rules! audio {
|
||||
(|
|
||||
$self1:ident:
|
||||
$Struct:ident$(<$($L:lifetime),*$($T:ident$(:$U:path)?),*>)?,$c:ident,$s:ident
|
||||
|$cb:expr$(;|$self2:ident,$e:ident|$cb2:expr)?) => {
|
||||
impl $(<$($L),*$($T $(: $U)?),*>)? Audio for $Struct $(<$($L),*$($T),*>)? {
|
||||
#[inline] fn process (&mut $self1, $c: &Client, $s: &ProcessScope) -> Control { $cb }
|
||||
$(#[inline] fn handle (&mut $self2, $e: JackEvent) { $cb2 })?
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Event enum for JACK events.
|
||||
#[derive(Debug, Clone, PartialEq)] pub enum JackEvent {
|
||||
ThreadInit,
|
||||
Shutdown(ClientStatus, Arc<str>),
|
||||
Freewheel(bool),
|
||||
SampleRate(Frames),
|
||||
ClientRegistration(Arc<str>, bool),
|
||||
PortRegistration(PortId, bool),
|
||||
PortRename(PortId, Arc<str>, Arc<str>),
|
||||
PortsConnected(PortId, PortId, bool),
|
||||
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);
|
||||
}
|
||||
unsafe fn shutdown(&mut self, status: ClientStatus, reason: &str) {
|
||||
self.0(JackEvent::Shutdown(status, reason.into()));
|
||||
}
|
||||
fn freewheel(&mut self, _: &Client, enabled: bool) {
|
||||
self.0(JackEvent::Freewheel(enabled));
|
||||
}
|
||||
fn sample_rate(&mut self, _: &Client, frames: Frames) -> Control {
|
||||
self.0(JackEvent::SampleRate(frames));
|
||||
Control::Quit
|
||||
}
|
||||
fn client_registration(&mut self, _: &Client, name: &str, reg: bool) {
|
||||
self.0(JackEvent::ClientRegistration(name.into(), reg));
|
||||
}
|
||||
fn port_registration(&mut self, _: &Client, id: PortId, reg: bool) {
|
||||
self.0(JackEvent::PortRegistration(id, reg));
|
||||
}
|
||||
fn port_rename(&mut self, _: &Client, id: PortId, old: &str, new: &str) -> Control {
|
||||
self.0(JackEvent::PortRename(id, old.into(), new.into()));
|
||||
Control::Continue
|
||||
}
|
||||
fn ports_connected(&mut self, _: &Client, a: PortId, b: PortId, are: bool) {
|
||||
self.0(JackEvent::PortsConnected(a, b, are));
|
||||
}
|
||||
fn graph_reorder(&mut self, _: &Client) -> Control {
|
||||
self.0(JackEvent::GraphReorder);
|
||||
Control::Continue
|
||||
}
|
||||
fn xrun(&mut self, _: &Client) -> Control {
|
||||
self.0(JackEvent::XRun);
|
||||
Control::Continue
|
||||
}
|
||||
}
|
||||
|
||||
/// 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>>;
|
||||
/// This is the notification handler wrapper for a boxed realtime callback.
|
||||
pub type DynamicAudioHandler<'j> =
|
||||
ClosureProcessHandler<(), BoxedAudioHandler<'j>>;
|
||||
/// This is a boxed realtime callback.
|
||||
pub type BoxedAudioHandler<'j> =
|
||||
Box<dyn FnMut(&Client, &ProcessScope) -> Control + Send + Sync + 'j>;
|
||||
/// This is the notification handler wrapper for a boxed [JackEvent] callback.
|
||||
pub type DynamicNotifications<'j> =
|
||||
Notifications<BoxedJackEventHandler<'j>>;
|
||||
/// This is a boxed [JackEvent] callback.
|
||||
pub type BoxedJackEventHandler<'j> =
|
||||
Box<dyn Fn(JackEvent) + Send + Sync + 'j>;
|
||||
|
|
@ -1,159 +0,0 @@
|
|||
use crate::*;
|
||||
use super::*;
|
||||
|
||||
pub trait JackPort<'j>: HasJack<'j> {
|
||||
type Port: PortSpec;
|
||||
type Pair: PortSpec;
|
||||
fn port (&self) -> &Port<Self::Port>;
|
||||
}
|
||||
|
||||
pub trait ConnectTo<'j, T>: JackPort<'j> {
|
||||
fn connect_to (&'j self, to: &T) -> Usually<ConnectStatus>;
|
||||
}
|
||||
|
||||
#[macro_export] macro_rules! connect_to {
|
||||
(<$lt:lifetime>|$self:ident:$Self:ty, $port:ident:$Port:ty|$expr:expr) => {
|
||||
impl<$lt> ConnectTo<$lt, &$Port> for $Self {
|
||||
fn connect_to (&$self, $port: &$Port) -> Usually<ConnectStatus> {
|
||||
$expr
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
pub trait ConnectAuto<'j>: JackPort<'j> + ConnectTo<'j, &'j Port<Unowned>> {
|
||||
fn connections (&self) -> &[Connect];
|
||||
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 port_by_id (&self, id: u32) -> Option<Port<Unowned>> {
|
||||
self.with_client(|c|c.port_by_id(id))
|
||||
}
|
||||
fn port_by_name (&self, name: impl AsRef<str>) -> Option<Port<Unowned>> {
|
||||
self.with_client(|c|c.port_by_name(name.as_ref()))
|
||||
}
|
||||
fn connect_to_matching (&self) -> Usually<()> {
|
||||
for connect in self.connections().iter() {
|
||||
//panic!("{connect:?}");
|
||||
let status = match &connect.name {
|
||||
Exact(name) => self.connect_exact(name),
|
||||
RegExp(re) => self.connect_regexp(re, connect.scope),
|
||||
}?;
|
||||
*connect.status.write().unwrap() = status;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn connect_exact (&self, name: &str) ->
|
||||
Usually<Vec<(Port<Unowned>, Arc<str>, ConnectStatus)>>
|
||||
{
|
||||
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, scope: ConnectScope
|
||||
) -> Usually<Vec<(Port<Unowned>, Arc<str>, ConnectStatus)>> {
|
||||
self.with_client(|c|{
|
||||
let mut status = vec![];
|
||||
let ports = c.ports(Some(&re), None, PortFlags::empty());
|
||||
for port in ports.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));
|
||||
if port_status == Connected && scope == One {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(status)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum ConnectName {
|
||||
/** Exact match */
|
||||
Exact(Arc<str>),
|
||||
/** Match regular expression */
|
||||
RegExp(Arc<str>),
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq)] pub enum ConnectScope {
|
||||
One,
|
||||
All
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq)] pub enum ConnectStatus {
|
||||
Missing,
|
||||
Disconnected,
|
||||
Connected,
|
||||
Mismatch,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)] pub struct Connect {
|
||||
pub name: ConnectName,
|
||||
pub scope: ConnectScope,
|
||||
pub status: Arc<RwLock<Vec<(Port<Unowned>, Arc<str>, ConnectStatus)>>>,
|
||||
pub info: Arc<String>,
|
||||
}
|
||||
|
||||
impl Connect {
|
||||
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 info = format!("=:{}", name.as_ref()).into();
|
||||
let name = Exact(name.as_ref().into());
|
||||
Self { name, scope: One, status: Arc::new(RwLock::new(vec![])), info }
|
||||
}
|
||||
pub fn regexp (name: impl AsRef<str>) -> Self {
|
||||
let info = format!("~:{}", name.as_ref()).into();
|
||||
let name = RegExp(name.as_ref().into());
|
||||
Self { name, scope: One, status: Arc::new(RwLock::new(vec![])), info }
|
||||
}
|
||||
pub fn regexp_all (name: impl AsRef<str>) -> Self {
|
||||
let info = format!("+:{}", name.as_ref()).into();
|
||||
let name = RegExp(name.as_ref().into());
|
||||
Self { name, scope: All, status: Arc::new(RwLock::new(vec![])), info }
|
||||
}
|
||||
pub fn info (&self) -> Arc<str> {
|
||||
let status = {
|
||||
let status = self.status.read().unwrap();
|
||||
let mut ok = 0;
|
||||
for (_, _, state) in status.iter() {
|
||||
if *state == Connected {
|
||||
ok += 1
|
||||
}
|
||||
}
|
||||
format!("{ok}/{}", status.len())
|
||||
};
|
||||
let scope = match self.scope {
|
||||
One => " ", All => "*",
|
||||
};
|
||||
let name = match &self.name {
|
||||
Exact(name) => format!("= {name}"), RegExp(name) => format!("~ {name}"),
|
||||
};
|
||||
format!(" ({}) {} {}", status, scope, name).into()
|
||||
}
|
||||
}
|
||||
|
|
@ -88,7 +88,6 @@ mod time; pub use self::time::*;
|
|||
mod note; pub use self::note::*;
|
||||
pub mod jack; pub use self::jack::*;
|
||||
pub mod midi; pub use self::midi::*;
|
||||
pub mod audio; pub use self::audio::*;
|
||||
|
||||
pub(crate) use std::sync::{Arc, atomic::{AtomicUsize, AtomicBool, Ordering::Relaxed}};
|
||||
pub(crate) use std::fmt::Debug;
|
||||
|
|
|
|||
|
|
@ -9,10 +9,6 @@ pub use ::midly::{
|
|||
live::*,
|
||||
};
|
||||
|
||||
mod midi_in; pub use self::midi_in::*;
|
||||
mod midi_out; pub use self::midi_out::*;
|
||||
mod midi_hold; pub use self::midi_hold::*;
|
||||
|
||||
/// Return boxed iterator of MIDI events
|
||||
pub fn parse_midi_input <'a> (input: ::jack::MidiIter<'a>) -> Box<dyn Iterator<Item=(usize, LiveEvent<'a>, &'a [u8])> + 'a> {
|
||||
Box::new(input.map(|::jack::RawMidi { time, bytes }|(
|
||||
|
|
@ -30,3 +26,12 @@ pub fn all_notes_off (output: &mut [Vec<Vec<u8>>]) {
|
|||
evt.write(&mut buf).unwrap();
|
||||
output[0].push(buf);
|
||||
}
|
||||
|
||||
/// Update notes_in array
|
||||
pub fn update_keys (keys: &mut[bool;128], message: &MidiMessage) {
|
||||
match message {
|
||||
MidiMessage::NoteOn { key, .. } => { keys[key.as_int() as usize] = true; }
|
||||
MidiMessage::NoteOff { key, .. } => { keys[key.as_int() as usize] = false; },
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,10 +0,0 @@
|
|||
use crate::*;
|
||||
|
||||
/// Update notes_in array
|
||||
pub fn update_keys (keys: &mut[bool;128], message: &MidiMessage) {
|
||||
match message {
|
||||
MidiMessage::NoteOn { key, .. } => { keys[key.as_int() as usize] = true; }
|
||||
MidiMessage::NoteOff { key, .. } => { keys[key.as_int() as usize] = false; },
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,152 +0,0 @@
|
|||
use crate::*;
|
||||
|
||||
//impl_port!(MidiInput: MidiOut -> MidiIn |j, n|j.register_port::<MidiOut>(n));
|
||||
|
||||
#[derive(Debug)] pub struct MidiInput<'j> {
|
||||
/// Handle to JACK client, for receiving reconnect events.
|
||||
jack: Jack<'j>,
|
||||
/// Port name
|
||||
name: Arc<str>,
|
||||
/// Port handle.
|
||||
port: Port<MidiOut>,
|
||||
/// List of ports to connect to.
|
||||
connections: Vec<Connect>
|
||||
}
|
||||
impl<'j> AsRef<Port<MidiOut>> for MidiInput<'j> {
|
||||
fn as_ref (&self) -> &Port<MidiOut> { &self.port }
|
||||
}
|
||||
impl<'j> MidiInput<'j> {
|
||||
pub fn new (jack: &Jack, name: impl AsRef<str>, connect: &[Connect])
|
||||
-> Usually<Self>
|
||||
{
|
||||
let port = Self {
|
||||
port: jack.register_port::<MidiIn>(name.as_ref())?,
|
||||
jack,
|
||||
name: name.into(),
|
||||
connections: connect.to_vec()
|
||||
};
|
||||
port.connect_to_matching()?;
|
||||
Ok(port)
|
||||
}
|
||||
pub fn name (&self) -> &Arc<str> {
|
||||
&self.name
|
||||
}
|
||||
pub fn port (&self) -> &Port<MidiOut> {
|
||||
&self.port
|
||||
}
|
||||
pub fn port_mut (&mut self) -> &mut Port<MidiOut> {
|
||||
&mut self.port
|
||||
}
|
||||
pub fn into_port (self) -> Port<MidiOut> {
|
||||
self.port
|
||||
}
|
||||
pub fn close (self) -> Usually<()> {
|
||||
let Self { jack, port, .. } = self;
|
||||
Ok(jack.with_client(|client|client.unregister_port(port))?)
|
||||
}
|
||||
pub fn parsed <'a> (&'a self, scope: &'a ProcessScope) -> impl Iterator<Item=(usize, LiveEvent<'a>, &'a [u8])> {
|
||||
parse_midi_input(self.port().iter(scope))
|
||||
}
|
||||
}
|
||||
impl<'j> HasJack<'j> for MidiInput<'j> {
|
||||
fn jack (&self) -> &'j Jack<'j> { &self.jack }
|
||||
}
|
||||
impl<'j> JackPort<'j> for MidiInput<'j> {
|
||||
type Port = MidiIn;
|
||||
type Pair = MidiOut;
|
||||
fn port (&self) -> &Port<MidiOut> { &self.port }
|
||||
}
|
||||
//impl<'j, T: AsRef<str>> ConnectTo<'j, T> for MidiInput<'j> {
|
||||
//fn connect_to (&self, to: &T) -> Usually<ConnectStatus> {
|
||||
//self.with_client(|c|if let Some(ref port) = c.port_by_name(to.as_ref()) {
|
||||
//self.connect_to(port)
|
||||
//} else {
|
||||
//Ok(Missing)
|
||||
//})
|
||||
//}
|
||||
//}
|
||||
connect_to!(<'j>|self: MidiInput<'j>, port: &str|{
|
||||
self.with_client(|c|if let Some(ref port) = c.port_by_name(port.as_ref()) {
|
||||
self.connect_to(port)
|
||||
} else {
|
||||
Ok(Missing)
|
||||
})
|
||||
});
|
||||
connect_to!(<'j>|self: MidiInput<'j>, port: Port<MidiOut>|{
|
||||
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
|
||||
}))
|
||||
});
|
||||
connect_to!(<'j>|self: MidiInput<'j>, port: Port<Unowned>|{
|
||||
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<'j> ConnectAuto<'j> for MidiInput<'j> {
|
||||
fn connections (&self) -> &[Connect] {
|
||||
&self.connections
|
||||
}
|
||||
}
|
||||
|
||||
#[tengri_proc::command(MidiInput)]
|
||||
impl MidiInputCommand {
|
||||
//fn _todo_ (_port: &mut MidiInput) -> Perhaps<Self> { Ok(None) }
|
||||
}
|
||||
|
||||
impl<T: Has<Vec<MidiInput>>> HasMidiIns for T {
|
||||
fn midi_ins (&self) -> &Vec<MidiInput> {
|
||||
self.get()
|
||||
}
|
||||
fn midi_ins_mut (&mut self) -> &mut Vec<MidiInput> {
|
||||
self.get_mut()
|
||||
}
|
||||
}
|
||||
|
||||
/// Trait for thing that may receive MIDI.
|
||||
pub trait HasMidiIns {
|
||||
fn midi_ins (&self) -> &Vec<MidiInput>;
|
||||
fn midi_ins_mut (&mut self) -> &mut Vec<MidiInput>;
|
||||
/// Collect MIDI input from app ports (TODO preallocate large buffers)
|
||||
fn midi_input_collect <'a> (&'a self, scope: &'a ProcessScope) -> CollectedMidiInput<'a> {
|
||||
self.midi_ins().iter()
|
||||
.map(|port|port.port().iter(scope)
|
||||
.map(|RawMidi { time, bytes }|(time, LiveEvent::parse(bytes)))
|
||||
.collect::<Vec<_>>())
|
||||
.collect::<Vec<_>>()
|
||||
}
|
||||
fn midi_ins_with_sizes <'a> (&'a self) ->
|
||||
impl Iterator<Item=(usize, &Arc<str>, &[Connect], usize, usize)> + Send + Sync + 'a
|
||||
{
|
||||
let mut y = 0;
|
||||
self.midi_ins().iter().enumerate().map(move|(i, input)|{
|
||||
let height = 1 + input.conn().len();
|
||||
let data = (i, input.name(), input.conn(), y, y + height);
|
||||
y += height;
|
||||
data
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub type CollectedMidiInput<'a> = Vec<Vec<(u32, Result<LiveEvent<'a>, MidiError>)>>;
|
||||
|
||||
impl<'j, T: HasMidiIns + HasJack<'j>> AddMidiIn for T {
|
||||
fn midi_in_add (&mut self) -> Usually<()> {
|
||||
let index = self.midi_ins().len();
|
||||
let port = MidiInput::new(self.jack(), &format!("M/{index}"), &[])?;
|
||||
self.midi_ins_mut().push(port);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// May create new MIDI input ports.
|
||||
pub trait AddMidiIn {
|
||||
fn midi_in_add (&mut self) -> Usually<()>;
|
||||
}
|
||||
|
|
@ -1,199 +0,0 @@
|
|||
use crate::*;
|
||||
|
||||
#[derive(Debug)] pub struct MidiOutput {
|
||||
/// Handle to JACK client, for receiving reconnect events.
|
||||
jack: Jack<'static>,
|
||||
/// Port name
|
||||
name: Arc<str>,
|
||||
/// Port handle.
|
||||
port: Port<MidiOut>,
|
||||
/// List of ports to connect to.
|
||||
conn: Vec<Connect>,
|
||||
/// List of currently held notes.
|
||||
held: Arc<RwLock<[bool;128]>>,
|
||||
/// Buffer
|
||||
note_buffer: Vec<u8>,
|
||||
/// Buffer
|
||||
output_buffer: Vec<Vec<Vec<u8>>>,
|
||||
}
|
||||
|
||||
has!(Jack<'static>: |self: MidiOutput|self.jack);
|
||||
|
||||
impl MidiOutput {
|
||||
pub fn new (jack: &Jack, name: impl AsRef<str>, connect: &[Connect])
|
||||
-> Usually<Self>
|
||||
{
|
||||
let jack = jack.clone();
|
||||
let port = jack.register_port::<MidiOut>(name.as_ref())?;
|
||||
let name = name.as_ref().into();
|
||||
let conn = connect.to_vec();
|
||||
let port = Self {
|
||||
jack,
|
||||
port,
|
||||
name,
|
||||
conn,
|
||||
held: Arc::new([false;128].into()),
|
||||
note_buffer: vec![0;8],
|
||||
output_buffer: vec![vec![];65536],
|
||||
};
|
||||
port.connect_to_matching()?;
|
||||
Ok(port)
|
||||
}
|
||||
pub fn name (&self) -> &Arc<str> {
|
||||
&self.name
|
||||
}
|
||||
pub fn port (&self) -> &Port<MidiOut> {
|
||||
&self.port
|
||||
}
|
||||
pub fn port_mut (&mut self) -> &mut Port<MidiOut> {
|
||||
&mut self.port
|
||||
}
|
||||
pub fn into_port (self) -> Port<MidiOut> {
|
||||
self.port
|
||||
}
|
||||
pub fn close (self) -> Usually<()> {
|
||||
let Self { jack, port, .. } = self;
|
||||
Ok(jack.with_client(|client|client.unregister_port(port))?)
|
||||
}
|
||||
/// Clear the section of the output buffer that we will be using,
|
||||
/// emitting "all notes off" at start of buffer if requested.
|
||||
pub fn buffer_clear (&mut self, scope: &ProcessScope, reset: bool) {
|
||||
let n_frames = (scope.n_frames() as usize).min(self.output_buffer.len());
|
||||
for frame in &mut self.output_buffer[0..n_frames] {
|
||||
frame.clear();
|
||||
}
|
||||
if reset {
|
||||
all_notes_off(&mut self.output_buffer);
|
||||
}
|
||||
}
|
||||
/// Write a note to the output buffer
|
||||
pub fn buffer_write <'a> (
|
||||
&'a mut self,
|
||||
sample: usize,
|
||||
event: LiveEvent,
|
||||
) {
|
||||
self.note_buffer.fill(0);
|
||||
event.write(&mut self.note_buffer).expect("failed to serialize MIDI event");
|
||||
self.output_buffer[sample].push(self.note_buffer.clone());
|
||||
// Update the list of currently held notes.
|
||||
if let LiveEvent::Midi { ref message, .. } = event {
|
||||
update_keys(&mut*self.held.write().unwrap(), message);
|
||||
}
|
||||
}
|
||||
/// Write a chunk of MIDI data from the output buffer to the output port.
|
||||
pub fn buffer_emit (&mut self, scope: &ProcessScope) {
|
||||
let samples = scope.n_frames() as usize;
|
||||
let mut writer = self.port.writer(scope);
|
||||
for (time, events) in self.output_buffer.iter().enumerate().take(samples) {
|
||||
for bytes in events.iter() {
|
||||
writer.write(&RawMidi { time: time as u32, bytes }).unwrap_or_else(|_|{
|
||||
panic!("Failed to write MIDI data: {bytes:?}");
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl AsRef<Port<MidiOut>> for MidiOutput {
|
||||
fn as_ref (&self) -> &Port<MidiOut> {
|
||||
&self.port
|
||||
}
|
||||
}
|
||||
|
||||
impl JackPort<'static> for MidiOutput {
|
||||
type Port = MidiOut;
|
||||
type Pair = MidiIn;
|
||||
fn port (&self) -> &Port<MidiOut> { &self.port }
|
||||
}
|
||||
|
||||
impl ConnectTo<'static, &str> for MidiOutput {
|
||||
fn connect_to (&self, to: &str) -> Usually<ConnectStatus> {
|
||||
self.with_client(|c|if let Some(ref port) = c.port_by_name(to.as_ref()) {
|
||||
self.connect_to(port)
|
||||
} else {
|
||||
Ok(Missing)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl ConnectTo<'static, &Port<Unowned>> for MidiOutput {
|
||||
fn connect_to (&self, port: &Port<Unowned>) -> Usually<ConnectStatus> {
|
||||
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 ConnectTo<'static, &Port<MidiIn>> for MidiOutput {
|
||||
fn connect_to (&self, port: &Port<MidiIn>) -> Usually<ConnectStatus> {
|
||||
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 ConnectAuto<'static> for MidiOutput {
|
||||
fn connections (&self) -> &[Connect] {
|
||||
&self.conn
|
||||
}
|
||||
}
|
||||
|
||||
#[tengri_proc::command(MidiOutput)]
|
||||
impl MidiOutputCommand {
|
||||
fn _todo_ (_port: &mut MidiOutput) -> Perhaps<Self> { Ok(None) }
|
||||
}
|
||||
|
||||
impl<T: Has<Vec<MidiOutput>>> HasMidiOuts for T {
|
||||
fn midi_outs (&self) -> &Vec<MidiOutput> {
|
||||
self.get()
|
||||
}
|
||||
fn midi_outs_mut (&mut self) -> &mut Vec<MidiOutput> {
|
||||
self.get_mut()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// Trait for thing that may output MIDI.
|
||||
pub trait HasMidiOuts {
|
||||
fn midi_outs (&self) -> &Vec<MidiOutput>;
|
||||
fn midi_outs_mut (&mut self) -> &mut Vec<MidiOutput>;
|
||||
fn midi_outs_with_sizes <'a> (&'a self) ->
|
||||
impl Iterator<Item=(usize, &Arc<str>, &[Connect], usize, usize)> + Send + Sync + 'a
|
||||
{
|
||||
let mut y = 0;
|
||||
self.midi_outs().iter().enumerate().map(move|(i, output)|{
|
||||
let height = 1 + output.conn().len();
|
||||
let data = (i, output.name(), output.conn(), y, y + height);
|
||||
y += height;
|
||||
data
|
||||
})
|
||||
}
|
||||
fn midi_outs_emit (&mut self, scope: &ProcessScope) {
|
||||
for port in self.midi_outs_mut().iter_mut() {
|
||||
port.buffer_emit(scope)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Trail for thing that may gain new MIDI ports.
|
||||
impl<'j, T: HasMidiOuts + HasJack<'j>> AddMidiOut for T {
|
||||
fn midi_out_add (&mut self) -> Usually<()> {
|
||||
let index = self.midi_outs().len();
|
||||
let port = MidiOutput::new(self.jack(), &format!("{index}/M"), &[])?;
|
||||
self.midi_outs_mut().push(port);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// May create new MIDI output ports.
|
||||
pub trait AddMidiOut {
|
||||
fn midi_out_add (&mut self) -> Usually<()>;
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue