Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

13.0 KB
Raw Blame
"""Runtime audio-device hot-swap watcher (BUG-102).

PortAudio freezes its device table at initialization, so a process that runs
for hours never sees a headset being plugged in or pulled out. Every layer
above therefore degrades at once: the persistent output stream keeps writing
to a vanished or no-longer-default device (blocking writes, seconds-long
stalls — perceived as "everything lags"), and the microphone watchdog can
only re-open devices from the stale table, so it retries a dead endpoint
forever and can never find the newly arrived one.

This module owns the ONE cross-platform cure, in three parts:

1. **Detection** — poll the out-of-process device probe
   (`dodaios.audio.devices._query_tables_fresh`), which is safe while this
   process holds live streams, and compare a name-based topology signature.
   No OS-specific listener; Windows, macOS, and Linux share the poller.
2. **Coordinated refresh** — when a topology change persists and native
   playback is idle: discard every
   registered capture stream and the player's output stream, re-initialize
   PortAudio under the established re-init lock (safe ONLY with no live
   streams — the BUG-058 native-fault hazard), and invalidate every resolve
   cache. The existing self-healers do the rest: the mic stall watchdog
   reopens against the now-fresh table within ~a second, and the player
   reopens lazily on the next playback.
3. **The open guard** — every native stream open holds ``stream_open_guard``
   so no stream can come to life BETWEEN terminate and initialize.

Everything degrades safely: a failed probe means "no judgment", a failed
stream close prevents re-initialization, and a headless install without
sounddevice never gets past the first probe. Nothing here runs on the boot
critical path (AP-26) — the watcher starts after honest voice readiness.
"""

from __future__ import annotations

import asyncio
import contextlib
import logging
import threading
import weakref
from collections.abc import Callable, Iterator
from typing import Any

log = logging.getLogger("dodaios.audio.topology")

# Serializes native stream opens against the PortAudio re-init window. An
# RLock so a guarded open path may nest (candidate loops re-enter freely).
_OPEN_LOCK = threading.RLock()
# A cancelled asyncio waiter can leave a native output worker running. Count
# the synchronous operations themselves, including open-to-publication gaps.
_native_operations = 0
# Keep handles until close succeeds, including streams awaiting publication or
# asynchronous disposal. Losing the Python owner does not close a native handle.
_native_streams: dict[int, Any] = {}

# Live MicrophoneCapture instances that a refresh must quiesce. WeakSet: a
# capture that forgot to unregister can never be kept alive by the watcher.
# The lock covers every add/discard/snapshot — the event loop registers
# captures while the refresh worker thread iterates, and a bare WeakSet is
# not safe against that ("set changed size during iteration").
_captures_lock = threading.Lock()
_captures: weakref.WeakSet[Any] = weakref.WeakSet()

# Steady-state cadence. Each probe spawns a full Python + PortAudio subprocess,
# so the former 5 s poll cost 12 interpreter cold starts per MINUTE for the
# entire life of the app — ~4-6 % of a core on the fastest supported machine and
# 20-50 % of one core on the hardware the project actually targets (an
# Intel-2019 Mac, a dual-core VPS), competing directly with wake inference.
# Hot-plug reaction does not suffer: ``request_topology_probe`` fires an
# immediate probe from the signals that really mean "a device vanished".
DEFAULT_POLL_S = 30.0
# One burst of CoreAudio/WASAPI events accompanies a single physical plug;
# wait this long after the first divergent signature so the refresh runs once
# against the settled topology instead of once per event.
_SETTLE_S = 1.5
# Shortest gap between two probes when device-loss signals ask for one early.
# A mic that keeps stalling or failing to open fires those signals back to
# back; without a floor every one of them started another probe process.
MIN_PROBE_GAP_S = 10.0


# Set while a watcher runs, so a device-loss signal can skip the poll wait.
_probe_request: asyncio.Event | None = None
_probe_loop: asyncio.AbstractEventLoop | None = None


def request_topology_probe() -> None:
    """Ask the watcher to probe NOW instead of at the next poll.

    Call this from the signals that actually mean "a device may have vanished"
    — a mic stall and a failed stream open — so raising the steady-state poll
    interval costs nothing in hot-plug responsiveness. Safe from any thread,
    and a silent no-op when no watcher is running (tests, headless).
    """
    event, loop = _probe_request, _probe_loop
    if event is None or loop is None or loop.is_closed():
        return
    with contextlib.suppress(RuntimeError):  # loop shutting down
        loop.call_soon_threadsafe(event.set)


def stream_open_guard() -> threading.RLock:
    """Lock every native PortAudio stream open must hold (``with ...():``)."""
    return _OPEN_LOCK


@contextlib.contextmanager
def native_stream_operation() -> Iterator[None]:
    """Keep PortAudio alive until a synchronous native operation has exited.

    Only admission holds the open lock. Playback and abort must remain able
    to run concurrently, and a topology refresh defers instead of waiting on
    a potentially wedged native write.
    """
    global _native_operations
    with _OPEN_LOCK:
        _native_operations += 1
    try:
        yield
    finally:
        with _OPEN_LOCK:
            _native_operations -= 1


def register_capture(capture: Any) -> None:
    with _captures_lock:
        _captures.add(capture)


def register_native_stream(stream: Any) -> None:
    """Called under the open guard as soon as PortAudio returns a handle."""
    with _OPEN_LOCK:
        _native_streams[id(stream)] = stream


def unregister_native_stream(stream: Any) -> None:
    """Remove a handle only after its native close completed successfully."""
    with _OPEN_LOCK:
        _native_streams.pop(id(stream), None)


def unregister_capture(capture: Any) -> None:
    with _captures_lock:
        _captures.discard(capture)


def topology_signature(tables: Any) -> str | None:
    """Reduce a device-table snapshot to a comparable identity string.

    Built from device NAMES with their I/O roles plus the default pair —
    never from indices, which shuffle on every enumeration and would cause
    refresh churn without any physical change.
    """
    if not tables:
        return None
    devices, _hostapis, defaults = tables
    entries = []
    for device in devices:
        has_input = int(device.get("max_input_channels") or 0) > 0
        has_output = int(device.get("max_output_channels") or 0) > 0
        if not (has_input or has_output):
            continue
        name = " ".join(str(device.get("name", "")).split()).casefold()
        entries.append(f"{name}|{int(has_input)}{int(has_output)}")

    def _default_name(index: int | None) -> str:
        if index is None or not 0 <= index < len(devices):
            return ""
        return " ".join(str(devices[index].get("name", "")).split()).casefold()

    return (
        ";".join(sorted(entries))
        + f"##in={_default_name(defaults[0])}##out={_default_name(defaults[1])}"
    )


def _fresh_signature() -> str | None:
    try:
        import sounddevice  # noqa: F401, PLC0415 — headless short-circuit
    except Exception:  # noqa: BLE001 — no audio stack → never spawn the probe
        return None
    from dodaios.audio.devices import _query_tables_fresh

    return topology_signature(_query_tables_fresh())


def refresh_audio_backend(player: Any, output_device: Any = None) -> bool:
    """Coordinated PortAudio re-init after a topology change. Worker-thread.

    Order matters: quiesce every native stream FIRST (a terminate with live
    streams is the BUG-058 native-fault path), then re-init under the shared
    boot re-init lock, then drop every stale resolve cache. Reopening is left
    to the owners — the capture watchdog and the player's lazy open — so this
    function never creates a stream itself.
    """
    try:
        import sounddevice as sd  # noqa: PLC0415 — desktop-only optional dep
    except Exception:  # noqa: BLE001 — headless install
        return False
    try:
        from dodaios.audio.capture import _invalidate_resolve_cache
        from dodaios.audio.device_init import _REINIT_LOCK

        with _OPEN_LOCK:
            if _native_operations or getattr(player, "audio_backend_busy", False):
                log.debug("Audio backend refresh deferred until playback is idle")
                return False
            with _captures_lock:
                captures = list(_captures)
            for capture in captures:
                try:
                    if capture.discard_native_stream() is False:
                        return False
                except Exception:  # noqa: BLE001 — a live stream forbids re-init
                    log.warning(
                        "Capture discard during refresh failed", exc_info=True
                    )
                    return False
            if player is not None:
                try:
                    if player.invalidate_device_cache() is False:
                        return False
                except Exception:  # noqa: BLE001
                    log.debug(
                        "Player invalidate during refresh failed", exc_info=True
                    )
                    return False
            if _native_streams:
                log.debug("Audio backend refresh deferred: native streams remain open")
                return False
            with _REINIT_LOCK:
                with contextlib.suppress(Exception):
                    sd._terminate()
                try:
                    sd._initialize()
                except Exception as exc:  # noqa: BLE001
                    log.warning("PortAudio re-initialization failed: %s", exc)
                    return False
            _invalidate_resolve_cache()
            if player is not None:
                # Re-resolve the CONFIGURED spec against the fresh table; a
                # stale resolved index must never survive the re-init.
                with contextlib.suppress(Exception):
                    player.set_device(output_device)
    except Exception:  # noqa: BLE001 — a failed refresh must never kill the watcher
        log.warning("Audio backend refresh failed", exc_info=True)
        return False
    return True


async def watch_topology(
    player: Any,
    output_device: Any = None,
    *,
    poll_s: float = DEFAULT_POLL_S,
    min_gap_s: float = MIN_PROBE_GAP_S,
    probe: Callable[[], str | None] | None = None,
    refresh: Callable[[], bool] | None = None,
) -> None:
    """Poll for device hot-swap and refresh the audio backend on change.

    Runs forever; the owner cancels it on shutdown. ``probe``/``refresh`` are
    injectable for tests; the defaults use the out-of-process device probe
    and :func:`refresh_audio_backend`.
    """
    global _probe_request, _probe_loop
    probe = probe or _fresh_signature
    refresh = refresh or (lambda: refresh_audio_backend(player, output_device))
    _probe_request = asyncio.Event()
    _probe_loop = asyncio.get_running_loop()
    loop = _probe_loop
    last: str | None = None
    last_probe_at = float("-inf")
    while True:
        # Wake early when a device-loss signal fires, otherwise poll.
        requested = True
        try:
            await asyncio.wait_for(_probe_request.wait(), timeout=poll_s)
        except TimeoutError:  # the poll interval elapsed: a timed probe, not an error
            requested = False
        if requested:
            # An early request still honours the floor between probes.
            remaining = min_gap_s - (loop.time() - last_probe_at)
            if remaining > 0:
                await asyncio.sleep(remaining)
        _probe_request.clear()
        last_probe_at = loop.time()
        signature = await asyncio.to_thread(probe)
        if signature is None:
            # Probe unavailable (headless, worker timeout) — no judgment.
            continue
        if last is None:
            last = signature
            continue
        if signature == last:
            continue
        await asyncio.sleep(_SETTLE_S)
        settled = await asyncio.to_thread(probe)
        if settled is None or settled == last:
            # A transient enumeration change (e.g. PipeWire closing a mic)
            # does not justify terminating the process-wide audio backend.
            continue
        log.info(
            "Audio device topology changed — refreshing the audio backend "
            "(streams reopen automatically)."
        )
        ok = await asyncio.to_thread(refresh)
        log.info("Audio backend refresh %s.", "completed" if ok else "deferred or failed")
        if ok:
            last = settled


__all__ = [
    "DEFAULT_POLL_S",
    "MIN_PROBE_GAP_S",
    "refresh_audio_backend",
    "native_stream_operation",
    "register_capture",
    "stream_open_guard",
    "topology_signature",
    "unregister_capture",
    "watch_topology",
]