1mod device;
12#[cfg(all(feature = "midir", target_os = "linux"))]
13pub mod hotplug;
14pub mod logue;
15mod parse;
16mod push;
17#[cfg(feature = "midir")]
18pub use device::scan;
19pub use device::{Candidate, DRIVERS, Device, Opened, Opening, candidates, driver, run_all, wait};
20pub use push::{InputSender, PushLink};
21use std::collections::VecDeque;
22use std::sync::mpsc::{Receiver, RecvTimeoutError, Sender, channel};
23use std::sync::{Arc, Mutex};
24use std::time::Instant;
25
26#[cfg(feature = "midir")]
27use midir::{Ignore, MidiInput, MidiInputConnection, MidiOutput, MidiOutputConnection};
28use oscyl_driver::engine::OpError;
29use oscyl_driver::sysex::Framer;
30use oscyl_driver::{DriverError, Simulator};
31use oscyl_korg_minilogue_xd::adapter::XdSimulator;
32use oscyl_korg_minilogue_xd::sim::SimDevice;
33
34#[cfg(feature = "midir")]
35const CLIENT: &str = "oscyl";
36
37#[derive(Debug, thiserror::Error)]
38pub enum Error {
39 #[error("no supported synth found")]
40 NotFound,
41 #[error("more than one MIDI port matches {0:?}")]
42 Ambiguous(String),
43 #[error("MIDI port went away: {0}")]
44 Disconnected(String),
45 #[error("MIDI error: {0}")]
46 Midi(String),
47 #[error(transparent)]
48 Op(#[from] OpError),
49 #[error(
50 "{0} gave no recognised answer to the device inquiry; check that the synth is \
51 on and accepts SysEx on this port"
52 )]
53 Silent(String),
54 #[error(
55 "our own messages come back on {0} (MIDI thru or a loop), so replies cannot be \
56 trusted; turn the loop off"
57 )]
58 Loopback(String),
59 #[error(transparent)]
60 Driver(#[from] DriverError),
61}
62
63#[cfg(feature = "midir")]
64fn midi_err(e: impl std::fmt::Display) -> Error {
65 Error::Midi(e.to_string())
66}
67
68pub fn port_label(name: &str) -> String {
74 let numbered = name
75 .strip_prefix("MIDIIN")
76 .or_else(|| name.strip_prefix("MIDIOUT"))
77 .and_then(|rest| rest.split_once(" ("))
78 .and_then(|(n, rest)| Some((n, rest.strip_suffix(')')?)));
79 match numbered {
80 Some((n, product)) if !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit()) => {
81 format!("{product} _ MIDI {n}")
82 }
83 _ => name.to_string(),
84 }
85}
86
87#[cfg(feature = "midir")]
88pub fn list_ports() -> Result<Vec<String>, Error> {
90 let input = MidiInput::new(CLIENT).map_err(midi_err)?;
91 let output = MidiOutput::new(CLIENT).map_err(midi_err)?;
92 let mut names = Vec::new();
93 for p in input.ports() {
94 names.push(format!(
95 "in: {}",
96 port_label(&input.port_name(&p).map_err(midi_err)?)
97 ));
98 }
99 for p in output.ports() {
100 names.push(format!(
101 "out: {}",
102 port_label(&output.port_name(&p).map_err(midi_err)?)
103 ));
104 }
105 Ok(names)
106}
107
108#[cfg(feature = "midir")]
109fn select(names: &[String], pattern: &str, matches: &dyn Fn(&str) -> bool) -> Result<usize, Error> {
111 let mut hits = names.iter().enumerate().filter(|(_, n)| matches(n));
112 match (hits.next(), hits.next()) {
113 (Some((i, _)), None) => Ok(i),
114 (None, _) => Err(Error::NotFound),
115 (Some(_), Some(_)) => Err(Error::Ambiguous(pattern.to_string())),
116 }
117}
118
119pub trait Link: Send {
121 fn send(&mut self, bytes: &[u8]) -> Result<(), Error>;
123 fn recv_until(&mut self, deadline: Instant) -> Result<Option<Vec<u8>>, Error>;
126 fn ring_on_input(&mut self, _bell: Sender<()>) {}
130 fn synchronous(&self) -> bool {
134 false
135 }
136}
137
138#[cfg(feature = "midir")]
139pub struct MidirLink {
141 out: Out,
142 _in: MidiInputConnection<()>,
143 inbox: Inbox,
144}
145
146#[cfg(feature = "midir")]
147impl MidirLink {
148 pub fn open_exact(name: &str) -> Result<MidirLink, Error> {
150 match MidirLink::open_matching(name, &|n| n == name) {
151 Ok((link, _)) => Ok(link),
152 Err(Error::NotFound) => Err(Error::Disconnected(name.into())),
153 Err(e) => Err(e),
154 }
155 }
156
157 fn open_matching(
158 pattern: &str,
159 matches: &dyn Fn(&str) -> bool,
160 ) -> Result<(MidirLink, String), Error> {
161 let mut input = MidiInput::new(CLIENT).map_err(midi_err)?;
162 input.ignore(Ignore::None);
163 let output = MidiOutput::new(CLIENT).map_err(midi_err)?;
164 let (in_ports, out_ports) = (input.ports(), output.ports());
165 let names = |f: &dyn Fn(usize) -> String, n: usize| (0..n).map(f).collect::<Vec<_>>();
166 let in_names = names(
167 &|i| port_label(&input.port_name(&in_ports[i]).unwrap_or_default()),
168 in_ports.len(),
169 );
170 let out_names = names(
171 &|i| port_label(&output.port_name(&out_ports[i]).unwrap_or_default()),
172 out_ports.len(),
173 );
174 let (i, o) = (
175 select(&in_names, pattern, matches)?,
176 select(&out_names, pattern, matches)?,
177 );
178
179 let (inbox, feed) = inbox();
180 let conn_in = input
181 .connect(
182 &in_ports[i],
183 "in",
184 move |_, bytes, _| {
185 if bytes.iter().all(|&b| b >= 0xF8) {
188 return;
189 }
190 trace("<-", bytes);
191 feed.push(bytes)
192 },
193 (),
194 )
195 .map_err(midi_err)?;
196 let out = match Out::raw(&out_ports[o].id()) {
197 Some(raw) => raw,
198 None => Out::Seq(output.connect(&out_ports[o], "out").map_err(midi_err)?),
199 };
200 let link = MidirLink {
201 out,
202 _in: conn_in,
203 inbox,
204 };
205 Ok((link, out_names[o].clone()))
206 }
207}
208
209#[cfg(feature = "midir")]
211enum Out {
212 Seq(MidiOutputConnection),
214 #[cfg(target_os = "linux")]
221 Raw(alsa::rawmidi::Rawmidi),
222}
223
224#[cfg(feature = "midir")]
225impl Out {
226 #[cfg(target_os = "linux")]
229 fn raw(id: &str) -> Option<Out> {
230 let (client, port) = id.split_once(':')?;
231 let (client, port): (i32, i32) = (client.parse().ok()?, port.parse().ok()?);
232 let seq = alsa::seq::Seq::open(None, None, false).ok()?;
233 let card = seq.get_any_client_info(client).ok()?.get_card().ok()?;
234 let name = format!("hw:{card},0,{port}");
238 alsa::rawmidi::Rawmidi::new(&name, alsa::Direction::Playback, true)
239 .ok()
240 .map(Out::Raw)
241 }
242
243 #[cfg(not(target_os = "linux"))]
244 fn raw(_: &str) -> Option<Out> {
245 None
246 }
247
248 fn send(&mut self, msg: &[u8]) -> Result<(), Error> {
249 let lost = |e: &dyn std::fmt::Display| Error::Disconnected(e.to_string());
250 match self {
251 Out::Seq(c) => c.send(msg).map_err(|e| lost(&e)),
252 #[cfg(target_os = "linux")]
253 Out::Raw(r) => {
254 use alsa::poll::Descriptors;
255 let mut rest = msg;
256 while !rest.is_empty() {
257 match std::io::Write::write(&mut r.io(), rest) {
258 Ok(n) => rest = &rest[n..],
259 Err(e) if e.raw_os_error() == Some(-11) => {
261 let mut fds = r.get().map_err(|e| lost(&e))?;
264 if alsa::poll::poll(&mut fds, 5000).map_err(|e| lost(&e))? == 0 {
265 return Err(lost(&"the synth stopped taking data"));
266 }
267 }
268 Err(e) => return Err(lost(&e)),
269 }
270 }
271 Ok(())
272 }
273 }
274 }
275}
276
277#[cfg(feature = "midir")]
278impl Link for MidirLink {
279 fn send(&mut self, bytes: &[u8]) -> Result<(), Error> {
282 for chunk in split_messages(bytes) {
283 trace("->", chunk);
284 self.out.send(chunk)?;
285 }
286 Ok(())
287 }
288
289 fn recv_until(&mut self, deadline: Instant) -> Result<Option<Vec<u8>>, Error> {
290 self.inbox.recv_until(deadline)
291 }
292
293 fn ring_on_input(&mut self, bell: Sender<()>) {
294 self.inbox.ring_on_input(bell);
295 }
296}
297
298#[cfg(feature = "midir")]
301fn trace(dir: &str, bytes: &[u8]) {
302 use std::sync::LazyLock;
303 static START: LazyLock<Option<Instant>> =
304 LazyLock::new(|| std::env::var_os("OSCYL_MIDI_TRACE").map(|_| Instant::now()));
305 let Some(start) = *START else { return };
306 let head: Vec<String> = bytes.iter().take(12).map(|b| format!("{b:02X}")).collect();
307 eprintln!(
308 "{:>9.3} {dir} {} ({} bytes)",
309 start.elapsed().as_secs_f64(),
310 head.join(" "),
311 bytes.len()
312 );
313}
314
315type Bell = Arc<Mutex<Option<Sender<()>>>>;
316
317struct Inbox {
320 rx: Receiver<Vec<u8>>,
321 parser: parse::Parser,
323 pending: VecDeque<Vec<u8>>,
324 bell: Bell,
325}
326
327struct Feed {
329 tx: Sender<Vec<u8>>,
330 bell: Bell,
331}
332
333fn inbox() -> (Inbox, Feed) {
334 let (tx, rx) = channel();
335 let bell = Bell::default();
336 let feed = Feed {
337 tx,
338 bell: bell.clone(),
339 };
340 let inbox = Inbox {
341 rx,
342 parser: parse::Parser::default(),
343 pending: VecDeque::new(),
344 bell,
345 };
346 (inbox, feed)
347}
348
349impl Feed {
350 fn push(&self, bytes: &[u8]) {
352 drop(self.tx.send(bytes.to_vec()));
353 ring(&self.bell);
354 }
355}
356
357impl Drop for Feed {
360 fn drop(&mut self) {
361 drop(std::mem::replace(&mut self.tx, channel().0));
362 ring(&self.bell);
363 }
364}
365
366fn ring(bell: &Bell) {
367 if let Some(bell) = bell.lock().ok().as_deref().and_then(Option::as_ref) {
368 let _ = bell.send(());
369 }
370}
371
372impl Inbox {
373 fn recv_until(&mut self, deadline: Instant) -> Result<Option<Vec<u8>>, Error> {
374 loop {
375 if let Some(m) = self.pending.pop_front() {
376 return Ok(Some(m));
377 }
378 let wait = deadline.saturating_duration_since(Instant::now());
379 match self.rx.recv_timeout(wait) {
380 Ok(bytes) => self.pending.extend(self.parser.push(&bytes)),
381 Err(RecvTimeoutError::Timeout) => return Ok(None),
382 Err(RecvTimeoutError::Disconnected) => {
383 return Err(Error::Disconnected("input closed".into()));
384 }
385 }
386 }
387 }
388
389 fn ring_on_input(&mut self, bell: Sender<()>) {
390 if let Ok(mut b) = self.bell.lock() {
391 *b = Some(bell);
392 }
393 }
394}
395
396#[cfg(feature = "midir")]
397fn split_messages(bytes: &[u8]) -> Vec<&[u8]> {
400 let (mut out, mut start) = (vec![], 0);
401 for (i, &b) in bytes.iter().enumerate() {
402 match b {
403 0xF0 if i > start => {
404 out.push(&bytes[start..i]);
405 start = i;
406 }
407 0xF7 => {
408 out.push(&bytes[start..=i]);
409 start = i + 1;
410 }
411 _ => {}
412 }
413 }
414 if start < bytes.len() {
415 out.push(&bytes[start..]);
416 }
417 out
418}
419
420pub struct SimLink {
423 sim: Box<dyn Simulator>,
424 framer: Framer,
425 replies: VecDeque<Vec<u8>>,
426}
427
428impl SimLink {
429 pub fn new(sim: SimDevice) -> SimLink {
430 SimLink::from_sim(Box::new(XdSimulator(sim)))
431 }
432
433 pub fn from_sim(sim: Box<dyn Simulator>) -> SimLink {
435 SimLink {
436 sim,
437 framer: Framer::new(),
438 replies: VecDeque::new(),
439 }
440 }
441}
442
443impl Link for SimLink {
444 fn synchronous(&self) -> bool {
445 true
446 }
447
448 fn send(&mut self, bytes: &[u8]) -> Result<(), Error> {
449 for msg in self.framer.push(bytes) {
450 self.replies.extend(self.sim.handle(&msg));
451 }
452 Ok(())
453 }
454
455 fn recv_until(&mut self, _deadline: Instant) -> Result<Option<Vec<u8>>, Error> {
458 Ok(self.replies.pop_front())
459 }
460}
461
462#[cfg(all(test, feature = "midir"))]
463mod tests {
464 #[test]
465 fn windows_numbered_ports_pair_up_under_the_android_name() {
466 use super::port_label;
467 assert_eq!(
468 port_label("MIDIIN2 (minilogue xd)"),
469 "minilogue xd _ MIDI 2"
470 );
471 assert_eq!(
472 port_label("MIDIOUT2 (minilogue xd)"),
473 "minilogue xd _ MIDI 2"
474 );
475 for kept in [
476 "minilogue xd",
477 "minilogue xd:minilogue xd _ SOUND 24:1",
478 "MIDIIN (x)",
479 "MIDIINx (y)",
480 ] {
481 assert_eq!(port_label(kept), kept);
482 }
483 }
484
485 use super::*;
486
487 fn names(v: &[&str]) -> Vec<String> {
488 v.iter().map(std::string::ToString::to_string).collect()
489 }
490
491 #[test]
492 fn selects_the_sound_port() {
493 let n = names(&[
494 "Midi Through:Midi Through Port-0 14:0",
495 "minilogue xd:minilogue xd _ MIDI OUT 28:0",
496 "minilogue xd:minilogue xd _ SOUND 28:1",
497 ]);
498 fn has(p: &str) -> impl Fn(&str) -> bool + use<'_> {
499 move |n| n.contains(p)
500 }
501 let sound = "minilogue xd _ SOUND";
502 assert_eq!(select(&n, sound, &has(sound)).unwrap(), 2);
503 assert!(matches!(
504 select(&n, "nothing", &has("nothing")),
505 Err(Error::NotFound)
506 ));
507 assert!(matches!(
508 select(&n, "minilogue xd", &has("minilogue xd")),
509 Err(Error::Ambiguous(_))
510 ));
511 }
512
513 #[test]
514 fn split_sends_each_message() {
515 let (a, b) = (
516 [0xF0, 0x01, 0x2F, 0x05, 0, 1, 0xF7],
517 [0xF0, 0x01, 0x2F, 0x06, 0xF7],
518 );
519 let both = [&a[..], &b[..]].concat();
520 assert_eq!(split_messages(&both), vec![&a[..], &b[..]]);
521 assert_eq!(split_messages(&a), vec![&a[..]]);
522 assert_eq!(
523 split_messages(&[0xB0, 0x63, 0x01]),
524 vec![&[0xB0, 0x63, 0x01][..]]
525 );
526 }
527}