Skip to main content

oscyl_midi/
hotplug.rs

1//! Notice synths being plugged in or unplugged, from ALSA sequencer
2//! announcements (event-driven: the caller polls the file descriptors from
3//! its own main loop and calls [`PortWatcher::drain_changes`] when they
4//! are ready).
5
6use std::ffi::CString;
7use std::os::fd::RawFd;
8
9use alsa::poll::Descriptors;
10use alsa::seq::{Addr, EventType, PortCap, PortSubscribe, PortType, Seq};
11
12use crate::{Candidate, Error, candidates};
13
14/// A synth's port came or went.
15#[derive(Debug, Clone, PartialEq, Eq)]
16pub enum Change {
17    Appeared(Candidate),
18    Gone(Candidate),
19}
20
21/// What changed from `old` to `new`: appearances first, in order.
22/// What changed from `old` to `new`. `cycled` names the ports that exited
23/// meanwhile, as `"client:port"`, or `"client:"` for a whole client: one
24/// still listed under the same name left and came back.
25fn diff(old: &[Candidate], new: &[Candidate], cycled: &[String]) -> Vec<Change> {
26    let left = |c: &Candidate| {
27        let addr = c.port.rsplit(' ').next().unwrap_or_default();
28        cycled.iter().any(|x| {
29            if x.ends_with(':') {
30                addr.starts_with(x.as_str())
31            } else {
32                addr == x
33            }
34        })
35    };
36    let appeared = new.iter().filter(|c| !old.contains(c));
37    let gone = old.iter().filter(|c| !new.contains(c));
38    let back = old.iter().filter(|c| new.contains(c) && left(c));
39    let back: Vec<Change> = back
40        .flat_map(|c| [Change::Gone(c.clone()), Change::Appeared(c.clone())])
41        .collect();
42    appeared
43        .cloned()
44        .map(Change::Appeared)
45        .chain(gone.cloned().map(Change::Gone))
46        .chain(back)
47        .collect()
48}
49
50pub struct PortWatcher {
51    seq: Seq,
52    ports: Vec<Candidate>,
53}
54
55fn alsa_err(e: alsa::Error) -> Error {
56    Error::Midi(e.to_string())
57}
58
59impl PortWatcher {
60    pub fn new() -> Result<PortWatcher, Error> {
61        let seq = Seq::open(None, Some(alsa::Direction::Capture), true).map_err(alsa_err)?;
62        let name = CString::new("oscyl-watch").expect("no NUL");
63        seq.set_client_name(&name).map_err(alsa_err)?;
64        let port = seq
65            .create_simple_port(
66                &name,
67                PortCap::WRITE | PortCap::SUBS_WRITE | PortCap::NO_EXPORT,
68                PortType::MIDI_GENERIC | PortType::APPLICATION,
69            )
70            .map_err(alsa_err)?;
71        let sub = PortSubscribe::empty().map_err(alsa_err)?;
72        sub.set_sender(Addr::system_announce());
73        sub.set_dest(Addr {
74            client: seq.client_id().map_err(alsa_err)?,
75            port,
76        });
77        seq.subscribe_port(&sub).map_err(alsa_err)?;
78        let mut w = PortWatcher { seq, ports: vec![] };
79        w.ports = w.scan();
80        Ok(w)
81    }
82
83    /// Every synth port present right now.
84    pub fn candidates(&self) -> &[Candidate] {
85        &self.ports
86    }
87
88    /// File descriptors to watch for readability.
89    pub fn fds(&self) -> Vec<RawFd> {
90        let target = (&self.seq, Some(alsa::Direction::Capture));
91        let mut fds = vec![libc_pollfd(); target.count()];
92        match target.fill(&mut fds) {
93            Ok(n) => fds[..n].iter().map(|p| p.fd).collect(),
94            Err(_) => Vec::new(),
95        }
96    }
97
98    /// Read pending announcements; returns each synth port that came or
99    /// went.
100    pub fn drain_changes(&mut self) -> Vec<Change> {
101        let (mut relevant, mut cycled) = (false, Vec::new());
102        {
103            let mut input = self.seq.input();
104            while let Ok(ev) = input.event_input() {
105                let addr = ev.get_data::<Addr>();
106                match (ev.get_type(), addr) {
107                    (EventType::PortExit, Some(a)) => {
108                        cycled.push(format!("{}:{}", a.client, a.port))
109                    }
110                    (EventType::ClientExit, Some(a)) => cycled.push(format!("{}:", a.client)),
111                    _ => {}
112                }
113                relevant |= matches!(
114                    ev.get_type(),
115                    EventType::PortStart
116                        | EventType::PortExit
117                        | EventType::ClientStart
118                        | EventType::ClientExit
119                );
120            }
121        }
122        if !relevant {
123            return vec![];
124        }
125        let now = self.scan();
126        let changes = diff(&self.ports, &now, &cycled);
127        self.ports = now;
128        changes
129    }
130
131    /// Synth ports, named as midir names them so [`crate::Device::open`]
132    /// finds them. Enumerates through this watcher's own sequencer handle:
133    /// opening other clients here would itself be announced and wake the
134    /// watcher again, forever.
135    fn scan(&self) -> Vec<Candidate> {
136        let duplex = PortCap::READ | PortCap::WRITE;
137        let mut names = vec![];
138        for client in alsa::seq::ClientIter::new(&self.seq) {
139            let Ok(cname) = client.get_name() else {
140                continue;
141            };
142            for port in alsa::seq::PortIter::new(&self.seq, client.get_client()) {
143                if !port.get_capability().contains(duplex) {
144                    continue;
145                }
146                if let Ok(pname) = port.get_name() {
147                    let (c, p) = (port.get_client(), port.get_port());
148                    names.push(format!("{cname}:{pname} {c}:{p}"));
149                }
150            }
151        }
152        candidates(&names)
153    }
154}
155
156fn libc_pollfd() -> alsa::poll::pollfd {
157    alsa::poll::pollfd {
158        fd: -1,
159        events: 0,
160        revents: 0,
161    }
162}
163
164#[cfg(test)]
165mod tests {
166    use super::*;
167
168    #[test]
169    fn diff_reports_each_device() {
170        let c = |ports: &[&str]| {
171            crate::candidates(&ports.iter().map(ToString::to_string).collect::<Vec<_>>())
172        };
173        let (xd1, xd2, rev2) = (
174            "minilogue xd:minilogue xd _ SOUND 28:1",
175            "minilogue xd:minilogue xd _ SOUND 32:1",
176            "Prophet Rev2:Prophet Rev2 MIDI 1 36:0",
177        );
178        assert_eq!(
179            diff(&c(&[xd1, rev2]), &c(&[xd1, xd2]), &[]),
180            [
181                Change::Appeared(c(&[xd2])[0].clone()),
182                Change::Gone(c(&[rev2])[0].clone())
183            ]
184        );
185        assert!(diff(&c(&[xd1]), &c(&[xd1]), &[]).is_empty());
186    }
187
188    /// A port that exits and starts again between two drains keeps its
189    /// name: it is still reported gone, then back, so its synth reconnects.
190    #[test]
191    fn diff_reports_a_port_that_cycled_under_the_same_name() {
192        let xd = crate::candidates(&["minilogue xd:minilogue xd _ SOUND 28:1".to_string()]);
193        let cycled = vec![Change::Gone(xd[0].clone()), Change::Appeared(xd[0].clone())];
194        assert_eq!(diff(&xd, &xd, &["28:1".into()]), cycled);
195        assert_eq!(diff(&xd, &xd, &["28:".into()]), cycled, "its client exited");
196        assert!(diff(&xd, &xd, &["2:".into(), "28:0".into()]).is_empty());
197    }
198
199    /// Needs an ALSA sequencer; skipped where none exists (e.g. CI).
200    #[test]
201    fn watcher_opens_and_starts_quiet() {
202        let Ok(mut w) = PortWatcher::new() else {
203            return;
204        };
205        assert!(!w.fds().is_empty());
206        assert!(
207            w.drain_changes().is_empty(),
208            "no announcements without a port change"
209        );
210        // Checking presence must not itself cause announcements.
211        let _ = w.scan();
212        assert!(w.drain_changes().is_empty());
213    }
214}