1use std::collections::VecDeque;
5use std::fmt;
6use std::sync::mpsc::{Receiver, Sender, channel};
7use std::time::{Duration, Instant};
8
9#[cfg(feature = "midir")]
10use midir::{MidiInput, MidiOutput};
11use oscyl_driver::engine::OpError;
12use oscyl_driver::sysex::DEVICE_INQUIRY;
13use oscyl_driver::{Driver, DriverError, DriverSession, SessionEvent, SessionOp};
14use oscyl_korg_minilogue_xd::session as xd;
15
16use crate::logue::{UnitEvent, UnitOp, UnitSession, unit_session};
17#[cfg(feature = "midir")]
18use crate::{CLIENT, MidirLink, midi_err};
19use crate::{Error, Link, SimLink};
20
21const INQUIRY_BOUND: Duration = Duration::from_secs(2);
24
25pub static DRIVERS: &[&dyn Driver] = &[
27 &oscyl_korg_minilogue_xd::DRIVER,
28 &oscyl_sequential_prophet_rev2::DRIVER,
29 &oscyl_korg_prologue::DRIVER,
30];
31
32pub fn driver(id: &str) -> Option<&'static dyn Driver> {
34 DRIVERS.iter().copied().find(|d| d.info().id == id)
35}
36
37#[derive(Clone)]
40pub struct Candidate {
41 pub driver: &'static dyn Driver,
42 pub port: String,
45}
46
47impl PartialEq for Candidate {
48 fn eq(&self, other: &Candidate) -> bool {
49 self.driver.info().id == other.driver.info().id && self.port == other.port
50 }
51}
52
53impl Eq for Candidate {}
54
55impl fmt::Debug for Candidate {
56 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
57 write!(f, "{} on {:?}", self.driver.info().id, self.port)
58 }
59}
60
61pub fn candidates(ports: &[String]) -> Vec<Candidate> {
64 ports
65 .iter()
66 .flat_map(|port| {
67 DRIVERS
68 .iter()
69 .filter(|d| d.port_hint().iter().any(|h| port.contains(h)))
70 .map(|&driver| Candidate {
71 driver,
72 port: port.clone(),
73 })
74 })
75 .collect()
76}
77
78#[cfg(feature = "midir")]
79pub fn scan() -> Result<Vec<Candidate>, Error> {
82 let input = MidiInput::new(CLIENT).map_err(midi_err)?;
83 let output = MidiOutput::new(CLIENT).map_err(midi_err)?;
84 let ins: Vec<String> = input
85 .ports()
86 .iter()
87 .filter_map(|p| input.port_name(p).ok())
88 .map(|n| crate::port_label(&n))
89 .collect();
90 let duplex: Vec<String> = output
91 .ports()
92 .iter()
93 .filter_map(|p| output.port_name(p).ok())
94 .map(|n| crate::port_label(&n))
95 .filter(|n| ins.contains(n))
96 .collect();
97 Ok(candidates(&duplex))
98}
99
100pub struct Device {
108 driver: &'static dyn Driver,
109 port_name: String,
110 channel: u8,
111 session: Box<dyn DriverSession>,
112 link: Box<dyn Link>,
113 outstanding: usize,
115 identity: Vec<u8>,
117 bell: Option<Sender<()>>,
119 checked: bool,
122 internal_at: Option<usize>,
124 units: Option<Box<dyn UnitSession>>,
126 unit_outstanding: usize,
127 unit_events: VecDeque<UnitEvent>,
128 panel: Panel,
130 held: VecDeque<SessionOp>,
132}
133
134impl Device {
135 #[cfg(feature = "midir")]
136 pub fn open(c: &Candidate) -> Result<Device, Error> {
138 let link = MidirLink::open_exact(&c.port)?;
139 Device::connect(c.driver, Box::new(link), c.port.clone())
140 }
141
142 pub fn simulated(driver: &'static dyn Driver) -> Result<Device, Error> {
144 let link = SimLink::from_sim(driver.simulator());
145 let name = format!("simulated {}", driver.info().model);
146 Device::connect(driver, Box::new(link), name)
147 }
148
149 pub fn demo(driver: &'static dyn Driver) -> Result<Device, Error> {
152 let link = SimLink::from_sim(driver.demo_simulator());
153 let name = format!("simulated {}", driver.info().model);
154 Device::connect(driver, Box::new(link), name)
155 }
156
157 pub fn connect(
160 driver: &'static dyn Driver,
161 link: Box<dyn Link>,
162 port_name: String,
163 ) -> Result<Device, Error> {
164 let mut o = Opening::start(driver, link, port_name)?;
165 loop {
166 let deadline = o.deadline;
167 match o.link_mut().recv_until(deadline)? {
168 Some(msg) => {
169 if let Some(done) = o.answer(msg) {
170 return done;
171 }
172 }
173 None => return Err(Error::Silent(o.port_name)),
174 }
175 }
176 }
177
178 fn identified(
180 driver: &'static dyn Driver,
181 link: Box<dyn Link>,
182 port_name: String,
183 msg: Vec<u8>,
184 ) -> Device {
185 let channel = msg.get(2).copied().filter(|c| *c < 16).unwrap_or(0);
186 Device {
187 driver,
188 port_name,
189 channel,
190 session: driver.session(channel),
191 link,
192 outstanding: 0,
193 identity: msg,
194 bell: None,
195 checked: false,
196 internal_at: None,
197 units: None,
198 unit_outstanding: 0,
199 unit_events: VecDeque::new(),
200 held: VecDeque::new(),
201 panel: Panel::default(),
202 }
203 }
204
205 pub fn driver(&self) -> &'static dyn Driver {
206 self.driver
207 }
208
209 pub fn port_name(&self) -> &str {
210 &self.port_name
211 }
212
213 pub fn channel(&self) -> u8 {
217 self.channel
218 }
219
220 pub fn firmware(&self) -> Option<String> {
222 self.driver.firmware(&self.identity)
223 }
224
225 pub fn send(&mut self, msg: &[u8]) -> Result<(), Error> {
228 self.link.send(msg)
229 }
230
231 pub fn recv_until(&mut self, deadline: Instant) -> Result<Option<Vec<u8>>, Error> {
234 loop {
235 match self.link.recv_until(deadline)? {
236 Some(msg) => {
237 if let Some(msg) = self.input(msg) {
238 return Ok(Some(msg));
239 }
240 }
241 None => return Ok(None),
242 }
243 }
244 }
245
246 #[cfg(feature = "midir")]
247 pub fn open_xd(port: Option<&str>) -> Result<Device, Error> {
250 let xd = oscyl_korg_minilogue_xd::DRIVER.info().id;
251 let c = crate::scan()?
252 .into_iter()
253 .find(|c| c.driver.info().id == xd && port.is_none_or(|p| c.port.contains(p)))
254 .ok_or(Error::NotFound)?;
255 Device::open(&c)
256 }
257
258 pub fn close(&mut self) {
262 self.link = Box::new(Closed);
263 }
264
265 pub fn poll_selected(&mut self) -> Option<u16> {
268 self.panel.selected.pop_front()
269 }
270
271 pub fn poll_control(&mut self) -> Option<(u8, u8)> {
274 self.panel.controls.pop_front()
275 }
276
277 fn input(&mut self, msg: Vec<u8>) -> Option<Vec<u8>> {
280 self.panel.input(self.driver, self.channel, msg)
281 }
282
283 pub fn ring_on_input(&mut self, bell: Sender<()>) {
285 self.link.ring_on_input(bell.clone());
286 self.bell = Some(bell);
287 }
288
289 pub fn submit(&mut self, op: SessionOp) -> Result<(), Error> {
292 if self.units_busy() {
293 self.held.push_back(op);
294 } else {
295 self.session.submit(op)?;
296 }
297 self.outstanding += 1;
298 Ok(())
299 }
300
301 fn units_busy(&self) -> bool {
302 self.units.as_ref().is_some_and(|u| !u.is_idle())
303 }
304
305 pub fn submit_units(&mut self, op: UnitOp) -> Result<(), Error> {
311 if self.units.is_none() {
312 self.units = Some(unit_session(self.driver, self.channel).ok_or_else(|| {
313 Error::Driver(DriverError(format!(
314 "the {} has no user units",
315 self.driver.info().model
316 )))
317 })?);
318 }
319 if !self.checked && self.internal_at.is_none() && !self.units_busy() {
320 self.session.submit(SessionOp::ReadCurrent)?;
321 self.internal_at = Some(self.outstanding - self.held.len());
322 }
323 self.units.as_mut().expect("made above").submit(op);
324 self.unit_outstanding += 1;
325 Ok(())
326 }
327
328 pub fn poll_unit_event(&mut self) -> Option<UnitEvent> {
330 self.unit_events.pop_front()
331 }
332
333 pub fn is_idle(&self) -> bool {
335 self.session.is_idle() && !self.units_busy() && self.held.is_empty()
336 }
337
338 pub fn cancel(&mut self, on_event: &mut dyn FnMut(&SessionEvent)) {
342 self.session = self.driver.session(self.channel);
343 self.held.clear();
344 self.internal_at = None;
345 for _ in 0..std::mem::take(&mut self.outstanding) {
346 on_event(&SessionEvent::Failed(OpError::Cancelled));
347 }
348 self.units = None;
349 for _ in 0..std::mem::take(&mut self.unit_outstanding) {
350 self.unit_events
351 .push_back(UnitEvent::Failed(OpError::Cancelled));
352 }
353 }
354
355 pub fn pump(
360 &mut self,
361 on_event: &mut dyn FnMut(&SessionEvent),
362 ) -> Result<Option<Instant>, Error> {
363 let now = Instant::now();
364 if self.units_busy() && self.session.is_idle() && self.checked {
366 return self.pump_units(now);
367 }
368 while let Some(msg) = self.session.poll_transmit(now) {
369 self.link.send(&msg)?;
370 }
371 while let Some(msg) = self.link.recv_until(now)? {
372 if let Some(msg) = self.input(msg) {
373 self.session.handle_input(&msg);
374 }
375 }
376 self.session.handle_timeout(now);
377 self.events(on_event);
378 if self.session.is_idle() {
379 return Ok(self.units_busy().then_some(now));
381 }
382 match self.session.next_deadline() {
383 Some(deadline) if self.link.synchronous() => {
386 self.session.handle_timeout(deadline);
387 self.events(on_event);
388 Ok(Some(now))
389 }
390 Some(deadline) => Ok(Some(deadline)),
391 None => Ok(Some(now)),
393 }
394 }
395
396 fn pump_units(&mut self, now: Instant) -> Result<Option<Instant>, Error> {
397 let units = self.units.as_mut().expect("busy");
398 while let Some(msg) = units.poll_transmit(now) {
399 self.link.send(&msg)?;
400 }
401 while let Some(msg) = self.link.recv_until(now)? {
402 if let Some(msg) = self.panel.input(self.driver, self.channel, msg) {
403 units.handle_input(&msg);
404 }
405 }
406 units.handle_timeout(now);
407 if let Some(deadline) = units.next_deadline()
408 && self.link.synchronous()
409 {
410 units.handle_timeout(deadline);
412 }
413 let deadline = units.next_deadline();
414 while let Some(e) = units.poll_event() {
415 if matches!(e, UnitEvent::Done | UnitEvent::Failed(_)) {
416 self.unit_outstanding = self.unit_outstanding.saturating_sub(1);
417 }
418 self.unit_events.push_back(e);
419 }
420 if !self.units_busy() {
421 for op in std::mem::take(&mut self.held) {
423 self.session.submit(op)?;
424 }
425 return Ok(Some(now));
426 }
427 Ok(Some(match deadline {
428 Some(d) if !self.link.synchronous() => d,
429 _ => now,
430 }))
431 }
432
433 pub fn run_units(
436 &mut self,
437 op: UnitOp,
438 mut on_event: impl FnMut(&UnitEvent),
439 ) -> Result<(), Error> {
440 self.submit_units(op)?;
441 let (bell, rung) = channel();
442 let before = self.bell.clone();
443 self.ring_on_input(bell);
444 let result = loop {
445 let next = match self.pump(&mut |_| {}) {
446 Ok(n) => n,
447 Err(e) => break Err(e),
448 };
449 let mut end = None;
450 while let Some(e) = self.poll_unit_event() {
451 on_event(&e);
452 match e {
453 UnitEvent::Done if self.unit_outstanding == 0 => end = Some(Ok(())),
454 UnitEvent::Failed(err) => end = Some(Err(Error::Op(err))),
455 _ => {}
456 }
457 }
458 if let Some(r) = end {
459 break r;
460 }
461 wait(&rung, next);
462 };
463 if let Some(b) = before {
464 self.ring_on_input(b);
465 }
466 result
467 }
468
469 pub fn run_xd(
476 &mut self,
477 op: xd::Op,
478 mut on_event: impl FnMut(&xd::Event),
479 ) -> Result<(), Error> {
480 if self.driver.info().id != oscyl_korg_minilogue_xd::DRIVER.info().id {
481 return Err(Error::Driver(DriverError(format!(
482 "the {} has no user units",
483 self.driver.info().model
484 ))));
485 }
486 if !self.is_idle() {
487 return Err(Error::Driver(DriverError(
488 "the synth is busy with another operation".into(),
489 )));
490 }
491 if !self.checked {
492 self.run(SessionOp::ReadCurrent, |_| {})?;
493 self.checked = true;
494 }
495 let mut session = xd::Session::new(xd::Xd {
496 channel: self.channel,
497 });
498 session.submit(op);
499 loop {
500 while let Some(msg) = session.poll_transmit(Instant::now()) {
501 self.link.send(&msg)?;
502 }
503 if let Some(deadline) = session.next_deadline() {
504 match self.link.recv_until(deadline)? {
505 Some(msg) => {
506 if let Some(msg) = self.input(msg) {
507 session.handle_input(&msg);
508 }
509 session.handle_timeout(Instant::now());
510 }
511 None => session.handle_timeout(deadline),
513 }
514 }
515 while let Some(ev) = session.poll_event() {
516 on_event(&ev);
517 match ev {
518 xd::Event::OpDone => return Ok(()),
519 xd::Event::OpFailed(e) => return Err(e.into()),
520 _ => {}
521 }
522 }
523 }
524 }
525
526 fn events(&mut self, on_event: &mut dyn FnMut(&SessionEvent)) {
527 while let Some(e) = self.session.poll_event() {
528 let ends = matches!(e, SessionEvent::Done | SessionEvent::Failed(_));
529 if self.internal_at == Some(0) {
531 if ends {
532 self.internal_at = None;
533 self.checked = true;
534 }
535 continue;
536 }
537 if ends {
538 self.checked = true;
540 self.outstanding = self.outstanding.saturating_sub(1);
541 if let Some(k) = self.internal_at.as_mut() {
542 *k -= 1;
543 }
544 }
545 on_event(&e);
546 }
547 }
548
549 pub fn run(
552 &mut self,
553 op: SessionOp,
554 mut on_event: impl FnMut(&SessionEvent),
555 ) -> Result<(), Error> {
556 self.submit(op)?;
557 let mut failed = None;
558 let mut results = run_all(&mut [self], |_, e| {
559 if let SessionEvent::Failed(err) = e {
560 failed.get_or_insert(err.clone());
561 }
562 on_event(e);
563 });
564 results.pop().expect("one device")?;
565 failed.map_or(Ok(()), |e| Err(Error::Op(e)))
566 }
567}
568
569struct Closed;
571
572impl Link for Closed {
573 fn send(&mut self, _: &[u8]) -> Result<(), Error> {
574 Err(Error::Disconnected("closed".into()))
575 }
576
577 fn recv_until(&mut self, _: Instant) -> Result<Option<Vec<u8>>, Error> {
578 Err(Error::Disconnected("closed".into()))
579 }
580}
581
582#[derive(Default)]
584struct Panel {
585 bank: (u8, u8),
587 selected: VecDeque<u16>,
589 controls: VecDeque<(u8, u8)>,
591}
592
593impl Panel {
594 fn input(&mut self, driver: &dyn Driver, channel: u8, msg: Vec<u8>) -> Option<Vec<u8>> {
598 if msg.first() == Some(&0xF0) {
599 return Some(msg);
600 }
601 if msg.first().is_none_or(|s| s & 0x0F != channel) {
602 return None;
603 }
604 match (msg[0] & 0xF0, msg.get(1), msg.get(2)) {
605 (0xB0, Some(0), Some(&v)) => self.bank.0 = v,
606 (0xB0, Some(32), Some(&v)) => self.bank.1 = v,
607 (0xB0, Some(&cc), Some(&v)) => {
608 if self.controls.len() >= 1024 {
610 self.controls.pop_front();
611 }
612 self.controls.push_back((cc, v));
613 }
614 (0xC0, Some(&p), _) => {
615 let (msb, lsb) = self.bank;
616 self.selected.extend(driver.program_slot(msb, lsb, p));
617 }
618 _ => {}
619 }
620 None
621 }
622}
623
624pub struct Opening {
627 driver: &'static dyn Driver,
628 link: Option<Box<dyn Link>>,
630 port_name: String,
631 deadline: Instant,
632}
633
634pub enum Opened {
636 Ready(Box<Device>),
637 Waiting(Opening),
638 Failed(Error),
639}
640
641impl Opening {
642 #[cfg(feature = "midir")]
643 pub fn open(c: &Candidate) -> Result<Opening, Error> {
645 let link = MidirLink::open_exact(&c.port)?;
646 Opening::start(c.driver, Box::new(link), c.port.clone())
647 }
648
649 pub fn start(
651 driver: &'static dyn Driver,
652 mut link: Box<dyn Link>,
653 port_name: String,
654 ) -> Result<Opening, Error> {
655 link.send(&DEVICE_INQUIRY)?;
656 Ok(Opening {
657 driver,
658 link: Some(link),
659 port_name,
660 deadline: Instant::now() + INQUIRY_BOUND,
661 })
662 }
663
664 pub fn driver(&self) -> &'static dyn Driver {
665 self.driver
666 }
667
668 pub fn port_name(&self) -> &str {
669 &self.port_name
670 }
671
672 pub fn ring_on_input(&mut self, bell: Sender<()>) {
674 self.link_mut().ring_on_input(bell);
675 }
676
677 fn answer(&mut self, msg: Vec<u8>) -> Option<Result<Device, Error>> {
680 if msg.first() != Some(&0xF0) {
681 return None;
682 }
683 if msg == DEVICE_INQUIRY {
684 return Some(Err(Error::Loopback(self.port_name.clone())));
685 }
686 self.driver.recognize(&msg).then(|| {
687 let link = self.link.take().expect("answered once");
688 Ok(Device::identified(
689 self.driver,
690 link,
691 std::mem::take(&mut self.port_name),
692 msg,
693 ))
694 })
695 }
696
697 pub fn poll(mut self, now: Instant) -> Opened {
700 loop {
701 match self.link_mut().recv_until(now) {
702 Ok(Some(msg)) => match self.answer(msg) {
703 Some(Ok(d)) => return Opened::Ready(Box::new(d)),
704 Some(Err(e)) => return Opened::Failed(e),
705 None => {}
706 },
707 Ok(None) if now >= self.deadline || self.link_mut().synchronous() => {
708 return Opened::Failed(Error::Silent(self.port_name));
709 }
710 Ok(None) => return Opened::Waiting(self),
711 Err(e) => return Opened::Failed(e),
712 }
713 }
714 }
715
716 fn link_mut(&mut self) -> &mut Box<dyn Link> {
717 self.link.as_mut().expect("open until answered")
718 }
719
720 pub fn deadline(&self) -> Instant {
722 self.deadline
723 }
724}
725
726pub fn wait(bell: &Receiver<()>, until: Option<Instant>) {
731 let _ = match until {
732 Some(t) => bell
733 .recv_timeout(t.saturating_duration_since(Instant::now()))
734 .ok(),
735 None => bell.recv().ok(),
736 };
737 while bell.try_recv().is_ok() {}
738}
739
740pub fn run_all(
745 devices: &mut [&mut Device],
746 mut on_event: impl FnMut(usize, &SessionEvent),
747) -> Vec<Result<(), Error>> {
748 let (bell, rung) = channel();
749 let before: Vec<Option<Sender<()>>> = devices.iter().map(|d| d.bell.clone()).collect();
751 for d in devices.iter_mut() {
752 d.ring_on_input(bell.clone());
753 }
754 let mut results: Vec<Result<(), Error>> = devices.iter().map(|_| Ok(())).collect();
755 loop {
756 let mut next: Option<Instant> = None;
757 for (i, d) in devices.iter_mut().enumerate() {
758 if results[i].is_err() {
759 continue;
760 }
761 match d.pump(&mut |e| on_event(i, e)) {
762 Ok(Some(t)) => next = Some(next.map_or(t, |n| n.min(t))),
763 Ok(None) => {}
764 Err(e) => results[i] = Err(e),
765 }
766 }
767 if next.is_none() {
768 for (d, b) in devices.iter_mut().zip(before) {
769 if let Some(b) = b {
770 d.ring_on_input(b);
771 }
772 }
773 return results;
774 }
775 wait(&rung, next);
776 }
777}
778
779#[cfg(test)]
780mod tests {
781 use super::*;
782 use crate::{InputSender, PushLink};
783 use std::sync::{Arc, Mutex};
784
785 fn xd() -> (Device, InputSender) {
788 let d = driver("korg-minilogue-xd").unwrap();
789 let back: Arc<Mutex<Option<InputSender>>> = Arc::default();
790 let to = back.clone();
791 let mut sim = d.simulator();
792 let mut framer = oscyl_driver::sysex::Framer::new();
793 let (link, input) = PushLink::new(Box::new(move |bytes| {
794 for m in framer.push(bytes) {
795 for reply in sim.handle(&m) {
796 if let Some(i) = to.lock().unwrap().as_ref() {
797 i.push(&reply);
798 }
799 }
800 }
801 Ok(())
802 }));
803 *back.lock().unwrap() = Some(input.clone());
804 (
805 Device::connect(d, Box::new(link), "usb xd".into()).unwrap(),
806 input,
807 )
808 }
809
810 #[test]
814 fn the_synth_picking_a_program_is_reported_as_its_slot() {
815 let (mut d, input) = xd();
816 input.push(&[0xB0, 0x00, 0x00, 0xB0, 0x20, 0x02, 0xC0, 0x05]);
817 input.push(&[0xC1, 0x07, 0x90, 0x40, 0x7F]);
818 input.push(&[0xC0, 0x09]);
819 d.pump(&mut |_| {}).unwrap();
820 assert_eq!(d.poll_selected(), Some(205));
821 assert_eq!(d.poll_selected(), Some(209));
822 assert_eq!(d.poll_selected(), None);
823 }
824
825 #[test]
828 fn the_panels_knobs_come_through() {
829 let (mut d, input) = xd();
830 input.push(&[0xB0, 0x3F, 0x05, 0xB0, 0x2B, 0x55, 0xB0, 0x00, 0x00]);
831 input.push(&[0x90, 0x40, 0x7F, 0xB1, 0x2B, 0x01]);
832 d.pump(&mut |_| {}).unwrap();
833 assert_eq!(d.poll_control(), Some((0x3F, 0x05)));
834 assert_eq!(d.poll_control(), Some((0x2B, 0x55)));
835 assert_eq!(d.poll_control(), None);
836 }
837
838 #[test]
841 fn a_program_picked_during_a_read_leaves_the_read_whole() {
842 let (mut d, input) = xd();
843 input.push(&[0xB0, 0x20, 0x01, 0xC0, 0x00]);
844 let mut got = None;
845 d.run(SessionOp::ReadCurrent, |e| {
846 if let SessionEvent::Current(p) = e {
847 got = Some(p.len());
848 }
849 })
850 .unwrap();
851 assert!(got.is_some());
852 assert_eq!(d.poll_selected(), Some(100));
853 }
854}