run_mod_ui_service.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  1. #!/usr/bin/env python3
  2. """Run mod-ui under pw-jack and keep its mod-host session active."""
  3. import argparse
  4. import os
  5. import signal
  6. import subprocess
  7. import sys
  8. import time
  9. from pathlib import Path
  10. import yaml
  11. from mod_ui_websocket import ModUiWebSocketClient
  12. from observe_pipewire import parse_pw_link_output
  13. PIPEWIRE_BOUNDARY_TIMEOUT = 35
  14. def load_mod_ui_board_links(state_path):
  15. state = yaml.safe_load(Path(state_path).read_text(encoding="utf-8"))
  16. processors = state["routing"]["mod_host_chains"]["voice"]["processors"]
  17. links = []
  18. for index in range(1, len(processors)):
  19. previous = processors[index - 1]
  20. current = processors[index]
  21. links.append(
  22. (
  23. f"/graph/{previous['mod_ui_instance'].removeprefix('/graph/')}/"
  24. f"{previous['output_port'].split(':', 1)[1]}",
  25. f"/graph/{current['mod_ui_instance'].removeprefix('/graph/')}/"
  26. f"{current['input_port'].split(':', 1)[1]}",
  27. )
  28. )
  29. links.append(
  30. (
  31. f"/graph/{processors[-1]['mod_ui_instance'].removeprefix('/graph/')}/"
  32. f"{processors[-1]['output_port'].split(':', 1)[1]}",
  33. "/graph/playback_3",
  34. )
  35. )
  36. return tuple(links)
  37. def _resolve_host_alias(port):
  38. graph_path = port.removeprefix("/graph/")
  39. if "/" not in graph_path:
  40. if graph_path.startswith("playback_"):
  41. channel = int(graph_path.removeprefix("playback_"))
  42. if 1 <= channel <= 4:
  43. return (
  44. "rigforge.mod-host-output.playback:"
  45. f"playback_AUX{channel - 1}"
  46. )
  47. return port
  48. if graph_path.startswith("capture_"):
  49. channel = int(graph_path.removeprefix("capture_"))
  50. if 1 <= channel <= 4:
  51. return f"rigforge.mod-host-input.capture:capture_AUX{channel - 1}"
  52. return port
  53. return port
  54. instance, symbol = graph_path.split("/", 1)
  55. instance_indices = {
  56. "rigforge_voice_high_pass": 2,
  57. "rigforge_voice_compressor": 3,
  58. "rigforge_voice_de_esser": 4,
  59. "rigforge_voice_reverb": 5,
  60. }
  61. if instance in instance_indices:
  62. effect_ports = {
  63. "rigforge_voice_high_pass": {"in": "in", "out": "out"},
  64. "rigforge_voice_compressor": {"in": "in", "out": "out"},
  65. "rigforge_voice_de_esser": {"in": "in", "out": "out"},
  66. "rigforge_voice_reverb": {
  67. "input_l": "lv2_audio_in_1",
  68. "output_l": "lv2_audio_out_1",
  69. },
  70. }
  71. resolved_symbol = effect_ports.get(instance, {}).get(symbol)
  72. return (
  73. f"effect_{instance_indices[instance]}:{resolved_symbol}"
  74. if resolved_symbol
  75. else port
  76. )
  77. return port
  78. def guitar_boundary_links(capture_ports, playback_ports):
  79. captures = [port.strip() for port in capture_ports if port.strip()]
  80. playbacks = [port.strip() for port in playback_ports if port.strip()]
  81. if not captures or not playbacks:
  82. raise RuntimeError("Rigforge guitar PipeWire boundary ports are not configured")
  83. return (
  84. (captures[0], "effect_0:input"),
  85. ("effect_1:out", playbacks[0]),
  86. )
  87. def wait_for_guitar_boundary_links(
  88. capture_ports,
  89. playback_ports,
  90. runner=subprocess.run,
  91. timeout=10,
  92. interval=0.2,
  93. clock=time.monotonic,
  94. sleep=time.sleep,
  95. ):
  96. expected = guitar_boundary_links(capture_ports, playback_ports)
  97. deadline = clock() + timeout
  98. missing = list(expected)
  99. last_error = None
  100. while True:
  101. try:
  102. result = runner(
  103. ["pw-link", "-l"],
  104. check=False,
  105. capture_output=True,
  106. text=True,
  107. )
  108. if result.returncode == 0:
  109. observed = parse_pw_link_output(result.stdout)
  110. missing = [edge for edge in expected if edge not in observed]
  111. if not missing:
  112. return
  113. last_error = None
  114. else:
  115. last_error = f"pw-link exited with status {result.returncode}"
  116. except (OSError, ValueError) as error:
  117. last_error = str(error)
  118. remaining = deadline - clock()
  119. if remaining <= 0:
  120. details = ", ".join(f"{source} -> {destination}" for source, destination in missing)
  121. message = f"mod-ui did not restore guitar PipeWire boundary links: {details}"
  122. if last_error:
  123. message += f" ({last_error})"
  124. raise RuntimeError(message)
  125. sleep(min(interval, remaining))
  126. def wait_for_graph_links(
  127. expected,
  128. resolve_host_port=lambda port: port,
  129. runner=subprocess.run,
  130. timeout=10,
  131. interval=0.2,
  132. clock=time.monotonic,
  133. sleep=time.sleep,
  134. ):
  135. expected = tuple(
  136. (
  137. resolve_host_port(source),
  138. resolve_host_port(destination),
  139. )
  140. for source, destination in expected
  141. )
  142. deadline = clock() + timeout
  143. missing = list(expected)
  144. last_error = None
  145. while True:
  146. try:
  147. result = runner(
  148. ["pw-link", "-l"],
  149. check=False,
  150. capture_output=True,
  151. text=True,
  152. )
  153. if result.returncode == 0:
  154. observed = parse_pw_link_output(result.stdout)
  155. missing = [edge for edge in expected if edge not in observed]
  156. if not missing:
  157. return
  158. last_error = None
  159. else:
  160. last_error = f"pw-link exited with status {result.returncode}"
  161. except (OSError, ValueError) as error:
  162. last_error = str(error)
  163. remaining = deadline - clock()
  164. if remaining <= 0:
  165. details = ", ".join(
  166. f"{source} -> {destination}" for source, destination in missing
  167. )
  168. message = f"mod-ui did not restore declared pedalboard links: {details}"
  169. if last_error:
  170. message += f" ({last_error})"
  171. raise RuntimeError(message)
  172. sleep(min(interval, remaining))
  173. def run_service(
  174. launcher,
  175. pw_jack,
  176. host,
  177. port,
  178. websocket_path,
  179. timeout,
  180. popen=subprocess.Popen,
  181. capture_ports=(),
  182. playback_ports=(),
  183. pw_link_runner=subprocess.run,
  184. state_path=None,
  185. ):
  186. process = popen([str(pw_jack), str(launcher)])
  187. stopping = [False]
  188. def request_stop(_signum, _frame):
  189. stopping[0] = True
  190. old_term = signal.signal(signal.SIGTERM, request_stop)
  191. old_int = signal.signal(signal.SIGINT, request_stop)
  192. client = ModUiWebSocketClient(host, port, websocket_path, timeout=2)
  193. deadline = time.monotonic() + timeout
  194. try:
  195. while not stopping[0]:
  196. if process.poll() is not None:
  197. raise RuntimeError(f"mod-ui launcher exited with status {process.returncode}")
  198. try:
  199. client.connect()
  200. break
  201. except OSError:
  202. if time.monotonic() >= deadline:
  203. raise RuntimeError(
  204. f"mod-ui WebSocket did not become ready on {host}:{port}{websocket_path}"
  205. )
  206. time.sleep(0.25)
  207. loading = False
  208. loaded_board = False
  209. if not stopping[0]:
  210. print("Waiting for mod-ui to finish loading the current pedalboard")
  211. while not stopping[0]:
  212. if process.poll() is not None:
  213. raise RuntimeError(f"mod-ui launcher exited with status {process.returncode}")
  214. message = client.serve_once(timeout=0.5)
  215. if message and message.startswith("loading_start "):
  216. loading = True
  217. loaded_board = False
  218. elif message and message.startswith("loading_end ") and loading:
  219. loaded_board = True
  220. loading = False
  221. if loaded_board:
  222. break
  223. if time.monotonic() >= deadline:
  224. raise RuntimeError("mod-ui did not finish loading a pedalboard before timeout")
  225. if not loaded_board and not stopping[0]:
  226. raise RuntimeError("mod-ui did not load its prepared Rigforge default pedalboard")
  227. if not stopping[0]:
  228. print("Verifying mod-ui guitar PipeWire boundary links")
  229. wait_for_guitar_boundary_links(
  230. capture_ports,
  231. playback_ports,
  232. runner=pw_link_runner,
  233. timeout=PIPEWIRE_BOUNDARY_TIMEOUT,
  234. )
  235. if state_path is not None:
  236. print("Verifying mod-ui voice chain links")
  237. wait_for_graph_links(
  238. load_mod_ui_board_links(state_path),
  239. resolve_host_port=_resolve_host_alias,
  240. runner=pw_link_runner,
  241. timeout=PIPEWIRE_BOUNDARY_TIMEOUT,
  242. )
  243. print("mod-ui pedalboard loaded; keeping its mod-host session active")
  244. while not stopping[0]:
  245. if process.poll() is not None:
  246. raise RuntimeError(f"mod-ui launcher exited with status {process.returncode}")
  247. client.serve_once(timeout=0.5)
  248. finally:
  249. signal.signal(signal.SIGTERM, old_term)
  250. signal.signal(signal.SIGINT, old_int)
  251. client.close()
  252. if process.poll() is None:
  253. process.terminate()
  254. try:
  255. process.wait(timeout=5)
  256. except subprocess.TimeoutExpired:
  257. process.kill()
  258. process.wait()
  259. def main(argv=None):
  260. parser = argparse.ArgumentParser(description=__doc__)
  261. parser.add_argument("--launcher", type=Path, required=True)
  262. parser.add_argument("--pw-jack", type=Path, default=Path("/usr/bin/pw-jack"))
  263. parser.add_argument("--host", default="127.0.0.1")
  264. parser.add_argument("--port", type=int, default=8888)
  265. parser.add_argument("--websocket-path", default="/websocket")
  266. parser.add_argument("--timeout", type=float, default=60)
  267. parser.add_argument(
  268. "--state",
  269. type=Path,
  270. default=Path(__file__).resolve().parents[1] / "config" / "desired-state.yaml",
  271. )
  272. args = parser.parse_args(argv)
  273. if not args.launcher.is_file():
  274. print(f"ERROR: mod-ui launcher is missing: {args.launcher}", file=sys.stderr)
  275. return 1
  276. if not args.pw_jack.is_file():
  277. print(f"ERROR: pw-jack is missing: {args.pw_jack}", file=sys.stderr)
  278. return 1
  279. try:
  280. run_service(
  281. args.launcher,
  282. args.pw_jack,
  283. args.host,
  284. args.port,
  285. args.websocket_path,
  286. args.timeout,
  287. capture_ports=os.environ.get("MOD_RIGFORGE_CAPTURE_PORTS", "").split(","),
  288. playback_ports=os.environ.get("MOD_RIGFORGE_PLAYBACK_PORTS", "").split(","),
  289. state_path=args.state,
  290. )
  291. except (OSError, RuntimeError, ValueError) as error:
  292. print(f"ERROR: {error}", file=sys.stderr)
  293. return 1
  294. return 0
  295. if __name__ == "__main__":
  296. raise SystemExit(main())