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
This commit is contained in:
Dandaedre 2026-10-15 02:37:30 +02:00
parent ff2e39e135
commit 51d1e5bd25
Signed by: Dandaedre
GPG Key ID: 440C6592E8A26D99
7 changed files with 257 additions and 2 deletions

View File

@ -63,6 +63,16 @@ pub struct MixerSnapshot {
pub backend: String,
pub status: String,
pub objects: Vec<MixerObject>,
pub devices: Vec<MidiDevice>,
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct MidiDevice {
pub id: String,
pub label: String,
pub status: String,
pub backend_id: Option<String>,
pub error: Option<String>,
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]

View File

@ -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};

View File

@ -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<StreamHandle, MetadataView>,
applications: Vec<ConfiguredApplication>,
groups: Vec<ConfiguredGroup>,
devices: Vec<MidiDevice>,
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<MidiDevice>) {
self.devices = devices;
}
pub fn request(
&mut self,
request: ClientRequest,

View File

@ -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<Self, LocalError> {
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)?;

View File

@ -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),

View File

@ -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<SurfaceId, String>,
connections: BTreeMap<SurfaceId, MidiInputConnection>,
sender: SyncSender<MidiInputEvent>,
receiver: Receiver<MidiInputEvent>,
last_scan: Option<Instant>,
scan_error: Option<String>,
}
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<Self, String> {
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::<Result<Vec<_>, 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<MidiDevice> {
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::<Result<Vec<_>, _>>()?;
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,
}]
);
}
}

View File

@ -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<Item = (&SurfaceId, &SurfaceStatus)> {
self.entries.iter().map(|(id, entry)| (id, &entry.status))
}
}
fn disconnect_current(id: &SurfaceId, entry: &mut Entry, actions: &mut Vec<SurfaceAction>) {