wait_mod_host_ports.py 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138
  1. import argparse
  2. import subprocess
  3. import sys
  4. import time
  5. from pathlib import Path
  6. import yaml
  7. from validate_desired_state import validate_state
  8. def required_ports(state):
  9. routing = state["routing"]
  10. chain = routing["mod_host_chains"]["guitar"]
  11. mix = routing["mix"]
  12. boundary = state["deployment"]["mod_host_ports"]
  13. channels = boundary["channel_map"]
  14. return (
  15. {
  16. *(
  17. f"{boundary['input_source_name']}:capture_{channel}"
  18. for channel in channels
  19. ),
  20. *(
  21. f"{boundary['output_source_name']}:capture_{channel}"
  22. for channel in channels
  23. ),
  24. },
  25. {
  26. *(
  27. f"{boundary['input_sink_name']}:playback_{channel}"
  28. for channel in channels
  29. ),
  30. *(
  31. f"{boundary['output_sink_name']}:playback_{channel}"
  32. for channel in channels
  33. ),
  34. *(
  35. f"rigforge.direct-mix.input:playback_AUX{index}"
  36. for index in range(4)
  37. ),
  38. chain["mix_input"],
  39. mix["output_port"],
  40. },
  41. )
  42. def list_ports(direction, runner):
  43. result = runner(
  44. ["pw-link", direction],
  45. check=True,
  46. capture_output=True,
  47. text=True,
  48. timeout=2,
  49. )
  50. return {line.strip() for line in result.stdout.splitlines() if line.strip()}
  51. def wait_for_required_ports(
  52. state,
  53. timeout,
  54. runner=subprocess.run,
  55. sleeper=time.sleep,
  56. clock=time.monotonic,
  57. ):
  58. required_outputs, required_inputs = required_ports(state)
  59. deadline = clock() + timeout
  60. last_error = None
  61. while True:
  62. try:
  63. outputs = list_ports("-o", runner)
  64. inputs = list_ports("-i", runner)
  65. last_error = None
  66. missing_outputs = required_outputs - outputs
  67. missing_inputs = required_inputs - inputs
  68. if not missing_outputs and not missing_inputs:
  69. return
  70. except (OSError, subprocess.CalledProcessError, subprocess.TimeoutExpired) as error:
  71. last_error = str(error)
  72. missing_outputs = required_outputs
  73. missing_inputs = required_inputs
  74. if clock() >= deadline:
  75. details = (
  76. f"missing outputs={sorted(missing_outputs)}, "
  77. f"missing inputs={sorted(missing_inputs)}"
  78. )
  79. if last_error:
  80. details += f"; last pw-link error: {last_error}"
  81. raise RuntimeError(
  82. "PipeWire ports required by mod-host did not become ready before "
  83. f"the {timeout}s timeout ({details})"
  84. )
  85. sleeper(min(0.5, max(0.0, deadline - clock())))
  86. def main(argv=None):
  87. root = Path(__file__).resolve().parents[1]
  88. parser = argparse.ArgumentParser(
  89. description="Wait until PipeWire exposes the mod-host boundaries and mixer ports."
  90. )
  91. parser.add_argument("--state", type=Path, default=root / "config" / "desired-state.yaml")
  92. parser.add_argument("--timeout", type=float)
  93. args = parser.parse_args(argv)
  94. try:
  95. with args.state.open(encoding="utf-8") as stream:
  96. state = yaml.safe_load(stream)
  97. errors = validate_state(state)
  98. if errors:
  99. raise ValueError("invalid desired state: " + "; ".join(errors))
  100. timeout = (
  101. args.timeout
  102. if args.timeout is not None
  103. else state["deployment"]["mod_host"]["port_wait_timeout_seconds"]
  104. )
  105. if timeout <= 0:
  106. raise ValueError("--timeout must be positive")
  107. wait_for_required_ports(state, timeout)
  108. except (
  109. OSError,
  110. RuntimeError,
  111. ValueError,
  112. TypeError,
  113. KeyError,
  114. yaml.YAMLError,
  115. subprocess.CalledProcessError,
  116. ) as error:
  117. print(f"ERROR: {error}", file=sys.stderr)
  118. return 1
  119. print("Required PipeWire ports are ready for mod-host.")
  120. return 0
  121. if __name__ == "__main__":
  122. raise SystemExit(main())