wip: fixing port autoconnect

This commit is contained in:
🪞👃🪞 2024-07-11 14:15:29 +03:00
parent 6979fd67ec
commit 32dc708096
5 changed files with 98 additions and 94 deletions

View file

@ -186,7 +186,7 @@ fn delete_track (app: &mut App) -> Usually<bool> {
if app.tracks.len() > 0 { if app.tracks.len() > 0 {
let track = app.tracks.remove(app.track_cursor); let track = app.tracks.remove(app.track_cursor);
app.track_cursor = app.track_cursor.saturating_sub(1); app.track_cursor = app.track_cursor.saturating_sub(1);
app.client().unregister_port(track.midi_out)?; track.midi_out.map(|port|app.client().unregister_port(port)).transpose()?;
return Ok(true) return Ok(true)
} }
Ok(false) Ok(false)

View file

@ -14,6 +14,11 @@ macro_rules! edn {
} }
impl App { impl App {
pub fn from_edn (src: &str) -> Usually<Self> {
let mut app = Self::new()?;
app.load_edn(src)?;
Ok(app)
}
pub fn load_edn (&mut self, mut src: &str) -> Usually<&mut Self> { pub fn load_edn (&mut self, mut src: &str) -> Usually<&mut Self> {
loop { loop {
match clojure_reader::edn::read(src) { match clojure_reader::edn::read(src) {
@ -123,28 +128,9 @@ impl Track {
}, },
_ => {} _ => {}
}); });
let (left, right) = (app.audio_out(0), app.audio_out(1));
let track = app.add_track(Some(name.as_str()))?; let track = app.add_track(Some(name.as_str()))?;
for phrase in phrases { for phrase in phrases { track.phrases.push(phrase); }
track.phrases.push(phrase); for device in devices { track.add_device(device)?; }
}
for device in devices {
track.add_device(device)?;
}
if let Some(device) = track.devices.get(0) {
device.client.as_client().connect_ports(
&track.midi_out,
&device.midi_ins()?[0],
)?;
}
if let Some(device) = track.devices.get(track.devices.len() - 1) {
if let Some(ref left) = left {
device.connect_audio_out(0, left)?;
}
if let Some(ref right) = right {
device.connect_audio_out(1, right)?;
}
}
Ok(track) Ok(track)
} }
} }

View file

@ -14,8 +14,12 @@ use crate::{core::*, model::*};
/// Application entrypoint. /// Application entrypoint.
pub fn main () -> Usually<()> { pub fn main () -> Usually<()> {
let mut app = App::new(include_str!("../demos/project.edn"))?; let app = App::from_edn(include_str!("../demos/project.edn"))?
app.connect_to_midi_ins(&["nanoKEY Studio.*capture.*"])?; .with_midi_ins(&["nanoKEY Studio.*capture.*"])?
app.connect_to_audio_outs(&["Komplete.+:playback_FL", "Komplete.+:playback_FR"])?; .with_audio_outs(&["Komplete.+:playback_FL", "Komplete.+:playback_FR"])?
run(app.activate()?).map(|_|()) .activate(Some(|app: &Arc<RwLock<App>>| {
Ok(())
}))?;
run(app)?;
Ok(())
} }

View file

@ -20,8 +20,11 @@ pub struct App {
pub xdg: Option<Arc<XdgApp>>, pub xdg: Option<Arc<XdgApp>>,
/// Main JACK client. /// Main JACK client.
pub jack: Option<JackClient>, pub jack: Option<JackClient>,
/// Main MIDI controller. /// Map of external MIDI outs in the jack graph
/// to internal MIDI ins of this app.
pub midi_in: Option<Port<MidiIn>>, pub midi_in: Option<Port<MidiIn>>,
/// Names of ports to connect to main MIDI IN.
pub midi_ins: Vec<String>,
/// Main audio outputs. /// Main audio outputs.
pub audio_outs: Vec<Arc<Port<Unowned>>>, pub audio_outs: Vec<Arc<Port<Unowned>>>,
/// JACK transport handle. /// JACK transport handle.
@ -70,23 +73,27 @@ pub struct App {
pub chunk_size: usize, pub chunk_size: usize,
/// Quantization factor /// Quantization factor
pub quant: usize, pub quant: usize,
/// Init callbacks called once after root JACK client has activated.
pub callbacks: Vec<Box<dyn (FnOnce(Arc<RwLock<Self>>)->Usually<()>) + Send + Sync>>
} }
impl App { impl App {
pub fn new (project: &str) -> Usually<Self> { pub fn new () -> Usually<Self> {
let xdg = Arc::new(microxdg::XdgApp::new("tek")?); let xdg = Arc::new(microxdg::XdgApp::new("tek")?);
let first_run = crate::config::AppPaths::new(&xdg)?.should_create(); let first_run = crate::config::AppPaths::new(&xdg)?.should_create();
let jack = JackClient::Inactive(Client::new("tek", ClientOptions::NO_START_SERVER)?.0); let jack = JackClient::Inactive(Client::new("tek", ClientOptions::NO_START_SERVER)?.0);
let transport = jack.transport(); let transport = jack.transport();
let mut app = Self { Ok(Self {
arranger_mode: false, arranger_mode: false,
audio_outs: vec![], audio_outs: vec![],
callbacks: vec![],
chain_mode: false, chain_mode: false,
chunk_size: 0, chunk_size: 0,
entered: true, entered: true,
jack: Some(jack), jack: Some(jack),
metronome: false, metronome: false,
midi_in: None, midi_in: None,
midi_ins: vec![],
modal: first_run.then(||crate::config::SetupModal(Some(xdg.clone())).boxed()), modal: first_run.then(||crate::config::SetupModal(Some(xdg.clone())).boxed()),
note_cursor: 0, note_cursor: 0,
note_start: 2, note_start: 2,
@ -106,9 +113,7 @@ impl App {
tracks: vec![], tracks: vec![],
transport: Some(transport), transport: Some(transport),
xdg: Some(xdg), xdg: Some(xdg),
}; })
app.load_edn(project)?;
Ok(app)
} }
} }
@ -118,7 +123,7 @@ process!(App |self, _client, scope| {
) = self.process_update_time(&scope); ) = self.process_update_time(&scope);
for track in self.tracks.iter_mut() { for track in self.tracks.iter_mut() {
track.process( track.process(
self.midi_in.as_ref().unwrap().iter(scope), self.midi_in.as_ref().map(|p|p.iter(&scope)),
&self.timebase, &self.timebase,
self.playing, self.playing,
self.play_started, self.play_started,
@ -133,11 +138,49 @@ process!(App |self, _client, scope| {
Control::Continue Control::Continue
}); });
impl App { impl App {
pub fn activate (mut self) -> Usually<Arc<RwLock<Self>>> { pub fn with_midi_ins (mut self, names: &[&str]) -> Usually<Self> {
self.midi_ins = names.iter().map(|x|x.to_string()).collect();
Ok(self)
}
pub fn with_audio_outs (mut self, names: &[&str]) -> Usually<Self> {
let client = self.client();
self.audio_outs = names
.iter()
.map(|name|client
.ports(Some(name), None, PortFlags::empty())
.get(0)
.map(|name|client.port_by_name(name)))
.flatten()
.filter_map(|x|x)
.map(Arc::new)
.collect();
Ok(self)
}
pub fn connect_to_midi_ins (&mut self, ports: &[&str]) -> Usually<&mut Self> {
let client = self.client();
let midi_in = client.register_port("midi-in", MidiIn)?;
ports
.iter()
.map(|name|client
.ports(Some(name), None, PortFlags::empty())
.iter()
.map(|name|{
if let Some(port) = client.port_by_name(name) {
client.connect_ports(&port, &midi_in)?;
}
Ok(())
})
.collect::<Usually<()>>())
.collect::<Usually<()>>()?;
self.midi_in = Some(midi_in);
Ok(self)
}
pub fn activate (mut self, init: Option<impl FnOnce(&Arc<RwLock<Self>>)->Usually<()>>) -> Usually<Arc<RwLock<Self>>> {
let jack = self.jack.take().expect("no jack client"); let jack = self.jack.take().expect("no jack client");
let state = Arc::new(RwLock::new(self)); let app = Arc::new(RwLock::new(self));
state.write().unwrap().jack = Some(jack.activate(&state, Self::process)?); app.write().unwrap().jack = Some(jack.activate(&app.clone(), Self::process)?);
Ok(state) if let Some(init) = init { init(&app)?; }
Ok(app)
} }
pub fn process (state: &Arc<RwLock<Self>>, client: &Client, scope: &ProcessScope) -> Control { pub fn process (state: &Arc<RwLock<Self>>, client: &Client, scope: &ProcessScope) -> Control {
state.write().unwrap().process(client, scope) state.write().unwrap().process(client, scope)
@ -201,7 +244,7 @@ impl App {
name: Option<&str>, name: Option<&str>,
) -> Usually<&mut Track> { ) -> Usually<&mut Track> {
let name = name.ok_or_else(||self.new_track_name())?; let name = name.ok_or_else(||self.new_track_name())?;
self.tracks.push(Track::new(&name, self.client(), None, None)?); self.tracks.push(Track::new(&name, None, None)?);
self.track_cursor = self.tracks.len(); self.track_cursor = self.tracks.len();
Ok(&mut self.tracks[self.track_cursor - 1]) Ok(&mut self.tracks[self.track_cursor - 1])
} }
@ -211,7 +254,7 @@ impl App {
init: impl FnOnce(&Client, &mut Track)->Usually<()>, init: impl FnOnce(&Client, &mut Track)->Usually<()>,
) -> Usually<&mut Track> { ) -> Usually<&mut Track> {
let name = name.ok_or_else(||self.new_track_name())?; let name = name.ok_or_else(||self.new_track_name())?;
let mut track = Track::new(&name, self.client(), None, None)?; let mut track = Track::new(&name, None, None)?;
init(self.client(), &mut track)?; init(self.client(), &mut track)?;
self.tracks.push(track); self.tracks.push(track);
self.track_cursor = self.tracks.len(); self.track_cursor = self.tracks.len();
@ -334,39 +377,6 @@ impl App {
//phrase //phrase
//} //}
//} //}
pub fn connect_to_midi_ins (&mut self, ports: &[&str]) -> Usually<&mut Self> {
let client = self.client();
let midi_in = client.register_port("midi-in", MidiIn)?;
ports
.iter()
.map(|name|client
.ports(Some(name), None, PortFlags::empty())
.iter()
.map(|name|{
if let Some(port) = client.port_by_name(name) {
client.connect_ports(&port, &midi_in)?;
}
Ok(())
})
.collect::<Usually<()>>())
.collect::<Usually<()>>()?;
self.midi_in = Some(midi_in);
Ok(self)
}
pub fn connect_to_audio_outs (&mut self, ports: &[&str]) -> Usually<&mut Self> {
let client = self.client();
self.audio_outs = ports
.iter()
.map(|name|client
.ports(Some(name), None, PortFlags::empty())
.get(0)
.map(|name|client.port_by_name(name)))
.flatten()
.filter_map(|x|x)
.map(Arc::new)
.collect();
Ok(self)
}
} }
struct Selection<'a> { struct Selection<'a> {

View file

@ -14,7 +14,7 @@ pub struct Track {
/// Phrase selector /// Phrase selector
pub sequence: Option<usize>, pub sequence: Option<usize>,
/// Output from current sequence. /// Output from current sequence.
pub midi_out: Port<MidiOut>, pub midi_out: Option<Port<MidiOut>>,
midi_out_buf: Vec<Vec<Vec<u8>>>, midi_out_buf: Vec<Vec<Vec<u8>>>,
/// Device chain /// Device chain
pub devices: Vec<JackDevice>, pub devices: Vec<JackDevice>,
@ -28,25 +28,15 @@ pub struct Track {
/// Highlight keys on piano roll. /// Highlight keys on piano roll.
pub notes_out: [bool;128], pub notes_out: [bool;128],
} }
ports!(Track {
audio: {
outs: |_t|Ok(vec![]),
}
midi: {
ins: |_t|Ok(vec![]),
outs: |_t|Ok(vec![]),
}
});
impl Track { impl Track {
pub fn new ( pub fn new (
name: &str, name: &str,
jack: &Client,
phrases: Option<Vec<Phrase>>, phrases: Option<Vec<Phrase>>,
devices: Option<Vec<JackDevice>>, devices: Option<Vec<JackDevice>>,
) -> Usually<Self> { ) -> Usually<Self> {
Ok(Self { Ok(Self {
name: name.to_string(), name: name.to_string(),
midi_out: jack.register_port(name, MidiOut)?, midi_out: None,
midi_out_buf: vec![vec![];16384], midi_out_buf: vec![vec![];16384],
notes_in: [false;128], notes_in: [false;128],
notes_out: [false;128], notes_out: [false;128],
@ -75,9 +65,25 @@ impl Track {
pub fn first_device (&self) -> Option<RwLockReadGuard<Box<dyn Device>>> { pub fn first_device (&self) -> Option<RwLockReadGuard<Box<dyn Device>>> {
self.get_device(0) self.get_device(0)
} }
pub fn connect_first_device (&self) -> Usually<()> {
if let (Some(port), Some(device)) = (&self.midi_out, self.devices.get(0)) {
device.client.as_client().connect_ports(&port, &device.midi_ins()?[0])?;
}
Ok(())
}
pub fn last_device (&self) -> Option<RwLockReadGuard<Box<dyn Device>>> { pub fn last_device (&self) -> Option<RwLockReadGuard<Box<dyn Device>>> {
self.get_device(self.devices.len().saturating_sub(1)) self.get_device(self.devices.len().saturating_sub(1))
} }
pub fn connect_last_device (&self, app: &App) -> Usually<()> {
Ok(match self.devices.get(self.devices.len().saturating_sub(1)) {
Some(device) => {
app.audio_out(0).map(|left|device.connect_audio_out(0, &left)).transpose()?;
app.audio_out(1).map(|right|device.connect_audio_out(0, &right)).transpose()?;
()
},
None => ()
})
}
pub fn add_device (&mut self, device: JackDevice) -> Usually<&mut JackDevice> { pub fn add_device (&mut self, device: JackDevice) -> Usually<&mut JackDevice> {
self.devices.push(device); self.devices.push(device);
let index = self.devices.len() - 1; let index = self.devices.len() - 1;
@ -125,7 +131,7 @@ impl Track {
} }
pub fn process ( pub fn process (
&mut self, &mut self,
input: MidiIter, input: Option<MidiIter>,
timebase: &Arc<Timebase>, timebase: &Arc<Timebase>,
playing: Option<TransportState>, playing: Option<TransportState>,
started: Option<(usize, usize)>, started: Option<(usize, usize)>,
@ -161,9 +167,9 @@ impl Track {
(frame0.saturating_sub(start_frame), frames, period) (frame0.saturating_sub(start_frame), frames, period)
); );
// Monitor and record input // Monitor and record input
if self.recording || self.monitoring { if input.is_some() && (self.recording || self.monitoring) {
// For highlighting keys and note repeat // For highlighting keys and note repeat
for (frame, event, bytes) in parse_midi_input(input) { for (frame, event, bytes) in parse_midi_input(input.unwrap()) {
match event { match event {
LiveEvent::Midi { message, .. } => { LiveEvent::Midi { message, .. } => {
if self.monitoring { if self.monitoring {
@ -195,16 +201,14 @@ impl Track {
} }
} }
} }
} else if self.monitoring { } else if input.is_some() && self.monitoring {
for (frame, event, bytes) in parse_midi_input(input) { for (frame, event, bytes) in parse_midi_input(input.unwrap()) {
self.process_monitor_event(frame, &event, bytes) self.process_monitor_event(frame, &event, bytes)
} }
} }
write_midi_output( if let Some(out) = &mut self.midi_out {
&mut self.midi_out.writer(scope), write_midi_output(&mut out.writer(scope), &self.midi_out_buf, frames);
&self.midi_out_buf, }
frames
);
} }
#[inline] #[inline]