mod_ui_pipewire.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. """PipeWire link helpers used by the Rigforge mod-ui host integration."""
  2. import subprocess
  3. import time
  4. def boundary_connection(
  5. port_from,
  6. port_to,
  7. capture_ports,
  8. playback_ports,
  9. resolve_host_port,
  10. ):
  11. """Translate mod-ui graph boundary cables to concrete PipeWire ports."""
  12. capture_symbol = port_from.rsplit("/", 1)[-1]
  13. capture_port = capture_ports.get(capture_symbol)
  14. if capture_port:
  15. return capture_port, resolve_host_port(port_to)
  16. playback_symbol = port_to.rsplit("/", 1)[-1]
  17. playback_port = playback_ports.get(playback_symbol)
  18. if playback_port:
  19. return resolve_host_port(port_from), playback_port
  20. return None
  21. def _link_status(source, destination, runner):
  22. try:
  23. result = runner(
  24. ["pw-link", "-l"],
  25. check=False,
  26. capture_output=True,
  27. text=True,
  28. )
  29. except OSError:
  30. return None
  31. if result.returncode != 0:
  32. return None
  33. current_port = None
  34. for line in result.stdout.splitlines():
  35. if line.startswith(" |-> "):
  36. if current_port == source and line.removeprefix(" |-> ") == destination:
  37. return True
  38. elif line.startswith(" |<- "):
  39. if current_port == destination and line.removeprefix(" |<- ") == source:
  40. return True
  41. else:
  42. current_port = line.strip()
  43. return False
  44. def connect_link(
  45. source,
  46. destination,
  47. runner=subprocess.run,
  48. retries=0,
  49. retry_interval=0.1,
  50. ):
  51. for attempt in range(retries + 1):
  52. try:
  53. result = runner(
  54. ["pw-link", source, destination],
  55. check=False,
  56. capture_output=True,
  57. text=True,
  58. )
  59. except OSError:
  60. return False
  61. if result.returncode == 0 or _link_status(source, destination, runner) is True:
  62. return True
  63. if attempt < retries:
  64. time.sleep(retry_interval)
  65. return False
  66. def disconnect_link(source, destination, runner=subprocess.run):
  67. try:
  68. result = runner(
  69. ["pw-link", "-d", source, destination],
  70. check=False,
  71. capture_output=True,
  72. text=True,
  73. )
  74. except OSError:
  75. return False
  76. return result.returncode == 0 or _link_status(source, destination, runner) is False