From 51d1e5bd2581fecf3e7ee7d49ecffcb206cd259c Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Thu, 15 Oct 2026 02:37:30 +0200 Subject: [PATCH] feat(M5.3): own live MIDI surface connections Tests: cargo test --locked -p fader_master --all-targets --all-features Tests: cargo test --locked -p midi --all-targets --all-features Lint: cargo clippy --locked -p fader_master -p midi --all-targets --all-features -- -D warnings Smoke: APC MINI connected as backend 36:0 while PipeWire mixer remained ready --- fader_master/src/ipc.rs | 10 ++ fader_master/src/lib.rs | 1 + fader_master/src/live.rs | 11 +- fader_master/src/local.rs | 8 ++ fader_master/src/main.rs | 6 + fader_master/src/midi_runtime.rs | 218 +++++++++++++++++++++++++++++++ midi/src/lifecycle.rs | 5 + 7 files changed, 257 insertions(+), 2 deletions(-) create mode 100644 fader_master/src/midi_runtime.rs diff --git a/fader_master/src/ipc.rs b/fader_master/src/ipc.rs index e6e1315..f19e5a5 100644 --- a/fader_master/src/ipc.rs +++ b/fader_master/src/ipc.rs @@ -63,6 +63,16 @@ pub struct MixerSnapshot { pub backend: String, pub status: String, pub objects: Vec, + pub devices: Vec, +} + +#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)] +pub struct MidiDevice { + pub id: String, + pub label: String, + pub status: String, + pub backend_id: Option, + pub error: Option, } #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)] diff --git a/fader_master/src/lib.rs b/fader_master/src/lib.rs index 17502b7..99c38be 100644 --- a/fader_master/src/lib.rs +++ b/fader_master/src/lib.rs @@ -6,6 +6,7 @@ pub mod cli; pub mod ipc; pub mod live; pub mod local; +pub mod midi_runtime; pub mod tui_client; use std::{collections::BTreeMap, error::Error, fmt}; diff --git a/fader_master/src/live.rs b/fader_master/src/live.rs index 5b83de7..9bb7c16 100644 --- a/fader_master/src/live.rs +++ b/fader_master/src/live.rs @@ -10,8 +10,8 @@ use thiserror::Error; use volume_lib::WorkerEvent; use crate::ipc::{ - ClientRequest, MixerObject, MixerObjectKey, MixerObjectKind, MixerSnapshot, PROTOCOL_VERSION, - RequestCommand, ResponseResult, ServerResponse, + ClientRequest, MidiDevice, MixerObject, MixerObjectKey, MixerObjectKind, MixerSnapshot, + PROTOCOL_VERSION, RequestCommand, ResponseResult, ServerResponse, }; #[derive(Clone, Debug)] @@ -42,6 +42,7 @@ pub struct LiveMixerState { metadata: BTreeMap, applications: Vec, groups: Vec, + devices: Vec, write_ceiling: Gain, backend: String, status: String, @@ -101,6 +102,7 @@ impl LiveMixerState { metadata: BTreeMap::new(), applications, groups, + devices: Vec::new(), write_ceiling, backend: backend.into(), status: "connecting".to_owned(), @@ -170,9 +172,14 @@ impl LiveMixerState { backend: self.backend.clone(), status: self.status.clone(), objects, + devices: self.devices.clone(), } } + pub fn set_devices(&mut self, devices: Vec) { + self.devices = devices; + } + pub fn request( &mut self, request: ClientRequest, diff --git a/fader_master/src/local.rs b/fader_master/src/local.rs index c58d179..1514e3c 100644 --- a/fader_master/src/local.rs +++ b/fader_master/src/local.rs @@ -51,6 +51,8 @@ pub enum LocalError { WorkerCommand, #[error("audio worker event lane disconnected")] WorkerDisconnected, + #[error("MIDI runtime configuration failed: {0}")] + MidiRuntime(String), #[error(transparent)] Mixer(#[from] crate::live::LiveMixerError), #[error(transparent)] @@ -167,6 +169,7 @@ pub struct LocalServer { listener: OwnedListener, worker: PulseWorker, mixer: LiveMixerState, + midi: crate::midi_runtime::MidiRuntime, } impl LocalServer { @@ -175,10 +178,13 @@ impl LocalServer { write_ceiling: Gain, profile: &Profile, ) -> Result { + let midi = + crate::midi_runtime::MidiRuntime::new(profile).map_err(LocalError::MidiRuntime)?; Ok(Self { listener: OwnedListener::bind(socket)?, worker: PulseWorker::spawn(BackendEpoch::new(1), 256), mixer: LiveMixerState::new(write_ceiling, "pulse", profile)?, + midi, }) } @@ -190,6 +196,8 @@ impl LocalServer { } pub fn tick(&mut self) -> Result<(), LocalError> { + self.midi.tick(); + self.mixer.set_devices(self.midi.snapshot()); match self.worker.receive_timeout(SERVER_TICK) { Ok(event) => { let commands = self.mixer.worker_event(event)?; diff --git a/fader_master/src/main.rs b/fader_master/src/main.rs index 0c6995b..b1b0a1e 100644 --- a/fader_master/src/main.rs +++ b/fader_master/src/main.rs @@ -130,6 +130,12 @@ fn status(socket_override: Option<&Path>) -> Result<()> { object.error ); } + for device in snapshot.devices { + println!( + "device={} label={:?} status={} backend_id={:?} error={:?}", + device.id, device.label, device.status, device.backend_id, device.error + ); + } Ok(()) } ResponseResult::Error { message, .. } => bail!(message), diff --git a/fader_master/src/midi_runtime.rs b/fader_master/src/midi_runtime.rs new file mode 100644 index 0000000..f31dbc7 --- /dev/null +++ b/fader_master/src/midi_runtime.rs @@ -0,0 +1,218 @@ +use std::{ + collections::BTreeMap, + sync::mpsc::{Receiver, SyncSender, TryRecvError, sync_channel}, + time::{Duration, Instant}, +}; + +use fader_config::Profile; +use fader_core::SurfaceId; +use midi::{ + DeviceMatch, LinuxIdentityCatalog, MidiInputCatalog, MidiInputConnection, MidiInputEvent, + SurfaceAction, SurfaceAssignment, SurfaceLifecycle, SurfaceStatus, +}; + +use crate::ipc::MidiDevice; + +const SCAN_INTERVAL: Duration = Duration::from_secs(1); +const EVENT_CAPACITY: usize = 256; + +/// Owns native MIDI input connections and periodically reconciles hotplug state. +pub struct MidiRuntime { + lifecycle: SurfaceLifecycle, + labels: BTreeMap, + connections: BTreeMap, + sender: SyncSender, + receiver: Receiver, + last_scan: Option, + scan_error: Option, +} + +impl std::fmt::Debug for MidiRuntime { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter + .debug_struct("MidiRuntime") + .field("surfaces", &self.labels.len()) + .field("connections", &self.connections.len()) + .field("scan_error", &self.scan_error) + .finish() + } +} + +impl MidiRuntime { + pub fn new(profile: &Profile) -> Result { + let mut labels = BTreeMap::new(); + let assignments = profile + .surfaces() + .iter() + .map(|surface| { + let id = SurfaceId::new(surface.id()).map_err(|error| error.to_string())?; + labels.insert(id.clone(), surface.label().to_owned()); + Ok(SurfaceAssignment { + surface: id, + expected: DeviceMatch { + port_name: surface.input_port().to_owned(), + vendor_id: surface.usb_vendor_id().map(str::to_owned), + product_id: surface.usb_product_id().map(str::to_owned), + serial: surface.usb_serial().map(str::to_owned), + path: surface.usb_path().map(str::to_owned), + }, + manual_backend_id: surface.manual_backend_id().map(str::to_owned), + }) + }) + .collect::, String>>()?; + let lifecycle = SurfaceLifecycle::new(assignments).map_err(|error| error.to_string())?; + let (sender, receiver) = sync_channel(EVENT_CAPACITY); + Ok(Self { + lifecycle, + labels, + connections: BTreeMap::new(), + sender, + receiver, + last_scan: None, + scan_error: None, + }) + } + + pub fn tick(&mut self) { + if self + .last_scan + .is_none_or(|last| last.elapsed() >= SCAN_INTERVAL) + { + self.scan(); + self.last_scan = Some(Instant::now()); + } + loop { + match self.receiver.try_recv() { + // Routing is activated in the next boundary; draining keeps the + // native callback bounded without allowing audio side effects. + Ok(MidiInputEvent::Message { .. }) => {} + Ok(MidiInputEvent::Malformed { error, .. }) => { + self.scan_error = Some(format!("malformed MIDI input: {error}")); + } + Err(TryRecvError::Empty | TryRecvError::Disconnected) => break, + } + } + if self + .connections + .values() + .any(MidiInputConnection::overflowed) + { + self.scan_error = Some("MIDI input queue overflowed; reconnect required".to_owned()); + } + } + + #[must_use] + pub fn snapshot(&self) -> Vec { + self.lifecycle + .statuses() + .map(|(id, status)| { + let (name, backend_id, status_error) = match status { + SurfaceStatus::Missing => ("missing", None, None), + SurfaceStatus::Ambiguous { .. } => ("ambiguous", None, None), + SurfaceStatus::Connecting { backend_id, .. } => { + ("connecting", Some(backend_id.clone()), None) + } + SurfaceStatus::Connected { backend_id, .. } => { + ("connected", Some(backend_id.clone()), None) + } + SurfaceStatus::Error { + backend_id, + message, + } => ("error", Some(backend_id.clone()), Some(message.clone())), + }; + MidiDevice { + id: id.as_str().to_owned(), + label: self + .labels + .get(id) + .cloned() + .unwrap_or_else(|| id.as_str().to_owned()), + status: name.to_owned(), + backend_id, + error: status_error.or_else(|| self.scan_error.clone()), + } + }) + .collect() + } + + fn scan(&mut self) { + let result = self.discover_and_reconcile(); + self.scan_error = result.err(); + } + + fn discover_and_reconcile(&mut self) -> Result<(), String> { + let catalog = + MidiInputCatalog::new("fader_master discovery").map_err(|error| error.to_string())?; + let ports = catalog.ports().map_err(|error| error.to_string())?; + let identities = LinuxIdentityCatalog::new().map_err(|error| error.to_string())?; + let visible = ports + .iter() + .map(|port| identities.inspect(port).map_err(|error| error.to_string())) + .collect::, _>>()?; + for action in self.lifecycle.reconcile(&visible) { + match action { + SurfaceAction::Disconnect { surface, .. } => { + self.connections.remove(&surface); + } + SurfaceAction::Connect { + surface, + backend_id, + .. + } => { + self.connect(surface, &backend_id); + } + } + } + Ok(()) + } + + fn connect(&mut self, surface: SurfaceId, backend_id: &str) { + let result = (|| { + let catalog = MidiInputCatalog::new("fader_master input")?; + let ports = catalog.ports()?; + let port = ports + .iter() + .find(|port| port.id() == backend_id) + .ok_or_else(|| midi::MidiTransportError::Connect("port disappeared".to_owned()))?; + catalog.connect( + port, + &format!("fader_master {} input", surface.as_str()), + surface.clone(), + self.sender.clone(), + ) + })(); + match result { + Ok(connection) => { + self.connections.insert(surface.clone(), connection); + let _ = self.lifecycle.connection_succeeded(&surface, backend_id); + } + Err(error) => { + let _ = self + .lifecycle + .connection_failed(&surface, backend_id, error.to_string()); + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn configured_surfaces_exist_as_missing_before_native_discovery() { + let profile = + Profile::parse(include_str!("../../examples/profiles/arch-pipewire.toml")).unwrap(); + let runtime = MidiRuntime::new(&profile).unwrap(); + assert_eq!( + runtime.snapshot(), + vec![MidiDevice { + id: "apc-mini".into(), + label: "APC MINI".into(), + status: "missing".into(), + backend_id: None, + error: None, + }] + ); + } +} diff --git a/midi/src/lifecycle.rs b/midi/src/lifecycle.rs index c28ab72..434d2f5 100644 --- a/midi/src/lifecycle.rs +++ b/midi/src/lifecycle.rs @@ -246,6 +246,11 @@ impl SurfaceLifecycle { pub fn status(&self, surface: &SurfaceId) -> Option<&SurfaceStatus> { self.entries.get(surface).map(|entry| &entry.status) } + + /// All configured surface states in stable ID order. + pub fn statuses(&self) -> impl Iterator { + self.entries.iter().map(|(id, entry)| (id, &entry.status)) + } } fn disconnect_current(id: &SurfaceId, entry: &mut Entry, actions: &mut Vec) {