| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322 |
- #!/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
- import yaml
- from mod_ui_websocket import ModUiWebSocketClient
- from observe_pipewire import parse_pw_link_output
- PIPEWIRE_BOUNDARY_TIMEOUT = 35
- def load_mod_ui_board_links(state_path):
- state = yaml.safe_load(Path(state_path).read_text(encoding="utf-8"))
- processors = state["routing"]["mod_host_chains"]["voice"]["processors"]
- links = []
- for index in range(1, len(processors)):
- previous = processors[index - 1]
- current = processors[index]
- 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/{processors[-1]['mod_ui_instance'].removeprefix('/graph/')}/"
- f"{processors[-1]['output_port'].split(':', 1)[1]}",
- "/graph/playback_3",
- )
- )
- return tuple(links)
- def _resolve_host_alias(port):
- graph_path = port.removeprefix("/graph/")
- if "/" not in graph_path:
- if graph_path.startswith("playback_"):
- channel = int(graph_path.removeprefix("playback_"))
- if 1 <= channel <= 4:
- return (
- "rigforge.mod-host-output.playback:"
- f"playback_AUX{channel - 1}"
- )
- return port
- 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}"
- return port
- return port
- instance, symbol = graph_path.split("/", 1)
- instance_indices = {
- "rigforge_voice_high_pass": 2,
- "rigforge_voice_compressor": 3,
- "rigforge_voice_de_esser": 4,
- "rigforge_voice_reverb": 5,
- }
- if instance in instance_indices:
- effect_ports = {
- "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",
- },
- }
- resolved_symbol = effect_ports.get(instance, {}).get(symbol)
- return (
- f"effect_{instance_indices[instance]}:{resolved_symbol}"
- if resolved_symbol
- else port
- )
- return port
- 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 wait_for_graph_links(
- expected,
- resolve_host_port=lambda port: port,
- runner=subprocess.run,
- timeout=10,
- interval=0.2,
- clock=time.monotonic,
- sleep=time.sleep,
- ):
- expected = tuple(
- (
- resolve_host_port(source),
- resolve_host_port(destination),
- )
- for source, destination in expected
- )
- 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 declared pedalboard 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,
- state_path=None,
- ):
- 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)
- loading = False
- loaded_board = False
- 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_start "):
- loading = True
- loaded_board = False
- elif message and message.startswith("loading_end ") and loading:
- loaded_board = True
- loading = False
- if loaded_board:
- break
- if time.monotonic() >= deadline:
- raise RuntimeError("mod-ui did not finish loading a pedalboard before timeout")
- if not loaded_board and not stopping[0]:
- raise RuntimeError("mod-ui did not load its prepared Rigforge default pedalboard")
- 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,
- timeout=PIPEWIRE_BOUNDARY_TIMEOUT,
- )
- if state_path is not None:
- print("Verifying mod-ui voice chain links")
- wait_for_graph_links(
- load_mod_ui_board_links(state_path),
- resolve_host_port=_resolve_host_alias,
- runner=pw_link_runner,
- timeout=PIPEWIRE_BOUNDARY_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}")
- 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)
- parser.add_argument(
- "--state",
- type=Path,
- default=Path(__file__).resolve().parents[1] / "config" / "desired-state.yaml",
- )
- 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(","),
- state_path=args.state,
- )
- except (OSError, RuntimeError, ValueError) as error:
- print(f"ERROR: {error}", file=sys.stderr)
- return 1
- return 0
- if __name__ == "__main__":
- raise SystemExit(main())
|