Skip to main content

wavegraph_remote/
usb.rs

1use crate::{Transport, protocol};
2use alloc::{sync::Arc, vec::Vec};
3use core::sync::atomic::{AtomicBool, Ordering};
4use core::time::Duration;
5use fm1_usb::{Device, MidiConnection, MidiPorts};
6use std::{
7    io,
8    sync::mpsc::{self, Receiver, RecvTimeoutError, TrySendError},
9};
10
11const REPLY_CAPACITY: usize = 64;
12
13/// Bidirectional FM-1 MIDI connection using the system MIDI driver.
14///
15/// Only WaveGraph remote replies enter the bounded receive queue. Other musical
16/// MIDI and USB log traffic remain independent. Callback overflow fails a query
17/// explicitly instead of silently accepting an incomplete snapshot.
18pub struct UsbTransport {
19    connection: MidiConnection,
20    replies: Receiver<Vec<u8>>,
21    overflow: Arc<AtomicBool>,
22}
23
24impl core::fmt::Debug for UsbTransport {
25    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
26        f.debug_struct("UsbTransport").finish_non_exhaustive()
27    }
28}
29
30impl UsbTransport {
31    /// Open a named MIDI pair, or use `fm1-usb` automatic device/log discovery.
32    ///
33    /// A name bypasses the log probe and can select firmware without logging.
34    /// Discovery is performed on the control thread, never the audio callback.
35    /// `timeout` bounds each log-discovery request, not the entire connection
36    /// attempt: automatic discovery can probe multiple ports and make multiple
37    /// requests per port. A named port skips those requests.
38    ///
39    /// # Errors
40    /// Returns an error for a missing/ambiguous device or unavailable MIDI ports.
41    pub fn connect(port: Option<&str>, timeout: Duration) -> io::Result<Self> {
42        let ports = if let Some(name) = port {
43            MidiPorts::by_name(name)?
44        } else {
45            Device::find()?.log_ports(None, timeout)?.0
46        };
47        Self::open(&ports)
48    }
49
50    /// Open a previously selected pair of FM-1 MIDI ports.
51    ///
52    /// # Errors
53    /// Returns an error if either MIDI port cannot be opened.
54    pub fn open(ports: &MidiPorts) -> io::Result<Self> {
55        let (sender, replies) = mpsc::sync_channel(REPLY_CAPACITY);
56        let overflow = Arc::new(AtomicBool::new(false));
57        let callback_overflow = Arc::clone(&overflow);
58        let connection = ports.connect(move |_, message| {
59            if !protocol::is_remote(message) {
60                return;
61            }
62            if message.len() > protocol::MAX_FRAME {
63                callback_overflow.store(true, Ordering::Release);
64                return;
65            }
66            if let Err(TrySendError::Full(_)) = sender.try_send(message.to_vec()) {
67                callback_overflow.store(true, Ordering::Release);
68            }
69        })?;
70        Ok(Self {
71            connection,
72            replies,
73            overflow,
74        })
75    }
76
77    fn check_overflow(&self) -> io::Result<()> {
78        if self.overflow.swap(false, Ordering::AcqRel) {
79            for _ in 0..REPLY_CAPACITY {
80                if self.replies.try_recv().is_err() {
81                    break;
82                }
83            }
84            return Err(io::Error::new(
85                io::ErrorKind::InvalidData,
86                "WaveGraph reply queue overflowed or a reply was oversized; retry discovery",
87            ));
88        }
89        Ok(())
90    }
91}
92
93impl Transport for UsbTransport {
94    fn send(&mut self, message: &[u8]) -> io::Result<()> {
95        self.connection.send(message)
96    }
97
98    fn receive(&mut self, timeout: Duration) -> io::Result<Vec<u8>> {
99        self.check_overflow()?;
100        let received = self.replies.recv_timeout(timeout);
101        // A dropped oversized reply does not wake recv_timeout. Attribute the
102        // error to this query even if it happened while the receiver waited.
103        self.check_overflow()?;
104        received.map_err(|error| match error {
105            RecvTimeoutError::Timeout => {
106                io::Error::new(io::ErrorKind::TimedOut, "MIDI receive timed out")
107            }
108            RecvTimeoutError::Disconnected => {
109                io::Error::new(io::ErrorKind::BrokenPipe, "MIDI connection closed")
110            }
111        })
112    }
113}