midi_action_bridge.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  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("mod_ui", {})
  141. user_files_directory = deployment.get("user_files_directory")
  142. if not safe_relative_path(user_files_directory):
  143. raise ValueError("deployment.mod_ui.user_files_directory must be a safe relative path")
  144. if user_files_root is None:
  145. user_files_root = Path.home() / Path(*PurePosixPath(user_files_directory).parts)
  146. user_files_root = Path(user_files_root).resolve()
  147. ui_model = (user_files_root / "NAM Models" / "Rigforge" / source_path.name).resolve()
  148. if not ui_model.is_relative_to(user_files_root):
  149. raise ValueError(f"mod-ui NAM model escapes its user-files directory: {ui_model}")
  150. if not ui_model.is_file():
  151. raise FileNotFoundError(
  152. f"mod-ui NAM model copy is missing: {ui_model}; reinstall mod-ui to stage it"
  153. )
  154. source_digest = hashlib.sha256(source_path.read_bytes()).digest()
  155. ui_digest = hashlib.sha256(ui_model.read_bytes()).digest()
  156. if source_digest != ui_digest:
  157. raise RuntimeError(f"mod-ui NAM model copy differs from its repository source: {ui_model}")
  158. return ui_model
  159. def mod_ui_command(config, instance, property_uri, value):
  160. with ModUiWebSocketClient(
  161. config["host"],
  162. config["port"],
  163. config["websocket_path"],
  164. ) as client:
  165. return client.set_patch(instance, property_uri, value)
  166. def select_nam_model(action, state, repo_root, command=None, user_files_root=None):
  167. processor = resolve_processor(state, action["target"])
  168. models = processor["available_models"]
  169. requested_id = action["model"]
  170. fallback_id = action["fallback_model"]
  171. requested_source = resolve_asset(repo_root, models[requested_id])
  172. selected_id = requested_id
  173. selected_source = requested_source
  174. if not requested_source.is_file():
  175. selected_id = fallback_id
  176. selected_source = resolve_asset(repo_root, models[fallback_id])
  177. if not selected_source.is_file():
  178. raise FileNotFoundError(
  179. f"requested NAM model and fallback are both missing: "
  180. f"{requested_source}, {selected_source}"
  181. )
  182. print(
  183. f"WARNING: NAM model {requested_id!r} is missing; "
  184. f"using fallback {fallback_id!r} ({selected_source})",
  185. file=sys.stderr,
  186. )
  187. selected_path = resolve_mod_ui_model(
  188. state, repo_root, selected_source, user_files_root=user_files_root
  189. )
  190. ui_config = bridge_config(state)["mod_ui"]
  191. instance = processor["mod_ui_instance"]
  192. property_uri = processor["file_property"]
  193. if command is None:
  194. command = lambda instance, property_uri, value: mod_ui_command(
  195. ui_config, instance, property_uri, value
  196. )
  197. if not command(instance, property_uri, str(selected_path)):
  198. raise RuntimeError(f"mod-ui did not apply NAM model {selected_id!r}")
  199. return selected_id, selected_path
  200. def binding_index(bindings):
  201. return {
  202. (entry["event"]["channel"], entry["event"]["note"]): entry
  203. for entry in bindings["bindings"]
  204. }
  205. def handle_midi_message(
  206. message, bindings, state, repo_root, command=None, user_files_root=None
  207. ):
  208. if not message or len(message) < 3:
  209. return None
  210. status, note, velocity = message[:3]
  211. if (status & 0xF0) != 0x90 or velocity == 0:
  212. return None
  213. channel = status & 0x0F
  214. binding = bindings.get((channel, note))
  215. if binding is None:
  216. return None
  217. model_id, model_path = select_nam_model(
  218. binding["action"],
  219. state,
  220. repo_root,
  221. command=command,
  222. user_files_root=user_files_root,
  223. )
  224. return {
  225. "binding": binding["id"],
  226. "channel": channel,
  227. "note": note,
  228. "model": model_id,
  229. "path": model_path,
  230. }
  231. def list_midi_ports():
  232. try:
  233. import rtmidi
  234. except ImportError as error:
  235. raise RuntimeError(
  236. "python-rtmidi is required; install the python3-rtmidi package"
  237. ) from error
  238. midi_in = rtmidi.MidiIn()
  239. ports = midi_in.get_ports()
  240. if not ports:
  241. print("No ALSA MIDI input ports found.")
  242. for index, name in enumerate(ports):
  243. print(f"{index}: {name}")
  244. def open_midi_input(rtmidi, name_contains):
  245. midi_in = rtmidi.MidiIn()
  246. ports = midi_in.get_ports()
  247. matches = [
  248. (index, name) for index, name in enumerate(ports)
  249. if name_contains.casefold() in name.casefold()
  250. ]
  251. if len(matches) != 1:
  252. available = ", ".join(ports) if ports else "(none)"
  253. raise RuntimeError(
  254. f"expected exactly one MIDI input containing {name_contains!r}; "
  255. f"found {len(matches)}. Available inputs: {available}"
  256. )
  257. index, name = matches[0]
  258. midi_in.open_port(index, "Rigforge MIDI action bridge")
  259. return midi_in, name
  260. def run_bridge(state, bindings, repo_root, rtmidi_module=None, sleeper=time.sleep):
  261. if rtmidi_module is None:
  262. try:
  263. import rtmidi as rtmidi_module
  264. except ImportError as error:
  265. raise RuntimeError(
  266. "python-rtmidi is required; install the python3-rtmidi package"
  267. ) from error
  268. config = bridge_config(state)
  269. name_contains = config["input_port_name_contains"]
  270. actions = binding_index(bindings)
  271. ui_config = config["mod_ui"]
  272. mod_ui_client = ModUiWebSocketClient(
  273. ui_config["host"],
  274. ui_config["port"],
  275. ui_config["websocket_path"],
  276. )
  277. def set_nam_model(instance, property_uri, value):
  278. return mod_ui_client.set_patch(instance, property_uri, value)
  279. print(f"Looking for ALSA MIDI input containing {name_contains!r}…")
  280. while True:
  281. midi_in = None
  282. try:
  283. midi_in, port_name = open_midi_input(rtmidi_module, name_contains)
  284. print(f"Listening on {port_name}")
  285. while True:
  286. if mod_ui_client.connection is not None:
  287. try:
  288. mod_ui_client.serve_once(timeout=0.001)
  289. except (OSError, RuntimeError) as error:
  290. print(f"mod-ui WebSocket closed: {error}; reconnecting on next action", file=sys.stderr)
  291. mod_ui_client.close()
  292. received = midi_in.get_message()
  293. if received:
  294. try:
  295. result = handle_midi_message(
  296. received[0], actions, state, repo_root,
  297. command=set_nam_model,
  298. )
  299. if result:
  300. print(
  301. f"{result['binding']}: MIDI ch {result['channel'] + 1} "
  302. f"note {result['note']} -> {result['model']}"
  303. )
  304. except (OSError, RuntimeError, ValueError, KeyError) as error:
  305. print(f"MIDI action failed: {error}", file=sys.stderr)
  306. mod_ui_client.close()
  307. sleeper(0.005)
  308. except KeyboardInterrupt:
  309. return
  310. except (OSError, RuntimeError) as error:
  311. print(f"MIDI bridge: {error}; retrying in 2 seconds", file=sys.stderr)
  312. sleeper(2)
  313. finally:
  314. if midi_in is not None:
  315. midi_in.close_port()
  316. mod_ui_client.close()
  317. def main(argv=None):
  318. root = Path(__file__).resolve().parents[1]
  319. parser = argparse.ArgumentParser(description=__doc__)
  320. parser.add_argument("--state", type=Path, default=root / "config" / "desired-state.yaml")
  321. parser.add_argument("--bindings", type=Path)
  322. parser.add_argument("--repo-root", type=Path, default=root)
  323. parser.add_argument("--check", action="store_true", help="validate state and bindings, then exit")
  324. parser.add_argument("--list-ports", action="store_true", help="list available ALSA MIDI inputs")
  325. args = parser.parse_args(argv)
  326. if args.list_ports:
  327. try:
  328. list_midi_ports()
  329. except RuntimeError as error:
  330. print(f"ERROR: {error}", file=sys.stderr)
  331. return 1
  332. return 0
  333. try:
  334. state, bindings, repo_root = load_configuration(
  335. args.state, args.bindings, args.repo_root
  336. )
  337. if args.check:
  338. print(f"Valid MIDI bindings: {len(bindings['bindings'])}")
  339. return 0
  340. run_bridge(state, bindings, repo_root)
  341. except (OSError, RuntimeError, ValueError, KeyError, TypeError, yaml.YAMLError) as error:
  342. print(f"ERROR: {error}", file=sys.stderr)
  343. return 1
  344. return 0
  345. if __name__ == "__main__":
  346. raise SystemExit(main())