run_mod_ui_service.py 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  1. #!/usr/bin/env python3
  2. """Run mod-ui under pw-jack and keep its mod-host session active."""
  3. import argparse
  4. import signal
  5. import subprocess
  6. import sys
  7. import time
  8. from pathlib import Path
  9. import yaml
  10. from mod_ui_websocket import ModUiWebSocketClient
  11. from observe_pipewire import list_ports, parse_pw_link_output
  12. def mod_ui_audio_boundary_links(state):
  13. chain = state["routing"]["mod_host_chains"]["guitar"]
  14. processors = chain["processors"]
  15. if not processors:
  16. raise ValueError("the mod-ui guitar chain has no processors")
  17. return (
  18. (chain["source_port"], processors[0]["input_port"]),
  19. (processors[-1]["output_port"], chain["mod_ui_output_port"]),
  20. )
  21. def ensure_mod_ui_audio_links(state, runner=subprocess.run):
  22. """Restore only the two board-to-boundary audio cables owned by mod-ui."""
  23. result = runner(
  24. ["pw-link", "-l"],
  25. check=True,
  26. capture_output=True,
  27. text=True,
  28. )
  29. links = parse_pw_link_output(result.stdout)
  30. expected = mod_ui_audio_boundary_links(state)
  31. missing = [edge for edge in expected if edge not in links]
  32. if not missing:
  33. return 0
  34. outputs = list_ports(runner, "-o")
  35. inputs = list_ports(runner, "-i")
  36. for source, destination in missing:
  37. if source not in outputs:
  38. raise RuntimeError(f"mod-ui audio source port is unavailable: {source}")
  39. if destination not in inputs:
  40. raise RuntimeError(f"mod-ui audio destination port is unavailable: {destination}")
  41. runner(
  42. ["pw-link", source, destination],
  43. check=True,
  44. capture_output=True,
  45. text=True,
  46. )
  47. print(f"Restored mod-ui audio cable: {source} -> {destination}")
  48. result = runner(
  49. ["pw-link", "-l"],
  50. check=True,
  51. capture_output=True,
  52. text=True,
  53. )
  54. remaining = [
  55. edge for edge in expected
  56. if edge not in parse_pw_link_output(result.stdout)
  57. ]
  58. if remaining:
  59. source, destination = remaining[0]
  60. raise RuntimeError(
  61. f"mod-ui audio cable is still missing after repair: {source} -> {destination}"
  62. )
  63. return len(missing)
  64. def run_service(
  65. launcher,
  66. pw_jack,
  67. host,
  68. port,
  69. websocket_path,
  70. timeout,
  71. state,
  72. popen=subprocess.Popen,
  73. pw_link_runner=subprocess.run,
  74. ):
  75. process = popen([str(pw_jack), str(launcher)])
  76. stopping = [False]
  77. def request_stop(_signum, _frame):
  78. stopping[0] = True
  79. old_term = signal.signal(signal.SIGTERM, request_stop)
  80. old_int = signal.signal(signal.SIGINT, request_stop)
  81. client = ModUiWebSocketClient(host, port, websocket_path, timeout=2)
  82. deadline = time.monotonic() + timeout
  83. repair_audio_links = False
  84. next_audio_link_repair = 0.0
  85. try:
  86. while not stopping[0]:
  87. if process.poll() is not None:
  88. raise RuntimeError(f"mod-ui launcher exited with status {process.returncode}")
  89. try:
  90. client.connect()
  91. break
  92. except OSError:
  93. if time.monotonic() >= deadline:
  94. raise RuntimeError(
  95. f"mod-ui WebSocket did not become ready on {host}:{port}{websocket_path}"
  96. )
  97. time.sleep(0.25)
  98. if not stopping[0]:
  99. print("Waiting for mod-ui to finish loading the current pedalboard")
  100. while not stopping[0]:
  101. if process.poll() is not None:
  102. raise RuntimeError(f"mod-ui launcher exited with status {process.returncode}")
  103. message = client.serve_once(timeout=0.5)
  104. if message and message.startswith("loading_end "):
  105. repair_audio_links = True
  106. break
  107. if time.monotonic() >= deadline:
  108. raise RuntimeError("mod-ui did not finish loading a pedalboard before timeout")
  109. print("mod-ui pedalboard loaded; keeping its mod-host session active")
  110. while not stopping[0]:
  111. if process.poll() is not None:
  112. raise RuntimeError(f"mod-ui launcher exited with status {process.returncode}")
  113. message = client.serve_once(timeout=0.5)
  114. if message and message.startswith("loading_end "):
  115. repair_audio_links = True
  116. next_audio_link_repair = 0.0
  117. if repair_audio_links and time.monotonic() >= next_audio_link_repair:
  118. try:
  119. repaired = ensure_mod_ui_audio_links(state, runner=pw_link_runner)
  120. if repaired == 0:
  121. print("mod-ui audio boundary cables are already connected")
  122. repair_audio_links = False
  123. except (OSError, subprocess.CalledProcessError, RuntimeError, ValueError) as error:
  124. print(f"ERROR: could not ensure mod-ui audio boundary cables: {error}", file=sys.stderr)
  125. next_audio_link_repair = time.monotonic() + 2.0
  126. finally:
  127. signal.signal(signal.SIGTERM, old_term)
  128. signal.signal(signal.SIGINT, old_int)
  129. client.close()
  130. if process.poll() is None:
  131. process.terminate()
  132. try:
  133. process.wait(timeout=5)
  134. except subprocess.TimeoutExpired:
  135. process.kill()
  136. process.wait()
  137. def main(argv=None):
  138. root = Path(__file__).resolve().parents[1]
  139. parser = argparse.ArgumentParser(description=__doc__)
  140. parser.add_argument("--launcher", type=Path, required=True)
  141. parser.add_argument("--pw-jack", type=Path, default=Path("/usr/bin/pw-jack"))
  142. parser.add_argument("--host", default="127.0.0.1")
  143. parser.add_argument("--port", type=int, default=8888)
  144. parser.add_argument("--websocket-path", default="/websocket")
  145. parser.add_argument("--timeout", type=float, default=60)
  146. args = parser.parse_args(argv)
  147. if not args.launcher.is_file():
  148. print(f"ERROR: mod-ui launcher is missing: {args.launcher}", file=sys.stderr)
  149. return 1
  150. if not args.pw_jack.is_file():
  151. print(f"ERROR: pw-jack is missing: {args.pw_jack}", file=sys.stderr)
  152. return 1
  153. try:
  154. with (root / "config" / "desired-state.yaml").open(encoding="utf-8") as stream:
  155. state = yaml.safe_load(stream)
  156. run_service(
  157. args.launcher,
  158. args.pw_jack,
  159. args.host,
  160. args.port,
  161. args.websocket_path,
  162. args.timeout,
  163. state,
  164. )
  165. except (OSError, RuntimeError, ValueError) as error:
  166. print(f"ERROR: {error}", file=sys.stderr)
  167. return 1
  168. return 0
  169. if __name__ == "__main__":
  170. raise SystemExit(main())