run_mod_ui_service.py 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  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. from mod_ui_websocket import ModUiWebSocketClient
  11. from observe_pipewire import parse_pw_link_output
  12. PIPEWIRE_BOUNDARY_TIMEOUT = 35
  13. def guitar_boundary_links(capture_ports, playback_ports):
  14. captures = [port.strip() for port in capture_ports if port.strip()]
  15. playbacks = [port.strip() for port in playback_ports if port.strip()]
  16. if not captures or not playbacks:
  17. raise RuntimeError("Rigforge guitar PipeWire boundary ports are not configured")
  18. return (
  19. (captures[0], "effect_0:input"),
  20. ("effect_1:out", playbacks[0]),
  21. )
  22. def wait_for_guitar_boundary_links(
  23. capture_ports,
  24. playback_ports,
  25. runner=subprocess.run,
  26. timeout=10,
  27. interval=0.2,
  28. clock=time.monotonic,
  29. sleep=time.sleep,
  30. ):
  31. expected = guitar_boundary_links(capture_ports, playback_ports)
  32. deadline = clock() + timeout
  33. missing = list(expected)
  34. last_error = None
  35. while True:
  36. try:
  37. result = runner(
  38. ["pw-link", "-l"],
  39. check=False,
  40. capture_output=True,
  41. text=True,
  42. )
  43. if result.returncode == 0:
  44. observed = parse_pw_link_output(result.stdout)
  45. missing = [edge for edge in expected if edge not in observed]
  46. if not missing:
  47. return
  48. last_error = None
  49. else:
  50. last_error = f"pw-link exited with status {result.returncode}"
  51. except (OSError, ValueError) as error:
  52. last_error = str(error)
  53. remaining = deadline - clock()
  54. if remaining <= 0:
  55. details = ", ".join(f"{source} -> {destination}" for source, destination in missing)
  56. message = f"mod-ui did not restore guitar PipeWire boundary links: {details}"
  57. if last_error:
  58. message += f" ({last_error})"
  59. raise RuntimeError(message)
  60. sleep(min(interval, remaining))
  61. def run_service(
  62. launcher,
  63. pw_jack,
  64. host,
  65. port,
  66. websocket_path,
  67. timeout,
  68. popen=subprocess.Popen,
  69. capture_ports=(),
  70. playback_ports=(),
  71. pw_link_runner=subprocess.run,
  72. ):
  73. process = popen([str(pw_jack), str(launcher)])
  74. stopping = [False]
  75. def request_stop(_signum, _frame):
  76. stopping[0] = True
  77. old_term = signal.signal(signal.SIGTERM, request_stop)
  78. old_int = signal.signal(signal.SIGINT, request_stop)
  79. client = ModUiWebSocketClient(host, port, websocket_path, timeout=2)
  80. deadline = time.monotonic() + timeout
  81. try:
  82. while not stopping[0]:
  83. if process.poll() is not None:
  84. raise RuntimeError(f"mod-ui launcher exited with status {process.returncode}")
  85. try:
  86. client.connect()
  87. break
  88. except OSError:
  89. if time.monotonic() >= deadline:
  90. raise RuntimeError(
  91. f"mod-ui WebSocket did not become ready on {host}:{port}{websocket_path}"
  92. )
  93. time.sleep(0.25)
  94. if not stopping[0]:
  95. print("Waiting for mod-ui to finish loading the current pedalboard")
  96. while not stopping[0]:
  97. if process.poll() is not None:
  98. raise RuntimeError(f"mod-ui launcher exited with status {process.returncode}")
  99. message = client.serve_once(timeout=0.5)
  100. if message and message.startswith("loading_end "):
  101. break
  102. if time.monotonic() >= deadline:
  103. raise RuntimeError("mod-ui did not finish loading a pedalboard before timeout")
  104. if not stopping[0]:
  105. print("Verifying mod-ui guitar PipeWire boundary links")
  106. wait_for_guitar_boundary_links(
  107. capture_ports,
  108. playback_ports,
  109. runner=pw_link_runner,
  110. timeout=PIPEWIRE_BOUNDARY_TIMEOUT,
  111. )
  112. print("mod-ui pedalboard loaded; keeping its mod-host session active")
  113. while not stopping[0]:
  114. if process.poll() is not None:
  115. raise RuntimeError(f"mod-ui launcher exited with status {process.returncode}")
  116. client.serve_once(timeout=0.5)
  117. finally:
  118. signal.signal(signal.SIGTERM, old_term)
  119. signal.signal(signal.SIGINT, old_int)
  120. client.close()
  121. if process.poll() is None:
  122. process.terminate()
  123. try:
  124. process.wait(timeout=5)
  125. except subprocess.TimeoutExpired:
  126. process.kill()
  127. process.wait()
  128. def main(argv=None):
  129. parser = argparse.ArgumentParser(description=__doc__)
  130. parser.add_argument("--launcher", type=Path, required=True)
  131. parser.add_argument("--pw-jack", type=Path, default=Path("/usr/bin/pw-jack"))
  132. parser.add_argument("--host", default="127.0.0.1")
  133. parser.add_argument("--port", type=int, default=8888)
  134. parser.add_argument("--websocket-path", default="/websocket")
  135. parser.add_argument("--timeout", type=float, default=60)
  136. args = parser.parse_args(argv)
  137. if not args.launcher.is_file():
  138. print(f"ERROR: mod-ui launcher is missing: {args.launcher}", file=sys.stderr)
  139. return 1
  140. if not args.pw_jack.is_file():
  141. print(f"ERROR: pw-jack is missing: {args.pw_jack}", file=sys.stderr)
  142. return 1
  143. try:
  144. run_service(
  145. args.launcher,
  146. args.pw_jack,
  147. args.host,
  148. args.port,
  149. args.websocket_path,
  150. args.timeout,
  151. capture_ports=os.environ.get("MOD_RIGFORGE_CAPTURE_PORTS", "").split(","),
  152. playback_ports=os.environ.get("MOD_RIGFORGE_PLAYBACK_PORTS", "").split(","),
  153. )
  154. except (OSError, RuntimeError, ValueError) as error:
  155. print(f"ERROR: {error}", file=sys.stderr)
  156. return 1
  157. return 0
  158. if __name__ == "__main__":
  159. raise SystemExit(main())