diagnose_mod_ui.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  1. #!/usr/bin/env python3
  2. """Read-only diagnostics for the running mod-ui pedalboard and its PipeWire links."""
  3. import argparse
  4. import json
  5. import subprocess
  6. import sys
  7. from pathlib import Path
  8. from urllib.parse import urlencode
  9. from urllib.request import urlopen
  10. import yaml
  11. from observe_pipewire import parse_pw_link_output
  12. from load_mod_ui_pedalboard import (
  13. request_load_through_ui,
  14. wait_http,
  15. )
  16. def load_mod_ui_board_links(state_path):
  17. state = yaml.safe_load(Path(state_path).read_text(encoding="utf-8"))
  18. chains = state["routing"]["mod_host_chains"]
  19. links = []
  20. guitar_processors = chains["guitar"]["processors"]
  21. links.extend(
  22. (
  23. (
  24. "/graph/capture_1",
  25. f"/graph/{guitar_processors[0]['mod_ui_instance'].removeprefix('/graph/')}/"
  26. f"{guitar_processors[0]['input_port'].split(':', 1)[1]}",
  27. ),
  28. (
  29. f"/graph/{guitar_processors[-1]['mod_ui_instance'].removeprefix('/graph/')}/"
  30. f"{guitar_processors[-1]['output_port'].split(':', 1)[1]}",
  31. "/graph/playback_1",
  32. ),
  33. )
  34. )
  35. for channel in (2, 4):
  36. links.append((f"/graph/capture_{channel}", f"/graph/playback_{channel}"))
  37. voice = chains["voice"]
  38. voice_processors = voice["processors"]
  39. links.append(
  40. (
  41. f"/graph/{voice['mod_ui_input_port']}",
  42. f"/graph/{voice_processors[0]['mod_ui_instance'].removeprefix('/graph/')}/"
  43. f"{voice_processors[0]['input_port'].split(':', 1)[1]}",
  44. )
  45. )
  46. for previous, current in zip(voice_processors, voice_processors[1:]):
  47. links.append(
  48. (
  49. f"/graph/{previous['mod_ui_instance'].removeprefix('/graph/')}/"
  50. f"{previous['output_port'].split(':', 1)[1]}",
  51. f"/graph/{current['mod_ui_instance'].removeprefix('/graph/')}/"
  52. f"{current['input_port'].split(':', 1)[1]}",
  53. )
  54. )
  55. links.append(
  56. (
  57. f"/graph/{voice_processors[-1]['mod_ui_instance'].removeprefix('/graph/')}/"
  58. f"{voice_processors[-1]['output_port'].split(':', 1)[1]}",
  59. f"/graph/{voice['mod_ui_output_port']}",
  60. )
  61. )
  62. return tuple(links)
  63. def _resolve_host_alias(port):
  64. graph_path = port.removeprefix("/graph/")
  65. if "/" not in graph_path:
  66. if graph_path.startswith("capture_"):
  67. channel = int(graph_path.removeprefix("capture_"))
  68. if 1 <= channel <= 4:
  69. return f"rigforge.mod-host-input.capture:capture_AUX{channel - 1}"
  70. if graph_path.startswith("playback_"):
  71. channel = int(graph_path.removeprefix("playback_"))
  72. if 1 <= channel <= 4:
  73. return f"rigforge.mod-host-output.playback:playback_AUX{channel - 1}"
  74. return None
  75. instance, symbol = graph_path.split("/", 1)
  76. instance_indices = {
  77. "rigforge_nam": 0,
  78. "rigforge_ir": 1,
  79. "rigforge_voice_high_pass": 2,
  80. "rigforge_voice_compressor": 3,
  81. "rigforge_voice_de_esser": 4,
  82. "rigforge_voice_reverb": 5,
  83. }
  84. effect_ports = {
  85. "rigforge_nam": {"input": "input", "output": "output"},
  86. "rigforge_ir": {"in": "in", "out": "out"},
  87. "rigforge_voice_high_pass": {"in": "in", "out": "out"},
  88. "rigforge_voice_compressor": {"in": "in", "out": "out"},
  89. "rigforge_voice_de_esser": {"in": "in", "out": "out"},
  90. "rigforge_voice_reverb": {
  91. "input_l": "lv2_audio_in_1",
  92. "output_l": "lv2_audio_out_1",
  93. },
  94. }
  95. resolved_symbol = effect_ports.get(instance, {}).get(symbol)
  96. if instance in instance_indices and resolved_symbol:
  97. if instance == "rigforge_voice_reverb" and symbol in ("input_l", "output_l"):
  98. return f"effect_5:lv2_audio_{'in' if symbol == 'input_l' else 'out'}_1"
  99. return f"effect_{instance_indices[instance]}:{resolved_symbol}"
  100. return None
  101. def fetch_pedalboard_info(host, port, bundlepath, timeout=5):
  102. query = urlencode({"bundlepath": str(bundlepath)})
  103. with urlopen(f"http://{host}:{port}/pedalboard/info/?{query}", timeout=timeout) as response:
  104. return json.loads(response.read().decode("utf-8"))
  105. def fetch_active_pedalboard_info(host, port, timeout=5):
  106. query = urlencode({"bundlepath": ""})
  107. with urlopen(
  108. f"http://{host}:{port}/pedalboard/info/?{query}", timeout=timeout
  109. ) as response:
  110. return json.loads(response.read().decode("utf-8"))
  111. def inspect_runtime(state_path, host, port, runner=subprocess.run, timeout=5):
  112. state = yaml.safe_load(Path(state_path).read_text(encoding="utf-8"))
  113. mod_ui = state["deployment"]["mod_ui"]
  114. data_root = Path.home() / mod_ui["last_state_file"]
  115. try:
  116. last_state = json.loads(data_root.read_text(encoding="utf-8"))
  117. except (OSError, ValueError) as error:
  118. return 1, [f"Cannot read mod-ui last-state file {data_root}: {error}"]
  119. board_path = last_state.get("pedalboard")
  120. if not board_path or not Path(board_path).is_dir():
  121. try:
  122. info = fetch_active_pedalboard_info(host, port, timeout=timeout)
  123. except Exception as error:
  124. return 1, [
  125. f"No readable selected pedalboard in {data_root}",
  126. f"Cannot read active pedalboard metadata from mod-ui API: {error}",
  127. ]
  128. if not info.get("plugins"):
  129. return 1, [f"No selected pedalboard in {data_root}; mod-ui API reports no active plugins"]
  130. board_path = info.get("bundlepath") or "(active board reported by mod-ui API)"
  131. messages = [
  132. f"Active pedalboard reported by mod-ui API: {board_path}",
  133. f"Bundle metadata: {info.get('title')!r}, "
  134. f"{len(info.get('plugins', []))} plugins, "
  135. f"{len(info.get('connections', []))} connections",
  136. ]
  137. else:
  138. try:
  139. info = fetch_pedalboard_info(host, port, board_path, timeout=timeout)
  140. except Exception as bundle_error:
  141. try:
  142. info = fetch_active_pedalboard_info(host, port, timeout=timeout)
  143. except Exception as api_error:
  144. return 1, [
  145. f"Cannot read selected pedalboard metadata: {bundle_error}",
  146. f"Cannot read active pedalboard metadata from mod-ui API: {api_error}",
  147. ]
  148. if not info.get("plugins"):
  149. return 1, [
  150. f"Cannot read selected pedalboard metadata: {bundle_error}",
  151. "mod-ui API reports no active plugins",
  152. ]
  153. board_path = info.get("bundlepath") or "(active board reported by mod-ui API)"
  154. messages = [
  155. f"Active pedalboard reported by mod-ui API: {board_path}",
  156. f"Bundle metadata: {info.get('title')!r}, "
  157. f"{len(info.get('plugins', []))} plugins, "
  158. f"{len(info.get('connections', []))} connections",
  159. ]
  160. else:
  161. messages = [
  162. f"Host-selected bundle: {board_path}",
  163. f"Bundle metadata: {info.get('title')!r}, "
  164. f"{len(info.get('plugins', []))} plugins, "
  165. f"{len(info.get('connections', []))} connections",
  166. ]
  167. failures = []
  168. if not info.get("plugins"):
  169. failures.append("The selected bundle contains no plugins according to the mod-ui API")
  170. expected_links = load_mod_ui_board_links(state_path)
  171. pipewire = runner(
  172. ["pw-link", "-l"],
  173. check=False,
  174. capture_output=True,
  175. text=True,
  176. )
  177. if pipewire.returncode != 0:
  178. failures.append(f"pw-link -l exited with status {pipewire.returncode}")
  179. else:
  180. observed = parse_pw_link_output(pipewire.stdout)
  181. missing = [
  182. (source, target)
  183. for source, target in expected_links
  184. if (
  185. not _resolve_host_alias(source)
  186. or not _resolve_host_alias(target)
  187. or (
  188. _resolve_host_alias(source),
  189. _resolve_host_alias(target),
  190. )
  191. not in observed
  192. )
  193. ]
  194. if missing:
  195. failures.append(
  196. "Missing declared pedalboard PipeWire links: "
  197. + ", ".join(f"{src} -> {dst}" for src, dst in missing)
  198. )
  199. else:
  200. messages.append(
  201. f"All {len(expected_links)} declared pedalboard links are present"
  202. )
  203. return (1 if failures else 0), messages + [
  204. f"ERROR: {failure}" for failure in failures
  205. ]
  206. def load_active_pedalboard(board_path, host, port, timeout=20):
  207. """Load through mod-ui's browser path and observe its real load lifecycle."""
  208. wait_http(host, port, timeout)
  209. message = request_load_through_ui(host, port, Path(board_path), timeout)
  210. if not message.startswith("loading_start "):
  211. raise RuntimeError(f"unexpected pedalboard load response: {message}")
  212. def main(argv=None):
  213. parser = argparse.ArgumentParser(description=__doc__)
  214. parser.add_argument(
  215. "--state",
  216. type=Path,
  217. default=Path(__file__).resolve().parents[1] / "config" / "desired-state.yaml",
  218. )
  219. parser.add_argument("--host", default="127.0.0.1")
  220. parser.add_argument("--port", type=int, default=8888)
  221. parser.add_argument(
  222. "--load",
  223. action="store_true",
  224. help="load the last selected pedalboard through mod-ui's active session before checking",
  225. )
  226. args = parser.parse_args(argv)
  227. try:
  228. if args.load:
  229. state = yaml.safe_load(args.state.read_text(encoding="utf-8"))
  230. last_state = (
  231. Path.home() / state["deployment"]["mod_ui"]["last_state_file"]
  232. )
  233. last_data = json.loads(last_state.read_text(encoding="utf-8"))
  234. board_path = last_data.get("pedalboard")
  235. if not board_path:
  236. raise ValueError("mod-ui last-state file has no selected pedalboard")
  237. load_active_pedalboard(board_path, args.host, args.port, timeout=20)
  238. status, messages = inspect_runtime(args.state, args.host, args.port)
  239. except (OSError, KeyError, TypeError, ValueError) as error:
  240. print(f"ERROR: {error}", file=sys.stderr)
  241. return 1
  242. for message in messages:
  243. print(message)
  244. return status
  245. if __name__ == "__main__":
  246. raise SystemExit(main())