dymokomi/luce-midi
Source of release 0.1.0
0.1.0 / tools / midi-probe / main.lucb
## Lists the MIDI sources and destinations, then opens an input on every
## source and logs each event for a few seconds (`midi-probe 10` for ten),
## pumping the main run loop so device changes are seen too.
## `midi-probe 3 ID` also sends a note on, the same note with velocity 0 and
## a control change to the destination with unique id ID (pick a virtual
## bus that echoes back to a source, to see the input path end to end).
import atomic
import strings
from luce_midi import midi
from luce_midi.midi import Endpoint, Event, Input, Output
extern var kCFRunLoopDefaultMode: void*
extern func CFRunLoopRunInMode(mode: void*, seconds: f64, after_source: bool) -> i32
struct Counter:
var wakes: @u64
func woken(context: void*?):
let raw = context else return
let counter = (Counter*)raw
_ = counter.wakes.add(1, .relaxed)
func show(kind: str, endpoints: const Endpoint[]):
for endpoint in endpoints:
let state = "online" if endpoint.online else "offline"
print(f"{kind}\t{endpoint.id}\t{state}\t{endpoint.name()}")
pub func main(arguments: str[]) -> i32!:
var seconds: i64 = 5
if arguments.length > 1:
seconds = strings.parse_i64(arguments[1]) else 5
var listed: Endpoint[64] = ---
let source_total = midi.sources(listed)
print(f"{source_total} sources")
show("source", listed[0..<source_total])
let destination_total = midi.destinations(listed)
print(f"{destination_total} destinations")
show("destination", listed[0..<destination_total])
var counter = Counter(wakes = 0)
var input = try Input.open(on_wake = woken, wake_context = (void*)&counter, name = "midi-probe")
defer input.close()
let ring = input.main() else return 1
print(f"listening to {input.connected()} sources for {seconds} s")
let started = midi.now_nanos()
if arguments.length > 2:
let target = (i32)(strings.parse_i64(arguments[2]) else 0)
var output = try Output.open(name = "midi-probe out")
defer output.close()
try output.send(target, 0x90, 60, 100)
try output.send(target, 0x90, 60, 0)
try output.send(target, 0xB0, 7, 99)
print(f"sent three messages to {target}")
var generation = input.generation()
var events: u64 = 0
var event = Event(source = 0, status = 0, data1 = 0, data2 = 0, nanos = 0)
while midi.now_nanos() - started < (u64)seconds * 1000000000:
_ = CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.05, false)
while ring.next(&event):
events += 1
let at = f64(event.nanos -% started) / 1000000.0
print(f"{at:.1f} ms\tsource {event.source}\t{event.status:x} {event.data1} {event.data2}")
let now = input.generation()
if now != generation:
generation = now
print(f"setup changed (generation {now}), {input.connected()} sources connected")
let again = midi.sources(listed)
show("source", listed[0..<again])
print(f"{events} events, {counter.wakes.load(.relaxed)} wakes, {ring.dropped()} dropped; audio ring holds {(input.audio() else return 1).pending()}")
return 0