|
|
@@ -2,191 +2,15 @@
|
|
|
"""Run mod-ui under pw-jack and keep its mod-host session active."""
|
|
|
|
|
|
import argparse
|
|
|
-import os
|
|
|
+import http.client
|
|
|
import signal
|
|
|
import subprocess
|
|
|
import sys
|
|
|
import time
|
|
|
from pathlib import Path
|
|
|
-
|
|
|
-import yaml
|
|
|
+from urllib.request import urlopen
|
|
|
|
|
|
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(
|
|
|
@@ -197,11 +21,14 @@ def run_service(
|
|
|
websocket_path,
|
|
|
timeout,
|
|
|
popen=subprocess.Popen,
|
|
|
- capture_ports=(),
|
|
|
- playback_ports=(),
|
|
|
- pw_link_runner=subprocess.run,
|
|
|
- state_path=None,
|
|
|
+ healthcheck=None,
|
|
|
):
|
|
|
+ """Launch mod-ui and retain the WebSocket session needed by mod-host.
|
|
|
+
|
|
|
+ This process supervises mod-ui and owns its session connection only. It
|
|
|
+ deliberately does not decide whether the pedalboard loaded or whether
|
|
|
+ PipeWire links are present; those are separate diagnostics.
|
|
|
+ """
|
|
|
process = popen([str(pw_jack), str(launcher)])
|
|
|
stopping = [False]
|
|
|
|
|
|
@@ -211,62 +38,53 @@ def run_service(
|
|
|
old_term = signal.signal(signal.SIGTERM, request_stop)
|
|
|
old_int = signal.signal(signal.SIGINT, request_stop)
|
|
|
client = ModUiWebSocketClient(host, port, websocket_path, timeout=2)
|
|
|
+ check_health = healthcheck or (lambda: check_http_health(host, port, 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:
|
|
|
+ if not stopping[0]:
|
|
|
+ deadline = time.monotonic() + timeout
|
|
|
+ while not stopping[0] and time.monotonic() < deadline:
|
|
|
+ if process.poll() is not None:
|
|
|
raise RuntimeError(
|
|
|
- f"mod-ui WebSocket did not become ready on {host}:{port}{websocket_path}"
|
|
|
+ f"mod-ui launcher exited with status {process.returncode}"
|
|
|
)
|
|
|
+ try:
|
|
|
+ if check_health():
|
|
|
+ break
|
|
|
+ except (OSError, TimeoutError, http.client.HTTPException):
|
|
|
+ pass
|
|
|
time.sleep(0.25)
|
|
|
+ else:
|
|
|
+ if not stopping[0]:
|
|
|
+ raise RuntimeError("mod-ui HTTP endpoint did not become ready")
|
|
|
+ print("mod-ui HTTP endpoint ready")
|
|
|
|
|
|
- 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")
|
|
|
+ next_connect_attempt = 0.0
|
|
|
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)
|
|
|
+ raise RuntimeError(
|
|
|
+ f"mod-ui launcher exited with status {process.returncode}"
|
|
|
+ )
|
|
|
+ try:
|
|
|
+ if client.connection is None:
|
|
|
+ if time.monotonic() < next_connect_attempt:
|
|
|
+ time.sleep(min(0.25, next_connect_attempt - time.monotonic()))
|
|
|
+ continue
|
|
|
+ try:
|
|
|
+ client.connect()
|
|
|
+ print("mod-ui WebSocket session active; keeping mod-host connected")
|
|
|
+ except (OSError, TimeoutError):
|
|
|
+ client.close()
|
|
|
+ client = ModUiWebSocketClient(
|
|
|
+ host, port, websocket_path, timeout=2
|
|
|
+ )
|
|
|
+ next_connect_attempt = time.monotonic() + 0.25
|
|
|
+ continue
|
|
|
+ client.serve_once(timeout=0.5)
|
|
|
+ except (OSError, TimeoutError, ConnectionError):
|
|
|
+ client.close()
|
|
|
+ client = ModUiWebSocketClient(host, port, websocket_path, timeout=2)
|
|
|
+ next_connect_attempt = time.monotonic() + 0.25
|
|
|
finally:
|
|
|
signal.signal(signal.SIGTERM, old_term)
|
|
|
signal.signal(signal.SIGINT, old_int)
|
|
|
@@ -280,6 +98,11 @@ def run_service(
|
|
|
process.wait()
|
|
|
|
|
|
|
|
|
+def check_http_health(host, port, timeout=2):
|
|
|
+ with urlopen(f"http://{host}:{port}/ping/", timeout=timeout) as response:
|
|
|
+ return 200 <= response.status < 400
|
|
|
+
|
|
|
+
|
|
|
def main(argv=None):
|
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
|
parser.add_argument("--launcher", type=Path, required=True)
|
|
|
@@ -288,11 +111,6 @@ def main(argv=None):
|
|
|
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)
|
|
|
@@ -308,9 +126,6 @@ def main(argv=None):
|
|
|
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)
|