run_mod_ui_service.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  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. return f"effect_{instance_indices[instance]}:{symbol}"
  63. return port
  64. def guitar_boundary_links(capture_ports, playback_ports):
  65. captures = [port.strip() for port in capture_ports if port.strip()]
  66. playbacks = [port.strip() for port in playback_ports if port.strip()]
  67. if not captures or not playbacks:
  68. raise RuntimeError("Rigforge guitar PipeWire boundary ports are not configured")
  69. return (
  70. (captures[0], "effect_0:input"),
  71. ("effect_1:out", playbacks[0]),
  72. )
  73. def wait_for_guitar_boundary_links(
  74. capture_ports,
  75. playback_ports,
  76. runner=subprocess.run,
  77. timeout=10,
  78. interval=0.2,
  79. clock=time.monotonic,
  80. sleep=time.sleep,
  81. ):
  82. expected = guitar_boundary_links(capture_ports, playback_ports)
  83. deadline = clock() + timeout
  84. missing = list(expected)
  85. last_error = None
  86. while True:
  87. try:
  88. result = runner(
  89. ["pw-link", "-l"],
  90. check=False,
  91. capture_output=True,
  92. text=True,
  93. )
  94. if result.returncode == 0:
  95. observed = parse_pw_link_output(result.stdout)
  96. missing = [edge for edge in expected if edge not in observed]
  97. if not missing:
  98. return
  99. last_error = None
  100. else:
  101. last_error = f"pw-link exited with status {result.returncode}"
  102. except (OSError, ValueError) as error:
  103. last_error = str(error)
  104. remaining = deadline - clock()
  105. if remaining <= 0:
  106. details = ", ".join(f"{source} -> {destination}" for source, destination in missing)
  107. message = f"mod-ui did not restore guitar PipeWire boundary links: {details}"
  108. if last_error:
  109. message += f" ({last_error})"
  110. raise RuntimeError(message)
  111. sleep(min(interval, remaining))
  112. def wait_for_graph_links(
  113. expected,
  114. resolve_host_port=lambda port: port,
  115. runner=subprocess.run,
  116. timeout=10,
  117. interval=0.2,
  118. clock=time.monotonic,
  119. sleep=time.sleep,
  120. ):
  121. expected = tuple(
  122. (
  123. resolve_host_port(source),
  124. resolve_host_port(destination),
  125. )
  126. for source, destination in expected
  127. )
  128. deadline = clock() + timeout
  129. missing = list(expected)
  130. last_error = None
  131. while True:
  132. try:
  133. result = runner(
  134. ["pw-link", "-l"],
  135. check=False,
  136. capture_output=True,
  137. text=True,
  138. )
  139. if result.returncode == 0:
  140. observed = parse_pw_link_output(result.stdout)
  141. missing = [edge for edge in expected if edge not in observed]
  142. if not missing:
  143. return
  144. last_error = None
  145. else:
  146. last_error = f"pw-link exited with status {result.returncode}"
  147. except (OSError, ValueError) as error:
  148. last_error = str(error)
  149. remaining = deadline - clock()
  150. if remaining <= 0:
  151. details = ", ".join(
  152. f"{source} -> {destination}" for source, destination in missing
  153. )
  154. message = f"mod-ui did not restore declared pedalboard links: {details}"
  155. if last_error:
  156. message += f" ({last_error})"
  157. raise RuntimeError(message)
  158. sleep(min(interval, remaining))
  159. def run_service(
  160. launcher,
  161. pw_jack,
  162. host,
  163. port,
  164. websocket_path,
  165. timeout,
  166. popen=subprocess.Popen,
  167. capture_ports=(),
  168. playback_ports=(),
  169. pw_link_runner=subprocess.run,
  170. state_path=None,
  171. ):
  172. process = popen([str(pw_jack), str(launcher)])
  173. stopping = [False]
  174. def request_stop(_signum, _frame):
  175. stopping[0] = True
  176. old_term = signal.signal(signal.SIGTERM, request_stop)
  177. old_int = signal.signal(signal.SIGINT, request_stop)
  178. client = ModUiWebSocketClient(host, port, websocket_path, timeout=2)
  179. deadline = time.monotonic() + timeout
  180. try:
  181. while not stopping[0]:
  182. if process.poll() is not None:
  183. raise RuntimeError(f"mod-ui launcher exited with status {process.returncode}")
  184. try:
  185. client.connect()
  186. break
  187. except OSError:
  188. if time.monotonic() >= deadline:
  189. raise RuntimeError(
  190. f"mod-ui WebSocket did not become ready on {host}:{port}{websocket_path}"
  191. )
  192. time.sleep(0.25)
  193. loading = False
  194. loaded_board = False
  195. if not stopping[0]:
  196. print("Waiting for mod-ui to finish loading the current pedalboard")
  197. while not stopping[0]:
  198. if process.poll() is not None:
  199. raise RuntimeError(f"mod-ui launcher exited with status {process.returncode}")
  200. message = client.serve_once(timeout=0.5)
  201. if message and message.startswith("loading_start "):
  202. loading = True
  203. loaded_board = False
  204. elif message and message.startswith("loading_end ") and loading:
  205. loaded_board = True
  206. loading = False
  207. if loaded_board:
  208. break
  209. if time.monotonic() >= deadline:
  210. raise RuntimeError("mod-ui did not finish loading a pedalboard before timeout")
  211. if not loaded_board and not stopping[0]:
  212. raise RuntimeError("mod-ui did not load its prepared Rigforge default pedalboard")
  213. if not stopping[0]:
  214. print("Verifying mod-ui guitar PipeWire boundary links")
  215. wait_for_guitar_boundary_links(
  216. capture_ports,
  217. playback_ports,
  218. runner=pw_link_runner,
  219. timeout=PIPEWIRE_BOUNDARY_TIMEOUT,
  220. )
  221. if state_path is not None:
  222. print("Verifying mod-ui voice chain links")
  223. wait_for_graph_links(
  224. load_mod_ui_board_links(state_path),
  225. resolve_host_port=_resolve_host_alias,
  226. runner=pw_link_runner,
  227. timeout=PIPEWIRE_BOUNDARY_TIMEOUT,
  228. )
  229. print("mod-ui pedalboard loaded; keeping its mod-host session active")
  230. while not stopping[0]:
  231. if process.poll() is not None:
  232. raise RuntimeError(f"mod-ui launcher exited with status {process.returncode}")
  233. client.serve_once(timeout=0.5)
  234. finally:
  235. signal.signal(signal.SIGTERM, old_term)
  236. signal.signal(signal.SIGINT, old_int)
  237. client.close()
  238. if process.poll() is None:
  239. process.terminate()
  240. try:
  241. process.wait(timeout=5)
  242. except subprocess.TimeoutExpired:
  243. process.kill()
  244. process.wait()
  245. def main(argv=None):
  246. parser = argparse.ArgumentParser(description=__doc__)
  247. parser.add_argument("--launcher", type=Path, required=True)
  248. parser.add_argument("--pw-jack", type=Path, default=Path("/usr/bin/pw-jack"))
  249. parser.add_argument("--host", default="127.0.0.1")
  250. parser.add_argument("--port", type=int, default=8888)
  251. parser.add_argument("--websocket-path", default="/websocket")
  252. parser.add_argument("--timeout", type=float, default=60)
  253. parser.add_argument(
  254. "--state",
  255. type=Path,
  256. default=Path(__file__).resolve().parents[1] / "config" / "desired-state.yaml",
  257. )
  258. args = parser.parse_args(argv)
  259. if not args.launcher.is_file():
  260. print(f"ERROR: mod-ui launcher is missing: {args.launcher}", file=sys.stderr)
  261. return 1
  262. if not args.pw_jack.is_file():
  263. print(f"ERROR: pw-jack is missing: {args.pw_jack}", file=sys.stderr)
  264. return 1
  265. try:
  266. run_service(
  267. args.launcher,
  268. args.pw_jack,
  269. args.host,
  270. args.port,
  271. args.websocket_path,
  272. args.timeout,
  273. capture_ports=os.environ.get("MOD_RIGFORGE_CAPTURE_PORTS", "").split(","),
  274. playback_ports=os.environ.get("MOD_RIGFORGE_PLAYBACK_PORTS", "").split(","),
  275. state_path=args.state,
  276. )
  277. except (OSError, RuntimeError, ValueError) as error:
  278. print(f"ERROR: {error}", file=sys.stderr)
  279. return 1
  280. return 0
  281. if __name__ == "__main__":
  282. raise SystemExit(main())