| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173 |
- #!/usr/bin/env python3
- """Run mod-ui under pw-jack and keep its mod-host session active."""
- import argparse
- import os
- import signal
- import subprocess
- import sys
- import time
- from pathlib import Path
- from mod_ui_websocket import ModUiWebSocketClient
- from observe_pipewire import parse_pw_link_output
- def guitar_boundary_links(capture_ports, playback_ports):
- captures = [port.strip() for port in capture_ports if port.strip()]
- playbacks = [port.strip() for port in playback_ports if port.strip()]
- if not captures or not playbacks:
- raise RuntimeError("Rigforge guitar PipeWire boundary ports are not configured")
- return (
- (captures[0], "effect_0:input"),
- ("effect_1:out", playbacks[0]),
- )
- def wait_for_guitar_boundary_links(
- capture_ports,
- playback_ports,
- runner=subprocess.run,
- timeout=10,
- interval=0.2,
- clock=time.monotonic,
- sleep=time.sleep,
- ):
- expected = guitar_boundary_links(capture_ports, playback_ports)
- deadline = clock() + timeout
- missing = list(expected)
- last_error = None
- while True:
- try:
- result = runner(
- ["pw-link", "-l"],
- check=False,
- capture_output=True,
- text=True,
- )
- if result.returncode == 0:
- observed = parse_pw_link_output(result.stdout)
- missing = [edge for edge in expected if edge not in observed]
- if not missing:
- return
- last_error = None
- else:
- last_error = f"pw-link exited with status {result.returncode}"
- except (OSError, ValueError) as error:
- last_error = str(error)
- remaining = deadline - clock()
- if remaining <= 0:
- details = ", ".join(f"{source} -> {destination}" for source, destination in missing)
- message = f"mod-ui did not restore guitar PipeWire boundary links: {details}"
- if last_error:
- message += f" ({last_error})"
- raise RuntimeError(message)
- sleep(min(interval, remaining))
- def run_service(
- launcher,
- pw_jack,
- host,
- port,
- websocket_path,
- timeout,
- popen=subprocess.Popen,
- capture_ports=(),
- playback_ports=(),
- 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
- 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 "):
- break
- if time.monotonic() >= deadline:
- raise RuntimeError("mod-ui did not finish loading a pedalboard before timeout")
- if not stopping[0]:
- print("Verifying mod-ui guitar PipeWire boundary links")
- wait_for_guitar_boundary_links(
- capture_ports,
- playback_ports,
- runner=pw_link_runner,
- )
- 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}")
- client.serve_once(timeout=0.5)
- 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):
- 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:
- run_service(
- args.launcher,
- args.pw_jack,
- args.host,
- args.port,
- args.websocket_path,
- args.timeout,
- capture_ports=os.environ.get("MOD_RIGFORGE_CAPTURE_PORTS", "").split(","),
- playback_ports=os.environ.get("MOD_RIGFORGE_PLAYBACK_PORTS", "").split(","),
- )
- except (OSError, RuntimeError, ValueError) as error:
- print(f"ERROR: {error}", file=sys.stderr)
- return 1
- return 0
- if __name__ == "__main__":
- raise SystemExit(main())
|