| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188 |
- #!/usr/bin/env python3
- """Run mod-ui under pw-jack and keep its mod-host session active."""
- import argparse
- import signal
- import subprocess
- import sys
- import time
- from pathlib import Path
- import yaml
- from mod_ui_websocket import ModUiWebSocketClient
- from observe_pipewire import list_ports, parse_pw_link_output
- def mod_ui_audio_boundary_links(state):
- chain = state["routing"]["mod_host_chains"]["guitar"]
- processors = chain["processors"]
- if not processors:
- raise ValueError("the mod-ui guitar chain has no processors")
- return (
- (chain["source_port"], processors[0]["input_port"]),
- (processors[-1]["output_port"], chain["mod_ui_output_port"]),
- )
- def ensure_mod_ui_audio_links(state, runner=subprocess.run):
- """Restore only the two board-to-boundary audio cables owned by mod-ui."""
- result = runner(
- ["pw-link", "-l"],
- check=True,
- capture_output=True,
- text=True,
- )
- links = parse_pw_link_output(result.stdout)
- expected = mod_ui_audio_boundary_links(state)
- missing = [edge for edge in expected if edge not in links]
- if not missing:
- return 0
- outputs = list_ports(runner, "-o")
- inputs = list_ports(runner, "-i")
- for source, destination in missing:
- if source not in outputs:
- raise RuntimeError(f"mod-ui audio source port is unavailable: {source}")
- if destination not in inputs:
- raise RuntimeError(f"mod-ui audio destination port is unavailable: {destination}")
- runner(
- ["pw-link", source, destination],
- check=True,
- capture_output=True,
- text=True,
- )
- print(f"Restored mod-ui audio cable: {source} -> {destination}")
- result = runner(
- ["pw-link", "-l"],
- check=True,
- capture_output=True,
- text=True,
- )
- remaining = [
- edge for edge in expected
- if edge not in parse_pw_link_output(result.stdout)
- ]
- if remaining:
- source, destination = remaining[0]
- raise RuntimeError(
- f"mod-ui audio cable is still missing after repair: {source} -> {destination}"
- )
- return len(missing)
- def run_service(
- launcher,
- pw_jack,
- host,
- port,
- websocket_path,
- timeout,
- state,
- popen=subprocess.Popen,
- pw_link_runner=subprocess.run,
- ):
- process = popen([str(pw_jack), str(launcher)])
- stopping = [False]
- def request_stop(_signum, _frame):
- stopping[0] = True
- old_term = signal.signal(signal.SIGTERM, request_stop)
- old_int = signal.signal(signal.SIGINT, request_stop)
- client = ModUiWebSocketClient(host, port, websocket_path, timeout=2)
- deadline = time.monotonic() + timeout
- repair_audio_links = False
- next_audio_link_repair = 0.0
- try:
- while not stopping[0]:
- if process.poll() is not None:
- raise RuntimeError(f"mod-ui launcher exited with status {process.returncode}")
- try:
- client.connect()
- break
- except OSError:
- if time.monotonic() >= deadline:
- raise RuntimeError(
- f"mod-ui WebSocket did not become ready on {host}:{port}{websocket_path}"
- )
- time.sleep(0.25)
- if not stopping[0]:
- print("Waiting for mod-ui to finish loading the current pedalboard")
- while not stopping[0]:
- if process.poll() is not None:
- raise RuntimeError(f"mod-ui launcher exited with status {process.returncode}")
- message = client.serve_once(timeout=0.5)
- if message and message.startswith("loading_end "):
- repair_audio_links = True
- break
- if time.monotonic() >= deadline:
- raise RuntimeError("mod-ui did not finish loading a pedalboard before timeout")
- print("mod-ui pedalboard loaded; keeping its mod-host session active")
- while not stopping[0]:
- if process.poll() is not None:
- raise RuntimeError(f"mod-ui launcher exited with status {process.returncode}")
- message = client.serve_once(timeout=0.5)
- if message and message.startswith("loading_end "):
- repair_audio_links = True
- next_audio_link_repair = 0.0
- if repair_audio_links and time.monotonic() >= next_audio_link_repair:
- try:
- repaired = ensure_mod_ui_audio_links(state, runner=pw_link_runner)
- if repaired == 0:
- print("mod-ui audio boundary cables are already connected")
- repair_audio_links = False
- except (OSError, subprocess.CalledProcessError, RuntimeError, ValueError) as error:
- print(f"ERROR: could not ensure mod-ui audio boundary cables: {error}", file=sys.stderr)
- next_audio_link_repair = time.monotonic() + 2.0
- finally:
- signal.signal(signal.SIGTERM, old_term)
- signal.signal(signal.SIGINT, old_int)
- client.close()
- if process.poll() is None:
- process.terminate()
- try:
- process.wait(timeout=5)
- except subprocess.TimeoutExpired:
- process.kill()
- process.wait()
- def main(argv=None):
- root = Path(__file__).resolve().parents[1]
- parser = argparse.ArgumentParser(description=__doc__)
- parser.add_argument("--launcher", type=Path, required=True)
- parser.add_argument("--pw-jack", type=Path, default=Path("/usr/bin/pw-jack"))
- parser.add_argument("--host", default="127.0.0.1")
- parser.add_argument("--port", type=int, default=8888)
- parser.add_argument("--websocket-path", default="/websocket")
- parser.add_argument("--timeout", type=float, default=60)
- args = parser.parse_args(argv)
- if not args.launcher.is_file():
- print(f"ERROR: mod-ui launcher is missing: {args.launcher}", file=sys.stderr)
- return 1
- if not args.pw_jack.is_file():
- print(f"ERROR: pw-jack is missing: {args.pw_jack}", file=sys.stderr)
- return 1
- try:
- with (root / "config" / "desired-state.yaml").open(encoding="utf-8") as stream:
- state = yaml.safe_load(stream)
- run_service(
- args.launcher,
- args.pw_jack,
- args.host,
- args.port,
- args.websocket_path,
- args.timeout,
- state,
- )
- except (OSError, RuntimeError, ValueError) as error:
- print(f"ERROR: {error}", file=sys.stderr)
- return 1
- return 0
- if __name__ == "__main__":
- raise SystemExit(main())
|