#!/usr/bin/env python3 """Read-only diagnostics for the running mod-ui pedalboard and its PipeWire links.""" import argparse import json import subprocess import sys from pathlib import Path from urllib.parse import urlencode from urllib.request import urlopen import yaml from observe_pipewire import parse_pw_link_output from load_mod_ui_pedalboard import ( request_load_through_ui, wait_http, ) def load_mod_ui_board_links(state_path): state = yaml.safe_load(Path(state_path).read_text(encoding="utf-8")) chains = state["routing"]["mod_host_chains"] links = [] guitar_processors = chains["guitar"]["processors"] links.extend( ( ( "/graph/capture_1", f"/graph/{guitar_processors[0]['mod_ui_instance'].removeprefix('/graph/')}/" f"{guitar_processors[0]['input_port'].split(':', 1)[1]}", ), ( f"/graph/{guitar_processors[-1]['mod_ui_instance'].removeprefix('/graph/')}/" f"{guitar_processors[-1]['output_port'].split(':', 1)[1]}", "/graph/playback_1", ), ) ) for channel in (2, 4): links.append((f"/graph/capture_{channel}", f"/graph/playback_{channel}")) voice = chains["voice"] voice_processors = voice["processors"] links.append( ( f"/graph/{voice['mod_ui_input_port']}", f"/graph/{voice_processors[0]['mod_ui_instance'].removeprefix('/graph/')}/" f"{voice_processors[0]['input_port'].split(':', 1)[1]}", ) ) for previous, current in zip(voice_processors, voice_processors[1:]): links.append( ( f"/graph/{previous['mod_ui_instance'].removeprefix('/graph/')}/" f"{previous['output_port'].split(':', 1)[1]}", f"/graph/{current['mod_ui_instance'].removeprefix('/graph/')}/" f"{current['input_port'].split(':', 1)[1]}", ) ) links.append( ( f"/graph/{voice_processors[-1]['mod_ui_instance'].removeprefix('/graph/')}/" f"{voice_processors[-1]['output_port'].split(':', 1)[1]}", f"/graph/{voice['mod_ui_output_port']}", ) ) return tuple(links) def _resolve_host_alias(port): graph_path = port.removeprefix("/graph/") if "/" not in graph_path: if graph_path.startswith("capture_"): channel = int(graph_path.removeprefix("capture_")) if 1 <= channel <= 4: return f"rigforge.mod-host-input.capture:capture_AUX{channel - 1}" if graph_path.startswith("playback_"): channel = int(graph_path.removeprefix("playback_")) if 1 <= channel <= 4: return f"rigforge.mod-host-output.playback:playback_AUX{channel - 1}" return None instance, symbol = graph_path.split("/", 1) instance_indices = { "rigforge_nam": 0, "rigforge_ir": 1, "rigforge_voice_high_pass": 2, "rigforge_voice_compressor": 3, "rigforge_voice_de_esser": 4, "rigforge_voice_reverb": 5, } effect_ports = { "rigforge_nam": {"input": "input", "output": "output"}, "rigforge_ir": {"in": "in", "out": "out"}, "rigforge_voice_high_pass": {"in": "in", "out": "out"}, "rigforge_voice_compressor": {"in": "in", "out": "out"}, "rigforge_voice_de_esser": {"in": "in", "out": "out"}, "rigforge_voice_reverb": { "input_l": "lv2_audio_in_1", "output_l": "lv2_audio_out_1", "input_r": "lv2_audio_in_2", "output_r": "lv2_audio_out_2", }, } resolved_symbol = effect_ports.get(instance, {}).get(symbol) if instance in instance_indices and resolved_symbol: if instance == "rigforge_voice_reverb" and symbol in ("input_l", "output_l"): return f"effect_5:lv2_audio_{'in' if symbol == 'input_l' else 'out'}_1" return f"effect_{instance_indices[instance]}:{resolved_symbol}" return None def fetch_pedalboard_info(host, port, bundlepath, timeout=5): query = urlencode({"bundlepath": str(bundlepath)}) with urlopen(f"http://{host}:{port}/pedalboard/info/?{query}", timeout=timeout) as response: return json.loads(response.read().decode("utf-8")) def fetch_active_pedalboard_info(host, port, timeout=5): query = urlencode({"bundlepath": ""}) with urlopen( f"http://{host}:{port}/pedalboard/info/?{query}", timeout=timeout ) as response: return json.loads(response.read().decode("utf-8")) def inspect_runtime(state_path, host, port, runner=subprocess.run, timeout=5): state = yaml.safe_load(Path(state_path).read_text(encoding="utf-8")) mod_ui = state["deployment"]["mod_ui"] data_root = Path.home() / mod_ui["last_state_file"] try: last_state = json.loads(data_root.read_text(encoding="utf-8")) except (OSError, ValueError) as error: return 1, [f"Cannot read mod-ui last-state file {data_root}: {error}"] board_path = last_state.get("pedalboard") if not board_path or not Path(board_path).is_dir(): try: info = fetch_active_pedalboard_info(host, port, timeout=timeout) except Exception as error: return 1, [ f"No readable selected pedalboard in {data_root}", f"Cannot read active pedalboard metadata from mod-ui API: {error}", ] if not info.get("plugins"): return 1, [f"No selected pedalboard in {data_root}; mod-ui API reports no active plugins"] board_path = info.get("bundlepath") or "(active board reported by mod-ui API)" messages = [ f"Active pedalboard reported by mod-ui API: {board_path}", f"Bundle metadata: {info.get('title')!r}, " f"{len(info.get('plugins', []))} plugins, " f"{len(info.get('connections', []))} connections", ] else: try: info = fetch_pedalboard_info(host, port, board_path, timeout=timeout) except Exception as bundle_error: try: info = fetch_active_pedalboard_info(host, port, timeout=timeout) except Exception as api_error: return 1, [ f"Cannot read selected pedalboard metadata: {bundle_error}", f"Cannot read active pedalboard metadata from mod-ui API: {api_error}", ] if not info.get("plugins"): return 1, [ f"Cannot read selected pedalboard metadata: {bundle_error}", "mod-ui API reports no active plugins", ] board_path = info.get("bundlepath") or "(active board reported by mod-ui API)" messages = [ f"Active pedalboard reported by mod-ui API: {board_path}", f"Bundle metadata: {info.get('title')!r}, " f"{len(info.get('plugins', []))} plugins, " f"{len(info.get('connections', []))} connections", ] else: messages = [ f"Host-selected bundle: {board_path}", f"Bundle metadata: {info.get('title')!r}, " f"{len(info.get('plugins', []))} plugins, " f"{len(info.get('connections', []))} connections", ] failures = [] if not info.get("plugins"): failures.append("The selected bundle contains no plugins according to the mod-ui API") expected_links = load_mod_ui_board_links(state_path) pipewire = runner( ["pw-link", "-l"], check=False, capture_output=True, text=True, ) if pipewire.returncode != 0: failures.append(f"pw-link -l exited with status {pipewire.returncode}") else: observed = parse_pw_link_output(pipewire.stdout) missing = [ (source, target) for source, target in expected_links if ( not _resolve_host_alias(source) or not _resolve_host_alias(target) or ( _resolve_host_alias(source), _resolve_host_alias(target), ) not in observed ) ] if missing: failures.append( "Missing declared pedalboard PipeWire links: " + ", ".join(f"{src} -> {dst}" for src, dst in missing) ) else: messages.append( f"All {len(expected_links)} declared pedalboard links are present" ) return (1 if failures else 0), messages + [ f"ERROR: {failure}" for failure in failures ] def load_active_pedalboard(board_path, host, port, timeout=20): """Load through mod-ui's browser path and observe its real load lifecycle.""" wait_http(host, port, timeout) message = request_load_through_ui(host, port, Path(board_path), timeout) if not message.startswith("loading_start "): raise RuntimeError(f"unexpected pedalboard load response: {message}") def main(argv=None): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument( "--state", type=Path, default=Path(__file__).resolve().parents[1] / "config" / "desired-state.yaml", ) parser.add_argument("--host", default="127.0.0.1") parser.add_argument("--port", type=int, default=8888) parser.add_argument( "--load", action="store_true", help="load the last selected pedalboard through mod-ui's active session before checking", ) args = parser.parse_args(argv) try: if args.load: state = yaml.safe_load(args.state.read_text(encoding="utf-8")) last_state = ( Path.home() / state["deployment"]["mod_ui"]["last_state_file"] ) last_data = json.loads(last_state.read_text(encoding="utf-8")) board_path = last_data.get("pedalboard") if not board_path: raise ValueError("mod-ui last-state file has no selected pedalboard") load_active_pedalboard(board_path, args.host, args.port, timeout=20) status, messages = inspect_runtime(args.state, args.host, args.port) except (OSError, KeyError, TypeError, ValueError) as error: print(f"ERROR: {error}", file=sys.stderr) return 1 for message in messages: print(message) return status if __name__ == "__main__": raise SystemExit(main())