midi_action_bridge.py 13 KB

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