diagnose_mod_ui.py 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  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. processors = state["routing"]["mod_host_chains"]["voice"]["processors"]
  19. links = []
  20. for previous, current in zip(processors, processors[1:]):
  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("capture_"):
  41. channel = int(graph_path.removeprefix("capture_"))
  42. if 1 <= channel <= 4:
  43. return (
  44. "rigforge.mod-host-input.capture:"
  45. f"capture_AUX{channel - 1}"
  46. )
  47. return port
  48. if graph_path.startswith("playback_"):
  49. channel = int(graph_path.removeprefix("playback_"))
  50. if 1 <= channel <= 4:
  51. return (
  52. "rigforge.mod-host-output.playback:"
  53. f"playback_AUX{channel - 1}"
  54. )
  55. return port
  56. return port
  57. instance, symbol = graph_path.split("/", 1)
  58. instance_indices = {
  59. "rigforge_nam": 0,
  60. "rigforge_ir": 1,
  61. "rigforge_voice_high_pass": 2,
  62. "rigforge_voice_compressor": 3,
  63. "rigforge_voice_de_esser": 4,
  64. "rigforge_voice_reverb": 5,
  65. }
  66. effect_ports = {
  67. "rigforge_nam": {"input": "input", "output": "output"},
  68. "rigforge_ir": {"in": "in", "out": "out"},
  69. "rigforge_voice_high_pass": {"in": "in", "out": "out"},
  70. "rigforge_voice_compressor": {"in": "in", "out": "out"},
  71. "rigforge_voice_de_esser": {"in": "in", "out": "out"},
  72. "rigforge_voice_reverb": {
  73. "input_l": "lv2_audio_in_1",
  74. "output_l": "lv2_audio_out_1",
  75. },
  76. }
  77. resolved_symbol = effect_ports.get(instance, {}).get(symbol)
  78. if instance in instance_indices and resolved_symbol:
  79. port_aliases = {
  80. ("rigforge_nam", "input"): "input",
  81. ("rigforge_nam", "output"): "output",
  82. ("rigforge_ir", "in"): "in",
  83. ("rigforge_ir", "out"): "out",
  84. }
  85. alias = port_aliases.get((instance, symbol), resolved_symbol)
  86. return f"effect_{instance_indices[instance]}:{alias}"
  87. return port
  88. def fetch_pedalboard_info(host, port, bundlepath, timeout=5):
  89. query = urlencode({"bundlepath": str(bundlepath)})
  90. with urlopen(f"http://{host}:{port}/pedalboard/info/?{query}", timeout=timeout) as response:
  91. return json.loads(response.read().decode("utf-8"))
  92. def fetch_active_pedalboard_info(host, port, timeout=5):
  93. query = urlencode({"bundlepath": ""})
  94. with urlopen(
  95. f"http://{host}:{port}/pedalboard/info/?{query}", timeout=timeout
  96. ) as response:
  97. return json.loads(response.read().decode("utf-8"))
  98. def inspect_runtime(state_path, host, port, runner=subprocess.run, timeout=5):
  99. state = yaml.safe_load(Path(state_path).read_text(encoding="utf-8"))
  100. mod_ui = state["deployment"]["mod_ui"]
  101. data_root = Path.home() / mod_ui["last_state_file"]
  102. try:
  103. last_state = json.loads(data_root.read_text(encoding="utf-8"))
  104. except (OSError, ValueError) as error:
  105. return 1, [f"Cannot read mod-ui last-state file {data_root}: {error}"]
  106. board_path = last_state.get("pedalboard")
  107. if not board_path:
  108. try:
  109. info = fetch_active_pedalboard_info(host, port, timeout=timeout)
  110. except Exception as error:
  111. return 1, [
  112. f"No selected pedalboard in {data_root}",
  113. f"Cannot read active pedalboard metadata from mod-ui API: {error}",
  114. ]
  115. if not info.get("plugins"):
  116. return 1, [f"No selected pedalboard in {data_root}; mod-ui API reports no active plugins"]
  117. board_path = info.get("bundlepath") or "(active board reported by mod-ui API)"
  118. messages = [
  119. f"Active pedalboard reported by mod-ui API: {board_path}",
  120. f"Bundle metadata: {info.get('title')!r}, "
  121. f"{len(info.get('plugins', []))} plugins, "
  122. f"{len(info.get('connections', []))} connections",
  123. ]
  124. else:
  125. try:
  126. info = fetch_pedalboard_info(host, port, board_path, timeout=timeout)
  127. except Exception as error:
  128. return 1, [f"Cannot read pedalboard metadata from mod-ui API: {error}"]
  129. messages = [
  130. f"Host-selected bundle: {board_path}",
  131. f"Bundle metadata: {info.get('title')!r}, "
  132. f"{len(info.get('plugins', []))} plugins, "
  133. f"{len(info.get('connections', []))} connections",
  134. ]
  135. failures = []
  136. if not info.get("plugins"):
  137. failures.append("The selected bundle contains no plugins according to the mod-ui API")
  138. expected_links = load_mod_ui_board_links(state_path)
  139. pipewire = runner(
  140. ["pw-link", "-l"],
  141. check=False,
  142. capture_output=True,
  143. text=True,
  144. )
  145. if pipewire.returncode != 0:
  146. failures.append(f"pw-link -l exited with status {pipewire.returncode}")
  147. else:
  148. observed = parse_pw_link_output(pipewire.stdout)
  149. missing = [
  150. (source, target)
  151. for source, target in expected_links
  152. if (
  153. _resolve_host_alias(source),
  154. _resolve_host_alias(target),
  155. )
  156. not in observed
  157. ]
  158. if missing:
  159. failures.append(
  160. "Missing declared pedalboard PipeWire links: "
  161. + ", ".join(f"{src} -> {dst}" for src, dst in missing)
  162. )
  163. else:
  164. messages.append(f"All {len(expected_links)} declared voice-chain links are present")
  165. return (1 if failures else 0), messages + [
  166. f"ERROR: {failure}" for failure in failures
  167. ]
  168. def load_active_pedalboard(board_path, host, port, timeout=20):
  169. """Load through mod-ui's browser path and observe its real load lifecycle."""
  170. wait_http(host, port, timeout)
  171. message = request_load_through_ui(host, port, Path(board_path), timeout)
  172. if not message.startswith("loading_start "):
  173. raise RuntimeError(f"unexpected pedalboard load response: {message}")
  174. def main(argv=None):
  175. parser = argparse.ArgumentParser(description=__doc__)
  176. parser.add_argument(
  177. "--state",
  178. type=Path,
  179. default=Path(__file__).resolve().parents[1] / "config" / "desired-state.yaml",
  180. )
  181. parser.add_argument("--host", default="127.0.0.1")
  182. parser.add_argument("--port", type=int, default=8888)
  183. parser.add_argument(
  184. "--load",
  185. action="store_true",
  186. help="load the last selected pedalboard through mod-ui's active session before checking",
  187. )
  188. args = parser.parse_args(argv)
  189. try:
  190. if args.load:
  191. state = yaml.safe_load(args.state.read_text(encoding="utf-8"))
  192. last_state = (
  193. Path.home() / state["deployment"]["mod_ui"]["last_state_file"]
  194. )
  195. last_data = json.loads(last_state.read_text(encoding="utf-8"))
  196. board_path = last_data.get("pedalboard")
  197. if not board_path:
  198. raise ValueError("mod-ui last-state file has no selected pedalboard")
  199. load_active_pedalboard(board_path, args.host, args.port, timeout=20)
  200. status, messages = inspect_runtime(args.state, args.host, args.port)
  201. except (OSError, KeyError, TypeError, ValueError) as error:
  202. print(f"ERROR: {error}", file=sys.stderr)
  203. return 1
  204. for message in messages:
  205. print(message)
  206. return status
  207. if __name__ == "__main__":
  208. raise SystemExit(main())