midi_action_bridge.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  1. #!/usr/bin/env python3
  2. """Translate configured MIDI events into NAM model changes via mod-ui."""
  3. import argparse
  4. import hashlib
  5. import sys
  6. import time
  7. from pathlib import Path, PurePosixPath
  8. import yaml
  9. from mod_ui_websocket import ModUiWebSocketClient
  10. from validate_desired_state import safe_relative_path, validate_state
  11. def load_yaml(path):
  12. with path.open(encoding="utf-8") as stream:
  13. return yaml.safe_load(stream)
  14. def bridge_config(state):
  15. return state["controls"]["midi_bridge"]
  16. def resolve_processor(state, target):
  17. chain_id = target["chain"]
  18. processor_id = target["processor"]
  19. chain = state["routing"]["mod_host_chains"].get(chain_id)
  20. if not isinstance(chain, dict):
  21. raise ValueError(f"unknown mod-host chain in MIDI action: {chain_id}")
  22. processors = chain.get("processors")
  23. if not isinstance(processors, list):
  24. raise ValueError(f"mod-host chain has no processor list: {chain_id}")
  25. matches = [
  26. processor for processor in processors
  27. if isinstance(processor, dict) and processor.get("id") == processor_id
  28. ]
  29. if len(matches) != 1:
  30. raise ValueError(
  31. f"MIDI action target must identify exactly one processor: "
  32. f"{chain_id}.{processor_id}"
  33. )
  34. return matches[0]
  35. def validate_bindings(bindings, state):
  36. errors = []
  37. if not isinstance(bindings, dict):
  38. return ["MIDI bindings document root must be a mapping"]
  39. if bindings.get("schema_version") != 1:
  40. errors.append("MIDI bindings schema_version must be 1")
  41. entries = bindings.get("bindings")
  42. if not isinstance(entries, list):
  43. return errors + ["MIDI bindings must contain a bindings list"]
  44. binding_ids = set()
  45. events = set()
  46. for index, binding in enumerate(entries):
  47. location = f"bindings[{index}]"
  48. if not isinstance(binding, dict):
  49. errors.append(f"{location} must be a mapping")
  50. continue
  51. binding_id = binding.get("id")
  52. if not isinstance(binding_id, str) or not binding_id:
  53. errors.append(f"{location}.id must be a non-empty string")
  54. elif binding_id in binding_ids:
  55. errors.append(f"duplicate MIDI binding id: {binding_id}")
  56. else:
  57. binding_ids.add(binding_id)
  58. event = binding.get("event")
  59. if not isinstance(event, dict):
  60. errors.append(f"{location}.event must be a mapping")
  61. continue
  62. if event.get("type") != "note_on":
  63. errors.append(f"{location}.event.type must be note_on")
  64. continue
  65. channel = event.get("channel")
  66. note = event.get("note")
  67. if not isinstance(channel, int) or isinstance(channel, bool) or channel not in range(16):
  68. errors.append(f"{location}.event.channel must be an integer from 0 through 15")
  69. if not isinstance(note, int) or isinstance(note, bool) or note not in range(128):
  70. errors.append(f"{location}.event.note must be an integer from 0 through 127")
  71. if (
  72. isinstance(channel, int)
  73. and not isinstance(channel, bool)
  74. and channel in range(16)
  75. and isinstance(note, int)
  76. and not isinstance(note, bool)
  77. and note in range(128)
  78. ):
  79. event_key = (channel, note)
  80. if event_key in events:
  81. errors.append(f"duplicate MIDI note binding on channel {channel}, note {note}")
  82. events.add(event_key)
  83. action = binding.get("action")
  84. if not isinstance(action, dict):
  85. errors.append(f"{location}.action must be a mapping")
  86. continue
  87. if action.get("type") != "select_nam_model":
  88. errors.append(f"{location}.action.type must be select_nam_model")
  89. continue
  90. target = action.get("target")
  91. if not isinstance(target, dict) or set(target) != {"chain", "processor"}:
  92. errors.append(f"{location}.action.target must declare chain and processor")
  93. continue
  94. try:
  95. processor = resolve_processor(state, target)
  96. except (KeyError, TypeError, ValueError) as error:
  97. errors.append(f"{location}.action.target: {error}")
  98. continue
  99. if processor.get("plugin_uri") != "http://github.com/mikeoliphant/neural-amp-modeler-lv2":
  100. errors.append(f"{location}.action target is not a NAM processor")
  101. continue
  102. models = processor.get("available_models")
  103. if not isinstance(models, dict) or not models:
  104. errors.append(f"{location}.action target has no available_models")
  105. continue
  106. for model_field in ("model", "fallback_model"):
  107. model_id = action.get(model_field)
  108. if not isinstance(model_id, str) or model_id not in models:
  109. errors.append(
  110. f"{location}.action.{model_field} must name a model declared on its target"
  111. )
  112. return errors
  113. def load_configuration(state_path, bindings_path=None, repo_root=None):
  114. state = load_yaml(Path(state_path))
  115. state_errors = validate_state(state)
  116. if state_errors:
  117. raise ValueError("invalid desired state: " + "; ".join(state_errors))
  118. root = Path(repo_root).resolve() if repo_root is not None else Path(__file__).resolve().parents[1]
  119. config = bridge_config(state)
  120. declared_bindings = config["bindings_file"]
  121. if not safe_relative_path(declared_bindings):
  122. raise ValueError("controls.midi_bridge.bindings_file must be a safe relative path")
  123. path = Path(bindings_path) if bindings_path is not None else root / declared_bindings
  124. bindings = load_yaml(path)
  125. binding_errors = validate_bindings(bindings, state)
  126. if binding_errors:
  127. raise ValueError("invalid MIDI bindings: " + "; ".join(binding_errors))
  128. return state, bindings, root
  129. def resolve_asset(repo_root, relative_path):
  130. if not safe_relative_path(relative_path):
  131. raise ValueError(f"unsafe NAM model asset path: {relative_path!r}")
  132. relative = PurePosixPath(relative_path)
  133. resolved = (repo_root / Path(*relative.parts)).resolve()
  134. if not resolved.is_relative_to(repo_root.resolve()):
  135. raise ValueError(f"NAM model asset escapes the repository: {resolved}")
  136. return resolved
  137. def resolve_mod_ui_model(state, repo_root, source_path, user_files_root=None):
  138. """Resolve a repository NAM model to the matching mod-ui user-files copy."""
  139. source_path = Path(source_path).resolve()
  140. deployment = state.get("deployment", {}).get("midi_bridge", {})
  141. user_files_directory = deployment.get("models_directory")
  142. if not safe_relative_path(user_files_directory):
  143. raise ValueError("deployment.midi_bridge.models_directory must be a safe relative path")
  144. models_root = Path.home() / Path(*PurePosixPath(user_files_directory).parts)
  145. if user_files_root is not None:
  146. models_root = Path(user_files_root) / "NAM Models" / "Rigforge"
  147. models_root = models_root.resolve()
  148. ui_model = (models_root / source_path.name).resolve()
  149. if not ui_model.is_relative_to(models_root):
  150. raise ValueError(f"mod-ui NAM model escapes its models directory: {ui_model}")
  151. if not ui_model.is_file():
  152. raise FileNotFoundError(
  153. f"mod-ui NAM model copy is missing: {ui_model}; reinstall mod-ui to stage it"
  154. )
  155. source_digest = hashlib.sha256(source_path.read_bytes()).digest()
  156. ui_digest = hashlib.sha256(ui_model.read_bytes()).digest()
  157. if source_digest != ui_digest:
  158. raise RuntimeError(f"mod-ui NAM model copy differs from its repository source: {ui_model}")
  159. return ui_model
  160. def mod_ui_command(config, instance, property_uri, value):
  161. with ModUiWebSocketClient(
  162. config["host"],
  163. config["port"],
  164. config["websocket_path"],
  165. ) as client:
  166. return client.set_patch(instance, property_uri, value)
  167. def select_nam_model(action, state, repo_root, command=None, user_files_root=None):
  168. processor = resolve_processor(state, action["target"])
  169. models = processor["available_models"]
  170. requested_id = action["model"]
  171. fallback_id = action["fallback_model"]
  172. requested_source = resolve_asset(repo_root, models[requested_id])
  173. selected_id = requested_id
  174. selected_source = requested_source
  175. if not requested_source.is_file():
  176. selected_id = fallback_id
  177. selected_source = resolve_asset(repo_root, models[fallback_id])
  178. if not selected_source.is_file():
  179. raise FileNotFoundError(
  180. f"requested NAM model and fallback are both missing: "
  181. f"{requested_source}, {selected_source}"
  182. )
  183. print(
  184. f"WARNING: NAM model {requested_id!r} is missing; "
  185. f"using fallback {fallback_id!r} ({selected_source})",
  186. file=sys.stderr,
  187. )
  188. selected_path = resolve_mod_ui_model(
  189. state, repo_root, selected_source, user_files_root=user_files_root
  190. )
  191. ui_config = bridge_config(state)["mod_ui"]
  192. instance = processor["mod_ui_instance"]
  193. property_uri = processor["file_property"]
  194. if command is None:
  195. command = lambda instance, property_uri, value: mod_ui_command(
  196. ui_config, instance, property_uri, value
  197. )
  198. if not command(instance, property_uri, str(selected_path)):
  199. raise RuntimeError(f"mod-ui did not apply NAM model {selected_id!r}")
  200. return selected_id, selected_path
  201. def binding_index(bindings):
  202. return {
  203. (entry["event"]["channel"], entry["event"]["note"]): entry
  204. for entry in bindings["bindings"]
  205. }
  206. def handle_midi_message(
  207. message, bindings, state, repo_root, command=None, user_files_root=None
  208. ):
  209. if not message or len(message) < 3:
  210. return None
  211. status, note, velocity = message[:3]
  212. if (status & 0xF0) != 0x90 or velocity == 0:
  213. return None
  214. channel = status & 0x0F
  215. binding = bindings.get((channel, note))
  216. if binding is None:
  217. return None
  218. model_id, model_path = select_nam_model(
  219. binding["action"],
  220. state,
  221. repo_root,
  222. command=command,
  223. user_files_root=user_files_root,
  224. )
  225. return {
  226. "binding": binding["id"],
  227. "channel": channel,
  228. "note": note,
  229. "model": model_id,
  230. "path": model_path,
  231. }
  232. def list_midi_ports():
  233. try:
  234. import rtmidi
  235. except ImportError as error:
  236. raise RuntimeError(
  237. "python-rtmidi is required; install the python3-rtmidi package"
  238. ) from error
  239. midi_in = rtmidi.MidiIn()
  240. ports = midi_in.get_ports()
  241. if not ports:
  242. print("No ALSA MIDI input ports found.")
  243. for index, name in enumerate(ports):
  244. print(f"{index}: {name}")
  245. def open_midi_input(rtmidi, name_contains):
  246. midi_in = rtmidi.MidiIn()
  247. ports = midi_in.get_ports()
  248. matches = [
  249. (index, name) for index, name in enumerate(ports)
  250. if name_contains.casefold() in name.casefold()
  251. ]
  252. if len(matches) != 1:
  253. available = ", ".join(ports) if ports else "(none)"
  254. raise RuntimeError(
  255. f"expected exactly one MIDI input containing {name_contains!r}; "
  256. f"found {len(matches)}. Available inputs: {available}"
  257. )
  258. index, name = matches[0]
  259. midi_in.open_port(index, "Rigforge MIDI action bridge")
  260. return midi_in, name
  261. def run_bridge(state, bindings, repo_root, rtmidi_module=None, sleeper=time.sleep):
  262. if rtmidi_module is None:
  263. try:
  264. import rtmidi as rtmidi_module
  265. except ImportError as error:
  266. raise RuntimeError(
  267. "python-rtmidi is required; install the python3-rtmidi package"
  268. ) from error
  269. config = bridge_config(state)
  270. name_contains = config["input_port_name_contains"]
  271. actions = binding_index(bindings)
  272. ui_config = config["mod_ui"]
  273. mod_ui_client = ModUiWebSocketClient(
  274. ui_config["host"],
  275. ui_config["port"],
  276. ui_config["websocket_path"],
  277. )
  278. def set_nam_model(instance, property_uri, value):
  279. return mod_ui_client.set_patch(instance, property_uri, value)
  280. print(f"Looking for ALSA MIDI input containing {name_contains!r}…")
  281. while True:
  282. midi_in = None
  283. try:
  284. midi_in, port_name = open_midi_input(rtmidi_module, name_contains)
  285. print(f"Listening on {port_name}")
  286. while True:
  287. if mod_ui_client.connection is not None:
  288. try:
  289. mod_ui_client.serve_once(timeout=0.001)
  290. except (OSError, RuntimeError) as error:
  291. print(f"mod-ui WebSocket closed: {error}; reconnecting on next action", file=sys.stderr)
  292. mod_ui_client.close()
  293. received = midi_in.get_message()
  294. if received:
  295. try:
  296. result = handle_midi_message(
  297. received[0], actions, state, repo_root,
  298. command=set_nam_model,
  299. )
  300. if result:
  301. print(
  302. f"{result['binding']}: MIDI ch {result['channel'] + 1} "
  303. f"note {result['note']} -> {result['model']}"
  304. )
  305. except (OSError, RuntimeError, ValueError, KeyError) as error:
  306. print(f"MIDI action failed: {error}", file=sys.stderr)
  307. mod_ui_client.close()
  308. sleeper(0.005)
  309. except KeyboardInterrupt:
  310. return
  311. except (OSError, RuntimeError) as error:
  312. print(f"MIDI bridge: {error}; retrying in 2 seconds", file=sys.stderr)
  313. sleeper(2)
  314. finally:
  315. if midi_in is not None:
  316. midi_in.close_port()
  317. mod_ui_client.close()
  318. def main(argv=None):
  319. root = Path(__file__).resolve().parents[1]
  320. parser = argparse.ArgumentParser(description=__doc__)
  321. parser.add_argument("--state", type=Path, default=root / "config" / "desired-state.yaml")
  322. parser.add_argument("--bindings", type=Path)
  323. parser.add_argument("--repo-root", type=Path, default=root)
  324. parser.add_argument("--check", action="store_true", help="validate state and bindings, then exit")
  325. parser.add_argument("--list-ports", action="store_true", help="list available ALSA MIDI inputs")
  326. args = parser.parse_args(argv)
  327. if args.list_ports:
  328. try:
  329. list_midi_ports()
  330. except RuntimeError as error:
  331. print(f"ERROR: {error}", file=sys.stderr)
  332. return 1
  333. return 0
  334. try:
  335. state, bindings, repo_root = load_configuration(
  336. args.state, args.bindings, args.repo_root
  337. )
  338. if args.check:
  339. print(f"Valid MIDI bindings: {len(bindings['bindings'])}")
  340. return 0
  341. run_bridge(state, bindings, repo_root)
  342. except (OSError, RuntimeError, ValueError, KeyError, TypeError, yaml.YAMLError) as error:
  343. print(f"ERROR: {error}", file=sys.stderr)
  344. return 1
  345. return 0
  346. if __name__ == "__main__":
  347. raise SystemExit(main())