feat(M5.2): probe durable MIDI identity
Bridge ALSA sequencer client addresses to udev USB metadata and establish serial, physical-path, unique-model, and explicit-manual resolution policy. Keep M5.2 open until physical controller observations and identical-device checks are completed from the documented checklist. Tests: full locked workspace format, check, test, doctest, Clippy, release, and no-default-features gates passed. Tests: cargo +1.88.0 test -p midi --all-targets --all-features --locked Manual: enriched host probe correctly reported virtual port 14:0 with no USB metadata.
This commit is contained in:
parent
a5e98c8182
commit
d5229e5eca
|
|
@ -429,6 +429,12 @@ version = "0.5.0"
|
|||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
|
||||
|
||||
[[package]]
|
||||
name = "hermit-abi"
|
||||
version = "0.3.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d231dfb89cfffdbc30e7fc41579ed6066ad03abda9e567ccafae602b97ec5024"
|
||||
|
||||
[[package]]
|
||||
name = "ident_case"
|
||||
version = "1.0.1"
|
||||
|
|
@ -467,6 +473,17 @@ dependencies = [
|
|||
"syn 3.0.6",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "io-lifetimes"
|
||||
version = "1.0.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "eae7b9aee968036d54dce06cebaefd919e4472e753296daccd6d344e3e2df0c2"
|
||||
dependencies = [
|
||||
"hermit-abi",
|
||||
"libc",
|
||||
"windows-sys 0.48.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "itertools"
|
||||
version = "0.13.0"
|
||||
|
|
@ -606,6 +623,16 @@ dependencies = [
|
|||
"winapi",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "libudev-sys"
|
||||
version = "0.1.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3c8469b4a23b962c1396b9b451dda50ef5b283e8dd309d69033475fa9b334324"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"pkg-config",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "linux-raw-sys"
|
||||
version = "0.4.15"
|
||||
|
|
@ -652,9 +679,11 @@ checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
|
|||
name = "midi"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"alsa",
|
||||
"fader-core",
|
||||
"midir",
|
||||
"thiserror 2.0.21",
|
||||
"udev",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
|
@ -1304,6 +1333,18 @@ dependencies = [
|
|||
"ratatui",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "udev"
|
||||
version = "0.9.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "af4e37e9ea4401fc841ff54b9ddfc9be1079b1e89434c1a6a865dd68980f7e9f"
|
||||
dependencies = [
|
||||
"io-lifetimes",
|
||||
"libc",
|
||||
"libudev-sys",
|
||||
"pkg-config",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "unarray"
|
||||
version = "0.1.4"
|
||||
|
|
@ -1584,6 +1625,15 @@ dependencies = [
|
|||
"windows-targets 0.42.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-sys"
|
||||
version = "0.48.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9"
|
||||
dependencies = [
|
||||
"windows-targets 0.48.5",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-sys"
|
||||
version = "0.52.0"
|
||||
|
|
@ -1617,6 +1667,21 @@ dependencies = [
|
|||
"windows_x86_64_msvc 0.42.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-targets"
|
||||
version = "0.48.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9a2fa6e2155d7247be68c096456083145c183cbbbc2764150dda45a87197940c"
|
||||
dependencies = [
|
||||
"windows_aarch64_gnullvm 0.48.5",
|
||||
"windows_aarch64_msvc 0.48.5",
|
||||
"windows_i686_gnu 0.48.5",
|
||||
"windows_i686_msvc 0.48.5",
|
||||
"windows_x86_64_gnu 0.48.5",
|
||||
"windows_x86_64_gnullvm 0.48.5",
|
||||
"windows_x86_64_msvc 0.48.5",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-targets"
|
||||
version = "0.52.6"
|
||||
|
|
@ -1648,6 +1713,12 @@ version = "0.42.2"
|
|||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "597a5118570b68bc08d8d59125332c54f1ba9d9adeedeef5b99b02ba2b0698f8"
|
||||
|
||||
[[package]]
|
||||
name = "windows_aarch64_gnullvm"
|
||||
version = "0.48.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8"
|
||||
|
||||
[[package]]
|
||||
name = "windows_aarch64_gnullvm"
|
||||
version = "0.52.6"
|
||||
|
|
@ -1660,6 +1731,12 @@ version = "0.42.2"
|
|||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e08e8864a60f06ef0d0ff4ba04124db8b0fb3be5776a5cd47641e942e58c4d43"
|
||||
|
||||
[[package]]
|
||||
name = "windows_aarch64_msvc"
|
||||
version = "0.48.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc"
|
||||
|
||||
[[package]]
|
||||
name = "windows_aarch64_msvc"
|
||||
version = "0.52.6"
|
||||
|
|
@ -1672,6 +1749,12 @@ version = "0.42.2"
|
|||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c61d927d8da41da96a81f029489353e68739737d3beca43145c8afec9a31a84f"
|
||||
|
||||
[[package]]
|
||||
name = "windows_i686_gnu"
|
||||
version = "0.48.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e"
|
||||
|
||||
[[package]]
|
||||
name = "windows_i686_gnu"
|
||||
version = "0.52.6"
|
||||
|
|
@ -1690,6 +1773,12 @@ version = "0.42.2"
|
|||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "44d840b6ec649f480a41c8d80f9c65108b92d89345dd94027bfe06ac444d1060"
|
||||
|
||||
[[package]]
|
||||
name = "windows_i686_msvc"
|
||||
version = "0.48.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406"
|
||||
|
||||
[[package]]
|
||||
name = "windows_i686_msvc"
|
||||
version = "0.52.6"
|
||||
|
|
@ -1702,6 +1791,12 @@ version = "0.42.2"
|
|||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8de912b8b8feb55c064867cf047dda097f92d51efad5b491dfb98f6bbb70cb36"
|
||||
|
||||
[[package]]
|
||||
name = "windows_x86_64_gnu"
|
||||
version = "0.48.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e"
|
||||
|
||||
[[package]]
|
||||
name = "windows_x86_64_gnu"
|
||||
version = "0.52.6"
|
||||
|
|
@ -1714,6 +1809,12 @@ version = "0.42.2"
|
|||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "26d41b46a36d453748aedef1486d5c7a85db22e56aff34643984ea85514e94a3"
|
||||
|
||||
[[package]]
|
||||
name = "windows_x86_64_gnullvm"
|
||||
version = "0.48.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc"
|
||||
|
||||
[[package]]
|
||||
name = "windows_x86_64_gnullvm"
|
||||
version = "0.52.6"
|
||||
|
|
@ -1726,6 +1827,12 @@ version = "0.42.2"
|
|||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9aec5da331524158c6d1a4ac0ab1541149c0b9505fde06423b02f5ef0106b9f0"
|
||||
|
||||
[[package]]
|
||||
name = "windows_x86_64_msvc"
|
||||
version = "0.48.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538"
|
||||
|
||||
[[package]]
|
||||
name = "windows_x86_64_msvc"
|
||||
version = "0.52.6"
|
||||
|
|
|
|||
|
|
@ -11,6 +11,7 @@ repository = "https://git.dandaedre.com/MadGobblins/fader_master"
|
|||
publish = false
|
||||
|
||||
[workspace.dependencies]
|
||||
alsa = "0.12.1"
|
||||
fader-config = { path = "config" }
|
||||
fader-core = { path = "core" }
|
||||
midi = { path = "midi" }
|
||||
|
|
@ -26,6 +27,7 @@ thiserror = "2.0.21"
|
|||
toml = "0.8.23"
|
||||
toml_edit = "0.22.27"
|
||||
tui = { path = "tui" }
|
||||
udev = "0.9.3"
|
||||
volume_lib = { path = "sound" }
|
||||
|
||||
[profile.dev]
|
||||
|
|
|
|||
|
|
@ -171,7 +171,7 @@ PulseAudio compatibility is provided by `pipewire-pulse`; ALSA's mixer API expos
|
|||
|
||||
Use `midir` for input/output connections. A device profile maps CC/note/pitch-bend messages to controls and output messages; v1 supports 7-bit absolute CC and note/CC mute buttons, then 14-bit pairs, pitch bend, and declared relative encoder dialects. Channel values in TOML are 1–16 and translate once at the transport boundary. Note-on velocity zero is release. Toggle actions fire on press only; validate malformed lengths and data bytes. Ignore unrelated clock/active-sensing traffic; arbitrary SysEx protocols are deferred.
|
||||
|
||||
Persist a user surface ID plus matching hints: backend port identifier where usable, input/output port names, USB VID/PID, serial when available, and optional physical path. MIDI port indices and names alone are not durable identity. Linux identity enrichment may require ALSA sequencer-to-device mapping and udev; verify this bridge in a spike, since midir alone does not guarantee USB serial metadata. Identical serial-less devices cannot always be distinguished after moving USB ports: require explicit assignment when ambiguous and retain a disconnected placeholder rather than binding arbitrarily.
|
||||
Persist a user surface ID plus matching hints: backend port identifier where usable, input/output port names, USB VID/PID, serial when available, and optional physical path. MIDI port indices and names alone are not durable identity. On Linux, bridge midir's ALSA `client:port` through the sequencer client's card number to the udev `sound/cardN` device; user/virtual clients legitimately have no card. Match USB devices by serial first, physical `ID_PATH` second, and unique VID/PID/port-name last. Identical serial-less devices without a retained path require explicit current-port assignment and remain unresolved when ambiguous after topology changes. See the [identity spike](docs/midi-identity.md).
|
||||
|
||||
Keep bindings for absent surfaces. Re-enumerate ports on hotplug notifications or a bounded periodic scan, reconnect matching input/output ports independently, and resynchronize output from current observed state. Missing output does not disable input. Two devices may send the same channel/CC without collision because the surface ID is part of the key. [midir input/connection API](https://docs.rs/midir/latest/midir/struct.MidiInput.html), [udev discovery/monitoring](https://docs.rs/udev/latest/udev/)
|
||||
|
||||
|
|
|
|||
28
checklist.md
28
checklist.md
|
|
@ -182,3 +182,31 @@ Replace `INDEX` with the controller index from the list command.
|
|||
- [ ] Run `cargo test --locked -p midi --all-targets --no-default-features`.
|
||||
- [ ] Confirm both pass. The second command proves decoding and binding remain
|
||||
testable without an ALSA device or daemon.
|
||||
|
||||
## MIDI identity spike
|
||||
|
||||
These checks close M5.2. They do not save an assignment or test hotplug
|
||||
reconnection yet.
|
||||
|
||||
- [ ] With one USB MIDI controller connected, run
|
||||
`cargo run --locked -p midi --example midi_monitor -- list`.
|
||||
- [ ] Confirm its `PortIdentity` includes the ALSA `backend_id`, port `name`,
|
||||
four-digit USB `vendor_id` and `product_id`, and a udev `path`.
|
||||
- [ ] If the device has a serial number, confirm `serial` is `Some(...)` and
|
||||
record it. If it reports `None`, record that explicitly; this is valid device
|
||||
metadata, not a probe failure.
|
||||
- [ ] Disconnect and reconnect the controller to another USB socket. Record
|
||||
which of the ALSA backend ID, udev path, and serial changed. A real serial
|
||||
should remain stable while the physical path is expected to change.
|
||||
- [ ] If two identical controllers are available, connect both and confirm they
|
||||
have distinct serials or paths even when their port names and VID/PID match.
|
||||
- [ ] If the identical controllers have no serials, swap their USB sockets and
|
||||
confirm they cannot be identified independently of the sockets. This is the
|
||||
intentional manual-assignment case: the server must show ambiguity rather
|
||||
than choosing whichever ALSA port was enumerated first.
|
||||
- [ ] Run `cargo test --locked -p midi --test identity --all-features` and
|
||||
confirm the serial, path, ambiguity, and explicit-selection policy tests pass.
|
||||
|
||||
Report the controller model/firmware plus the complete `PortIdentity` lines.
|
||||
Do not redact USB serials unless you prefer not to store them in the project
|
||||
test record; a redacted but clearly stable/absent result is sufficient.
|
||||
|
|
|
|||
|
|
@ -9,7 +9,7 @@ The default build includes the PulseAudio protocol adapter and links to
|
|||
libpulse. On a Debian-family Linux system, install:
|
||||
|
||||
```sh
|
||||
sudo apt-get install build-essential pkg-config libasound2-dev libpulse-dev
|
||||
sudo apt-get install build-essential pkg-config libasound2-dev libpulse-dev libudev-dev
|
||||
rustup toolchain install 1.88.0 \
|
||||
--profile minimal \
|
||||
--component rustfmt \
|
||||
|
|
@ -21,7 +21,7 @@ On Arch Linux with PipeWire, install the client library, build tools, and the
|
|||
PulseAudio-compatible PipeWire service:
|
||||
|
||||
```sh
|
||||
sudo pacman -S --needed base-devel pkgconf alsa-lib libpulse pipewire-audio pipewire-pulse wireplumber
|
||||
sudo pacman -S --needed base-devel pkgconf alsa-lib libpulse systemd-libs pipewire-audio pipewire-pulse wireplumber
|
||||
pactl info
|
||||
```
|
||||
|
||||
|
|
@ -31,17 +31,18 @@ separate development package. The application communicates with PipeWire
|
|||
through `pipewire-pulse`; it does not require the standalone PulseAudio server.
|
||||
|
||||
The Pulse adapter works with PulseAudio and PipeWire's pipewire-pulse
|
||||
compatibility service. MIDI input uses ALSA's sequencer API through `midir`;
|
||||
PipeWire does not replace the `alsa-lib` build dependency. A build that
|
||||
deliberately excludes native audio and MIDI dependencies remains available:
|
||||
compatibility service. MIDI input uses ALSA's sequencer API through `midir`, and
|
||||
Linux identity enrichment uses libudev. PipeWire does not replace the
|
||||
`alsa-lib` build dependency. A build that deliberately excludes native audio
|
||||
and MIDI dependencies remains available:
|
||||
|
||||
```sh
|
||||
cargo build --workspace --no-default-features --locked
|
||||
```
|
||||
|
||||
Future native PipeWire, ALSA mixer, and udev adapters will add their own
|
||||
feature-gated development packages. The MIDI crate can also be checked without
|
||||
its native transport while retaining byte decoding and routing:
|
||||
Future native PipeWire and ALSA mixer adapters will add their own feature-gated
|
||||
development packages. The MIDI crate can also be checked without its native
|
||||
transport and identity discovery while retaining byte decoding and routing:
|
||||
|
||||
```sh
|
||||
cargo check -p midi --no-default-features --locked
|
||||
|
|
|
|||
|
|
@ -0,0 +1,40 @@
|
|||
# Linux MIDI identity spike
|
||||
|
||||
`midir` 0.11.1 exposes Linux ports as ALSA sequencer `client:port` addresses and
|
||||
human-readable names. Neither value is a durable USB identity: client numbers
|
||||
can change with connection and discovery order, while identical controllers can
|
||||
publish identical names.
|
||||
|
||||
For a kernel sequencer client, ALSA reports its sound-card number. The MIDI
|
||||
identity probe opens that card's udev `sound/cardN` device and copies:
|
||||
|
||||
- `ID_VENDOR_ID` and `ID_MODEL_ID` as the controller model key;
|
||||
- `ID_SERIAL_SHORT` when the USB device supplies a serial;
|
||||
- `ID_PATH` as the physical connection fallback.
|
||||
|
||||
User and virtual ALSA clients return no card number and therefore no USB
|
||||
metadata. They may be selected by a unique port name, but duplicate names remain
|
||||
ambiguous.
|
||||
|
||||
## Matching policy
|
||||
|
||||
1. Match the configured port name and, for USB devices, VID/PID.
|
||||
2. Prefer an exact serial when one was observed.
|
||||
3. Without a serial, prefer the retained physical path.
|
||||
4. A unique remaining model/name is safe to select.
|
||||
5. Multiple remaining candidates stay unassigned. An explicit backend-port
|
||||
choice may resolve the current topology, but the ephemeral ALSA address is
|
||||
not treated as durable evidence after reconnect or reboot.
|
||||
|
||||
This means two identical serial-less devices can remain attached to stable USB
|
||||
sockets and be distinguished by path. If they move between sockets, software
|
||||
cannot prove which physical unit is which; silently binding by enumeration order
|
||||
would risk controlling the wrong applications.
|
||||
|
||||
## Recorded host observation
|
||||
|
||||
On 2026-10-14, the Arch Linux host exposed only
|
||||
`PortIdentity { backend_id: "14:0", name: "Midi Through:Midi Through Port-0 14:0", usb: None }`.
|
||||
This validates the virtual-client fallback but is not physical-controller
|
||||
acceptance. The controller observations requested in `checklist.md` must be
|
||||
recorded before M5.2 is marked complete.
|
||||
|
|
@ -9,12 +9,14 @@ publish.workspace = true
|
|||
|
||||
[features]
|
||||
default = ["midir"]
|
||||
midir = ["dep:midir"]
|
||||
midir = ["dep:alsa", "dep:midir", "dep:udev"]
|
||||
|
||||
[dependencies]
|
||||
alsa = { workspace = true, optional = true }
|
||||
fader-core.workspace = true
|
||||
midir = { workspace = true, optional = true }
|
||||
thiserror.workspace = true
|
||||
udev = { workspace = true, optional = true }
|
||||
|
||||
[[example]]
|
||||
name = "midi_monitor"
|
||||
|
|
|
|||
|
|
@ -6,7 +6,7 @@ use std::{
|
|||
};
|
||||
|
||||
use fader_core::SurfaceId;
|
||||
use midi::MidiInputCatalog;
|
||||
use midi::{LinuxIdentityCatalog, MidiInputCatalog};
|
||||
|
||||
fn main() -> Result<(), Box<dyn Error>> {
|
||||
let mut arguments = std::env::args().skip(1);
|
||||
|
|
@ -14,8 +14,9 @@ fn main() -> Result<(), Box<dyn Error>> {
|
|||
let catalog = MidiInputCatalog::new("fader_master monitor")?;
|
||||
let ports = catalog.ports()?;
|
||||
if command == "list" {
|
||||
let identities = LinuxIdentityCatalog::new()?;
|
||||
for (index, port) in ports.iter().enumerate() {
|
||||
println!("index={index} id={:?} name={:?}", port.id(), port.name());
|
||||
println!("index={index} identity={:?}", identities.inspect(port)?);
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,137 @@
|
|||
/// USB metadata copied from udev for durable controller matching.
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub struct UsbDeviceIdentity {
|
||||
pub vendor_id: String,
|
||||
pub product_id: String,
|
||||
pub serial: Option<String>,
|
||||
pub path: Option<String>,
|
||||
}
|
||||
|
||||
/// One currently visible MIDI port and any durable metadata available for it.
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub struct PortIdentity {
|
||||
pub backend_id: String,
|
||||
pub name: String,
|
||||
pub usb: Option<UsbDeviceIdentity>,
|
||||
}
|
||||
|
||||
/// Persisted hints used to find a configured surface without relying on order.
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub struct DeviceMatch {
|
||||
pub port_name: String,
|
||||
pub vendor_id: Option<String>,
|
||||
pub product_id: Option<String>,
|
||||
pub serial: Option<String>,
|
||||
pub path: Option<String>,
|
||||
}
|
||||
|
||||
/// Evidence that made one current port unambiguous.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum MatchBasis {
|
||||
Serial,
|
||||
PhysicalPath,
|
||||
UniqueModel,
|
||||
Manual,
|
||||
}
|
||||
|
||||
/// Result of matching one configured surface against current ports.
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub enum PortResolution {
|
||||
Matched { index: usize, basis: MatchBasis },
|
||||
Missing,
|
||||
Ambiguous { candidate_indices: Vec<usize> },
|
||||
}
|
||||
|
||||
/// Resolves durable hints, optionally accepting an explicit current backend ID.
|
||||
#[must_use]
|
||||
pub fn resolve_port(
|
||||
expected: &DeviceMatch,
|
||||
ports: &[PortIdentity],
|
||||
manual_backend_id: Option<&str>,
|
||||
) -> PortResolution {
|
||||
let candidates: Vec<usize> = ports
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(index, port)| model_matches(expected, port).then_some(index))
|
||||
.collect();
|
||||
|
||||
if let Some(serial) = expected.serial.as_deref() {
|
||||
let serial_matches = candidates_matching(&candidates, ports, |usb| {
|
||||
usb.serial.as_deref() == Some(serial)
|
||||
});
|
||||
return finish(serial_matches, ports, manual_backend_id, MatchBasis::Serial);
|
||||
}
|
||||
if let Some(path) = expected.path.as_deref() {
|
||||
let path_matches =
|
||||
candidates_matching(&candidates, ports, |usb| usb.path.as_deref() == Some(path));
|
||||
return finish(
|
||||
path_matches,
|
||||
ports,
|
||||
manual_backend_id,
|
||||
MatchBasis::PhysicalPath,
|
||||
);
|
||||
}
|
||||
finish(
|
||||
candidates,
|
||||
ports,
|
||||
manual_backend_id,
|
||||
MatchBasis::UniqueModel,
|
||||
)
|
||||
}
|
||||
|
||||
fn model_matches(expected: &DeviceMatch, port: &PortIdentity) -> bool {
|
||||
if port.name != expected.port_name {
|
||||
return false;
|
||||
}
|
||||
match (&expected.vendor_id, &expected.product_id) {
|
||||
(Some(vendor), Some(product)) => port.usb.as_ref().is_some_and(|usb| {
|
||||
usb.vendor_id.eq_ignore_ascii_case(vendor)
|
||||
&& usb.product_id.eq_ignore_ascii_case(product)
|
||||
}),
|
||||
(None, None) => true,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn candidates_matching(
|
||||
candidates: &[usize],
|
||||
ports: &[PortIdentity],
|
||||
predicate: impl Fn(&UsbDeviceIdentity) -> bool,
|
||||
) -> Vec<usize> {
|
||||
candidates
|
||||
.iter()
|
||||
.copied()
|
||||
.filter(|index| ports[*index].usb.as_ref().is_some_and(&predicate))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn finish(
|
||||
candidates: Vec<usize>,
|
||||
ports: &[PortIdentity],
|
||||
manual_backend_id: Option<&str>,
|
||||
automatic_basis: MatchBasis,
|
||||
) -> PortResolution {
|
||||
match candidates.as_slice() {
|
||||
[] => PortResolution::Missing,
|
||||
[index] => PortResolution::Matched {
|
||||
index: *index,
|
||||
basis: automatic_basis,
|
||||
},
|
||||
_ => manual_backend_id
|
||||
.and_then(|selected| {
|
||||
candidates
|
||||
.iter()
|
||||
.copied()
|
||||
.find(|index| ports[*index].backend_id == selected)
|
||||
})
|
||||
.map_or_else(
|
||||
|| PortResolution::Ambiguous {
|
||||
candidate_indices: candidates,
|
||||
},
|
||||
|index| PortResolution::Matched {
|
||||
index,
|
||||
basis: MatchBasis::Manual,
|
||||
},
|
||||
),
|
||||
}
|
||||
}
|
||||
|
|
@ -3,11 +3,19 @@
|
|||
#![forbid(unsafe_code)]
|
||||
|
||||
mod decode;
|
||||
mod identity;
|
||||
#[cfg(all(feature = "midir", target_os = "linux"))]
|
||||
mod linux_identity;
|
||||
mod router;
|
||||
#[cfg(feature = "midir")]
|
||||
mod transport;
|
||||
|
||||
pub use decode::{ButtonEdge, DecodeError, MidiMessage, decode_message};
|
||||
pub use identity::{
|
||||
DeviceMatch, MatchBasis, PortIdentity, PortResolution, UsbDeviceIdentity, resolve_port,
|
||||
};
|
||||
#[cfg(all(feature = "midir", target_os = "linux"))]
|
||||
pub use linux_identity::{LinuxIdentityCatalog, LinuxIdentityError};
|
||||
pub use router::{MidiIntent, MidiRouter};
|
||||
#[cfg(feature = "midir")]
|
||||
pub use transport::{
|
||||
|
|
|
|||
|
|
@ -0,0 +1,111 @@
|
|||
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(_))
|
||||
));
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,114 @@
|
|||
use midi::{
|
||||
DeviceMatch, MatchBasis, PortIdentity, PortResolution, UsbDeviceIdentity, resolve_port,
|
||||
};
|
||||
|
||||
fn usb(serial: Option<&str>, path: &str) -> UsbDeviceIdentity {
|
||||
UsbDeviceIdentity {
|
||||
vendor_id: "1234".into(),
|
||||
product_id: "5678".into(),
|
||||
serial: serial.map(str::to_owned),
|
||||
path: Some(path.into()),
|
||||
}
|
||||
}
|
||||
|
||||
fn port(id: &str, serial: Option<&str>, path: &str) -> PortIdentity {
|
||||
PortIdentity {
|
||||
backend_id: id.into(),
|
||||
name: "Controller MIDI 1".into(),
|
||||
usb: Some(usb(serial, path)),
|
||||
}
|
||||
}
|
||||
|
||||
fn expected(serial: Option<&str>, path: Option<&str>) -> DeviceMatch {
|
||||
DeviceMatch {
|
||||
port_name: "Controller MIDI 1".into(),
|
||||
vendor_id: Some("1234".into()),
|
||||
product_id: Some("5678".into()),
|
||||
serial: serial.map(str::to_owned),
|
||||
path: path.map(str::to_owned),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn serial_distinguishes_identical_models_independent_of_port_order() {
|
||||
let ports = vec![
|
||||
port("28:0", Some("RIGHT"), "usb-0:2"),
|
||||
port("24:0", Some("LEFT"), "usb-0:1"),
|
||||
];
|
||||
|
||||
assert_eq!(
|
||||
resolve_port(&expected(Some("LEFT"), None), &ports, None),
|
||||
PortResolution::Matched {
|
||||
index: 1,
|
||||
basis: MatchBasis::Serial,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn physical_path_distinguishes_identical_serialless_models() {
|
||||
let ports = vec![
|
||||
port("28:0", None, "pci-1-usb-0:2"),
|
||||
port("24:0", None, "pci-1-usb-0:1"),
|
||||
];
|
||||
|
||||
assert_eq!(
|
||||
resolve_port(&expected(None, Some("pci-1-usb-0:2")), &ports, None),
|
||||
PortResolution::Matched {
|
||||
index: 0,
|
||||
basis: MatchBasis::PhysicalPath,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn serialless_same_model_stays_ambiguous_until_explicitly_selected() {
|
||||
let ports = vec![port("24:0", None, "usb-0:1"), port("28:0", None, "usb-0:2")];
|
||||
let hints = expected(None, None);
|
||||
assert_eq!(
|
||||
resolve_port(&hints, &ports, None),
|
||||
PortResolution::Ambiguous {
|
||||
candidate_indices: vec![0, 1],
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
resolve_port(&hints, &ports, Some("28:0")),
|
||||
PortResolution::Matched {
|
||||
index: 1,
|
||||
basis: MatchBasis::Manual,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn manual_selection_cannot_override_model_or_usb_mismatch() {
|
||||
let mut wrong = port("30:0", None, "usb-0:3");
|
||||
wrong.name = "Other Controller".into();
|
||||
assert_eq!(
|
||||
resolve_port(&expected(None, None), &[wrong], Some("30:0")),
|
||||
PortResolution::Missing
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_unique_virtual_port_can_fall_back_to_its_name() {
|
||||
let port = PortIdentity {
|
||||
backend_id: "128:0".into(),
|
||||
name: "DAW bridge".into(),
|
||||
usb: None,
|
||||
};
|
||||
let hints = DeviceMatch {
|
||||
port_name: "DAW bridge".into(),
|
||||
vendor_id: None,
|
||||
product_id: None,
|
||||
serial: None,
|
||||
path: None,
|
||||
};
|
||||
assert_eq!(
|
||||
resolve_port(&hints, &[port], None),
|
||||
PortResolution::Matched {
|
||||
index: 0,
|
||||
basis: MatchBasis::UniqueModel,
|
||||
}
|
||||
);
|
||||
}
|
||||
7
task.md
7
task.md
|
|
@ -158,6 +158,13 @@ Dependencies: M3; M4 for full end-to-end acceptance.
|
|||
An opt-in monitor lists real ports and watches one selected input without
|
||||
changing audio or saved configuration.
|
||||
- [ ] **M5.2 Identity spike:** inspect port identifiers and ALSA/udev USB mapping; establish serial/path/manual fallback policy. Acceptance: record metadata actually exposed by tested controllers, distinguish two identical models where possible, and demonstrate explicit ambiguity resolution where not possible.
|
||||
The Linux probe now maps midir's ALSA `client:port` through the sequencer
|
||||
client card number to udev, copying VID/PID, serial, and physical path. Pure
|
||||
policy tests prove serial and path matching survive port reorder and that two
|
||||
identical serial-less candidates stay ambiguous until manually selected.
|
||||
Keep this item open until physical controller metadata and the two-controller
|
||||
cases in the checklist are recorded; the current host exposes only the
|
||||
virtual `Midi Through` port.
|
||||
- [ ] **M5.3 Multi-surface lifecycle:** persist user IDs and independent input/output assignment; hotplug scanning/notification, retries and absent placeholders. Tests: unplug/replug/reboot-style port reorder preserve assignments; ambiguous serial-less matches stay unassigned; one failed device does not stop another.
|
||||
- [ ] **M5.4 Pickup:** crossing/tolerance, current physical position, reset on external change/rebind/reconnect/profile switch. Tests: old physical position cannot jump audio at startup; crossing activates; another surface re-arms pickup; above-range target can be picked up at the endpoint.
|
||||
- [ ] **M5.5 Physical smoke test:** one controller -> server -> application audio; then two controllers with overlapping MIDI message numbers. Acceptance: correct applications respond, bindings persist, and USB loss leaves server running. Record controller/firmware and environment.
|
||||
|
|
|
|||
Loading…
Reference in New Issue