293 lines
8.2 KiB
Rust
293 lines
8.2 KiB
Rust
use std::sync::{
|
|
Arc,
|
|
atomic::{AtomicBool, Ordering},
|
|
mpsc::{SyncSender, TrySendError},
|
|
};
|
|
|
|
use fader_core::SurfaceId;
|
|
use midir::{
|
|
Ignore, MidiInput, MidiInputConnection as NativeInputConnection, MidiInputPort, MidiOutput,
|
|
MidiOutputConnection as NativeOutputConnection, MidiOutputPort,
|
|
};
|
|
use thiserror::Error;
|
|
|
|
use crate::{DecodeError, MidiMessage, decode_message};
|
|
|
|
/// One port reported by midir, retaining its opaque backend handle.
|
|
pub struct InputPort {
|
|
id: String,
|
|
name: String,
|
|
native: MidiInputPort,
|
|
}
|
|
|
|
impl InputPort {
|
|
#[must_use]
|
|
pub fn id(&self) -> &str {
|
|
&self.id
|
|
}
|
|
|
|
#[must_use]
|
|
pub fn name(&self) -> &str {
|
|
&self.name
|
|
}
|
|
}
|
|
|
|
impl std::fmt::Debug for InputPort {
|
|
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
|
formatter
|
|
.debug_struct("InputPort")
|
|
.field("id", &self.id)
|
|
.field("name", &self.name)
|
|
.finish_non_exhaustive()
|
|
}
|
|
}
|
|
|
|
/// Copied result of one midir callback invocation.
|
|
#[derive(Clone, Debug, Eq, PartialEq)]
|
|
pub enum MidiInputEvent {
|
|
Message {
|
|
surface: SurfaceId,
|
|
timestamp_micros: u64,
|
|
message: MidiMessage,
|
|
},
|
|
Malformed {
|
|
surface: SurfaceId,
|
|
timestamp_micros: u64,
|
|
error: DecodeError,
|
|
},
|
|
}
|
|
|
|
/// Initialization, discovery, or connection failure at the midir boundary.
|
|
#[derive(Clone, Debug, Error, Eq, PartialEq)]
|
|
pub enum MidiTransportError {
|
|
#[error("could not initialize MIDI input: {0}")]
|
|
Initialize(String),
|
|
#[error("could not read MIDI port information: {0}")]
|
|
PortInfo(String),
|
|
#[error("could not connect MIDI input: {0}")]
|
|
Connect(String),
|
|
#[error("could not initialize MIDI output: {0}")]
|
|
OutputInitialize(String),
|
|
#[error("could not read MIDI output port information: {0}")]
|
|
OutputPortInfo(String),
|
|
#[error("could not connect MIDI output: {0}")]
|
|
OutputConnect(String),
|
|
#[error("could not send MIDI output: {0}")]
|
|
OutputSend(String),
|
|
}
|
|
|
|
/// One-use midir catalog; connecting consumes it because midir transfers input ownership.
|
|
pub struct MidiInputCatalog {
|
|
input: MidiInput,
|
|
}
|
|
|
|
impl MidiInputCatalog {
|
|
pub fn new(client_name: &str) -> Result<Self, MidiTransportError> {
|
|
let mut input = MidiInput::new(client_name)
|
|
.map_err(|error| MidiTransportError::Initialize(error.to_string()))?;
|
|
input.ignore(Ignore::None);
|
|
Ok(Self { input })
|
|
}
|
|
|
|
pub fn ports(&self) -> Result<Vec<InputPort>, MidiTransportError> {
|
|
self.input
|
|
.ports()
|
|
.into_iter()
|
|
.map(|native| {
|
|
let id = native.id();
|
|
let name = self
|
|
.input
|
|
.port_name(&native)
|
|
.map_err(|error| MidiTransportError::PortInfo(error.to_string()))?;
|
|
Ok(InputPort { id, name, native })
|
|
})
|
|
.collect()
|
|
}
|
|
|
|
/// Opens one device callback that only parses and nonblockingly enqueues.
|
|
pub fn connect(
|
|
self,
|
|
port: &InputPort,
|
|
connection_name: &str,
|
|
surface: SurfaceId,
|
|
sender: SyncSender<MidiInputEvent>,
|
|
) -> Result<MidiInputConnection, MidiTransportError> {
|
|
let overflowed = Arc::new(AtomicBool::new(false));
|
|
let callback_overflowed = Arc::clone(&overflowed);
|
|
let connection = self
|
|
.input
|
|
.connect(
|
|
&port.native,
|
|
connection_name,
|
|
move |timestamp_micros, bytes, _| {
|
|
enqueue_bytes(
|
|
&sender,
|
|
&callback_overflowed,
|
|
&surface,
|
|
timestamp_micros,
|
|
bytes,
|
|
);
|
|
},
|
|
(),
|
|
)
|
|
.map_err(|error| MidiTransportError::Connect(error.to_string()))?;
|
|
Ok(MidiInputConnection {
|
|
_connection: connection,
|
|
overflowed,
|
|
})
|
|
}
|
|
}
|
|
|
|
fn enqueue_bytes(
|
|
sender: &SyncSender<MidiInputEvent>,
|
|
overflowed: &AtomicBool,
|
|
surface: &SurfaceId,
|
|
timestamp_micros: u64,
|
|
bytes: &[u8],
|
|
) {
|
|
let event = match decode_message(bytes) {
|
|
Ok(Some(message)) => MidiInputEvent::Message {
|
|
surface: surface.clone(),
|
|
timestamp_micros,
|
|
message,
|
|
},
|
|
Ok(None) => return,
|
|
Err(error) => MidiInputEvent::Malformed {
|
|
surface: surface.clone(),
|
|
timestamp_micros,
|
|
error,
|
|
},
|
|
};
|
|
if matches!(sender.try_send(event), Err(TrySendError::Full(_))) {
|
|
overflowed.store(true, Ordering::Release);
|
|
}
|
|
}
|
|
|
|
/// Keeps a midir input open and exposes callback overflow as an explicit fault.
|
|
pub struct MidiInputConnection {
|
|
_connection: NativeInputConnection<()>,
|
|
overflowed: Arc<AtomicBool>,
|
|
}
|
|
|
|
/// One MIDI output port reported by midir.
|
|
pub struct OutputPort {
|
|
id: String,
|
|
name: String,
|
|
native: MidiOutputPort,
|
|
}
|
|
|
|
impl OutputPort {
|
|
#[must_use]
|
|
pub fn id(&self) -> &str {
|
|
&self.id
|
|
}
|
|
|
|
#[must_use]
|
|
pub fn name(&self) -> &str {
|
|
&self.name
|
|
}
|
|
}
|
|
|
|
/// One-use midir output catalog.
|
|
pub struct MidiOutputCatalog {
|
|
output: MidiOutput,
|
|
}
|
|
|
|
impl MidiOutputCatalog {
|
|
pub fn new(client_name: &str) -> Result<Self, MidiTransportError> {
|
|
MidiOutput::new(client_name)
|
|
.map(|output| Self { output })
|
|
.map_err(|error| MidiTransportError::OutputInitialize(error.to_string()))
|
|
}
|
|
|
|
pub fn ports(&self) -> Result<Vec<OutputPort>, MidiTransportError> {
|
|
self.output
|
|
.ports()
|
|
.into_iter()
|
|
.map(|native| {
|
|
let id = native.id();
|
|
let name = self
|
|
.output
|
|
.port_name(&native)
|
|
.map_err(|error| MidiTransportError::OutputPortInfo(error.to_string()))?;
|
|
Ok(OutputPort { id, name, native })
|
|
})
|
|
.collect()
|
|
}
|
|
|
|
pub fn connect(
|
|
self,
|
|
port: &OutputPort,
|
|
connection_name: &str,
|
|
) -> Result<MidiOutputConnection, MidiTransportError> {
|
|
self.output
|
|
.connect(&port.native, connection_name)
|
|
.map(|connection| MidiOutputConnection { connection })
|
|
.map_err(|error| MidiTransportError::OutputConnect(error.to_string()))
|
|
}
|
|
}
|
|
|
|
/// Keeps a native MIDI output open for synchronous, short-message writes.
|
|
pub struct MidiOutputConnection {
|
|
connection: NativeOutputConnection,
|
|
}
|
|
|
|
impl MidiOutputConnection {
|
|
pub fn send(&mut self, message: &[u8]) -> Result<(), MidiTransportError> {
|
|
self.connection
|
|
.send(message)
|
|
.map_err(|error| MidiTransportError::OutputSend(error.to_string()))
|
|
}
|
|
}
|
|
|
|
impl MidiInputConnection {
|
|
#[must_use]
|
|
pub fn overflowed(&self) -> bool {
|
|
self.overflowed.load(Ordering::Acquire)
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use std::sync::mpsc;
|
|
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn callback_path_never_blocks_and_marks_bounded_overflow() {
|
|
let (sender, receiver) = mpsc::sync_channel(1);
|
|
let overflowed = AtomicBool::new(false);
|
|
let surface = SurfaceId::new("fixture").unwrap();
|
|
|
|
enqueue_bytes(&sender, &overflowed, &surface, 10, &[0xb0, 7, 64]);
|
|
enqueue_bytes(&sender, &overflowed, &surface, 11, &[0x90, 32, 127]);
|
|
assert!(overflowed.load(Ordering::Acquire));
|
|
assert!(matches!(
|
|
receiver.try_recv(),
|
|
Ok(MidiInputEvent::Message {
|
|
timestamp_micros: 10,
|
|
..
|
|
})
|
|
));
|
|
}
|
|
|
|
#[test]
|
|
fn callback_reports_malformed_and_discards_clock_traffic() {
|
|
let (sender, receiver) = mpsc::sync_channel(2);
|
|
let overflowed = AtomicBool::new(false);
|
|
let surface = SurfaceId::new("fixture").unwrap();
|
|
|
|
enqueue_bytes(&sender, &overflowed, &surface, 20, &[0xb0, 7]);
|
|
enqueue_bytes(&sender, &overflowed, &surface, 21, &[0xf8]);
|
|
assert!(matches!(
|
|
receiver.try_recv(),
|
|
Ok(MidiInputEvent::Malformed {
|
|
timestamp_micros: 20,
|
|
..
|
|
})
|
|
));
|
|
assert!(receiver.try_recv().is_err());
|
|
assert!(!overflowed.load(Ordering::Acquire));
|
|
}
|
|
}
|