Skip to content

Live Target Discovery & Subscriptions

Discovery provides both zero-background-thread snapshots (discover, discover_query, find_app) and bounded real-time change streams (subscribe_discovery / subscribe_query).


Desktop apps frequently spawn multiple child processes (chrome.exe audio service utility, firefox plugin-container, macOS .app/Contents/Frameworks/... Helper.app, or Linux Flatpak/D-Bus scopes). Naive PID listing floods pickers with cryptic helper processes or merges unrelated scripts.

Discovery solves this deterministically across Windows, Linux, and macOS:

  1. Collapses helpers into their owning application root: Child audio helpers roll up into the top-level application (Google Chrome, Spotify, Zoom) using outermost .app bundle identity on macOS (canonicalizing .code_sign_clone paths), install-directory & executable hierarchy on Windows, and /proc/<pid>/cmdline + cgroup (app-flatpak-*, dbus-*) entrypoints on Linux.
  2. Stops before OS shells, session hosts, and runtime interpreters: Upward traversal halts before explorer.exe, svchost.exe, cmd.exe, pwsh.exe, systemd, gnome-shell, launchd, Finder, Dock, or shared interpreters (python3, node, gjs-console), so launching Chrome from VS Code’s terminal never merges Chrome’s audio into VS Code, and two unrelated Python apps never merge together.
  3. Excludes .monitor loopback sinks from microphones: On Linux PipeWire and PulseAudio, virtual monitor sources (*.monitor and internal cspa-mix-* nodes) are automatically excluded from input_devices so microphone pickers only list real physical or virtual capture inputs.

2. Deterministic Target Filtering vs find_app(NAME)

Section titled “2. Deterministic Target Filtering vs find_app(NAME)”

find_app("Spotify") is a convenient single-match helper, but string matching alone is not deterministic when multiple instances share a name (for example, two browser profiles or Python/Java workers — where find_app rejects an ambiguous match rather than guessing) or when display names differ across OS locales and Flatpak/bundle IDs.

For deterministic production selection, enumerate CaptureTargets via discover / discover_query, filter explicitly on active_audio, pid, executable_path, app_id, or device_id, optionally refine with with_gain(...) or with_backend(...), and pass those exact CaptureTarget records directly into capture / CaptureManager:

import os
import capture_system_or_process_audio as cspa
catalog = cspa.discover(active_only=False)
my_pid = os.getpid()
# Filter deterministically by audio state, PID, executable_path, or app_id:
selected = [
app.with_gain(0.9)
for app in catalog.applications
if app.active_audio is True and app.pid != my_pid
][:2] or [cspa.default_output()]
with cspa.capture(selected, silence_on_idle=True) as stream:
outcome = stream.read(480, timeout_ms=200)
print("Captured frames:", outcome.frames)

3. Structured DiscoveryQuery: Deduplication & Ordering

Section titled “3. Structured DiscoveryQuery: Deduplication & Ordering”

On Linux (PipeWire + PulseAudio) and macOS (CoreAudio + ScreenCaptureKit), the same logical app or device may be visible through two native backends simultaneously. DiscoveryQuery lets you control how multi-backend inventories are presented:

  • DiscoveryDedupe::ByLogicalTarget (Default): Deduplicates identical targets across backends, keeping the highest-priority backend while populating target.available_backends (e.g. [CoreAudio, ScreenCaptureKit]) so UIs can offer per-source backend overrides.
  • DiscoveryDedupe::PerBackend: Emits separate <backend>:<kind>:... entries for each backend so diagnostic tools can compare raw per-backend inventories side-by-side.
  • DiscoveryOrder: Sort results KindThenBackend (default) or BackendThenKind, and filter with active_only (currently playing audio) or include_non_audio.
import capture_system_or_process_audio as cspa
# Quick snapshot (zero background threads):
catalog = cspa.discover(active_only=False)
print("Apps:", len(catalog.applications), "Mics:", len(catalog.input_devices))
# Structured per-backend query:
query = cspa.DiscoveryQuery(
dedupe=cspa.DiscoveryDedupe.PER_BACKEND,
order=cspa.DiscoveryOrder.BACKEND_THEN_KIND,
active_only=True,
)
per_bk = cspa.discover_query(query)
for t in per_bk.targets:
print(t.id, t.backend, t.available_backends)

4. Bounded 256-Event Cursor Subscriptions & Resnapshot Recovery

Section titled “4. Bounded 256-Event Cursor Subscriptions & Resnapshot Recovery”

Interactive UIs (such as cspa-tui-demo or Electron source pickers) can subscribe to live inventory diffs without polling the OS in tight loops:

  • Event Kinds: Added, Removed, StateChanged (including PLAYING ↔\leftrightarrow IDLE transitions and friendly device renames), DefaultDeviceChanged, DefaultInputChanged, VisibilityChanged, WatcherFailed, and ResnapshotRequired.
  • Bounded Queue (max_discovery_queue = 256 default, range 32..=4096): Prevents unbounded memory growth if a UI thread pauses while hundreds of processes churn. If the queue overflows (sub.is_overflowed), calling sub.resnapshot() atomically reconciles a fresh baseline snapshot and resets the cursor!
import capture_system_or_process_audio as cspa
with cspa.subscribe_discovery(max_discovery_queue=256) as sub:
for ev in sub.poll_events():
print(ev.revision, ev.kind.value, ev.target_id)
if sub.is_overflowed:
fresh = sub.resnapshot()
print("Resnapshotted at revision:", fresh.revision, "count:", len(fresh.targets))

Continue to Execution Planning, CspaMixer & Live Hot-Swap.