Skip to main content

oscyl_midi/
lib.rs

1//! USB-MIDI transport for Oscyl synth drivers.
2//!
3//! [`candidates`] picks the ports any registered driver ([`DRIVERS`])
4//! claims; a [`Device`] drives one synth's driver session over a [`Link`]:
5//! `MidirLink` for a real synth on desktop (feature `midir`: ALSA on Linux, CoreMIDI on macOS, WinMM on Windows;
6//! input arrives through midir's callback as byte chunks and is framed into
7//! SysEx messages), [`PushLink`] on platforms that move the bytes
8//! themselves (Android, iOS), or [`SimLink`] for a simulated one. One
9//! thread can serve several devices at once.
10
11mod 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
68/// A port's name as Oscyl spells it on every platform. Windows' class
69/// driver names a device's later ports "MIDIIN2 (minilogue xd)" and
70/// "MIDIOUT2 (minilogue xd)"; both become "minilogue xd _ MIDI 2", the
71/// name such a port gets on Android (the mobile app's `midiPortName`), so
72/// the input and output pair up and the drivers' hints match.
73pub 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")]
88/// Names of all MIDI input and output ports, for diagnostics.
89pub 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")]
109/// The single index whose name `matches`; `pattern` names it in errors.
110fn 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
119/// A bidirectional SysEx connection to a synth.
120pub trait Link: Send {
121    /// Send complete messages (one or more SysEx messages back to back).
122    fn send(&mut self, bytes: &[u8]) -> Result<(), Error>;
123    /// Next complete SysEx message, or `None` when none arrives by
124    /// `deadline`.
125    fn recv_until(&mut self, deadline: Instant) -> Result<Option<Vec<u8>>, Error>;
126    /// Send `()` on `bell` after input arrives (the input first), so one
127    /// thread can wait on several links. A link whose input arrives on its
128    /// own (not [`Link::synchronous`]) must implement it.
129    fn ring_on_input(&mut self, _bell: Sender<()>) {}
130    /// True when input only ever arrives during a send (a simulator): all
131    /// of it is there once the send returns, so a deadline passes at once
132    /// instead of being waited for.
133    fn synchronous(&self) -> bool {
134        false
135    }
136}
137
138#[cfg(feature = "midir")]
139/// The real synth over midir (ALSA on Linux).
140pub struct MidirLink {
141    out: Out,
142    _in: MidiInputConnection<()>,
143    inbox: Inbox,
144}
145
146#[cfg(feature = "midir")]
147impl MidirLink {
148    /// Connect to the input and output named exactly `name`.
149    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                    // Clock and active sensing never reach a session: they
186                    // would wake the reader 48 times a second for nothing.
187                    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/// Where a link's output goes.
210#[cfg(feature = "midir")]
211enum Out {
212    /// midir's connection (the ALSA sequencer on Linux).
213    Seq(MidiOutputConnection),
214    /// The port's ALSA rawmidi device. The sequencer's bridge to a
215    /// hardware port drops any message bigger than its output buffer
216    /// (4 KiB; the kernel logs "seq_midi: MIDI output buffer overrun"),
217    /// and a unit upload is bigger. Writing here waits for room (through
218    /// poll; the device is opened non-blocking, since a blocking open
219    /// would wait for whoever holds the port).
220    #[cfg(target_os = "linux")]
221    Raw(alsa::rawmidi::Rawmidi),
222}
223
224#[cfg(feature = "midir")]
225impl Out {
226    /// The rawmidi device behind sequencer port `id` (`client:port`), when
227    /// it is a hardware port no one else is writing to.
228    #[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        // The sequencer numbers the first device's subdevices first, so
235        // port N is subdevice N there, or not there at all (the open
236        // fails and the sequencer is used).
237        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                        // rawmidi's write returns -EAGAIN when full.
260                        Err(e) if e.raw_os_error() == Some(-11) => {
261                            // Full: wait until the synth has taken some.
262                            // A stall this long is a synth gone quiet.
263                            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    /// midir 0.11.1's ALSA backend encodes only the first MIDI event of
280    /// each `send`, so each SysEx message of `bytes` goes out on its own.
281    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/// `OSCYL_MIDI_TRACE=1`: every message sent or received (not clock or
299/// active sensing) on stderr, with milliseconds since the first one.
300#[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
317/// The input half of a link whose bytes arrive on another thread: chunks
318/// queued by its [`Feed`], framed into SysEx messages on the reader side.
319struct Inbox {
320    rx: Receiver<Vec<u8>>,
321    /// SysEx and channel messages (a panel's program change).
322    parser: parse::Parser,
323    pending: VecDeque<Vec<u8>>,
324    bell: Bell,
325}
326
327/// Where an [`Inbox`]'s input is pushed; dropping it closes the input.
328struct 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    /// Queue `bytes`, then ring the bell.
351    fn push(&self, bytes: &[u8]) {
352        drop(self.tx.send(bytes.to_vec()));
353        ring(&self.bell);
354    }
355}
356
357/// Gone (closed, or dropped by the platform): the input closes, then the
358/// bell rings so a waiting reader sees it.
359impl 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")]
397/// `bytes` cut into complete SysEx messages; bytes outside a message (CC or
398/// NRPN runs) pass through as one chunk each.
399fn 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
420/// The simulated synth. Replies are computed when a message is sent and
421/// queued; receiving never waits.
422pub 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    /// Any driver's simulator.
434    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    /// A queued reply, or `None` at once: nothing more will ever arrive
456    /// for what was sent.
457    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}