mirror of
https://codeberg.org/unspeaker/tek.git
synced 2025-12-06 19:56:42 +01:00
wip: enabling autoconnecting ports
This commit is contained in:
parent
c23f52c87b
commit
fe70b57dc1
10 changed files with 375 additions and 424 deletions
|
|
@ -1,169 +1,151 @@
|
||||||
use crate::*;
|
use crate::*;
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
pub struct JackPort<T: PortSpec> {
|
pub struct JackPort<T: PortSpec> {
|
||||||
/// Handle to JACK client, for receiving reconnect events.
|
/// Handle to JACK client, for receiving reconnect events.
|
||||||
pub jack: Arc<RwLock<JackConnection>>,
|
pub jack: Arc<RwLock<JackConnection>>,
|
||||||
/// Port handle.
|
/// Port handle.
|
||||||
pub port: Port<T>,
|
pub port: Port<T>,
|
||||||
/// List of ports to connect to.
|
/// List of ports to connect to.
|
||||||
pub connect: Vec<PortConnect>
|
pub connect: Vec<PortConnection>
|
||||||
}
|
}
|
||||||
pub struct PortConnect {
|
impl<T: PortSpec> JackPort<T> {
|
||||||
pub name: PortConnectName,
|
pub fn connect_to_matching (&mut self) {
|
||||||
pub order: PortConnectScope,
|
use PortConnectionName::*;
|
||||||
pub status: Vec<(Port<Unowned>, PortConnectStatus)>,
|
use PortConnectionScope::*;
|
||||||
}
|
use PortConnectionStatus::*;
|
||||||
impl PortConnect {
|
for connect in self.connect.iter_mut() {
|
||||||
/// Connect to this exact port
|
let mut status = vec![];
|
||||||
pub fn exact (name: impl AsRef<str>) -> Self {
|
match &connect.name {
|
||||||
let name = PortConnectName::Exact(name.as_ref().into());
|
Exact(name) => for port in self.jack.ports(None, None, PortFlags::empty()).iter() {
|
||||||
Self { name, order: PortConnectScope::One, status: vec![] }
|
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);
|
||||||
|
status.push((port, 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);
|
||||||
|
status.push((port, port_status));
|
||||||
|
if port_status == Connected && connect.scope == One {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
connect.status = status
|
||||||
|
}
|
||||||
}
|
}
|
||||||
pub fn wildcard (name: impl AsRef<str>) -> Self {
|
fn try_both_ways <A: PortSpec, B: PortSpec> (
|
||||||
let name = PortConnectName::Wildcard(name.as_ref().into());
|
jack: &impl ConnectPort, port_a: &Port<A>, port_b: &Port<B>
|
||||||
Self { name, order: PortConnectScope::One, status: vec![] }
|
)
|
||||||
}
|
-> PortConnectionStatus
|
||||||
pub fn wildcard_all (name: impl AsRef<str>) -> Self {
|
{
|
||||||
let name = PortConnectName::Wildcard(name.as_ref().into());
|
if let Ok(_) = jack.connect_ports(port_a, port_b) {
|
||||||
Self { name, order: PortConnectScope::All, status: vec![] }
|
PortConnectionStatus::Connected
|
||||||
}
|
} else if let Ok(_) = jack.connect_ports(port_b, port_a) {
|
||||||
pub fn regexp (name: impl AsRef<str>) -> Self {
|
PortConnectionStatus::Connected
|
||||||
let name = PortConnectName::RegExp(name.as_ref().into());
|
} else {
|
||||||
Self { name, order: PortConnectScope::One, status: vec![] }
|
PortConnectionStatus::Mismatch
|
||||||
}
|
}
|
||||||
pub fn regexp_all (name: impl AsRef<str>) -> Self {
|
|
||||||
let name = PortConnectName::RegExp(name.as_ref().into());
|
|
||||||
Self { name, order: PortConnectScope::All, status: vec![] }
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
#[derive(Clone, Debug, PartialEq)]
|
#[derive(Clone, Debug, PartialEq)]
|
||||||
pub enum PortConnectName {
|
pub struct PortConnection {
|
||||||
/// Exact match
|
pub name: PortConnectionName,
|
||||||
Exact(Arc<str>),
|
pub scope: PortConnectionScope,
|
||||||
/// Match wildcard
|
pub status: Vec<(Port<Unowned>, PortConnectionStatus)>,
|
||||||
Wildcard(Arc<str>),
|
}
|
||||||
/// Match regular expression
|
impl PortConnection {
|
||||||
RegExp(Arc<str>),
|
/// 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![] }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#[derive(Clone, Debug, PartialEq)]
|
||||||
|
pub enum PortConnectionName {
|
||||||
|
/** Exact match */ Exact(Arc<str>),
|
||||||
|
/** Match regular expression */ RegExp(Arc<str>),
|
||||||
}
|
}
|
||||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||||
pub enum PortConnectScope { One, All }
|
pub enum PortConnectionScope { One, All }
|
||||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||||
pub enum PortConnectStatus { Missing, Disconnected, Connected, Mismatch, }
|
pub enum PortConnectionStatus { Missing, Disconnected, Connected, Mismatch, }
|
||||||
|
|
||||||
impl<T: PortSpec> AsRef<Port<T>> for JackPort<T> {
|
impl<T: PortSpec> AsRef<Port<T>> for JackPort<T> {
|
||||||
fn as_ref (&self) -> &Port<T> {
|
fn as_ref (&self) -> &Port<T> {
|
||||||
&self.port
|
&self.port
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
impl<T: PortSpec> JackPort<T> {
|
impl JackPort<MidiIn> {
|
||||||
pub fn midi_in (
|
pub fn new (
|
||||||
jack: Arc<RwLock<JackConnection>>, name: impl AsRef<str>, connect: &[PortConnect]
|
jack: &Arc<RwLock<JackConnection>>, name: impl AsRef<str>, connect: &[PortConnection]
|
||||||
) -> Usually<JackPort<MidiIn>> {
|
) -> Usually<Self> {
|
||||||
let input = jack.midi_in(name)?;
|
let mut port = JackPort {
|
||||||
for port in connect.iter() {
|
jack: jack.clone(),
|
||||||
let port = port.as_ref();
|
port: jack.midi_in(name)?,
|
||||||
if let Some(output) = jack.port_by_name(port).as_ref() {
|
connect: connect.to_vec()
|
||||||
jack.connect_ports(output, &input)?;
|
};
|
||||||
} else {
|
port.connect_to_matching();
|
||||||
panic!("Missing MIDI output: {port}. Use jack_lsp to list all port names.");
|
Ok(port)
|
||||||
}
|
|
||||||
}
|
|
||||||
Ok(JackPort { jack: jack.clone(), port: input, connect: connect.clone() })
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn midi_out (
|
|
||||||
jack: Arc<RwLock<JackConnection>>,
|
|
||||||
name: impl AsRef<str>,
|
|
||||||
connect: &[impl AsRef<str>]
|
|
||||||
) -> Usually<JackPort<MidiOut>> {
|
|
||||||
let output = jack.midi_out(name)?;
|
|
||||||
for port in connect.iter() {
|
|
||||||
let port = port.as_ref();
|
|
||||||
if let Some(input) = jack.port_by_name(port).as_ref() {
|
|
||||||
jack.connect_ports(&output, input)?;
|
|
||||||
} else {
|
|
||||||
panic!("Missing MIDI input: {port}. Use jack_lsp to list all port names.");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Ok(JackPort { jack: jack.clone(), port: output, connect: connect.into() })
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn audio_in (
|
|
||||||
jack: Arc<RwLock<JackConnection>>,
|
|
||||||
name: impl AsRef<str>,
|
|
||||||
connect: &[impl AsRef<str>]
|
|
||||||
) -> Usually<JackPort<AudioIn>> {
|
|
||||||
let input = jack.audio_in(name)?;
|
|
||||||
for port in connect.iter() {
|
|
||||||
let port = port.as_ref();
|
|
||||||
if let Some(output) = jack.port_by_name(port).as_ref() {
|
|
||||||
jack.connect_ports(output, &input)?;
|
|
||||||
} else {
|
|
||||||
panic!("Missing MIDI output: {port}. Use jack_lsp to list all port names.");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Ok(JackPort { jack: jack.clone(), port: input, connect: connect.into() })
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn audio_out (
|
|
||||||
jack: Arc<RwLock<JackConnection>>,
|
|
||||||
name: impl AsRef<str>,
|
|
||||||
connect: &[impl AsRef<str>]
|
|
||||||
) -> Usually<JackPort<AudioOut>> {
|
|
||||||
let output = jack.audio_out(name)?;
|
|
||||||
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(JackPort { jack: jack.clone(), port: output, connect: connect.into() })
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
impl JackPort<MidiOut> {
|
||||||
|
pub fn new (
|
||||||
/// This is a utility trait for things that may register or connect [Port]s.
|
jack: &Arc<RwLock<JackConnection>>, name: impl AsRef<str>, connect: &[PortConnection]
|
||||||
/// It contains shorthand methods to this purpose. It's implemented for
|
) -> Usually<Self> {
|
||||||
/// `Arc<RwLock<JackConnection>>` for terse port registration in the
|
let mut port = Self {
|
||||||
/// `init` callback of [JackClient::activate_with].
|
jack: jack.clone(),
|
||||||
pub trait RegisterPort {
|
port: jack.midi_out(name)?,
|
||||||
fn midi_in (&self, name: impl AsRef<str>) -> Usually<Port<MidiIn>>;
|
connect: connect.to_vec()
|
||||||
fn midi_out (&self, name: impl AsRef<str>) -> Usually<Port<MidiOut>>;
|
};
|
||||||
fn audio_in (&self, name: impl AsRef<str>) -> Usually<Port<AudioIn>>;
|
port.connect_to_matching();
|
||||||
fn audio_out (&self, name: impl AsRef<str>) -> Usually<Port<AudioOut>>;
|
Ok(port)
|
||||||
}
|
|
||||||
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>> {
|
impl JackPort<AudioIn> {
|
||||||
fn midi_in (&self, name: impl AsRef<str>) -> Usually<Port<MidiIn>> {
|
pub fn new (
|
||||||
self.read().unwrap().midi_in(name)
|
jack: &Arc<RwLock<JackConnection>>, name: impl AsRef<str>, connect: &[PortConnection]
|
||||||
|
) -> Usually<Self> {
|
||||||
|
let mut port = Self {
|
||||||
|
jack: jack.clone(),
|
||||||
|
port: jack.audio_in(name)?,
|
||||||
|
connect: connect.to_vec()
|
||||||
|
};
|
||||||
|
port.connect_to_matching();
|
||||||
|
Ok(port)
|
||||||
}
|
}
|
||||||
fn midi_out (&self, name: impl AsRef<str>) -> Usually<Port<MidiOut>> {
|
}
|
||||||
self.read().unwrap().midi_out(name)
|
impl JackPort<AudioOut> {
|
||||||
}
|
pub fn new (
|
||||||
fn audio_in (&self, name: impl AsRef<str>) -> Usually<Port<AudioIn>> {
|
jack: &Arc<RwLock<JackConnection>>, name: impl AsRef<str>, connect: &[PortConnection]
|
||||||
self.read().unwrap().audio_in(name)
|
) -> Usually<Self> {
|
||||||
}
|
let mut port = Self {
|
||||||
fn audio_out (&self, name: impl AsRef<str>) -> Usually<Port<AudioOut>> {
|
jack: jack.clone(),
|
||||||
self.read().unwrap().audio_out(name)
|
port: jack.audio_out(name)?,
|
||||||
|
connect: connect.to_vec()
|
||||||
|
};
|
||||||
|
port.connect_to_matching();
|
||||||
|
Ok(port)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub trait ConnectPort {
|
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 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>)
|
fn connect_ports <A: PortSpec, B: PortSpec> (&self, source: &Port<A>, target: &Port<B>)
|
||||||
-> Usually<()>;
|
-> Usually<()>;
|
||||||
|
|
@ -213,6 +195,9 @@ pub trait ConnectPort {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
impl ConnectPort for JackConnection {
|
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>> {
|
fn port_by_name (&self, name: impl AsRef<str>) -> Option<Port<Unowned>> {
|
||||||
self.client().port_by_name(name.as_ref())
|
self.client().port_by_name(name.as_ref())
|
||||||
}
|
}
|
||||||
|
|
@ -223,6 +208,9 @@ impl ConnectPort for JackConnection {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
impl<T: ConnectPort> ConnectPort for Arc<RwLock<T>> {
|
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>> {
|
fn port_by_name (&self, name: impl AsRef<str>) -> Option<Port<Unowned>> {
|
||||||
self.read().unwrap().port_by_name(name.as_ref())
|
self.read().unwrap().port_by_name(name.as_ref())
|
||||||
}
|
}
|
||||||
|
|
@ -233,6 +221,45 @@ impl<T: ConnectPort> ConnectPort for Arc<RwLock<T>> {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 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: 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)
|
||||||
|
}
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
///// Collection of JACK ports as [AudioIn]/[AudioOut]/[MidiIn]/[MidiOut].
|
///// Collection of JACK ports as [AudioIn]/[AudioOut]/[MidiIn]/[MidiOut].
|
||||||
//#[derive(Default, Debug)]
|
//#[derive(Default, Debug)]
|
||||||
//pub struct JackPorts {
|
//pub struct JackPorts {
|
||||||
|
|
|
||||||
|
|
@ -6,7 +6,8 @@ pub(crate) use ::jack::{
|
||||||
contrib::ClosureProcessHandler, NotificationHandler,
|
contrib::ClosureProcessHandler, NotificationHandler,
|
||||||
Client, AsyncClient, ClientOptions, ClientStatus,
|
Client, AsyncClient, ClientOptions, ClientStatus,
|
||||||
ProcessScope, Control, Frames,
|
ProcessScope, Control, Frames,
|
||||||
Port, PortId, PortSpec, Unowned, MidiIn, MidiOut, AudioIn, AudioOut,
|
Port, PortId, PortSpec, PortFlags,
|
||||||
|
Unowned, MidiIn, MidiOut, AudioIn, AudioOut,
|
||||||
};
|
};
|
||||||
|
|
||||||
mod from_jack; pub use self::from_jack::*;
|
mod from_jack; pub use self::from_jack::*;
|
||||||
|
|
|
||||||
|
|
@ -2,8 +2,8 @@ use crate::*;
|
||||||
|
|
||||||
/// Trait for thing that may receive MIDI.
|
/// Trait for thing that may receive MIDI.
|
||||||
pub trait HasMidiIns {
|
pub trait HasMidiIns {
|
||||||
fn midi_ins (&self) -> &Vec<Port<MidiIn>>;
|
fn midi_ins (&self) -> &Vec<JackPort<MidiIn>>;
|
||||||
fn midi_ins_mut (&mut self) -> &mut Vec<Port<MidiIn>>;
|
fn midi_ins_mut (&mut self) -> &mut Vec<JackPort<MidiIn>>;
|
||||||
fn has_midi_ins (&self) -> bool {
|
fn has_midi_ins (&self) -> bool {
|
||||||
!self.midi_ins().is_empty()
|
!self.midi_ins().is_empty()
|
||||||
}
|
}
|
||||||
|
|
@ -27,7 +27,7 @@ pub trait MidiRecordApi: HasClock + HasPlayPhrase + HasMidiIns {
|
||||||
let notes_in = self.notes_in().clone();
|
let notes_in = self.notes_in().clone();
|
||||||
let monitoring = self.monitoring();
|
let monitoring = self.monitoring();
|
||||||
for input in self.midi_ins_mut().iter() {
|
for input in self.midi_ins_mut().iter() {
|
||||||
for (sample, event, bytes) in parse_midi_input(input.iter(scope)) {
|
for (sample, event, bytes) in parse_midi_input(input.port.iter(scope)) {
|
||||||
if let LiveEvent::Midi { message, .. } = event {
|
if let LiveEvent::Midi { message, .. } = event {
|
||||||
if monitoring {
|
if monitoring {
|
||||||
midi_buf[sample].push(bytes.to_vec());
|
midi_buf[sample].push(bytes.to_vec());
|
||||||
|
|
@ -67,7 +67,7 @@ pub trait MidiRecordApi: HasClock + HasPlayPhrase + HasMidiIns {
|
||||||
let mut phrase = phrase.write().unwrap();
|
let mut phrase = phrase.write().unwrap();
|
||||||
let length = phrase.length;
|
let length = phrase.length;
|
||||||
for input in self.midi_ins_mut().iter() {
|
for input in self.midi_ins_mut().iter() {
|
||||||
for (sample, event, bytes) in parse_midi_input(input.iter(scope)) {
|
for (sample, event, bytes) in parse_midi_input(input.port.iter(scope)) {
|
||||||
if let LiveEvent::Midi { message, .. } = event {
|
if let LiveEvent::Midi { message, .. } = event {
|
||||||
phrase.record_event({
|
phrase.record_event({
|
||||||
let sample = (sample0 + sample - start) as f64;
|
let sample = (sample0 + sample - start) as f64;
|
||||||
|
|
|
||||||
|
|
@ -2,8 +2,8 @@ use crate::*;
|
||||||
|
|
||||||
/// Trait for thing that may output MIDI.
|
/// Trait for thing that may output MIDI.
|
||||||
pub trait HasMidiOuts {
|
pub trait HasMidiOuts {
|
||||||
fn midi_outs (&self) -> &Vec<Port<MidiOut>>;
|
fn midi_outs (&self) -> &Vec<JackPort<MidiOut>>;
|
||||||
fn midi_outs_mut (&mut self) -> &mut Vec<Port<MidiOut>>;
|
fn midi_outs_mut (&mut self) -> &mut Vec<JackPort<MidiOut>>;
|
||||||
fn has_midi_outs (&self) -> bool {
|
fn has_midi_outs (&self) -> bool {
|
||||||
!self.midi_outs().is_empty()
|
!self.midi_outs().is_empty()
|
||||||
}
|
}
|
||||||
|
|
@ -143,7 +143,7 @@ pub trait MidiPlaybackApi: HasPlayPhrase + HasClock + HasMidiOuts {
|
||||||
fn write (&mut self, scope: &ProcessScope, out: &[Vec<Vec<u8>>]) {
|
fn write (&mut self, scope: &ProcessScope, out: &[Vec<Vec<u8>>]) {
|
||||||
let samples = scope.n_frames() as usize;
|
let samples = scope.n_frames() as usize;
|
||||||
for port in self.midi_outs_mut().iter_mut() {
|
for port in self.midi_outs_mut().iter_mut() {
|
||||||
Self::write_port(&mut port.writer(scope), samples, out)
|
Self::write_port(&mut port.port.writer(scope), samples, out)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -35,9 +35,9 @@ pub struct MidiPlayer {
|
||||||
/// Send all notes off
|
/// Send all notes off
|
||||||
pub reset: bool, // TODO?: after Some(nframes)
|
pub reset: bool, // TODO?: after Some(nframes)
|
||||||
/// Record from MIDI ports to current sequence.
|
/// Record from MIDI ports to current sequence.
|
||||||
pub midi_ins: Vec<Port<MidiIn>>,
|
pub midi_ins: Vec<JackPort<MidiIn>>,
|
||||||
/// Play from current sequence to MIDI ports
|
/// Play from current sequence to MIDI ports
|
||||||
pub midi_outs: Vec<Port<MidiOut>>,
|
pub midi_outs: Vec<JackPort<MidiOut>>,
|
||||||
/// Notes currently held at input
|
/// Notes currently held at input
|
||||||
pub notes_in: Arc<RwLock<[bool; 128]>>,
|
pub notes_in: Arc<RwLock<[bool; 128]>>,
|
||||||
/// Notes currently held at output
|
/// Notes currently held at output
|
||||||
|
|
@ -47,33 +47,28 @@ pub struct MidiPlayer {
|
||||||
}
|
}
|
||||||
impl MidiPlayer {
|
impl MidiPlayer {
|
||||||
pub fn new (
|
pub fn new (
|
||||||
jack: &Arc<RwLock<JackConnection>>,
|
jack: &Arc<RwLock<JackConnection>>,
|
||||||
name: impl AsRef<str>,
|
name: impl AsRef<str>,
|
||||||
clip: Option<&Arc<RwLock<MidiClip>>>,
|
clip: Option<&Arc<RwLock<MidiClip>>>,
|
||||||
midi_from: &[impl AsRef<str>],
|
midi_from: &[PortConnection],
|
||||||
midi_to: &[impl AsRef<str>],
|
midi_to: &[PortConnection],
|
||||||
) -> Usually<Self> {
|
) -> Usually<Self> {
|
||||||
let name = name.as_ref();
|
let name = name.as_ref();
|
||||||
let midi_in = jack.midi_in(&format!("M/{name}"), midi_from)?;
|
let clock = Clock::from(jack);
|
||||||
jack.connect_midi_from(&midi_in, midi_from)?;
|
|
||||||
let midi_out = jack.midi_out(&format!("{name}/M"), midi_to)?;
|
|
||||||
jack.connect_midi_to(&midi_out, midi_to)?;
|
|
||||||
let clock = Clock::from(jack);
|
|
||||||
Ok(Self {
|
Ok(Self {
|
||||||
play_phrase: Some((Moment::zero(&clock.timebase), clip.cloned())),
|
play_phrase: Some((Moment::zero(&clock.timebase), clip.cloned())),
|
||||||
|
|
||||||
next_phrase: None,
|
next_phrase: None,
|
||||||
recording: false,
|
recording: false,
|
||||||
monitoring: false,
|
monitoring: false,
|
||||||
overdub: false,
|
overdub: false,
|
||||||
|
|
||||||
notes_in: RwLock::new([false;128]).into(),
|
notes_in: RwLock::new([false;128]).into(),
|
||||||
midi_ins: vec![midi_in],
|
notes_out: RwLock::new([false;128]).into(),
|
||||||
midi_outs: vec![midi_out],
|
note_buf: vec![0;8],
|
||||||
notes_out: RwLock::new([false;128]).into(),
|
reset: true,
|
||||||
note_buf: vec![0;8],
|
|
||||||
reset: true,
|
|
||||||
|
|
||||||
|
midi_ins: vec![JackPort::<MidiIn>::new(jack, format!("M/{name}"), midi_from)?,],
|
||||||
|
midi_outs: vec![JackPort::<MidiOut>::new(jack, format!("{name}/M"), midi_to)?, ],
|
||||||
clock,
|
clock,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
@ -114,26 +109,14 @@ from!(|state: (&Clock, &Arc<RwLock<MidiClip>>)|MidiPlayer = {
|
||||||
model
|
model
|
||||||
});
|
});
|
||||||
has_clock!(|self: MidiPlayer|&self.clock);
|
has_clock!(|self: MidiPlayer|&self.clock);
|
||||||
|
|
||||||
impl HasMidiIns for MidiPlayer {
|
impl HasMidiIns for MidiPlayer {
|
||||||
fn midi_ins (&self) -> &Vec<Port<MidiIn>> {
|
fn midi_ins (&self) -> &Vec<JackPort<MidiIn>> { &self.midi_ins }
|
||||||
&self.midi_ins
|
fn midi_ins_mut (&mut self) -> &mut Vec<JackPort<MidiIn>> { &mut self.midi_ins }
|
||||||
}
|
|
||||||
fn midi_ins_mut (&mut self) -> &mut Vec<Port<MidiIn>> {
|
|
||||||
&mut self.midi_ins
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl HasMidiOuts for MidiPlayer {
|
impl HasMidiOuts for MidiPlayer {
|
||||||
fn midi_outs (&self) -> &Vec<Port<MidiOut>> {
|
fn midi_outs (&self) -> &Vec<JackPort<MidiOut>> { &self.midi_outs }
|
||||||
&self.midi_outs
|
fn midi_outs_mut (&mut self) -> &mut Vec<JackPort<MidiOut>> { &mut self.midi_outs }
|
||||||
}
|
fn midi_note (&mut self) -> &mut Vec<u8> { &mut self.note_buf }
|
||||||
fn midi_outs_mut (&mut self) -> &mut Vec<Port<MidiOut>> {
|
|
||||||
&mut self.midi_outs
|
|
||||||
}
|
|
||||||
fn midi_note (&mut self) -> &mut Vec<u8> {
|
|
||||||
&mut self.note_buf
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Hosts the JACK callback for a single MIDI player
|
/// Hosts the JACK callback for a single MIDI player
|
||||||
|
|
|
||||||
158
src/main.rs
158
src/main.rs
|
|
@ -15,67 +15,38 @@ pub struct TekCli {
|
||||||
#[arg(short='s', long, default_value_t = true)] sync_follow: bool,
|
#[arg(short='s', long, default_value_t = true)] sync_follow: bool,
|
||||||
/// Initial tempo in beats per minute
|
/// Initial tempo in beats per minute
|
||||||
#[arg(short='b', long, default_value = None)] bpm: Option<f64>,
|
#[arg(short='b', long, default_value = None)] bpm: Option<f64>,
|
||||||
|
/// Whether to include a transport toolbar (default: true)
|
||||||
|
#[arg(short='t', long, default_value_t = true)] show_clock: bool,
|
||||||
|
/// MIDI outs to connect to (multiple instances accepted)
|
||||||
|
#[arg(short='I', long)] midi_from: Vec<String>,
|
||||||
|
/// MIDI outs to connect to (multiple instances accepted)
|
||||||
|
#[arg(short='i', long)] midi_from_re: Vec<String>,
|
||||||
|
/// MIDI ins to connect to (multiple instances accepted)
|
||||||
|
#[arg(short='O', long)] midi_to: Vec<String>,
|
||||||
|
/// MIDI ins to connect to (multiple instances accepted)
|
||||||
|
#[arg(short='o', long)] midi_to_re: Vec<String>,
|
||||||
|
/// Audio outs to connect to left input
|
||||||
|
#[arg(short='l', long)] l_from: Vec<String>,
|
||||||
|
/// Audio outs to connect to right input
|
||||||
|
#[arg(short='r', long)] r_from: Vec<String>,
|
||||||
|
/// Audio ins to connect from left output
|
||||||
|
#[arg(short='L', long)] l_to: Vec<String>,
|
||||||
|
/// Audio ins to connect from right output
|
||||||
|
#[arg(short='R', long)] r_to: Vec<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Subcommand)]
|
#[derive(Debug, Clone, Subcommand)]
|
||||||
pub enum TekMode {
|
pub enum TekMode {
|
||||||
/// A standalone transport view.
|
/// A standalone transport clock.
|
||||||
Clock,
|
Clock,
|
||||||
/// A MIDI sequencer.
|
/// A MIDI sequencer.
|
||||||
Sequencer {
|
Sequencer,
|
||||||
/// Whether to include a transport toolbar (default: true)
|
|
||||||
#[arg(short='t', long, default_value_t = true)] show_clock: bool,
|
|
||||||
/// MIDI outs to connect to (multiple instances accepted)
|
|
||||||
#[arg(short='i', long)] midi_from: Vec<String>,
|
|
||||||
/// MIDI ins to connect to (multiple instances accepted)
|
|
||||||
#[arg(short='o', long)] midi_to: Vec<String>,
|
|
||||||
},
|
|
||||||
/// A MIDI-controlled audio sampler.
|
/// A MIDI-controlled audio sampler.
|
||||||
Sampler {
|
Sampler,
|
||||||
/// MIDI outs to connect to (multiple instances accepted)
|
|
||||||
#[arg(short='i', long)] midi_from: Vec<String>,
|
|
||||||
/// Audio outs to connect to left input
|
|
||||||
#[arg(short='l', long)] l_from: Vec<String>,
|
|
||||||
/// Audio outs to connect to right input
|
|
||||||
#[arg(short='r', long)] r_from: Vec<String>,
|
|
||||||
/// Audio ins to connect from left output
|
|
||||||
#[arg(short='L', long)] l_to: Vec<String>,
|
|
||||||
/// Audio ins to connect from right output
|
|
||||||
#[arg(short='R', long)] r_to: Vec<String>,
|
|
||||||
},
|
|
||||||
/// Sequencer and sampler together.
|
/// Sequencer and sampler together.
|
||||||
Groovebox {
|
Groovebox,
|
||||||
/// Whether to include a transport toolbar (default: true)
|
|
||||||
#[arg(short='t', long, default_value_t = true)] show_clock: bool,
|
|
||||||
/// MIDI outs to connect to (multiple instances accepted)
|
|
||||||
#[arg(short='i', long)] midi_from: Vec<String>,
|
|
||||||
/// MIDI ins to connect to (multiple instances accepted)
|
|
||||||
#[arg(short='o', long)] midi_to: Vec<String>,
|
|
||||||
/// Audio outs to connect to left input
|
|
||||||
#[arg(short='l', long)] l_from: Vec<String>,
|
|
||||||
/// Audio outs to connect to right input
|
|
||||||
#[arg(short='r', long)] r_from: Vec<String>,
|
|
||||||
/// Audio ins to connect from left output
|
|
||||||
#[arg(short='L', long)] l_to: Vec<String>,
|
|
||||||
/// Audio ins to connect from right output
|
|
||||||
#[arg(short='R', long)] r_to: Vec<String>,
|
|
||||||
},
|
|
||||||
/// Multi-track MIDI sequencer.
|
/// Multi-track MIDI sequencer.
|
||||||
Arranger {
|
Arranger {
|
||||||
/// Whether to include a transport toolbar (default: true)
|
|
||||||
#[arg(short='t', long, default_value_t = true)] show_clock: bool,
|
|
||||||
/// MIDI outs to connect to (multiple instances accepted)
|
|
||||||
#[arg(short='i', long)] midi_from: Vec<String>,
|
|
||||||
/// MIDI ins to connect to (multiple instances accepted)
|
|
||||||
#[arg(short='o', long)] midi_to: Vec<String>,
|
|
||||||
/// Audio outs to connect to left input
|
|
||||||
#[arg(short='l', long)] l_from: Vec<String>,
|
|
||||||
/// Audio outs to connect to right input
|
|
||||||
#[arg(short='r', long)] r_from: Vec<String>,
|
|
||||||
/// Audio ins to connect from left output
|
|
||||||
#[arg(short='L', long)] l_to: Vec<String>,
|
|
||||||
/// Audio ins to connect from right output
|
|
||||||
#[arg(short='R', long)] r_to: Vec<String>,
|
|
||||||
/// Number of tracks
|
/// Number of tracks
|
||||||
#[arg(short = 'x', long, default_value_t = 16)] tracks: usize,
|
#[arg(short = 'x', long, default_value_t = 16)] tracks: usize,
|
||||||
/// Width of tracks
|
/// Width of tracks
|
||||||
|
|
@ -97,6 +68,12 @@ pub fn main () -> Usually<()> {
|
||||||
let name = cli.name.as_ref().map_or("tek", |x|x.as_str());
|
let name = cli.name.as_ref().map_or("tek", |x|x.as_str());
|
||||||
let jack = JackConnection::new(name)?;
|
let jack = JackConnection::new(name)?;
|
||||||
let engine = Tui::new()?;
|
let engine = Tui::new()?;
|
||||||
|
let mut midi_froms = vec![];
|
||||||
|
let mut midi_tos = vec![];
|
||||||
|
for port in cli.midi_from.iter() { midi_froms.push(PortConnection::exact(port.into())) }
|
||||||
|
for port in cli.midi_from_re.iter() { midi_froms.push(PortConnection::regexp(port.into())) }
|
||||||
|
for port in cli.midi_to.iter() { midi_tos.push(PortConnection::exact(port.into())) }
|
||||||
|
for port in cli.midi_to_re.iter() { midi_tos.push(PortConnection::regexp(port.into())) }
|
||||||
Ok(match cli.mode {
|
Ok(match cli.mode {
|
||||||
|
|
||||||
TekMode::Clock => engine.run(&jack.activate_with(|jack|Ok(TransportTui {
|
TekMode::Clock => engine.run(&jack.activate_with(|jack|Ok(TransportTui {
|
||||||
|
|
@ -104,15 +81,11 @@ pub fn main () -> Usually<()> {
|
||||||
jack: jack.clone()
|
jack: jack.clone()
|
||||||
}))?)?,
|
}))?)?,
|
||||||
|
|
||||||
TekMode::Sequencer {
|
TekMode::Sequencer => engine.run(&jack.activate_with(|jack|Ok({
|
||||||
midi_from, midi_to, ..
|
let length = 384;
|
||||||
} => engine.run(&jack.activate_with(|jack|Ok({
|
let color = Some(ItemColor::random().into());
|
||||||
let clock = Clock::from(jack);
|
let clip = Arc::new(RwLock::new(MidiClip::new("Clip", true, length, None, color)));
|
||||||
let clip = Arc::new(RwLock::new(MidiClip::new(
|
let player = MidiPlayer::new(&jack, name, Some(&clip), &midi_froms, &midi_tos)?;
|
||||||
"Clip", true, 4 * clock.timebase.ppq.get() as usize,
|
|
||||||
None, Some(ItemColor::random().into())
|
|
||||||
)));
|
|
||||||
let player = MidiPlayer::new(&jack, name, Some(&clip), &midi_from, &midi_to)?;
|
|
||||||
Sequencer {
|
Sequencer {
|
||||||
_jack: jack.clone(),
|
_jack: jack.clone(),
|
||||||
clock: player.clock.clone(),
|
clock: player.clock.clone(),
|
||||||
|
|
@ -130,9 +103,7 @@ pub fn main () -> Usually<()> {
|
||||||
}
|
}
|
||||||
}))?)?,
|
}))?)?,
|
||||||
|
|
||||||
TekMode::Sampler {
|
TekMode::Sampler => engine.run(&jack.activate_with(|jack|Ok(
|
||||||
midi_from, l_from, r_from, l_to, r_to, ..
|
|
||||||
} => engine.run(&jack.activate_with(|jack|Ok(
|
|
||||||
SamplerTui {
|
SamplerTui {
|
||||||
cursor: (0, 0),
|
cursor: (0, 0),
|
||||||
editing: None,
|
editing: None,
|
||||||
|
|
@ -141,53 +112,29 @@ pub fn main () -> Usually<()> {
|
||||||
note_lo: 36.into(),
|
note_lo: 36.into(),
|
||||||
note_pt: 36.into(),
|
note_pt: 36.into(),
|
||||||
color: ItemPalette::from(Color::Rgb(64, 128, 32)),
|
color: ItemPalette::from(Color::Rgb(64, 128, 32)),
|
||||||
state: Sampler::new(jack, &"sampler",
|
state: Sampler::new(jack, &"sampler", &midi_froms, &[&l_from, &r_from], &[&l_to, &r_to])?,
|
||||||
&midi_from,
|
|
||||||
&[&l_from, &r_from],
|
|
||||||
&[&l_to, &r_to],
|
|
||||||
)?,
|
|
||||||
}
|
}
|
||||||
))?)?,
|
))?)?,
|
||||||
|
|
||||||
TekMode::Groovebox {
|
TekMode::Groovebox => engine.run(&jack.activate_with(|jack|Ok({
|
||||||
midi_from, midi_to, l_from, r_from, l_to, r_to, ..
|
let length = 384;
|
||||||
} => engine.run(&jack.activate_with(|jack|Ok({
|
let color = Some(ItemColor::random().into());
|
||||||
let ppq = 96;
|
let clip = Arc::new(RwLock::new(MidiClip::new("Clip", true, length, None, color)));
|
||||||
let phrase = Arc::new(RwLock::new(MidiClip::new(
|
let mut player = MidiPlayer::new(jack, &"sequencer", Some(&clip), &midi_froms, &midi_tos)?;
|
||||||
"Clip",
|
let sampler = Sampler::new(jack, &"sampler", &midi_froms, &[&l_from, &r_from], &[&l_to, &r_to])?;
|
||||||
true,
|
jack.read().unwrap().client().connect_ports(&player.midi_outs[0].port, &sampler.midi_in.port)?;
|
||||||
4 * ppq,
|
|
||||||
None,
|
|
||||||
Some(ItemColor::random().into())
|
|
||||||
)));
|
|
||||||
let mut player = MidiPlayer::new(jack, &"sequencer", Some(&phrase),
|
|
||||||
&midi_from,
|
|
||||||
&midi_to
|
|
||||||
)?;
|
|
||||||
player.play_phrase = Some((Moment::zero(&player.clock.timebase), Some(phrase.clone())));
|
|
||||||
let sampler = Sampler::new(jack, &"sampler",
|
|
||||||
&midi_from,
|
|
||||||
&[&l_from, &r_from],
|
|
||||||
&[&l_to, &r_to ],
|
|
||||||
)?;
|
|
||||||
jack.read().unwrap().client().connect_ports(
|
|
||||||
&player.midi_outs[0],
|
|
||||||
&sampler.midi_in
|
|
||||||
)?;
|
|
||||||
let app = Groovebox {
|
let app = Groovebox {
|
||||||
player,
|
player,
|
||||||
sampler,
|
sampler,
|
||||||
_jack: jack.clone(),
|
pool: PoolModel::from(&clip),
|
||||||
|
editor: MidiEditor::from(&clip),
|
||||||
pool: PoolModel::from(&phrase),
|
|
||||||
editor: MidiEditor::from(&phrase),
|
|
||||||
|
|
||||||
compact: true,
|
compact: true,
|
||||||
status: true,
|
status: true,
|
||||||
size: Measure::new(),
|
size: Measure::new(),
|
||||||
midi_buf: vec![vec![];65536],
|
midi_buf: vec![vec![];65536],
|
||||||
note_buf: vec![],
|
note_buf: vec![],
|
||||||
perf: PerfModel::default(),
|
perf: PerfModel::default(),
|
||||||
|
_jack: jack.clone(),
|
||||||
};
|
};
|
||||||
if let Some(bpm) = cli.bpm {
|
if let Some(bpm) = cli.bpm {
|
||||||
app.clock().timebase.bpm.set(bpm);
|
app.clock().timebase.bpm.set(bpm);
|
||||||
|
|
@ -207,14 +154,13 @@ pub fn main () -> Usually<()> {
|
||||||
app
|
app
|
||||||
}))?)?,
|
}))?)?,
|
||||||
|
|
||||||
TekMode::Arranger {
|
TekMode::Arranger { scenes, tracks, track_width, .. } =>
|
||||||
scenes, tracks, track_width, midi_from, midi_to, ..
|
engine.run(&jack.activate_with(|jack|Ok({
|
||||||
} => engine.run(&jack.activate_with(|jack|Ok({
|
let mut app = Arranger::new(jack);
|
||||||
let mut app = Arranger::new(jack);
|
app.tracks_add(tracks, track_width, &midi_froms, &midi_tos)?;
|
||||||
app.tracks_add(tracks, track_width, midi_from.as_slice(), midi_to.as_slice())?;
|
app.scenes_add(scenes)?;
|
||||||
app.scenes_add(scenes)?;
|
app
|
||||||
app
|
}))?)?,
|
||||||
}))?)?,
|
|
||||||
|
|
||||||
_ => todo!()
|
_ => todo!()
|
||||||
})
|
})
|
||||||
|
|
|
||||||
|
|
@ -37,13 +37,9 @@ impl Arranger {
|
||||||
let color = track_color_1.mix(track_color_2, i as f32 / count as f32).into();
|
let color = track_color_1.mix(track_color_2, i as f32 / count as f32).into();
|
||||||
let mut track = self.track_add(None, Some(color))?;
|
let mut track = self.track_add(None, Some(color))?;
|
||||||
track.width = width;
|
track.width = width;
|
||||||
|
let port = JackPort::<MidiIn>::new(&jack, &format!("{}I", &track.name), &[])?;
|
||||||
let name = &format!("{}I", &track.name);
|
|
||||||
let port = jack.read().unwrap().client().register_port(&name, MidiIn::default())?;
|
|
||||||
track.player.midi_ins.push(port);
|
track.player.midi_ins.push(port);
|
||||||
|
let port = JackPort::<MidiOut>::new(&jack, &format!("{}O", &track.name), &[])?;
|
||||||
let name = &format!("{}O", &track.name);
|
|
||||||
let port = jack.read().unwrap().client().register_port(&name, MidiOut::default())?;
|
|
||||||
track.player.midi_outs.push(port);
|
track.player.midi_outs.push(port);
|
||||||
}
|
}
|
||||||
for connection in midi_from.iter() {
|
for connection in midi_from.iter() {
|
||||||
|
|
@ -51,14 +47,14 @@ impl Arranger {
|
||||||
let number = split.next().unwrap().trim();
|
let number = split.next().unwrap().trim();
|
||||||
if let Ok(track) = number.parse::<usize>() {
|
if let Ok(track) = number.parse::<usize>() {
|
||||||
if track < 1 {
|
if track < 1 {
|
||||||
panic!("Tracks are zero-indexed")
|
panic!("Tracks start from 1")
|
||||||
}
|
}
|
||||||
if track > count {
|
if track > count {
|
||||||
panic!("Tried to connect track {track} or {count}. Pass -t {track} to increase number of tracks.")
|
panic!("Tried to connect track {track} or {count}. Pass -t {track} to increase number of tracks.")
|
||||||
}
|
}
|
||||||
if let Some(port) = split.next() {
|
if let Some(port) = split.next() {
|
||||||
if let Some(port) = jack.read().unwrap().client().port_by_name(port).as_ref() {
|
if let Some(port) = jack.read().unwrap().client().port_by_name(port).as_ref() {
|
||||||
jack.read().unwrap().client().connect_ports(port, &self.tracks[track-1].player.midi_ins[0])?;
|
//jack.read().unwrap().client().connect_ports(port, &self.tracks[track-1].player.midi_ins[0])?;
|
||||||
} else {
|
} else {
|
||||||
panic!("Missing MIDI output: {port}. Use jack_lsp to list all port names.");
|
panic!("Missing MIDI output: {port}. Use jack_lsp to list all port names.");
|
||||||
}
|
}
|
||||||
|
|
@ -74,14 +70,14 @@ impl Arranger {
|
||||||
let number = split.next().unwrap().trim();
|
let number = split.next().unwrap().trim();
|
||||||
if let Ok(track) = number.parse::<usize>() {
|
if let Ok(track) = number.parse::<usize>() {
|
||||||
if track < 1 {
|
if track < 1 {
|
||||||
panic!("Tracks are zero-indexed")
|
panic!("Tracks start from 1")
|
||||||
}
|
}
|
||||||
if track > count {
|
if track > count {
|
||||||
panic!("Tried to connect track {track} or {count}. Pass -t {track} to increase number of tracks.")
|
panic!("Tried to connect track {track} or {count}. Pass -t {track} to increase number of tracks.")
|
||||||
}
|
}
|
||||||
if let Some(port) = split.next() {
|
if let Some(port) = split.next() {
|
||||||
if let Some(port) = jack.read().unwrap().client().port_by_name(port).as_ref() {
|
if let Some(port) = jack.read().unwrap().client().port_by_name(port).as_ref() {
|
||||||
jack.read().unwrap().client().connect_ports(&self.tracks[track-1].player.midi_outs[0], port)?;
|
//jack.read().unwrap().client().connect_ports(&self.tracks[track-1].player.midi_outs[0], port)?;
|
||||||
} else {
|
} else {
|
||||||
panic!("Missing MIDI input: {port}. Use jack_lsp to list all port names.");
|
panic!("Missing MIDI input: {port}. Use jack_lsp to list all port names.");
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -38,7 +38,7 @@ audio!(|self: Groovebox, client, scope|{
|
||||||
return Control::Quit
|
return Control::Quit
|
||||||
}
|
}
|
||||||
// TODO move these to editor and sampler:
|
// TODO move these to editor and sampler:
|
||||||
for RawMidi { time, bytes } in self.player.midi_ins[0].iter(scope) {
|
for RawMidi { time, bytes } in self.player.midi_ins[0].port.iter(scope) {
|
||||||
if let LiveEvent::Midi { message, .. } = LiveEvent::parse(bytes).unwrap() {
|
if let LiveEvent::Midi { message, .. } = LiveEvent::parse(bytes).unwrap() {
|
||||||
match message {
|
match message {
|
||||||
MidiMessage::NoteOn { ref key, .. } => {
|
MidiMessage::NoteOn { ref key, .. } => {
|
||||||
|
|
|
||||||
|
|
@ -2,12 +2,10 @@ mod sample; pub use self::sample::*;
|
||||||
mod sample_import; pub use self::sample_import::*;
|
mod sample_import; pub use self::sample_import::*;
|
||||||
mod sample_list; pub use self::sample_list::*;
|
mod sample_list; pub use self::sample_list::*;
|
||||||
mod sample_viewer; pub use self::sample_viewer::*;
|
mod sample_viewer; pub use self::sample_viewer::*;
|
||||||
mod sampler_audio; pub use self::sampler_audio::*;
|
|
||||||
mod sampler_command; pub use self::sampler_command::*;
|
mod sampler_command; pub use self::sampler_command::*;
|
||||||
mod sampler_status; pub use self::sampler_status::*;
|
mod sampler_status; pub use self::sampler_status::*;
|
||||||
mod sampler_tui; pub use self::sampler_tui::*;
|
mod sampler_tui; pub use self::sampler_tui::*;
|
||||||
mod voice; pub use self::voice::*;
|
mod voice; pub use self::voice::*;
|
||||||
|
|
||||||
use crate::*;
|
use crate::*;
|
||||||
use KeyCode::Char;
|
use KeyCode::Char;
|
||||||
use std::fs::File;
|
use std::fs::File;
|
||||||
|
|
@ -23,7 +21,6 @@ use symphonia::{
|
||||||
default::get_codecs,
|
default::get_codecs,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
/// The sampler plugin plays sounds.
|
/// The sampler plugin plays sounds.
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub struct Sampler {
|
pub struct Sampler {
|
||||||
|
|
@ -33,10 +30,10 @@ pub struct Sampler {
|
||||||
pub recording: Option<(usize, Arc<RwLock<Sample>>)>,
|
pub recording: Option<(usize, Arc<RwLock<Sample>>)>,
|
||||||
pub unmapped: Vec<Arc<RwLock<Sample>>>,
|
pub unmapped: Vec<Arc<RwLock<Sample>>>,
|
||||||
pub voices: Arc<RwLock<Vec<Voice>>>,
|
pub voices: Arc<RwLock<Vec<Voice>>>,
|
||||||
pub midi_in: Port<MidiIn>,
|
pub midi_in: JackPort<MidiIn>,
|
||||||
pub audio_ins: Vec<Port<AudioIn>>,
|
pub audio_ins: Vec<JackPort<AudioIn>>,
|
||||||
pub input_meter: Vec<f32>,
|
pub input_meter: Vec<f32>,
|
||||||
pub audio_outs: Vec<Port<AudioOut>>,
|
pub audio_outs: Vec<JackPort<AudioOut>>,
|
||||||
pub buffer: Vec<Vec<f32>>,
|
pub buffer: Vec<Vec<f32>>,
|
||||||
pub output_gain: f32
|
pub output_gain: f32
|
||||||
}
|
}
|
||||||
|
|
@ -44,21 +41,21 @@ impl Sampler {
|
||||||
pub fn new (
|
pub fn new (
|
||||||
jack: &Arc<RwLock<JackConnection>>,
|
jack: &Arc<RwLock<JackConnection>>,
|
||||||
name: impl AsRef<str>,
|
name: impl AsRef<str>,
|
||||||
midi_from: &[impl AsRef<str>],
|
midi_from: &[PortConnection],
|
||||||
audio_from: &[&[impl AsRef<str>];2],
|
audio_from: &[&[PortConnection];2],
|
||||||
audio_to: &[&[impl AsRef<str>];2],
|
audio_to: &[&[PortConnection];2],
|
||||||
) -> Usually<Self> {
|
) -> Usually<Self> {
|
||||||
let name = name.as_ref();
|
let name = name.as_ref();
|
||||||
Ok(Self {
|
Ok(Self {
|
||||||
midi_in: jack.midi_in(&format!("M/{name}"), midi_from)?,
|
midi_in: JackPort::<MidiIn>::new(jack, format!("M/{name}"), midi_from)?,
|
||||||
audio_ins: vec![
|
audio_ins: vec![
|
||||||
jack.audio_in(&format!("L/{name}"), audio_from[0])?,
|
JackPort::<AudioIn>::new(jack, &format!("L/{name}"), audio_from[0])?,
|
||||||
jack.audio_in(&format!("R/{name}"), audio_from[1])?
|
JackPort::<AudioIn>::new(jack, &format!("R/{name}"), audio_from[1])?,
|
||||||
],
|
],
|
||||||
input_meter: vec![0.0;2],
|
input_meter: vec![0.0;2],
|
||||||
audio_outs: vec![
|
audio_outs: vec![
|
||||||
jack.audio_out(&format!("{name}/L"), audio_to[0])?,
|
JackPort::<AudioOut>::new(jack, &format!("{name}/L"), audio_to[0])?,
|
||||||
jack.audio_out(&format!("{name}/R"), audio_to[1])?,
|
JackPort::<AudioOut>::new(jack, &format!("{name}/R"), audio_to[1])?,
|
||||||
],
|
],
|
||||||
jack: jack.clone(),
|
jack: jack.clone(),
|
||||||
name: name.into(),
|
name: name.into(),
|
||||||
|
|
@ -91,6 +88,120 @@ impl Sampler {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
audio!(|self: SamplerTui, client, scope|{
|
||||||
|
SamplerAudio(&mut self.state).process(client, scope)
|
||||||
|
});
|
||||||
|
|
||||||
|
pub struct SamplerAudio<'a>(pub &'a mut Sampler);
|
||||||
|
|
||||||
|
audio!(|self: SamplerAudio<'a>, _client, scope|{
|
||||||
|
self.0.process_midi_in(scope);
|
||||||
|
self.0.clear_output_buffer();
|
||||||
|
self.0.process_audio_out(scope);
|
||||||
|
self.0.write_output_buffer(scope);
|
||||||
|
self.0.process_audio_in(scope);
|
||||||
|
Control::Continue
|
||||||
|
});
|
||||||
|
|
||||||
|
impl Sampler {
|
||||||
|
|
||||||
|
pub fn process_audio_in (&mut self, scope: &ProcessScope) {
|
||||||
|
let Sampler { audio_ins, input_meter, recording, .. } = self;
|
||||||
|
if audio_ins.len() != input_meter.len() {
|
||||||
|
*input_meter = vec![0.0;audio_ins.len()];
|
||||||
|
}
|
||||||
|
if let Some((_, sample)) = recording {
|
||||||
|
let mut sample = sample.write().unwrap();
|
||||||
|
if sample.channels.len() != audio_ins.len() {
|
||||||
|
panic!("channel count mismatch");
|
||||||
|
}
|
||||||
|
let iterator = audio_ins.iter().zip(input_meter).zip(sample.channels.iter_mut());
|
||||||
|
let mut length = 0;
|
||||||
|
for ((input, meter), channel) in iterator {
|
||||||
|
let slice = input.port.as_slice(scope);
|
||||||
|
length = length.max(slice.len());
|
||||||
|
let total: f32 = slice.iter().map(|x|x.abs()).sum();
|
||||||
|
let count = slice.len() as f32;
|
||||||
|
*meter = 10. * (total / count).log10();
|
||||||
|
channel.extend_from_slice(slice);
|
||||||
|
}
|
||||||
|
sample.end += length;
|
||||||
|
} else {
|
||||||
|
for (input, meter) in audio_ins.iter().zip(input_meter) {
|
||||||
|
let slice = input.port.as_slice(scope);
|
||||||
|
let total: f32 = slice.iter().map(|x|x.abs()).sum();
|
||||||
|
let count = slice.len() as f32;
|
||||||
|
*meter = 10. * (total / count).log10();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Create [Voice]s from [Sample]s in response to MIDI input.
|
||||||
|
pub fn process_midi_in (&mut self, scope: &ProcessScope) {
|
||||||
|
let Sampler { midi_in, mapped, voices, .. } = self;
|
||||||
|
for RawMidi { time, bytes } in midi_in.port.iter(scope) {
|
||||||
|
if let LiveEvent::Midi { message, .. } = LiveEvent::parse(bytes).unwrap() {
|
||||||
|
match message {
|
||||||
|
MidiMessage::NoteOn { ref key, ref vel } => {
|
||||||
|
if let Some(ref sample) = mapped[key.as_int() as usize] {
|
||||||
|
voices.write().unwrap().push(Sample::play(sample, time as usize, vel));
|
||||||
|
}
|
||||||
|
},
|
||||||
|
MidiMessage::Controller { controller, value } => {
|
||||||
|
// TODO
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Zero the output buffer.
|
||||||
|
pub fn clear_output_buffer (&mut self) {
|
||||||
|
for buffer in self.buffer.iter_mut() {
|
||||||
|
buffer.fill(0.0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Mix all currently playing samples into the output.
|
||||||
|
pub fn process_audio_out (&mut self, scope: &ProcessScope) {
|
||||||
|
let Sampler { ref mut buffer, voices, output_gain, .. } = self;
|
||||||
|
let channel_count = buffer.len();
|
||||||
|
voices.write().unwrap().retain_mut(|voice|{
|
||||||
|
for index in 0..scope.n_frames() as usize {
|
||||||
|
if let Some(frame) = voice.next() {
|
||||||
|
for (channel, sample) in frame.iter().enumerate() {
|
||||||
|
// Averaging mixer:
|
||||||
|
//self.buffer[channel % channel_count][index] = (
|
||||||
|
//(self.buffer[channel % channel_count][index] + sample * self.output_gain) / 2.0
|
||||||
|
//);
|
||||||
|
buffer[channel % channel_count][index] += sample * *output_gain;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
true
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Write output buffer to output ports.
|
||||||
|
pub fn write_output_buffer (&mut self, scope: &ProcessScope) {
|
||||||
|
let Sampler { ref mut audio_outs, buffer, .. } = self;
|
||||||
|
for (i, port) in audio_outs.iter_mut().enumerate() {
|
||||||
|
let buffer = &buffer[i];
|
||||||
|
for (i, value) in port.port.as_mut_slice(scope).iter_mut().enumerate() {
|
||||||
|
*value = *buffer.get(i).unwrap_or(&0.0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
///////////////////////////////////////////////////////////////////////////////////////////////////
|
||||||
|
|
||||||
|
type MidiSample = (Option<u7>, Arc<RwLock<crate::Sample>>);
|
||||||
|
|
||||||
from_edn!("sampler" => |jack: &Arc<RwLock<JackConnection>>, args| -> crate::Sampler {
|
from_edn!("sampler" => |jack: &Arc<RwLock<JackConnection>>, args| -> crate::Sampler {
|
||||||
let mut name = String::new();
|
let mut name = String::new();
|
||||||
let mut dir = String::new();
|
let mut dir = String::new();
|
||||||
|
|
@ -120,8 +231,6 @@ from_edn!("sampler" => |jack: &Arc<RwLock<JackConnection>>, args| -> crate::Samp
|
||||||
Self::new(jack, &name)
|
Self::new(jack, &name)
|
||||||
});
|
});
|
||||||
|
|
||||||
type MidiSample = (Option<u7>, Arc<RwLock<crate::Sample>>);
|
|
||||||
|
|
||||||
from_edn!("sample" => |(_jack, dir): (&Arc<RwLock<JackConnection>>, &str), args| -> MidiSample {
|
from_edn!("sample" => |(_jack, dir): (&Arc<RwLock<JackConnection>>, &str), args| -> MidiSample {
|
||||||
let mut name = String::new();
|
let mut name = String::new();
|
||||||
let mut file = String::new();
|
let mut file = String::new();
|
||||||
|
|
|
||||||
|
|
@ -1,111 +0,0 @@
|
||||||
use crate::*;
|
|
||||||
|
|
||||||
audio!(|self: SamplerTui, client, scope|{
|
|
||||||
SamplerAudio(&mut self.state).process(client, scope)
|
|
||||||
});
|
|
||||||
|
|
||||||
pub struct SamplerAudio<'a>(pub &'a mut Sampler);
|
|
||||||
|
|
||||||
audio!(|self: SamplerAudio<'a>, _client, scope|{
|
|
||||||
self.0.process_midi_in(scope);
|
|
||||||
self.0.clear_output_buffer();
|
|
||||||
self.0.process_audio_out(scope);
|
|
||||||
self.0.write_output_buffer(scope);
|
|
||||||
self.0.process_audio_in(scope);
|
|
||||||
Control::Continue
|
|
||||||
});
|
|
||||||
|
|
||||||
impl Sampler {
|
|
||||||
|
|
||||||
pub fn process_audio_in (&mut self, scope: &ProcessScope) {
|
|
||||||
let Sampler { audio_ins, input_meter, recording, .. } = self;
|
|
||||||
if audio_ins.len() != input_meter.len() {
|
|
||||||
*input_meter = vec![0.0;audio_ins.len()];
|
|
||||||
}
|
|
||||||
if let Some((_, sample)) = recording {
|
|
||||||
let mut sample = sample.write().unwrap();
|
|
||||||
if sample.channels.len() != audio_ins.len() {
|
|
||||||
panic!("channel count mismatch");
|
|
||||||
}
|
|
||||||
let iterator = audio_ins.iter().zip(input_meter).zip(sample.channels.iter_mut());
|
|
||||||
let mut length = 0;
|
|
||||||
for ((input, meter), channel) in iterator {
|
|
||||||
let slice = input.as_slice(scope);
|
|
||||||
length = length.max(slice.len());
|
|
||||||
let total: f32 = slice.iter().map(|x|x.abs()).sum();
|
|
||||||
let count = slice.len() as f32;
|
|
||||||
*meter = 10. * (total / count).log10();
|
|
||||||
channel.extend_from_slice(slice);
|
|
||||||
}
|
|
||||||
sample.end += length;
|
|
||||||
} else {
|
|
||||||
for (input, meter) in audio_ins.iter().zip(input_meter) {
|
|
||||||
let slice = input.as_slice(scope);
|
|
||||||
let total: f32 = slice.iter().map(|x|x.abs()).sum();
|
|
||||||
let count = slice.len() as f32;
|
|
||||||
*meter = 10. * (total / count).log10();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Create [Voice]s from [Sample]s in response to MIDI input.
|
|
||||||
pub fn process_midi_in (&mut self, scope: &ProcessScope) {
|
|
||||||
let Sampler { midi_in, mapped, voices, .. } = self;
|
|
||||||
for RawMidi { time, bytes } in midi_in.iter(scope) {
|
|
||||||
if let LiveEvent::Midi { message, .. } = LiveEvent::parse(bytes).unwrap() {
|
|
||||||
match message {
|
|
||||||
MidiMessage::NoteOn { ref key, ref vel } => {
|
|
||||||
if let Some(ref sample) = mapped[key.as_int() as usize] {
|
|
||||||
voices.write().unwrap().push(Sample::play(sample, time as usize, vel));
|
|
||||||
}
|
|
||||||
},
|
|
||||||
MidiMessage::Controller { controller, value } => {
|
|
||||||
// TODO
|
|
||||||
}
|
|
||||||
_ => {}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Zero the output buffer.
|
|
||||||
pub fn clear_output_buffer (&mut self) {
|
|
||||||
for buffer in self.buffer.iter_mut() {
|
|
||||||
buffer.fill(0.0);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Mix all currently playing samples into the output.
|
|
||||||
pub fn process_audio_out (&mut self, scope: &ProcessScope) {
|
|
||||||
let Sampler { ref mut buffer, voices, output_gain, .. } = self;
|
|
||||||
let channel_count = buffer.len();
|
|
||||||
voices.write().unwrap().retain_mut(|voice|{
|
|
||||||
for index in 0..scope.n_frames() as usize {
|
|
||||||
if let Some(frame) = voice.next() {
|
|
||||||
for (channel, sample) in frame.iter().enumerate() {
|
|
||||||
// Averaging mixer:
|
|
||||||
//self.buffer[channel % channel_count][index] = (
|
|
||||||
//(self.buffer[channel % channel_count][index] + sample * self.output_gain) / 2.0
|
|
||||||
//);
|
|
||||||
buffer[channel % channel_count][index] += sample * *output_gain;
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
true
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Write output buffer to output ports.
|
|
||||||
pub fn write_output_buffer (&mut self, scope: &ProcessScope) {
|
|
||||||
let Sampler { ref mut audio_outs, buffer, .. } = self;
|
|
||||||
for (i, port) in audio_outs.iter_mut().enumerate() {
|
|
||||||
let buffer = &buffer[i];
|
|
||||||
for (i, value) in port.as_mut_slice(scope).iter_mut().enumerate() {
|
|
||||||
*value = *buffer.get(i).unwrap_or(&0.0);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue