audio_bridge.py 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. """Virtual audio bridge for feeding generated speech into Chrome's mic.
  2. Linux: pactl creates a null-sink plus a virtual source on the sink's monitor; callers set
  3. ``PULSE_SOURCE=<source_name>`` in Chrome's env. macOS: only verifies BlackHole 2ch is installed
  4. (the default-input switch is left to the user). Windows: unsupported.
  5. """
  6. from __future__ import annotations
  7. import contextlib
  8. import platform
  9. import subprocess
  10. from typing import Optional
  11. _BLACKHOLE_DEVICE = "BlackHole 2ch"
  12. def _pactl(*args: str, check: bool) -> subprocess.CompletedProcess:
  13. return subprocess.run(["pactl", *args], check=check, capture_output=True, text=True, encoding='utf-8',
  14. errors='replace', stdin=subprocess.DEVNULL)
  15. class AudioBridge:
  16. """Virtual audio device for Chrome fake-mic input: ``setup()`` before launch, ``teardown()`` after."""
  17. def __init__(self, name_prefix: str = "hermes_meet") -> None:
  18. self._name_prefix = name_prefix
  19. self._platform: Optional[str] = None
  20. self._device_name: Optional[str] = None
  21. self._write_target: Optional[str] = None
  22. self._module_ids: list[int] = []
  23. def _ready(self, value: Optional[str]) -> str:
  24. if not value:
  25. raise RuntimeError("AudioBridge not set up yet")
  26. return value
  27. device_name = property(lambda self: self._ready(self._device_name))
  28. write_target = property(lambda self: self._ready(self._write_target))
  29. def setup(self) -> dict:
  30. """Provision the device; raises RuntimeError on unsupported platforms or missing tools."""
  31. system = platform.system()
  32. impl = {"Linux": self._setup_linux, "Darwin": self._setup_darwin}.get(system)
  33. if impl is None:
  34. raise RuntimeError("windows not supported in v2" if system == "Windows"
  35. else f"unsupported platform: {system}")
  36. return impl()
  37. def teardown(self) -> None:
  38. """Release the virtual audio device. Idempotent; never raises."""
  39. for mod_id in reversed(self._module_ids): # linux only; virtual-source before null-sink
  40. with contextlib.suppress(Exception):
  41. _pactl("unload-module", str(mod_id), check=False)
  42. self._module_ids = []
  43. def _finish(self, tag: str, device: str, write_target: str, module_ids: list[int]) -> dict:
  44. self._platform = tag
  45. self._device_name = device
  46. self._write_target = write_target
  47. self._module_ids = module_ids
  48. return {"platform": tag, "device_name": device, "sample_rate": 48000, "channels": 2,
  49. "module_ids": list(module_ids), "write_target": write_target}
  50. def _setup_linux(self) -> dict:
  51. sink_name = f"{self._name_prefix}_sink"
  52. src_name = f"{self._name_prefix}_src"
  53. try:
  54. sink_out = _pactl(
  55. "load-module", "module-null-sink", f"sink_name={sink_name}",
  56. "sink_properties=device.description=HermesMeetSink", check=True)
  57. except FileNotFoundError as exc:
  58. raise RuntimeError("pactl not found — install PulseAudio/pipewire-pulse") from exc
  59. except subprocess.CalledProcessError as exc:
  60. raise RuntimeError(f"pactl load-module null-sink failed: {exc.stderr or exc}") from exc
  61. sink_mod_id = self._parse_module_id(sink_out.stdout)
  62. try:
  63. src_out = _pactl(
  64. "load-module", "module-virtual-source", f"source_name={src_name}",
  65. f"master={sink_name}.monitor", check=True)
  66. except subprocess.CalledProcessError as exc:
  67. # Roll back the null-sink we just created so we don't leak it.
  68. _pactl("unload-module", str(sink_mod_id), check=False)
  69. raise RuntimeError(f"pactl load-module virtual-source failed: {exc.stderr or exc}") from exc
  70. return self._finish("linux", src_name, sink_name, [sink_mod_id, self._parse_module_id(src_out.stdout)])
  71. def _setup_darwin(self) -> dict:
  72. try:
  73. out = subprocess.check_output(["system_profiler", "SPAudioDataType"], text=True, encoding='utf-8',
  74. errors='replace', stderr=subprocess.STDOUT, stdin=subprocess.DEVNULL)
  75. except FileNotFoundError as exc:
  76. raise RuntimeError("system_profiler not found (macOS-only command)") from exc
  77. except subprocess.CalledProcessError as exc:
  78. raise RuntimeError(f"system_profiler failed: {exc.output}") from exc
  79. if "BlackHole" not in out:
  80. raise RuntimeError("BlackHole virtual audio device not installed. "
  81. "Install via: brew install blackhole-2ch")
  82. return self._finish("darwin", _BLACKHOLE_DEVICE, _BLACKHOLE_DEVICE, [])
  83. @staticmethod
  84. def _parse_module_id(stdout: str) -> int:
  85. """pactl load-module prints the new module ID as the last token of its first line."""
  86. text = (stdout or "").strip()
  87. if not text:
  88. raise RuntimeError("pactl load-module returned empty stdout")
  89. token = text.splitlines()[0].strip().split()[-1]
  90. try:
  91. return int(token)
  92. except ValueError as exc:
  93. raise RuntimeError(f"could not parse pactl module id from: {stdout!r}") from exc