fader_master/midi/src/linux_identity.rs

112 lines
3.7 KiB
Rust

use alsa::Seq;
use thiserror::Error;
use crate::{InputPort, PortIdentity, UsbDeviceIdentity};
/// ALSA-sequencer to udev bridge used only for Linux device discovery.
pub struct LinuxIdentityCatalog {
sequence: Seq,
}
/// Failure while inspecting the live Linux MIDI topology.
#[derive(Debug, Error)]
pub enum LinuxIdentityError {
#[error("could not open the ALSA sequencer for identity discovery: {0}")]
OpenSequencer(String),
#[error("MIDI backend identifier {0:?} is not an ALSA client:port address")]
InvalidBackendId(String),
#[error("could not query ALSA client {client}: {message}")]
QueryClient { client: i32, message: String },
#[error("could not inspect udev sound device card{card}: {message}")]
InspectUdev { card: i32, message: String },
}
impl LinuxIdentityCatalog {
pub fn new() -> Result<Self, LinuxIdentityError> {
let sequence = Seq::open(None, None, true)
.map_err(|error| LinuxIdentityError::OpenSequencer(error.to_string()))?;
Ok(Self { sequence })
}
/// Copies the current port identity and enriches kernel clients with USB
/// metadata. Virtual/user clients legitimately have no associated card.
pub fn inspect(&self, port: &InputPort) -> Result<PortIdentity, LinuxIdentityError> {
let client = parse_alsa_client(port.id())?;
let client_info = self.sequence.get_any_client_info(client).map_err(|error| {
LinuxIdentityError::QueryClient {
client,
message: error.to_string(),
}
})?;
let usb = match client_info.get_card() {
Ok(card) if card >= 0 => inspect_usb_card(card)?,
Ok(_) | Err(_) => None,
};
Ok(PortIdentity {
backend_id: port.id().to_owned(),
name: port.name().to_owned(),
usb,
})
}
}
fn parse_alsa_client(backend_id: &str) -> Result<i32, LinuxIdentityError> {
let Some((client, port)) = backend_id.split_once(':') else {
return Err(LinuxIdentityError::InvalidBackendId(backend_id.to_owned()));
};
if port.parse::<u8>().is_err() {
return Err(LinuxIdentityError::InvalidBackendId(backend_id.to_owned()));
}
client
.parse::<i32>()
.map_err(|_| LinuxIdentityError::InvalidBackendId(backend_id.to_owned()))
}
fn inspect_usb_card(card: i32) -> Result<Option<UsbDeviceIdentity>, LinuxIdentityError> {
let device = udev::Device::from_subsystem_sysname("sound".to_owned(), format!("card{card}"))
.map_err(|error| LinuxIdentityError::InspectUdev {
card,
message: error.to_string(),
})?;
if property(&device, "ID_BUS").as_deref() != Some("usb") {
return Ok(None);
}
let (Some(vendor_id), Some(product_id)) = (
property(&device, "ID_VENDOR_ID"),
property(&device, "ID_MODEL_ID"),
) else {
return Ok(None);
};
Ok(Some(UsbDeviceIdentity {
vendor_id,
product_id,
serial: property(&device, "ID_SERIAL_SHORT"),
path: property(&device, "ID_PATH"),
}))
}
fn property(device: &udev::Device, name: &str) -> Option<String> {
device
.property_value(name)
.map(|value| value.to_string_lossy().into_owned())
.filter(|value| !value.is_empty())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parses_the_alsa_client_from_midir_backend_ids() {
assert_eq!(parse_alsa_client("24:3").unwrap(), 24);
assert!(matches!(
parse_alsa_client("not-an-address"),
Err(LinuxIdentityError::InvalidBackendId(_))
));
assert!(matches!(
parse_alsa_client("24:port"),
Err(LinuxIdentityError::InvalidBackendId(_))
));
}
}