feat: LiveSub 2차 — 자막 on/off, 모니터·위치 선택, GPU 저부하, 게임 용어집
이름을 Hearo → LiveSub 로 변경. 말장난보다 하는 일이 바로 보이는 쪽이 낫다. 자막 on/off - 전역 단축키 Ctrl+Alt+S (자막) / Ctrl+Alt+D (번역) — Windows RegisterHotKey + 네이티브 이벤트 필터라 게임 창이 떠 있어도 동작. 다른 OS 에서는 no-op - 단축키·체크박스·우클릭 메뉴가 모두 같은 경로를 타도록 통합 모니터 선택 + 디스코드식 배치 - placement.py: Qt 비의존 배치 계산 (모니터 목록 → 9분할 좌표) - AnchorGrid 위젯으로 3x3 위치 선택, 드래그하면 자유 배치로 전환 - 모니터 구성이 바뀌어도 자막이 화면 밖으로 사라지지 않도록 클램프 GPU 저부하 모드 (기본 켜짐) - 연산 정밀도 int8 강등, VRAM 상한 35%, 추론 후 60ms 양보, 300초 무음 시 모델 언로드, 중간 결과 비활성 - 기본 티어를 균형(6GB) → 신속(4GB) 으로 하향 - 8GB GPU 기준 자막 2.8GB / 게임 5.2GB 게임 용어집 번들 (304개) - 롤 74 · 발로란트 59 · 오버워치2 49 · FPS공통 46 · 마크 38 · 방송 38 - 체크박스로 켜고 끄며, 사용자가 직접 등록한 항목이 항상 우선 검증: pytest 91개 통과 (배치 14 + 팩 12 + UI 6 신규), ruff clean Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
72
src/livesub/audio/__init__.py
Normal file
72
src/livesub/audio/__init__.py
Normal file
@@ -0,0 +1,72 @@
|
||||
"""오디오 캡처 레이어."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
|
||||
from ..config import AudioConfig
|
||||
from .base import AudioSource, CaptureBackend, CaptureError
|
||||
from .file_source import FileCapture
|
||||
from .process_loopback import ProcessLoopbackCapture
|
||||
from .segmenter import Segment, Segmenter, SegmenterConfig
|
||||
from .wasapi_loopback import WasapiLoopbackCapture
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
__all__ = [
|
||||
"AudioSource",
|
||||
"CaptureBackend",
|
||||
"CaptureError",
|
||||
"FileCapture",
|
||||
"ProcessLoopbackCapture",
|
||||
"Segment",
|
||||
"Segmenter",
|
||||
"SegmenterConfig",
|
||||
"WasapiLoopbackCapture",
|
||||
"capture_capabilities",
|
||||
"create_capture",
|
||||
"list_sources",
|
||||
]
|
||||
|
||||
|
||||
def capture_capabilities() -> dict[str, bool]:
|
||||
"""현재 환경에서 어떤 캡처가 가능한지."""
|
||||
return {
|
||||
"process": ProcessLoopbackCapture.available(),
|
||||
"device": WasapiLoopbackCapture.available(),
|
||||
"file": True,
|
||||
}
|
||||
|
||||
|
||||
def list_sources() -> list[AudioSource]:
|
||||
"""프로그램 + 출력 장치를 한 목록으로."""
|
||||
sources: list[AudioSource] = []
|
||||
if ProcessLoopbackCapture.available():
|
||||
sources.extend(ProcessLoopbackCapture.list_sources())
|
||||
sources.extend(WasapiLoopbackCapture.list_sources())
|
||||
return sources
|
||||
|
||||
|
||||
def create_capture(config: AudioConfig) -> CaptureBackend:
|
||||
"""설정에 맞는 캡처 백엔드를 만든다. 불가능하면 장치 루프백으로 폴백."""
|
||||
backend = config.backend
|
||||
if backend == "file":
|
||||
return FileCapture(config.target_process_name)
|
||||
|
||||
want_process = backend in ("process", "auto") and config.target_pid > 0
|
||||
if want_process:
|
||||
if ProcessLoopbackCapture.available():
|
||||
return ProcessLoopbackCapture(config.target_pid)
|
||||
if backend == "process":
|
||||
raise CaptureError(
|
||||
"프로그램별 캡처를 쓰려면 livesub_capture.exe 가 필요합니다. "
|
||||
"native/process_loopback/build.ps1 로 빌드하거나 '출력 장치 전체'를 선택하세요."
|
||||
)
|
||||
log.warning("프로그램별 캡처를 쓸 수 없어 장치 루프백으로 전환합니다.")
|
||||
|
||||
if not WasapiLoopbackCapture.available():
|
||||
raise CaptureError(
|
||||
"이 환경에서는 오디오 캡처를 할 수 없습니다. "
|
||||
"Windows에서 PyAudioWPatch 설치 여부를 확인하세요."
|
||||
)
|
||||
return WasapiLoopbackCapture(config.device_index)
|
||||
146
src/livesub/audio/base.py
Normal file
146
src/livesub/audio/base.py
Normal file
@@ -0,0 +1,146 @@
|
||||
"""오디오 캡처 백엔드 공통 인터페이스.
|
||||
|
||||
모든 백엔드는 16kHz / mono / float32(-1.0~1.0) 프레임을 큐로 흘려보낸다.
|
||||
리샘플링과 다운믹스는 각 백엔드가 책임진다.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import abc
|
||||
import queue
|
||||
import threading
|
||||
from dataclasses import dataclass
|
||||
|
||||
import numpy as np
|
||||
|
||||
from ..constants import SAMPLE_RATE
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class AudioSource:
|
||||
"""UI에 노출되는 캡처 대상 한 줄."""
|
||||
|
||||
kind: str # "process" | "device"
|
||||
identifier: str # pid 문자열 또는 장치 인덱스
|
||||
label: str
|
||||
detail: str = ""
|
||||
icon_path: str = ""
|
||||
|
||||
@property
|
||||
def pid(self) -> int:
|
||||
return int(self.identifier) if self.kind == "process" else 0
|
||||
|
||||
@property
|
||||
def device_index(self) -> int:
|
||||
return int(self.identifier) if self.kind == "device" else -1
|
||||
|
||||
|
||||
class CaptureError(RuntimeError):
|
||||
"""캡처를 시작할 수 없을 때."""
|
||||
|
||||
|
||||
class CaptureBackend(abc.ABC):
|
||||
"""오디오 캡처 백엔드 베이스."""
|
||||
|
||||
name = "base"
|
||||
#: 특정 프로그램 소리만 분리해서 받을 수 있는가
|
||||
per_process = False
|
||||
|
||||
def __init__(self, max_queue_frames: int = 400) -> None:
|
||||
self._queue: queue.Queue[np.ndarray] = queue.Queue(maxsize=max_queue_frames)
|
||||
self._stop = threading.Event()
|
||||
self._thread: threading.Thread | None = None
|
||||
self._error: Exception | None = None
|
||||
|
||||
# --- 하위 클래스가 구현 -------------------------------------------
|
||||
@abc.abstractmethod
|
||||
def _run(self) -> None:
|
||||
"""블로킹 캡처 루프. self._stop 이 set 될 때까지 _emit() 호출."""
|
||||
|
||||
@staticmethod
|
||||
@abc.abstractmethod
|
||||
def available() -> bool:
|
||||
"""현재 환경에서 이 백엔드를 쓸 수 있는가."""
|
||||
|
||||
@staticmethod
|
||||
@abc.abstractmethod
|
||||
def list_sources() -> list[AudioSource]:
|
||||
"""선택 가능한 캡처 대상 목록."""
|
||||
|
||||
# --- 공통 동작 -----------------------------------------------------
|
||||
def start(self) -> None:
|
||||
if self._thread and self._thread.is_alive():
|
||||
return
|
||||
self._stop.clear()
|
||||
self._error = None
|
||||
self._thread = threading.Thread(
|
||||
target=self._thread_main, name=f"capture-{self.name}", daemon=True
|
||||
)
|
||||
self._thread.start()
|
||||
|
||||
def _thread_main(self) -> None:
|
||||
try:
|
||||
self._run()
|
||||
except Exception as exc: # noqa: BLE001 - 워커 스레드 경계
|
||||
self._error = exc
|
||||
|
||||
def stop(self, timeout: float = 2.0) -> None:
|
||||
self._stop.set()
|
||||
if self._thread:
|
||||
self._thread.join(timeout=timeout)
|
||||
self._thread = None
|
||||
|
||||
@property
|
||||
def running(self) -> bool:
|
||||
return bool(self._thread and self._thread.is_alive())
|
||||
|
||||
@property
|
||||
def error(self) -> Exception | None:
|
||||
return self._error
|
||||
|
||||
def _emit(self, frame: np.ndarray) -> None:
|
||||
"""캡처 프레임 투입. 큐가 가득 차면 가장 오래된 프레임을 버린다.
|
||||
|
||||
실시간 자막에서는 밀린 오디오보다 최신 오디오가 항상 더 가치 있다.
|
||||
"""
|
||||
try:
|
||||
self._queue.put_nowait(frame)
|
||||
except queue.Full:
|
||||
try:
|
||||
self._queue.get_nowait()
|
||||
self._queue.put_nowait(frame)
|
||||
except (queue.Empty, queue.Full):
|
||||
pass
|
||||
|
||||
def read(self, timeout: float = 0.5) -> np.ndarray | None:
|
||||
try:
|
||||
return self._queue.get(timeout=timeout)
|
||||
except queue.Empty:
|
||||
return None
|
||||
|
||||
def drain(self) -> None:
|
||||
while not self._queue.empty():
|
||||
try:
|
||||
self._queue.get_nowait()
|
||||
except queue.Empty:
|
||||
break
|
||||
|
||||
|
||||
def to_mono_16k(data: np.ndarray, channels: int, src_rate: int) -> np.ndarray:
|
||||
"""인터리브된 float32 PCM을 16kHz 모노로 변환."""
|
||||
if data.size == 0:
|
||||
return data.astype(np.float32, copy=False)
|
||||
audio = data.astype(np.float32, copy=False)
|
||||
if channels > 1:
|
||||
usable = (audio.size // channels) * channels
|
||||
audio = audio[:usable].reshape(-1, channels).mean(axis=1)
|
||||
if src_rate != SAMPLE_RATE and audio.size:
|
||||
# 선형 보간 리샘플. 음성인식 입력으로는 충분한 품질이며 의존성이 없다.
|
||||
duration = audio.size / src_rate
|
||||
target_len = max(1, int(duration * SAMPLE_RATE))
|
||||
audio = np.interp(
|
||||
np.linspace(0.0, audio.size - 1, target_len, dtype=np.float64),
|
||||
np.arange(audio.size, dtype=np.float64),
|
||||
audio,
|
||||
).astype(np.float32)
|
||||
return audio
|
||||
66
src/livesub/audio/file_source.py
Normal file
66
src/livesub/audio/file_source.py
Normal file
@@ -0,0 +1,66 @@
|
||||
"""파일/합성 오디오 캡처 백엔드.
|
||||
|
||||
실제 오디오 장치 없이 파이프라인 전체를 돌려볼 수 있게 해준다.
|
||||
개발·테스트·데모용이며 어느 OS에서나 동작한다.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
import wave
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
|
||||
from ..constants import FRAME_SAMPLES, SAMPLE_RATE
|
||||
from .base import AudioSource, CaptureBackend, CaptureError, to_mono_16k
|
||||
|
||||
|
||||
class FileCapture(CaptureBackend):
|
||||
"""WAV 파일을 실시간 속도로 재생하듯 흘려보낸다."""
|
||||
|
||||
name = "file"
|
||||
per_process = False
|
||||
|
||||
def __init__(self, path: str | Path, loop: bool = False, realtime: bool = True) -> None:
|
||||
super().__init__()
|
||||
self.path = Path(path)
|
||||
self.loop = loop
|
||||
self.realtime = realtime
|
||||
|
||||
@staticmethod
|
||||
def available() -> bool:
|
||||
return True
|
||||
|
||||
@staticmethod
|
||||
def list_sources() -> list[AudioSource]:
|
||||
return []
|
||||
|
||||
def _read_wav(self) -> np.ndarray:
|
||||
if not self.path.is_file():
|
||||
raise CaptureError(f"오디오 파일을 찾을 수 없습니다: {self.path}")
|
||||
with wave.open(str(self.path), "rb") as wf:
|
||||
channels = wf.getnchannels()
|
||||
rate = wf.getframerate()
|
||||
width = wf.getsampwidth()
|
||||
raw = wf.readframes(wf.getnframes())
|
||||
if width == 2:
|
||||
data = np.frombuffer(raw, dtype=np.int16).astype(np.float32) / 32768.0
|
||||
elif width == 4:
|
||||
data = np.frombuffer(raw, dtype=np.float32)
|
||||
else:
|
||||
raise CaptureError(f"지원하지 않는 샘플 폭입니다: {width * 8}bit")
|
||||
return to_mono_16k(data, channels, rate)
|
||||
|
||||
def _run(self) -> None:
|
||||
audio = self._read_wav()
|
||||
chunk = FRAME_SAMPLES * 5 # 100ms
|
||||
while not self._stop.is_set():
|
||||
for start in range(0, audio.size, chunk):
|
||||
if self._stop.is_set():
|
||||
return
|
||||
self._emit(audio[start : start + chunk].copy())
|
||||
if self.realtime:
|
||||
time.sleep(chunk / SAMPLE_RATE)
|
||||
if not self.loop:
|
||||
return
|
||||
168
src/livesub/audio/process_loopback.py
Normal file
168
src/livesub/audio/process_loopback.py
Normal file
@@ -0,0 +1,168 @@
|
||||
"""프로그램별 오디오 캡처 (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 ""
|
||||
188
src/livesub/audio/segmenter.py
Normal file
188
src/livesub/audio/segmenter.py
Normal file
@@ -0,0 +1,188 @@
|
||||
"""발화 구간 분할기.
|
||||
|
||||
캡처된 연속 오디오를 "한 문장" 단위로 잘라 음성인식에 넘긴다.
|
||||
외부 의존성 없이 동작하도록 적응형 노이즈 플로어 기반 에너지 VAD를 쓴다.
|
||||
webrtcvad 가 설치돼 있으면 더 정확한 판정을 위해 함께 사용한다.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
from dataclasses import dataclass
|
||||
|
||||
import numpy as np
|
||||
|
||||
from ..constants import FRAME_MS, FRAME_SAMPLES, SAMPLE_RATE
|
||||
|
||||
try: # pragma: no cover - 선택 의존성
|
||||
import webrtcvad
|
||||
except ImportError: # pragma: no cover
|
||||
webrtcvad = None # type: ignore[assignment]
|
||||
|
||||
|
||||
@dataclass
|
||||
class Segment:
|
||||
"""음성인식에 넘길 오디오 한 덩어리."""
|
||||
|
||||
audio: np.ndarray
|
||||
started_at: float
|
||||
ended_at: float
|
||||
is_final: bool = True
|
||||
|
||||
@property
|
||||
def duration_s(self) -> float:
|
||||
return self.audio.size / SAMPLE_RATE
|
||||
|
||||
|
||||
@dataclass
|
||||
class SegmenterConfig:
|
||||
silence_ms: int = 600
|
||||
min_segment_ms: int = 400
|
||||
max_segment_ms: int = 12_000
|
||||
partial_interval_ms: int = 900
|
||||
#: 노이즈 플로어 대비 몇 배 이상이면 발화로 볼지
|
||||
speech_ratio: float = 3.0
|
||||
#: 절대 무음 판정 하한 (RMS)
|
||||
absolute_floor: float = 2e-4
|
||||
vad_aggressiveness: int = 2
|
||||
#: 발화 시작 앞쪽에 붙일 여유분 (앞 음절 잘림 방지)
|
||||
lead_in_ms: int = 240
|
||||
|
||||
|
||||
class Segmenter:
|
||||
"""프레임을 받아 발화 구간을 뱉는 상태 기계.
|
||||
|
||||
`push()` 는 확정 구간(is_final=True) 또는 중간 결과(is_final=False)를
|
||||
돌려주거나, 아직 내보낼 게 없으면 None 을 돌려준다.
|
||||
"""
|
||||
|
||||
def __init__(self, config: SegmenterConfig | None = None) -> None:
|
||||
self.config = config or SegmenterConfig()
|
||||
self._vad = None
|
||||
if webrtcvad is not None:
|
||||
self._vad = webrtcvad.Vad(max(0, min(3, self.config.vad_aggressiveness)))
|
||||
|
||||
self._buffer: list[np.ndarray] = []
|
||||
self._lead_in: list[np.ndarray] = []
|
||||
self._pending = np.zeros(0, dtype=np.float32)
|
||||
self._noise_floor = 1e-3
|
||||
self._silence_ms = 0
|
||||
self._speech_ms = 0
|
||||
self._in_speech = False
|
||||
self._started_at = 0.0
|
||||
self._last_partial_ms = 0
|
||||
self._lead_in_frames = max(1, self.config.lead_in_ms // FRAME_MS)
|
||||
|
||||
# --- 입력 ----------------------------------------------------------
|
||||
def push(self, chunk: np.ndarray) -> list[Segment]:
|
||||
"""임의 길이의 오디오를 넣고 완성된 구간 목록을 받는다."""
|
||||
out: list[Segment] = []
|
||||
if chunk.size:
|
||||
self._pending = (
|
||||
chunk.astype(np.float32, copy=False)
|
||||
if self._pending.size == 0
|
||||
else np.concatenate((self._pending, chunk))
|
||||
)
|
||||
while self._pending.size >= FRAME_SAMPLES:
|
||||
frame = self._pending[:FRAME_SAMPLES]
|
||||
self._pending = self._pending[FRAME_SAMPLES:]
|
||||
segment = self._push_frame(frame)
|
||||
if segment is not None:
|
||||
out.append(segment)
|
||||
return out
|
||||
|
||||
def flush(self) -> Segment | None:
|
||||
"""남은 버퍼를 강제로 확정 구간으로 만든다 (캡처 종료 시)."""
|
||||
if not self._in_speech:
|
||||
return None
|
||||
return self._finish()
|
||||
|
||||
def reset(self) -> None:
|
||||
"""발화 상태만 초기화한다.
|
||||
|
||||
`_pending` 은 건드리지 않는다. 아직 프레임으로 쪼개지 못한 '입력' 이라
|
||||
여기서 버리면 한 구간을 확정한 직후의 오디오가 통째로 사라진다.
|
||||
"""
|
||||
self._buffer.clear()
|
||||
self._lead_in.clear()
|
||||
self._silence_ms = 0
|
||||
self._speech_ms = 0
|
||||
self._in_speech = False
|
||||
self._last_partial_ms = 0
|
||||
|
||||
# --- 내부 ----------------------------------------------------------
|
||||
def _push_frame(self, frame: np.ndarray) -> Segment | None:
|
||||
speech = self._is_speech(frame)
|
||||
cfg = self.config
|
||||
|
||||
if not self._in_speech:
|
||||
self._lead_in.append(frame)
|
||||
if len(self._lead_in) > self._lead_in_frames:
|
||||
self._lead_in.pop(0)
|
||||
if speech:
|
||||
self._in_speech = True
|
||||
self._started_at = time.monotonic()
|
||||
self._buffer = list(self._lead_in)
|
||||
self._lead_in = []
|
||||
self._silence_ms = 0
|
||||
self._speech_ms = FRAME_MS
|
||||
self._last_partial_ms = 0
|
||||
return None
|
||||
|
||||
self._buffer.append(frame)
|
||||
self._speech_ms += FRAME_MS
|
||||
self._silence_ms = 0 if speech else self._silence_ms + FRAME_MS
|
||||
|
||||
buffered_ms = len(self._buffer) * FRAME_MS
|
||||
if self._silence_ms >= cfg.silence_ms:
|
||||
if buffered_ms - self._silence_ms < cfg.min_segment_ms:
|
||||
self.reset() # 잡음 한 번 튄 것 — 버린다
|
||||
return None
|
||||
return self._finish()
|
||||
|
||||
if buffered_ms >= cfg.max_segment_ms:
|
||||
return self._finish()
|
||||
|
||||
if cfg.partial_interval_ms > 0:
|
||||
since = buffered_ms - self._last_partial_ms
|
||||
if since >= cfg.partial_interval_ms and buffered_ms >= cfg.min_segment_ms:
|
||||
self._last_partial_ms = buffered_ms
|
||||
return Segment(
|
||||
audio=np.concatenate(self._buffer),
|
||||
started_at=self._started_at,
|
||||
ended_at=time.monotonic(),
|
||||
is_final=False,
|
||||
)
|
||||
return None
|
||||
|
||||
def _finish(self) -> Segment:
|
||||
audio = np.concatenate(self._buffer) if self._buffer else np.zeros(0, np.float32)
|
||||
segment = Segment(
|
||||
audio=audio,
|
||||
started_at=self._started_at,
|
||||
ended_at=time.monotonic(),
|
||||
is_final=True,
|
||||
)
|
||||
self.reset()
|
||||
return segment
|
||||
|
||||
def _is_speech(self, frame: np.ndarray) -> bool:
|
||||
rms = float(np.sqrt(np.mean(np.square(frame), dtype=np.float64)))
|
||||
cfg = self.config
|
||||
|
||||
if rms < cfg.absolute_floor:
|
||||
self._noise_floor = min(self._noise_floor, max(rms, 1e-6))
|
||||
return False
|
||||
|
||||
energetic = rms > max(self._noise_floor * cfg.speech_ratio, cfg.absolute_floor)
|
||||
if not energetic:
|
||||
# 무음 구간에서만 노이즈 플로어를 천천히 따라가게 한다.
|
||||
self._noise_floor = 0.95 * self._noise_floor + 0.05 * rms
|
||||
|
||||
if self._vad is None:
|
||||
return energetic
|
||||
try:
|
||||
pcm16 = (np.clip(frame, -1.0, 1.0) * 32767.0).astype(np.int16).tobytes()
|
||||
return energetic and self._vad.is_speech(pcm16, SAMPLE_RATE)
|
||||
except Exception: # noqa: BLE001 - webrtcvad 는 프레임 길이에 민감
|
||||
return energetic
|
||||
95
src/livesub/audio/wasapi_loopback.py
Normal file
95
src/livesub/audio/wasapi_loopback.py
Normal file
@@ -0,0 +1,95 @@
|
||||
"""WASAPI 장치 루프백 캡처 (Windows).
|
||||
|
||||
출력 장치 전체의 소리를 받는다. 프로그램별 분리는 안 되지만 의존성이
|
||||
`PyAudioWPatch` 하나뿐이라 어디서나 바로 동작하는 기본 백엔드다.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import contextlib
|
||||
import logging
|
||||
|
||||
import numpy as np
|
||||
|
||||
from ..constants import FRAME_SAMPLES
|
||||
from .base import AudioSource, CaptureBackend, CaptureError, to_mono_16k
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
try: # pragma: no cover - 플랫폼 의존
|
||||
import pyaudiowpatch as pyaudio
|
||||
except ImportError: # pragma: no cover
|
||||
pyaudio = None # type: ignore[assignment]
|
||||
|
||||
|
||||
class WasapiLoopbackCapture(CaptureBackend):
|
||||
name = "device"
|
||||
per_process = False
|
||||
|
||||
def __init__(self, device_index: int = -1) -> None:
|
||||
super().__init__()
|
||||
self.device_index = device_index
|
||||
|
||||
@staticmethod
|
||||
def available() -> bool:
|
||||
return pyaudio is not None
|
||||
|
||||
@staticmethod
|
||||
def list_sources() -> list[AudioSource]:
|
||||
if pyaudio is None:
|
||||
return []
|
||||
sources: list[AudioSource] = []
|
||||
pa = pyaudio.PyAudio()
|
||||
try:
|
||||
default_index = -1
|
||||
with contextlib.suppress(OSError, LookupError):
|
||||
default_index = pa.get_default_wasapi_loopback()["index"]
|
||||
for info in pa.get_loopback_device_info_generator():
|
||||
idx = int(info["index"])
|
||||
sources.append(
|
||||
AudioSource(
|
||||
kind="device",
|
||||
identifier=str(idx),
|
||||
label=str(info["name"]).replace(" [Loopback]", ""),
|
||||
detail="기본 출력 장치" if idx == default_index else "출력 장치",
|
||||
)
|
||||
)
|
||||
finally:
|
||||
pa.terminate()
|
||||
return sources
|
||||
|
||||
def _resolve_device(self, pa) -> dict:
|
||||
if self.device_index >= 0:
|
||||
return pa.get_device_info_by_index(self.device_index)
|
||||
return pa.get_default_wasapi_loopback()
|
||||
|
||||
def _run(self) -> None: # pragma: no cover - 실제 오디오 장치 필요
|
||||
if pyaudio is None:
|
||||
raise CaptureError("PyAudioWPatch가 설치되지 않았습니다.")
|
||||
pa = pyaudio.PyAudio()
|
||||
stream = None
|
||||
try:
|
||||
info = self._resolve_device(pa)
|
||||
if info is None:
|
||||
raise CaptureError("루프백 장치를 찾지 못했습니다.")
|
||||
rate = int(info["defaultSampleRate"])
|
||||
channels = int(info["maxInputChannels"]) or 2
|
||||
chunk = max(FRAME_SAMPLES, int(rate * 0.02))
|
||||
stream = pa.open(
|
||||
format=pyaudio.paFloat32,
|
||||
channels=channels,
|
||||
rate=rate,
|
||||
input=True,
|
||||
input_device_index=int(info["index"]),
|
||||
frames_per_buffer=chunk,
|
||||
)
|
||||
log.info("장치 루프백 캡처 시작: %s (%dHz, %dch)", info["name"], rate, channels)
|
||||
while not self._stop.is_set():
|
||||
raw = stream.read(chunk, exception_on_overflow=False)
|
||||
data = np.frombuffer(raw, dtype=np.float32)
|
||||
self._emit(to_mono_16k(data, channels, rate))
|
||||
finally:
|
||||
if stream is not None:
|
||||
stream.stop_stream()
|
||||
stream.close()
|
||||
pa.terminate()
|
||||
Reference in New Issue
Block a user