run_mod_ui_service.py 6.0 KB

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