Implemented midi support`

This commit is contained in:
patben8 committed 2026-11-03 22:56:19 +01:00
1 parent f55b8f06e4
commit 8d0817b39e
41 files changed
+2827 -26

No files matched your search

+130 -3
View File
@@ -43,6 +43,38 @@ dependencies = [
"alloc-no-stdlib",
]
[[package]]
name = "alsa"
version = "0.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d3f93573e7ddb15145d27c58c0fa0a452faad9f5452ac17ed4554ea035ea9b71"
dependencies = [
"alsa-sys",
"bitflags 2.13.0",
"cfg-if",
"libc",
]
[[package]]
name = "alsa-sys"
version = "0.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f0320138053ef93099f168102c37b46ac0b9c53affc56ef7696633ad5477e2be"
dependencies = [
"cc",
"libc",
"pkg-config",
]
[[package]]
name = "android-build"
version = "0.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f9fc9904ad2ad097c3c1cfe2eacaaf0fc24710936fa9ed941cb310b7c6ed2ab7"
dependencies = [
"windows-sys 0.52.0",
]
[[package]]
name = "android_log-sys"
version = "0.3.2"
@@ -80,6 +112,7 @@ name = "app"
version = "0.1.1"
dependencies = [
"log",
"midir",
"serde",
"serde_json",
"tauri",
@@ -516,6 +549,27 @@ dependencies = [
"libc",
]
[[package]]
name = "coremidi"
version = "0.9.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a57ede822fdaf19280cf1320a5a5d3a522c75c910d01750af1e8122b6ad2595b"
dependencies = [
"block2",
"core-foundation 0.10.1",
"core-foundation-sys",
"coremidi-sys",
]
[[package]]
name = "coremidi-sys"
version = "3.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1a2b8c2cefa9a8f712213c5a1383ffe428efc8f1a1fd1e2f757be94daf7e256a"
dependencies = [
"core-foundation-sys",
]
[[package]]
name = "cpufeatures"
version = "0.2.17"
@@ -739,6 +793,16 @@ dependencies = [
"winapi",
]
[[package]]
name = "dlopen2"
version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "60768c353d76ba6dd1b6332a5dbbdd3bc2dddadc2935f4cc6a9d0f17ca8ecb6a"
dependencies = [
"libc",
"windows-sys 0.61.2",
]
[[package]]
name = "dlopen2_derive"
version = "0.4.3"
@@ -1706,6 +1770,15 @@ version = "1.0.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
[[package]]
name = "java-locator"
version = "0.1.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09c46c1fe465c59b1474e665e85e1256c3893dd00927b8d55f63b09044c1e64f"
dependencies = [
"glob",
]
[[package]]
name = "javascriptcore-rs"
version = "1.1.2"
@@ -1738,7 +1811,9 @@ dependencies = [
"cesu8",
"cfg-if",
"combine",
"java-locator",
"jni-sys 0.3.1",
"libloading",
"log",
"thiserror 1.0.69",
"walkdir",
@@ -1775,6 +1850,21 @@ dependencies = [
"syn 2.0.118",
]
[[package]]
name = "jni-min-helper"
version = "0.3.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "913370a00ba1851b0f3369b49d0f3e745da2d20d3f15ecc296a64234ccda45f7"
dependencies = [
"android-build",
"dlopen2 0.9.0",
"jni 0.21.1",
"libc",
"log",
"ndk-context",
"process_path",
]
[[package]]
name = "jni-sys"
version = "0.3.1"
@@ -1873,9 +1963,9 @@ dependencies = [
[[package]]
name = "libc"
version = "0.2.186"
version = "0.2.191"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66"
checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
[[package]]
name = "libdbus-sys"
@@ -1961,6 +2051,27 @@ dependencies = [
"autocfg",
]
[[package]]
name = "midir"
version = "0.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fea58b9250a667b032ff61fb1bf77aed74873152563f5cd613016dce4c821832"
dependencies = [
"alsa",
"cc",
"coremidi",
"jni 0.21.1",
"jni-min-helper",
"js-sys",
"libc",
"log",
"ndk-context",
"parking_lot",
"wasm-bindgen",
"web-sys",
"windows",
]
[[package]]
name = "mime"
version = "0.3.17"
@@ -2030,6 +2141,12 @@ dependencies = [
"thiserror 1.0.69",
]
[[package]]
name = "ndk-context"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "27b02d87554356db9e9a873add8782d4ea6e3e58ea071a9adb9a2e8ddb884a8b"
[[package]]
name = "ndk-sys"
version = "0.6.0+11769913"
@@ -2602,6 +2719,16 @@ dependencies = [
"unicode-ident",
]
[[package]]
name = "process_path"
version = "0.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f676f11eb0b3e2ea0fbaee218fa6b806689e2297b8c8adc5bf73df465c4f6171"
dependencies = [
"libc",
"winapi",
]
[[package]]
name = "ptr_meta"
version = "0.1.4"
@@ -3568,7 +3695,7 @@ dependencies = [
"crossbeam-channel",
"dbus",
"dispatch2",
"dlopen2",
"dlopen2 0.8.2",
"dpi",
"gdkwayland-sys",
"gdkx11-sys",
+2
View File
@@ -31,4 +31,6 @@ tokio = { version = "1", features = ["time"] } # timeout on the port handshake
# One-click update (UpdateDialog.tsx). No `zip` feature: it only unpacks
# v1-style zipped Windows installers (we ship the bare NSIS setup.exe), and
# every zip 4.x it would need is yanked.
# MIDI controller input (src/midi.rs): CoreMIDI on macOS, WinMM on Windows.
midir = "0.11"
tauri-plugin-updater = { version = "2.12", default-features = false, features = ["rustls-tls", "system-proxy"] }
+44
View File
@@ -0,0 +1,44 @@
// MIDI transport spike (macOS): a virtual CoreMIDI source named
// "Konduktor Flood" that sends a jog-like CC stream at a fixed rate, so the
// shell's MIDI path can be measured without hardware.
//
// cargo run --example midi_flood -- <rate Hz> <count> <start delay s>
//
// Each message is CC 33 on channel 1 with a 7-bit counter as its value, so
// the receiver can check for drops and reordering.
#[cfg(target_os = "macos")]
fn main() {
use midir::os::unix::VirtualOutput;
use midir::MidiOutput;
use std::time::{Duration, Instant};
let args: Vec<String> = std::env::args().collect();
let rate: f64 = args.get(1).and_then(|s| s.parse().ok()).unwrap_or(1000.0);
let count: u32 = args.get(2).and_then(|s| s.parse().ok()).unwrap_or(5000);
let delay: f64 = args.get(3).and_then(|s| s.parse().ok()).unwrap_or(3.0);
let out = MidiOutput::new("Konduktor Flood").expect("MIDI client");
let mut conn = out.create_virtual("Konduktor Flood").expect("virtual source");
std::thread::sleep(Duration::from_secs_f64(delay));
let start = Instant::now();
let step = Duration::from_secs_f64(1.0 / rate);
for i in 0..count {
let due = start + step * i;
while Instant::now() < due {
let left = due - Instant::now();
if left > Duration::from_micros(300) {
std::thread::sleep(left - Duration::from_micros(200));
}
}
conn.send(&[0xB0, 33, (i % 128) as u8]).expect("send");
}
eprintln!("sent {count} at {rate} Hz in {:.3} s", start.elapsed().as_secs_f64());
std::thread::sleep(Duration::from_secs(1));
}
#[cfg(not(target_os = "macos"))]
fn main() {
eprintln!("midi_flood needs CoreMIDI virtual ports (macOS).");
}
+11 -1
View File
@@ -37,6 +37,12 @@
// runs. Cancel in the Save / Discard prompt keeps the update staged, so the
// next ordinary quit installs it (without relaunching). A failed install is
// written to `failed.json` for the next launch's dialog to report.
//
// MIDI controllers (midi.rs): WKWebView has no Web MIDI, so the shell lists
// and opens the input ports itself and streams their messages to the page
// (`midi_ports` / `midi_open` / `midi_close`); everything else is the page's.
mod midi;
use std::collections::VecDeque;
use std::path::PathBuf;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
@@ -459,6 +465,7 @@ pub fn run() {
.manage(Staged(Mutex::new(None)))
.manage(Backend { status: Mutex::new(BackendStatus::Starting), generation: AtomicU64::new(0) })
.manage(Quit { allowed: AtomicBool::new(false), acked: AtomicBool::new(false) })
.manage(midi::MidiInputs::default())
.invoke_handler(tauri::generate_handler![
backend_status,
backend_restart,
@@ -467,7 +474,10 @@ pub fn run() {
quit_now,
update_download,
update_restart,
update_take_failure
update_take_failure,
midi::midi_ports,
midi::midi_open,
midi::midi_close
])
.on_window_event(|window, event| {
if let WindowEvent::CloseRequested { api, .. } = event {
+124
View File
@@ -0,0 +1,124 @@
// MIDI INPUT for controller mapping (decided 2026-11-03,
// .claude/discussions/discuss-midi-controllers-2026-11-03.md).
//
// WKWebView has no Web MIDI, so the shell reads the ports itself with midir
// (CoreMIDI on macOS, WinMM on Windows) and streams each port's messages to the
// page over a `Channel` — the frontend does all parsing, mapping and learning
// (lib/midi/). Input only: nothing is ever sent to a controller.
//
// Batching without a timer: the driver's callback queues each message on an
// mpsc; one sender thread per port blocks on it, then drains whatever else has
// queued and sends that as ONE batch. Idle, a message goes out the moment it
// arrives; under a jog wheel's flood, messages coalesce instead of queueing up
// one IPC call each. System messages (SysEx, MIDI clock, active sensing) are
// ignored at the driver: a 24-ppqn clock from a mixer would flood the page.
//
// `wall_us` is the wall clock (µs since the Unix epoch) when the driver handed
// the message over, so the page can measure transport latency against its own
// `Date.now()`.
use std::collections::HashMap;
use std::sync::mpsc;
use std::sync::Mutex;
use std::time::{SystemTime, UNIX_EPOCH};
use midir::{Ignore, MidiInput, MidiInputConnection, MidiInputPort};
use serde::Serialize;
use tauri::ipc::Channel;
use tauri::State;
#[derive(Clone, Serialize)]
pub struct MidiPacket {
pub wall_us: u64,
pub bytes: Vec<u8>,
}
/// Open connections by port name. Dropping one closes the port and ends its
/// sender thread (the callback's mpsc sender goes with it).
#[derive(Default)]
pub struct MidiInputs(Mutex<HashMap<String, MidiInputConnection<()>>>);
fn client() -> Result<MidiInput, String> {
let mut input = MidiInput::new("Konduktor").map_err(|e| e.to_string())?;
input.ignore(Ignore::All);
Ok(input)
}
/// Every input port with a unique name: two identical controllers are
/// "X" and "X #2", in the order the OS lists them.
fn named_ports(input: &MidiInput) -> Vec<(String, MidiInputPort)> {
let mut seen: HashMap<String, usize> = HashMap::new();
input
.ports()
.into_iter()
.filter_map(|p| {
let base = input.port_name(&p).ok()?;
let n = seen.entry(base.clone()).or_insert(0);
*n += 1;
let name = if *n == 1 { base } else { format!("{base} #{n}") };
Some((name, p))
})
.collect()
}
fn now_us() -> u64 {
SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_micros() as u64).unwrap_or(0)
}
#[tauri::command]
pub fn midi_ports() -> Result<Vec<String>, String> {
Ok(named_ports(&client()?).into_iter().map(|(name, _)| name).collect())
}
/// Open `port` and stream its messages to `on_message`. Opening a port that is
/// already open replaces the old connection (a page reload re-opens).
#[tauri::command]
pub fn midi_open(
inputs: State<'_, MidiInputs>,
port: String,
on_message: Channel<Vec<MidiPacket>>,
) -> Result<(), String> {
let input = client()?;
let found = named_ports(&input)
.into_iter()
.find(|(name, _)| *name == port)
.map(|(_, p)| p)
.ok_or_else(|| format!("MIDI port not found: {port}"))?;
let (tx, rx) = mpsc::channel::<MidiPacket>();
std::thread::Builder::new()
.name(format!("midi:{port}"))
.spawn(move || {
while let Ok(first) = rx.recv() {
let mut batch = vec![first];
while let Ok(more) = rx.try_recv() {
batch.push(more);
}
if on_message.send(batch).is_err() {
break; // the page went away
}
}
})
.map_err(|e| e.to_string())?;
let conn = input
.connect(
&found,
"Konduktor input",
move |_stamp, bytes, _| {
let _ = tx.send(MidiPacket { wall_us: now_us(), bytes: bytes.to_vec() });
},
(),
)
.map_err(|e| e.to_string())?;
inputs.0.lock().unwrap().insert(port, conn);
Ok(())
}
#[tauri::command]
pub fn midi_close(inputs: State<'_, MidiInputs>, port: String) {
if let Some(conn) = inputs.0.lock().unwrap().remove(&port) {
conn.close();
}
}