midi_action_bridge.py 17 KB

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