"""프로그램별 오디오 캡처 (Windows WASAPI process loopback). `native/process_loopback` 에서 빌드한 `livesub_capture.exe` 를 자식 프로세스로 띄우고 stdout 으로 흘러나오는 16kHz mono float32 PCM 을 그대로 읽는다. 보조 프로그램이 없으면 `available()` 이 False 를 돌려주고, 상위 레이어는 장치 루프백으로 자동 폴백한다. """ from __future__ import annotations import logging import subprocess import sys from pathlib import Path import numpy as np from ..constants import FRAME_SAMPLES from .base import AudioSource, CaptureBackend, CaptureError log = logging.getLogger(__name__) HELPER_NAME = "livesub_capture.exe" READ_BYTES = FRAME_SAMPLES * 4 * 5 # 100ms 분량 def helper_path() -> Path | None: """보조 프로그램 위치. 패키지 내부 → 저장소 빌드 폴더 순으로 찾는다.""" candidates = [ Path(__file__).resolve().parent.parent / "resources" / "bin" / HELPER_NAME, Path(__file__).resolve().parents[3] / "native" / "process_loopback" / "build" / "Release" / HELPER_NAME, ] for path in candidates: if path.is_file(): return path return None class ProcessLoopbackCapture(CaptureBackend): name = "process" per_process = True def __init__(self, pid: int, exclude: bool = False) -> None: super().__init__() self.pid = pid self.exclude = exclude self._proc: subprocess.Popen[bytes] | None = None @staticmethod def available() -> bool: return sys.platform == "win32" and helper_path() is not None @staticmethod def list_sources() -> list[AudioSource]: """현재 소리를 내고 있는(또는 낼 수 있는) 프로세스 목록.""" if sys.platform != "win32": return [] try: from pycaw.pycaw import AudioUtilities except ImportError: log.debug("pycaw 미설치 — 프로세스 목록을 만들 수 없습니다.") return [] seen: dict[int, AudioSource] = {} for session in AudioUtilities.GetAllSessions(): proc = session.Process if proc is None or proc.pid in seen: continue try: name = proc.name() except Exception: # noqa: BLE001 - 종료된 프로세스 continue title = _window_title(proc.pid) or name seen[proc.pid] = AudioSource( kind="process", identifier=str(proc.pid), label=title, detail=f"{name} (PID {proc.pid})", ) return sorted(seen.values(), key=lambda s: s.label.lower()) def _run(self) -> None: # pragma: no cover - Windows 전용 exe = helper_path() if exe is None: raise CaptureError( f"{HELPER_NAME} 를 찾지 못했습니다. " "native/process_loopback/build.ps1 로 먼저 빌드하세요." ) cmd = [str(exe), "--pid", str(self.pid)] if self.exclude: cmd.append("--exclude") self._proc = subprocess.Popen( cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, bufsize=0, creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0), ) assert self._proc.stdout is not None try: while not self._stop.is_set(): raw = self._proc.stdout.read(READ_BYTES) if not raw: code = self._proc.poll() err = b"" if self._proc.stderr is not None: err = self._proc.stderr.read() or b"" raise CaptureError( f"캡처 보조 프로그램이 종료되었습니다(코드 {code}): " f"{err.decode('utf-8', 'replace').strip()}" ) # 4바이트 정렬이 깨지면 float32 해석이 밀린다. usable = len(raw) - (len(raw) % 4) self._emit(np.frombuffer(raw[:usable], dtype=np.float32).copy()) finally: self._terminate() def _terminate(self) -> None: proc, self._proc = self._proc, None if proc is None: return if proc.poll() is None: proc.terminate() try: proc.wait(timeout=2) except subprocess.TimeoutExpired: proc.kill() for pipe in (proc.stdout, proc.stderr): if pipe is not None: pipe.close() def _window_title(pid: int) -> str: """해당 PID의 최상위 창 제목. 실패하면 빈 문자열.""" if sys.platform != "win32": return "" try: import ctypes from ctypes import wintypes user32 = ctypes.windll.user32 result: list[str] = [] @ctypes.WINFUNCTYPE(wintypes.BOOL, wintypes.HWND, wintypes.LPARAM) def callback(hwnd, _lparam): owner = wintypes.DWORD() user32.GetWindowThreadProcessId(hwnd, ctypes.byref(owner)) if owner.value != pid or not user32.IsWindowVisible(hwnd): return True length = user32.GetWindowTextLengthW(hwnd) if length <= 0: return True buf = ctypes.create_unicode_buffer(length + 1) user32.GetWindowTextW(hwnd, buf, length + 1) result.append(buf.value) return False user32.EnumWindows(callback, 0) return result[0] if result else "" except Exception: # noqa: BLE001 - 창 제목은 부가 정보일 뿐 return ""