mirror of
https://codeberg.org/unspeaker/tek.git
synced 2025-12-06 11:46:41 +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::*;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct JackPort<T: PortSpec> {
|
||||
/// Handle to JACK client, for receiving reconnect events.
|
||||
pub jack: Arc<RwLock<JackConnection>>,
|
||||
/// Port handle.
|
||||
pub port: Port<T>,
|
||||
/// List of ports to connect to.
|
||||
pub connect: Vec<PortConnect>
|
||||
pub connect: Vec<PortConnection>
|
||||
}
|
||||
pub struct PortConnect {
|
||||
pub name: PortConnectName,
|
||||
pub order: PortConnectScope,
|
||||
pub status: Vec<(Port<Unowned>, PortConnectStatus)>,
|
||||
}
|
||||
impl PortConnect {
|
||||
/// Connect to this exact port
|
||||
pub fn exact (name: impl AsRef<str>) -> Self {
|
||||
let name = PortConnectName::Exact(name.as_ref().into());
|
||||
Self { name, order: PortConnectScope::One, status: vec![] }
|
||||
impl<T: PortSpec> JackPort<T> {
|
||||
pub fn connect_to_matching (&mut self) {
|
||||
use PortConnectionName::*;
|
||||
use PortConnectionScope::*;
|
||||
use PortConnectionStatus::*;
|
||||
for connect in self.connect.iter_mut() {
|
||||
let mut status = vec![];
|
||||
match &connect.name {
|
||||
Exact(name) => for port in self.jack.ports(None, None, PortFlags::empty()).iter() {
|
||||
if port.as_str() == &**name {
|
||||
if let Some(port) = self.jack.port_by_name(port.as_str()) {
|
||||
let port_status = Self::try_both_ways(&self.jack, &port, &self.port);
|
||||
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 {
|
||||
let name = PortConnectName::Wildcard(name.as_ref().into());
|
||||
Self { name, order: PortConnectScope::One, status: vec![] }
|
||||
}
|
||||
pub fn wildcard_all (name: impl AsRef<str>) -> Self {
|
||||
let name = PortConnectName::Wildcard(name.as_ref().into());
|
||||
Self { name, order: PortConnectScope::All, status: vec![] }
|
||||
}
|
||||
pub fn regexp (name: impl AsRef<str>) -> Self {
|
||||
let name = PortConnectName::RegExp(name.as_ref().into());
|
||||
Self { name, order: PortConnectScope::One, status: vec![] }
|
||||
}
|
||||
pub fn regexp_all (name: impl AsRef<str>) -> Self {
|
||||
let name = PortConnectName::RegExp(name.as_ref().into());
|
||||
Self { name, order: PortConnectScope::All, status: vec![] }
|
||||
fn try_both_ways <A: PortSpec, B: PortSpec> (
|
||||
jack: &impl ConnectPort, port_a: &Port<A>, port_b: &Port<B>
|
||||
)
|
||||
-> PortConnectionStatus
|
||||
{
|
||||
if let Ok(_) = jack.connect_ports(port_a, port_b) {
|
||||
PortConnectionStatus::Connected
|
||||
} else if let Ok(_) = jack.connect_ports(port_b, port_a) {
|
||||
PortConnectionStatus::Connected
|
||||
} else {
|
||||
PortConnectionStatus::Mismatch
|
||||
}
|
||||
}
|
||||
}
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum PortConnectName {
|
||||
/// Exact match
|
||||
Exact(Arc<str>),
|
||||
/// Match wildcard
|
||||
Wildcard(Arc<str>),
|
||||
/// Match regular expression
|
||||
RegExp(Arc<str>),
|
||||
pub struct PortConnection {
|
||||
pub name: PortConnectionName,
|
||||
pub scope: PortConnectionScope,
|
||||
pub status: Vec<(Port<Unowned>, PortConnectionStatus)>,
|
||||
}
|
||||
impl PortConnection {
|
||||
/// 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)]
|
||||
pub enum PortConnectScope { One, All }
|
||||
pub enum PortConnectionScope { One, All }
|
||||
#[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> {
|
||||
fn as_ref (&self) -> &Port<T> {
|
||||
&self.port
|
||||
}
|
||||
}
|
||||
impl<T: PortSpec> JackPort<T> {
|
||||
pub fn midi_in (
|
||||
jack: Arc<RwLock<JackConnection>>, name: impl AsRef<str>, connect: &[PortConnect]
|
||||
) -> Usually<JackPort<MidiIn>> {
|
||||
let input = jack.midi_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.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<MidiIn> {
|
||||
pub fn new (
|
||||
jack: &Arc<RwLock<JackConnection>>, name: impl AsRef<str>, connect: &[PortConnection]
|
||||
) -> Usually<Self> {
|
||||
let mut port = JackPort {
|
||||
jack: jack.clone(),
|
||||
port: jack.midi_in(name)?,
|
||||
connect: connect.to_vec()
|
||||
};
|
||||
port.connect_to_matching();
|
||||
Ok(port)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// 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 JackPort<MidiOut> {
|
||||
pub fn new (
|
||||
jack: &Arc<RwLock<JackConnection>>, name: impl AsRef<str>, connect: &[PortConnection]
|
||||
) -> Usually<Self> {
|
||||
let mut port = Self {
|
||||
jack: jack.clone(),
|
||||
port: jack.midi_out(name)?,
|
||||
connect: connect.to_vec()
|
||||
};
|
||||
port.connect_to_matching();
|
||||
Ok(port)
|
||||
}
|
||||
}
|
||||
impl<T: RegisterPort> RegisterPort for Arc<RwLock<T>> {
|
||||
fn midi_in (&self, name: impl AsRef<str>) -> Usually<Port<MidiIn>> {
|
||||
self.read().unwrap().midi_in(name)
|
||||
impl JackPort<AudioIn> {
|
||||
pub fn new (
|
||||
jack: &Arc<RwLock<JackConnection>>, name: impl AsRef<str>, connect: &[PortConnection]
|
||||
) -> Usually<Self> {
|
||||
let mut port = Self {
|
||||
jack: jack.clone(),
|
||||
port: jack.audio_in(name)?,
|
||||
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)
|
||||
}
|
||||
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)
|
||||
}
|
||||
impl JackPort<AudioOut> {
|
||||
pub fn new (
|
||||
jack: &Arc<RwLock<JackConnection>>, name: impl AsRef<str>, connect: &[PortConnection]
|
||||
) -> Usually<Self> {
|
||||
let mut port = Self {
|
||||
jack: jack.clone(),
|
||||
port: jack.audio_out(name)?,
|
||||
connect: connect.to_vec()
|
||||
};
|
||||
port.connect_to_matching();
|
||||
Ok(port)
|
||||
}
|
||||
}
|
||||
|
||||
pub trait ConnectPort {
|
||||
fn ports (&self, re_name: Option<&str>, re_type: Option<&str>, flags: PortFlags) -> Vec<String>;
|
||||
fn port_by_name (&self, name: impl AsRef<str>) -> Option<Port<Unowned>>;
|
||||
fn connect_ports <A: PortSpec, B: PortSpec> (&self, source: &Port<A>, target: &Port<B>)
|
||||
-> Usually<()>;
|
||||
|
|
@ -213,6 +195,9 @@ pub trait ConnectPort {
|
|||
}
|
||||
}
|
||||
impl ConnectPort for JackConnection {
|
||||
fn ports (&self, re_name: Option<&str>, re_type: Option<&str>, flags: PortFlags) -> Vec<String> {
|
||||
self.client().ports(re_name, re_type, flags)
|
||||
}
|
||||
fn port_by_name (&self, name: impl AsRef<str>) -> Option<Port<Unowned>> {
|
||||
self.client().port_by_name(name.as_ref())
|
||||
}
|
||||
|
|
@ -223,6 +208,9 @@ impl ConnectPort for JackConnection {
|
|||
}
|
||||
}
|
||||
impl<T: ConnectPort> ConnectPort for Arc<RwLock<T>> {
|
||||
fn ports (&self, re_name: Option<&str>, re_type: Option<&str>, flags: PortFlags) -> Vec<String> {
|
||||
self.read().unwrap().ports(re_name, re_type, flags)
|
||||
}
|
||||
fn port_by_name (&self, name: impl AsRef<str>) -> Option<Port<Unowned>> {
|
||||
self.read().unwrap().port_by_name(name.as_ref())
|
||||
}
|
||||
|
|
@ -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].
|
||||
//#[derive(Default, Debug)]
|
||||
//pub struct JackPorts {
|
||||
|
|
|
|||
|
|
@ -6,7 +6,8 @@ pub(crate) use ::jack::{
|
|||
contrib::ClosureProcessHandler, NotificationHandler,
|
||||
Client, AsyncClient, ClientOptions, ClientStatus,
|
||||
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::*;
|
||||
|
|
|
|||
|
|
@ -2,8 +2,8 @@ use crate::*;
|
|||
|
||||
/// Trait for thing that may receive MIDI.
|
||||
pub trait HasMidiIns {
|
||||
fn midi_ins (&self) -> &Vec<Port<MidiIn>>;
|
||||
fn midi_ins_mut (&mut self) -> &mut Vec<Port<MidiIn>>;
|
||||
fn midi_ins (&self) -> &Vec<JackPort<MidiIn>>;
|
||||
fn midi_ins_mut (&mut self) -> &mut Vec<JackPort<MidiIn>>;
|
||||
fn has_midi_ins (&self) -> bool {
|
||||
!self.midi_ins().is_empty()
|
||||
}
|
||||
|
|
@ -27,7 +27,7 @@ pub trait MidiRecordApi: HasClock + HasPlayPhrase + HasMidiIns {
|
|||
let notes_in = self.notes_in().clone();
|
||||
let monitoring = self.monitoring();
|
||||
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 monitoring {
|
||||
midi_buf[sample].push(bytes.to_vec());
|
||||
|
|
@ -67,7 +67,7 @@ pub trait MidiRecordApi: HasClock + HasPlayPhrase + HasMidiIns {
|
|||
let mut phrase = phrase.write().unwrap();
|
||||
let length = phrase.length;
|
||||
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 {
|
||||
phrase.record_event({
|
||||
let sample = (sample0 + sample - start) as f64;
|
||||
|
|
|
|||
|
|
@ -2,8 +2,8 @@ use crate::*;
|
|||
|
||||
/// Trait for thing that may output MIDI.
|
||||
pub trait HasMidiOuts {
|
||||
fn midi_outs (&self) -> &Vec<Port<MidiOut>>;
|
||||
fn midi_outs_mut (&mut self) -> &mut Vec<Port<MidiOut>>;
|
||||
fn midi_outs (&self) -> &Vec<JackPort<MidiOut>>;
|
||||
fn midi_outs_mut (&mut self) -> &mut Vec<JackPort<MidiOut>>;
|
||||
fn has_midi_outs (&self) -> bool {
|
||||
!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>>]) {
|
||||
let samples = scope.n_frames() as usize;
|
||||
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
|
||||
pub reset: bool, // TODO?: after Some(nframes)
|
||||
/// 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
|
||||
pub midi_outs: Vec<Port<MidiOut>>,
|
||||
pub midi_outs: Vec<JackPort<MidiOut>>,
|
||||
/// Notes currently held at input
|
||||
pub notes_in: Arc<RwLock<[bool; 128]>>,
|
||||
/// Notes currently held at output
|
||||
|
|
@ -47,33 +47,28 @@ pub struct MidiPlayer {
|
|||
}
|
||||
impl MidiPlayer {
|
||||
pub fn new (
|
||||
jack: &Arc<RwLock<JackConnection>>,
|
||||
name: impl AsRef<str>,
|
||||
clip: Option<&Arc<RwLock<MidiClip>>>,
|
||||
midi_from: &[impl AsRef<str>],
|
||||
midi_to: &[impl AsRef<str>],
|
||||
jack: &Arc<RwLock<JackConnection>>,
|
||||
name: impl AsRef<str>,
|
||||
clip: Option<&Arc<RwLock<MidiClip>>>,
|
||||
midi_from: &[PortConnection],
|
||||
midi_to: &[PortConnection],
|
||||
) -> Usually<Self> {
|
||||
let name = name.as_ref();
|
||||
let midi_in = jack.midi_in(&format!("M/{name}"), midi_from)?;
|
||||
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);
|
||||
let name = name.as_ref();
|
||||
let clock = Clock::from(jack);
|
||||
Ok(Self {
|
||||
play_phrase: Some((Moment::zero(&clock.timebase), clip.cloned())),
|
||||
|
||||
next_phrase: None,
|
||||
recording: false,
|
||||
monitoring: false,
|
||||
overdub: false,
|
||||
|
||||
notes_in: RwLock::new([false;128]).into(),
|
||||
midi_ins: vec![midi_in],
|
||||
midi_outs: vec![midi_out],
|
||||
notes_out: RwLock::new([false;128]).into(),
|
||||
note_buf: vec![0;8],
|
||||
reset: true,
|
||||
notes_in: RwLock::new([false;128]).into(),
|
||||
notes_out: RwLock::new([false;128]).into(),
|
||||
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,
|
||||
})
|
||||
}
|
||||
|
|
@ -114,26 +109,14 @@ from!(|state: (&Clock, &Arc<RwLock<MidiClip>>)|MidiPlayer = {
|
|||
model
|
||||
});
|
||||
has_clock!(|self: MidiPlayer|&self.clock);
|
||||
|
||||
impl HasMidiIns for MidiPlayer {
|
||||
fn midi_ins (&self) -> &Vec<Port<MidiIn>> {
|
||||
&self.midi_ins
|
||||
}
|
||||
fn midi_ins_mut (&mut self) -> &mut Vec<Port<MidiIn>> {
|
||||
&mut self.midi_ins
|
||||
}
|
||||
fn midi_ins (&self) -> &Vec<JackPort<MidiIn>> { &self.midi_ins }
|
||||
fn midi_ins_mut (&mut self) -> &mut Vec<JackPort<MidiIn>> { &mut self.midi_ins }
|
||||
}
|
||||
|
||||
impl HasMidiOuts for MidiPlayer {
|
||||
fn midi_outs (&self) -> &Vec<Port<MidiOut>> {
|
||||
&self.midi_outs
|
||||
}
|
||||
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
|
||||
}
|
||||
fn midi_outs (&self) -> &Vec<JackPort<MidiOut>> { &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 }
|
||||
}
|
||||
|
||||
/// 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,
|
||||
/// Initial tempo in beats per minute
|
||||
#[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)]
|
||||
pub enum TekMode {
|
||||
/// A standalone transport view.
|
||||
/// A standalone transport clock.
|
||||
Clock,
|
||||
/// A MIDI 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>,
|
||||
},
|
||||
Sequencer,
|
||||
/// A MIDI-controlled audio 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>,
|
||||
},
|
||||
Sampler,
|
||||
/// Sequencer and sampler together.
|
||||
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>,
|
||||
},
|
||||
Groovebox,
|
||||
/// Multi-track MIDI sequencer.
|
||||
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
|
||||
#[arg(short = 'x', long, default_value_t = 16)] tracks: usize,
|
||||
/// 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 jack = JackConnection::new(name)?;
|
||||
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 {
|
||||
|
||||
TekMode::Clock => engine.run(&jack.activate_with(|jack|Ok(TransportTui {
|
||||
|
|
@ -104,15 +81,11 @@ pub fn main () -> Usually<()> {
|
|||
jack: jack.clone()
|
||||
}))?)?,
|
||||
|
||||
TekMode::Sequencer {
|
||||
midi_from, midi_to, ..
|
||||
} => engine.run(&jack.activate_with(|jack|Ok({
|
||||
let clock = Clock::from(jack);
|
||||
let clip = Arc::new(RwLock::new(MidiClip::new(
|
||||
"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)?;
|
||||
TekMode::Sequencer => engine.run(&jack.activate_with(|jack|Ok({
|
||||
let length = 384;
|
||||
let color = Some(ItemColor::random().into());
|
||||
let clip = Arc::new(RwLock::new(MidiClip::new("Clip", true, length, None, color)));
|
||||
let player = MidiPlayer::new(&jack, name, Some(&clip), &midi_froms, &midi_tos)?;
|
||||
Sequencer {
|
||||
_jack: jack.clone(),
|
||||
clock: player.clock.clone(),
|
||||
|
|
@ -130,9 +103,7 @@ pub fn main () -> Usually<()> {
|
|||
}
|
||||
}))?)?,
|
||||
|
||||
TekMode::Sampler {
|
||||
midi_from, l_from, r_from, l_to, r_to, ..
|
||||
} => engine.run(&jack.activate_with(|jack|Ok(
|
||||
TekMode::Sampler => engine.run(&jack.activate_with(|jack|Ok(
|
||||
SamplerTui {
|
||||
cursor: (0, 0),
|
||||
editing: None,
|
||||
|
|
@ -141,53 +112,29 @@ pub fn main () -> Usually<()> {
|
|||
note_lo: 36.into(),
|
||||
note_pt: 36.into(),
|
||||
color: ItemPalette::from(Color::Rgb(64, 128, 32)),
|
||||
state: Sampler::new(jack, &"sampler",
|
||||
&midi_from,
|
||||
&[&l_from, &r_from],
|
||||
&[&l_to, &r_to],
|
||||
)?,
|
||||
state: Sampler::new(jack, &"sampler", &midi_froms, &[&l_from, &r_from], &[&l_to, &r_to])?,
|
||||
}
|
||||
))?)?,
|
||||
|
||||
TekMode::Groovebox {
|
||||
midi_from, midi_to, l_from, r_from, l_to, r_to, ..
|
||||
} => engine.run(&jack.activate_with(|jack|Ok({
|
||||
let ppq = 96;
|
||||
let phrase = Arc::new(RwLock::new(MidiClip::new(
|
||||
"Clip",
|
||||
true,
|
||||
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
|
||||
)?;
|
||||
TekMode::Groovebox => engine.run(&jack.activate_with(|jack|Ok({
|
||||
let length = 384;
|
||||
let color = Some(ItemColor::random().into());
|
||||
let clip = Arc::new(RwLock::new(MidiClip::new("Clip", true, length, None, color)));
|
||||
let mut player = MidiPlayer::new(jack, &"sequencer", Some(&clip), &midi_froms, &midi_tos)?;
|
||||
let sampler = Sampler::new(jack, &"sampler", &midi_froms, &[&l_from, &r_from], &[&l_to, &r_to])?;
|
||||
jack.read().unwrap().client().connect_ports(&player.midi_outs[0].port, &sampler.midi_in.port)?;
|
||||
let app = Groovebox {
|
||||
player,
|
||||
sampler,
|
||||
_jack: jack.clone(),
|
||||
|
||||
pool: PoolModel::from(&phrase),
|
||||
editor: MidiEditor::from(&phrase),
|
||||
|
||||
pool: PoolModel::from(&clip),
|
||||
editor: MidiEditor::from(&clip),
|
||||
compact: true,
|
||||
status: true,
|
||||
size: Measure::new(),
|
||||
midi_buf: vec![vec![];65536],
|
||||
note_buf: vec![],
|
||||
perf: PerfModel::default(),
|
||||
_jack: jack.clone(),
|
||||
};
|
||||
if let Some(bpm) = cli.bpm {
|
||||
app.clock().timebase.bpm.set(bpm);
|
||||
|
|
@ -207,14 +154,13 @@ pub fn main () -> Usually<()> {
|
|||
app
|
||||
}))?)?,
|
||||
|
||||
TekMode::Arranger {
|
||||
scenes, tracks, track_width, midi_from, midi_to, ..
|
||||
} => engine.run(&jack.activate_with(|jack|Ok({
|
||||
let mut app = Arranger::new(jack);
|
||||
app.tracks_add(tracks, track_width, midi_from.as_slice(), midi_to.as_slice())?;
|
||||
app.scenes_add(scenes)?;
|
||||
app
|
||||
}))?)?,
|
||||
TekMode::Arranger { scenes, tracks, track_width, .. } =>
|
||||
engine.run(&jack.activate_with(|jack|Ok({
|
||||
let mut app = Arranger::new(jack);
|
||||
app.tracks_add(tracks, track_width, &midi_froms, &midi_tos)?;
|
||||
app.scenes_add(scenes)?;
|
||||
app
|
||||
}))?)?,
|
||||
|
||||
_ => todo!()
|
||||
})
|
||||
|
|
|
|||
|
|
@ -37,13 +37,9 @@ impl Arranger {
|
|||
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))?;
|
||||
track.width = width;
|
||||
|
||||
let name = &format!("{}I", &track.name);
|
||||
let port = jack.read().unwrap().client().register_port(&name, MidiIn::default())?;
|
||||
let port = JackPort::<MidiIn>::new(&jack, &format!("{}I", &track.name), &[])?;
|
||||
track.player.midi_ins.push(port);
|
||||
|
||||
let name = &format!("{}O", &track.name);
|
||||
let port = jack.read().unwrap().client().register_port(&name, MidiOut::default())?;
|
||||
let port = JackPort::<MidiOut>::new(&jack, &format!("{}O", &track.name), &[])?;
|
||||
track.player.midi_outs.push(port);
|
||||
}
|
||||
for connection in midi_from.iter() {
|
||||
|
|
@ -51,14 +47,14 @@ impl Arranger {
|
|||
let number = split.next().unwrap().trim();
|
||||
if let Ok(track) = number.parse::<usize>() {
|
||||
if track < 1 {
|
||||
panic!("Tracks are zero-indexed")
|
||||
panic!("Tracks start from 1")
|
||||
}
|
||||
if track > count {
|
||||
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) = 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 {
|
||||
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();
|
||||
if let Ok(track) = number.parse::<usize>() {
|
||||
if track < 1 {
|
||||
panic!("Tracks are zero-indexed")
|
||||
panic!("Tracks start from 1")
|
||||
}
|
||||
if track > count {
|
||||
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) = 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 {
|
||||
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
|
||||
}
|
||||
// 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() {
|
||||
match message {
|
||||
MidiMessage::NoteOn { ref key, .. } => {
|
||||
|
|
|
|||
|
|
@ -2,12 +2,10 @@ mod sample; pub use self::sample::*;
|
|||
mod sample_import; pub use self::sample_import::*;
|
||||
mod sample_list; pub use self::sample_list::*;
|
||||
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_status; pub use self::sampler_status::*;
|
||||
mod sampler_tui; pub use self::sampler_tui::*;
|
||||
mod voice; pub use self::voice::*;
|
||||
|
||||
use crate::*;
|
||||
use KeyCode::Char;
|
||||
use std::fs::File;
|
||||
|
|
@ -23,7 +21,6 @@ use symphonia::{
|
|||
default::get_codecs,
|
||||
};
|
||||
|
||||
|
||||
/// The sampler plugin plays sounds.
|
||||
#[derive(Debug)]
|
||||
pub struct Sampler {
|
||||
|
|
@ -33,10 +30,10 @@ pub struct Sampler {
|
|||
pub recording: Option<(usize, Arc<RwLock<Sample>>)>,
|
||||
pub unmapped: Vec<Arc<RwLock<Sample>>>,
|
||||
pub voices: Arc<RwLock<Vec<Voice>>>,
|
||||
pub midi_in: Port<MidiIn>,
|
||||
pub audio_ins: Vec<Port<AudioIn>>,
|
||||
pub midi_in: JackPort<MidiIn>,
|
||||
pub audio_ins: Vec<JackPort<AudioIn>>,
|
||||
pub input_meter: Vec<f32>,
|
||||
pub audio_outs: Vec<Port<AudioOut>>,
|
||||
pub audio_outs: Vec<JackPort<AudioOut>>,
|
||||
pub buffer: Vec<Vec<f32>>,
|
||||
pub output_gain: f32
|
||||
}
|
||||
|
|
@ -44,21 +41,21 @@ impl Sampler {
|
|||
pub fn new (
|
||||
jack: &Arc<RwLock<JackConnection>>,
|
||||
name: impl AsRef<str>,
|
||||
midi_from: &[impl AsRef<str>],
|
||||
audio_from: &[&[impl AsRef<str>];2],
|
||||
audio_to: &[&[impl AsRef<str>];2],
|
||||
midi_from: &[PortConnection],
|
||||
audio_from: &[&[PortConnection];2],
|
||||
audio_to: &[&[PortConnection];2],
|
||||
) -> Usually<Self> {
|
||||
let name = name.as_ref();
|
||||
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![
|
||||
jack.audio_in(&format!("L/{name}"), audio_from[0])?,
|
||||
jack.audio_in(&format!("R/{name}"), audio_from[1])?
|
||||
JackPort::<AudioIn>::new(jack, &format!("L/{name}"), audio_from[0])?,
|
||||
JackPort::<AudioIn>::new(jack, &format!("R/{name}"), audio_from[1])?,
|
||||
],
|
||||
input_meter: vec![0.0;2],
|
||||
audio_outs: vec![
|
||||
jack.audio_out(&format!("{name}/L"), audio_to[0])?,
|
||||
jack.audio_out(&format!("{name}/R"), audio_to[1])?,
|
||||
JackPort::<AudioOut>::new(jack, &format!("{name}/L"), audio_to[0])?,
|
||||
JackPort::<AudioOut>::new(jack, &format!("{name}/R"), audio_to[1])?,
|
||||
],
|
||||
jack: jack.clone(),
|
||||
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 {
|
||||
let mut name = 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)
|
||||
});
|
||||
|
||||
type MidiSample = (Option<u7>, Arc<RwLock<crate::Sample>>);
|
||||
|
||||
from_edn!("sample" => |(_jack, dir): (&Arc<RwLock<JackConnection>>, &str), args| -> MidiSample {
|
||||
let mut name = 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