diagnose_mod_ui.py 7.3 KB

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