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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
# -*- coding: utf-8 -*-
|
| 3 |
+
|
| 4 |
+
"""
|
| 5 |
+
AutoVol (Tray) — zero-config, self-healing auto volume learner.
|
| 6 |
+
|
| 7 |
+
What it tries to do:
|
| 8 |
+
- Watch "how loud the system audio is" (best effort: real loopback audio; fallback: peak meter).
|
| 9 |
+
- Learn when you turn volume down (stores the loudness level at that moment).
|
| 10 |
+
- Next time it detects you're above your learned loudness threshold, it gently ducks volume.
|
| 11 |
+
|
| 12 |
+
v0.10.11 fixes vs v0.10.10 (quality-of-life + fewer “sampler thrash” loops):
|
| 13 |
+
- BETTER: Smarter audio-device picking (especially avoids HDMI/Display endpoints when possible).
|
| 14 |
+
* soundcard loopback no longer blindly prefers a “bad” default speaker (HDMI/display/etc).
|
| 15 |
+
* sounddevice WASAPI output selection uses a score-based pick, not just default output.
|
| 16 |
+
- BETTER: Sampler selection preflight now requires actual sample flow (recent window n>0),
|
| 17 |
+
not just “stream opened”. This prevents picking a sampler that’s dead-on-arrival.
|
| 18 |
+
- BETTER: Adds per-sampler exponential backoff when a sampler repeatedly fails preflight,
|
| 19 |
+
so the system doesn’t rotate through the same broken sources every ~15s forever.
|
| 20 |
+
- BETTER: Pycaw “degraded” threshold relaxed so it keeps trying longer on flaky COM systems
|
| 21 |
+
instead of force-switching too aggressively.
|
| 22 |
+
- KEEP: Prior COM-finalizer safety and WinVolSTA thread join behavior.
|
| 23 |
+
|
| 24 |
+
Run:
|
| 25 |
+
python autovol_tray.py
|
| 26 |
+
|
| 27 |
+
Data dir (Windows):
|
| 28 |
+
%LOCALAPPDATA%\\AutoVol
|
| 29 |
+
"""
|
| 30 |
+
|
| 31 |
+
from __future__ import annotations
|
| 32 |
+
|
| 33 |
+
import os
|
| 34 |
+
import sys
|
| 35 |
+
import math
|
| 36 |
+
import time
|
| 37 |
+
import json
|
| 38 |
+
import platform
|
| 39 |
+
import threading
|
| 40 |
+
import argparse
|
| 41 |
+
import queue
|
| 42 |
+
import subprocess
|
| 43 |
+
import traceback
|
| 44 |
+
import logging
|
| 45 |
+
import gc
|
| 46 |
+
from logging.handlers import RotatingFileHandler
|
| 47 |
+
from typing import Deque, Dict, List, Optional, Tuple, Callable, Any
|
| 48 |
+
from collections import deque
|
| 49 |
+
from dataclasses import dataclass
|
| 50 |
+
|
| 51 |
+
__version__ = "0.10.11"
|
| 52 |
+
_WIN = platform.system().lower().startswith("win")
|
| 53 |
+
|
| 54 |
+
DEFAULT_SR = 48000
|
| 55 |
+
DEFAULT_FRAME_S = 0.20
|
| 56 |
+
DEFAULT_FRAMES = int(round(DEFAULT_SR * DEFAULT_FRAME_S))
|
| 57 |
+
|
| 58 |
+
# ------------------ dependency bootstrap ------------------
|
| 59 |
+
|
| 60 |
+
_NO_AUTOINSTALL = ("--no-autoinstall" in sys.argv)
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def _pip_install(pkgs: List[str]) -> bool:
|
| 64 |
+
"""Best-effort dependency install.
|
| 65 |
+
|
| 66 |
+
If you're NOT in a venv, install into per-user site-packages (avoids admin/permission issues).
|
| 67 |
+
If you're in a venv, install into the venv as normal.
|
| 68 |
+
"""
|
| 69 |
+
try:
|
| 70 |
+
in_venv = (getattr(sys, "base_prefix", sys.prefix) != sys.prefix) or bool(os.environ.get("VIRTUAL_ENV"))
|
| 71 |
+
cmd = [sys.executable, "-m", "pip", "install", "--upgrade"]
|
| 72 |
+
if not in_venv:
|
| 73 |
+
cmd.append("--user")
|
| 74 |
+
cmd += pkgs
|
| 75 |
+
p = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
|
| 76 |
+
if p.returncode != 0:
|
| 77 |
+
logging.info("[deps] pip failed (%s):\n%s", p.returncode, p.stdout[-3000:])
|
| 78 |
+
return (p.returncode == 0)
|
| 79 |
+
except Exception:
|
| 80 |
+
return False
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def _ensure_deps(auto_install: bool = True) -> None:
|
| 84 |
+
need: List[str] = []
|
| 85 |
+
|
| 86 |
+
try:
|
| 87 |
+
import numpy # noqa: F401
|
| 88 |
+
except Exception:
|
| 89 |
+
need.append("numpy")
|
| 90 |
+
|
| 91 |
+
try:
|
| 92 |
+
import PIL # noqa: F401
|
| 93 |
+
except Exception:
|
| 94 |
+
need.append("Pillow")
|
| 95 |
+
|
| 96 |
+
try:
|
| 97 |
+
import pystray # noqa: F401
|
| 98 |
+
except Exception:
|
| 99 |
+
need.append("pystray")
|
| 100 |
+
|
| 101 |
+
if _WIN:
|
| 102 |
+
try:
|
| 103 |
+
import comtypes # noqa: F401
|
| 104 |
+
except Exception:
|
| 105 |
+
need.append("comtypes")
|
| 106 |
+
try:
|
| 107 |
+
import pycaw # noqa: F401
|
| 108 |
+
except Exception:
|
| 109 |
+
need.append("pycaw")
|
| 110 |
+
try:
|
| 111 |
+
import win32api # type: ignore # noqa: F401
|
| 112 |
+
except Exception:
|
| 113 |
+
need.append("pywin32")
|
| 114 |
+
|
| 115 |
+
try:
|
| 116 |
+
import sounddevice # noqa: F401
|
| 117 |
+
except Exception:
|
| 118 |
+
need.append("sounddevice")
|
| 119 |
+
|
| 120 |
+
# Optional fallback
|
| 121 |
+
try:
|
| 122 |
+
import soundcard # noqa: F401
|
| 123 |
+
except Exception:
|
| 124 |
+
if auto_install:
|
| 125 |
+
need.append("soundcard")
|
| 126 |
+
|
| 127 |
+
# Optional VAD (do not force install)
|
| 128 |
+
try:
|
| 129 |
+
import webrtcvad # noqa: F401
|
| 130 |
+
except Exception:
|
| 131 |
+
pass
|
| 132 |
+
|
| 133 |
+
if need and auto_install:
|
| 134 |
+
_pip_install(need)
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
# Install before importing heavy deps (best effort).
|
| 138 |
+
try:
|
| 139 |
+
_ensure_deps(auto_install=(not _NO_AUTOINSTALL))
|
| 140 |
+
except Exception:
|
| 141 |
+
pass
|
| 142 |
+
|
| 143 |
+
# Third-party deps
|
| 144 |
+
import numpy as np
|
| 145 |
+
|
| 146 |
+
try:
|
| 147 |
+
import sounddevice as sd
|
| 148 |
+
except Exception:
|
| 149 |
+
sd = None
|
| 150 |
+
|
| 151 |
+
try:
|
| 152 |
+
import soundcard as sc
|
| 153 |
+
except Exception:
|
| 154 |
+
sc = None
|
| 155 |
+
|
| 156 |
+
try:
|
| 157 |
+
import webrtcvad # type: ignore
|
| 158 |
+
_HAVE_WEBRTCVAD = True
|
| 159 |
+
except Exception:
|
| 160 |
+
webrtcvad = None
|
| 161 |
+
_HAVE_WEBRTCVAD = False
|
| 162 |
+
|
| 163 |
+
import pystray
|
| 164 |
+
from pystray import MenuItem as Item, Menu
|
| 165 |
+
from PIL import Image, ImageDraw
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
# ------------------ logging ------------------
|
| 169 |
+
|
| 170 |
+
def _default_data_dir() -> str:
|
| 171 |
+
if _WIN and "LOCALAPPDATA" in os.environ:
|
| 172 |
+
return os.path.join(os.environ["LOCALAPPDATA"], "AutoVol")
|
| 173 |
+
return os.path.abspath(".")
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
def setup_logging(data_dir: str) -> str:
|
| 177 |
+
os.makedirs(data_dir, exist_ok=True)
|
| 178 |
+
log_path = os.path.join(data_dir, "autovol.log")
|
| 179 |
+
|
| 180 |
+
logger = logging.getLogger()
|
| 181 |
+
logger.setLevel(logging.INFO)
|
| 182 |
+
|
| 183 |
+
fmt = logging.Formatter("%(asctime)s %(levelname)s %(threadName)s %(message)s")
|
| 184 |
+
fh = RotatingFileHandler(log_path, maxBytes=512_000, backupCount=2, encoding="utf-8")
|
| 185 |
+
fh.setFormatter(fmt)
|
| 186 |
+
sh = logging.StreamHandler(sys.stdout)
|
| 187 |
+
sh.setFormatter(fmt)
|
| 188 |
+
|
| 189 |
+
logger.handlers = []
|
| 190 |
+
logger.addHandler(fh)
|
| 191 |
+
logger.addHandler(sh)
|
| 192 |
+
|
| 193 |
+
logging.info("AutoVol starting v%s (win=%s) data_dir=%s", __version__, _WIN, data_dir)
|
| 194 |
+
logging.info("Args: %s", " ".join(sys.argv))
|
| 195 |
+
if _NO_AUTOINSTALL:
|
| 196 |
+
logging.info("Auto-install deps: DISABLED (--no-autoinstall)")
|
| 197 |
+
return log_path
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
# ------------------ utils ------------------
|
| 201 |
+
|
| 202 |
+
_BAD_AUDIO_TOKENS = [
|
| 203 |
+
"hdmi", "display", "nvidia", "amd", "intel", "dp audio", "display audio", "vf", "virtual",
|
| 204 |
+
"monitor", "sonic", "nahimic", "remote", "wireless display",
|
| 205 |
+
]
|
| 206 |
+
|
| 207 |
+
_GOOD_AUDIO_TOKENS = [
|
| 208 |
+
"realtek", "speakers", "speaker", "headphones", "headphone", "usb", "dac", "analog", "line out",
|
| 209 |
+
]
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
def clamp(x: float, lo: float, hi: float) -> float:
|
| 213 |
+
return max(lo, min(hi, x))
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
def db_to_lin(db: float) -> float:
|
| 217 |
+
return 10.0 ** (db / 20.0)
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
def rms_dbfs(x: np.ndarray, eps: float = 1e-12) -> float:
|
| 221 |
+
if x is None or getattr(x, "size", 0) == 0:
|
| 222 |
+
return -100.0
|
| 223 |
+
if x.ndim == 2 and x.shape[1] > 1:
|
| 224 |
+
x = x.mean(axis=1)
|
| 225 |
+
rms = float(np.sqrt(np.mean(np.square(x), dtype=np.float64)))
|
| 226 |
+
if not np.isfinite(rms) or rms <= eps:
|
| 227 |
+
return -100.0
|
| 228 |
+
db = 20.0 * math.log10(max(eps, rms))
|
| 229 |
+
return float(max(min(db, 0.0), -100.0))
|
| 230 |
+
|
| 231 |
+
|
| 232 |
+
def safe_tooltip(s: str, max_len: int = 120) -> str:
|
| 233 |
+
"""
|
| 234 |
+
Windows NOTIFYICONDATAW tooltip limit is 128 WCHAR incl null.
|
| 235 |
+
Keep it comfortably below to avoid pystray ValueError.
|
| 236 |
+
"""
|
| 237 |
+
s = s.replace("\n", " ").strip()
|
| 238 |
+
if len(s) <= max_len:
|
| 239 |
+
return s
|
| 240 |
+
return s[: max_len - 1] + "…"
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
def name_score_audio_device(name: str) -> int:
|
| 244 |
+
"""
|
| 245 |
+
Heuristic: prefer likely-real speaker endpoints, avoid HDMI/display/virtual endpoints.
|
| 246 |
+
"""
|
| 247 |
+
n = (name or "").lower()
|
| 248 |
+
score = 0
|
| 249 |
+
for t in _GOOD_AUDIO_TOKENS:
|
| 250 |
+
if t in n:
|
| 251 |
+
score += 12
|
| 252 |
+
for t in _BAD_AUDIO_TOKENS:
|
| 253 |
+
if t in n:
|
| 254 |
+
score -= 18
|
| 255 |
+
if "realtek" in n:
|
| 256 |
+
score += 25
|
| 257 |
+
if "speaker" in n:
|
| 258 |
+
score += 10
|
| 259 |
+
if "headphone" in n:
|
| 260 |
+
score += 8
|
| 261 |
+
if "usb" in n:
|
| 262 |
+
score += 6
|
| 263 |
+
return score
|
| 264 |
+
|
| 265 |
+
|
| 266 |
+
def looks_bad_default_endpoint(name: str) -> bool:
|
| 267 |
+
n = (name or "").lower()
|
| 268 |
+
if any(t in n for t in _BAD_AUDIO_TOKENS):
|
| 269 |
+
return True
|
| 270 |
+
# Very low score is suspicious as "default"
|
| 271 |
+
return name_score_audio_device(name) < -5
|
| 272 |
+
|
| 273 |
+
|
| 274 |
+
@dataclass
|
| 275 |
+
class Stats:
|
| 276 |
+
p50: float
|
| 277 |
+
p70: float
|
| 278 |
+
p85: float
|
| 279 |
+
p95: float
|
| 280 |
+
n: int
|
| 281 |
+
|
| 282 |
+
|
| 283 |
+
class PercentileWindow:
|
| 284 |
+
def __init__(self, frame_s: float, history_s: float):
|
| 285 |
+
self.frame_s = float(frame_s)
|
| 286 |
+
self.buf: Deque[Tuple[float, float]] = deque(maxlen=int(history_s / frame_s) + 16)
|
| 287 |
+
self.lock = threading.Lock()
|
| 288 |
+
|
| 289 |
+
def push(self, ts: float, db: float) -> None:
|
| 290 |
+
with self.lock:
|
| 291 |
+
self.buf.append((ts, db))
|
| 292 |
+
|
| 293 |
+
def stats(self, window_s: float) -> Stats:
|
| 294 |
+
cutoff = time.time() - float(window_s)
|
| 295 |
+
with self.lock:
|
| 296 |
+
vals = [db for (ts, db) in self.buf if ts >= cutoff]
|
| 297 |
+
if not vals:
|
| 298 |
+
return Stats(-100.0, -100.0, -100.0, -100.0, 0)
|
| 299 |
+
vals.sort()
|
| 300 |
+
|
| 301 |
+
def pct(p: float) -> float:
|
| 302 |
+
k = int(round((len(vals) - 1) * clamp(p, 0.0, 1.0)))
|
| 303 |
+
return float(vals[k])
|
| 304 |
+
|
| 305 |
+
return Stats(p50=pct(0.50), p70=pct(0.70), p85=pct(0.85), p95=pct(0.95), n=len(vals))
|
| 306 |
+
|
| 307 |
+
|
| 308 |
+
# ------------------ samplers ------------------
|
| 309 |
+
|
| 310 |
+
class SamplerBase:
|
| 311 |
+
"""
|
| 312 |
+
Samplers should be "alive" even during silence.
|
| 313 |
+
Health is: are samples arriving (n>0), not whether audio is loud.
|
| 314 |
+
"""
|
| 315 |
+
def chosen_name(self) -> Optional[str]:
|
| 316 |
+
return None
|
| 317 |
+
|
| 318 |
+
def start(self) -> None:
|
| 319 |
+
pass
|
| 320 |
+
|
| 321 |
+
def stop(self) -> None:
|
| 322 |
+
pass
|
| 323 |
+
|
| 324 |
+
def get_last_block(self) -> Optional[np.ndarray]:
|
| 325 |
+
return None
|
| 326 |
+
|
| 327 |
+
def samples_recent(self, window_s: float = 1.5) -> bool:
|
| 328 |
+
try:
|
| 329 |
+
win = getattr(self, "win", None)
|
| 330 |
+
if win is None:
|
| 331 |
+
return False
|
| 332 |
+
st = win.stats(window_s)
|
| 333 |
+
return st.n > 0
|
| 334 |
+
except Exception:
|
| 335 |
+
return False
|
| 336 |
+
|
| 337 |
+
def sampler_key(self) -> str:
|
| 338 |
+
return self.__class__.__name__
|
| 339 |
+
|
| 340 |
+
|
| 341 |
+
class LoopbackSampler_SD(SamplerBase):
|
| 342 |
+
"""
|
| 343 |
+
sounddevice WASAPI loopback.
|
| 344 |
+
|
| 345 |
+
Key detail: some PortAudio/WASAPI builds on Windows do NOT support the blocking API
|
| 346 |
+
(you'll see: "Blocking API not supported yet"). To self-heal across machines, we run
|
| 347 |
+
the stream in CALLBACK mode and never call stream.read().
|
| 348 |
+
|
| 349 |
+
Strategy:
|
| 350 |
+
- Prefer explicit "(loopback)" INPUT devices when present.
|
| 351 |
+
- Otherwise, try output devices with WasapiSettings(loopback=True).
|
| 352 |
+
- Score devices to avoid HDMI/display endpoints when possible.
|
| 353 |
+
"""
|
| 354 |
+
|
| 355 |
+
def __init__(self, sr=DEFAULT_SR, frame_s=DEFAULT_FRAME_S, history_s=150.0):
|
| 356 |
+
self.sr = int(sr)
|
| 357 |
+
self.frame_s = float(frame_s)
|
| 358 |
+
self.frames = int(round(self.frame_s * self.sr))
|
| 359 |
+
self.win = PercentileWindow(frame_s, history_s)
|
| 360 |
+
|
| 361 |
+
self.ok = False
|
| 362 |
+
self._stop = threading.Event()
|
| 363 |
+
self._th: Optional[threading.Thread] = None
|
| 364 |
+
self._last_block: Optional[np.ndarray] = None
|
| 365 |
+
self._lb_lock = threading.Lock()
|
| 366 |
+
|
| 367 |
+
self._chosen: Optional[str] = None
|
| 368 |
+
self._dev_index: Optional[int] = None
|
| 369 |
+
self._extra = None
|
| 370 |
+
|
| 371 |
+
def chosen_name(self) -> Optional[str]:
|
| 372 |
+
return self._chosen if self.ok else None
|
| 373 |
+
|
| 374 |
+
def get_last_block(self) -> Optional[np.ndarray]:
|
| 375 |
+
with self._lb_lock:
|
| 376 |
+
return None if self._last_block is None else self._last_block.copy()
|
| 377 |
+
|
| 378 |
+
def _wasapi_idx(self) -> Optional[int]:
|
| 379 |
+
if sd is None:
|
| 380 |
+
return None
|
| 381 |
+
try:
|
| 382 |
+
hostapis = sd.query_hostapis()
|
| 383 |
+
for i, h in enumerate(hostapis):
|
| 384 |
+
if "wasapi" in str(h.get("name", "")).lower():
|
| 385 |
+
return i
|
| 386 |
+
except Exception:
|
| 387 |
+
return None
|
| 388 |
+
return None
|
| 389 |
+
|
| 390 |
+
def _pick_loopback_input_device(self) -> Optional[int]:
|
| 391 |
+
"""
|
| 392 |
+
Many systems expose loopback capture as a dedicated *input* device with "(loopback)" in name.
|
| 393 |
+
If present, prefer it.
|
| 394 |
+
"""
|
| 395 |
+
if sd is None or not _WIN:
|
| 396 |
+
return None
|
| 397 |
+
wasapi_idx = self._wasapi_idx()
|
| 398 |
+
if wasapi_idx is None:
|
| 399 |
+
return None
|
| 400 |
+
try:
|
| 401 |
+
devs = sd.query_devices()
|
| 402 |
+
except Exception:
|
| 403 |
+
return None
|
| 404 |
+
|
| 405 |
+
out_name = ""
|
| 406 |
+
try:
|
| 407 |
+
out_idx = int(sd.default.device[1])
|
| 408 |
+
out_name = str(sd.query_devices(out_idx).get("name", "")).lower()
|
| 409 |
+
except Exception:
|
| 410 |
+
out_name = ""
|
| 411 |
+
|
| 412 |
+
loopbacks: List[int] = []
|
| 413 |
+
for i, d in enumerate(devs):
|
| 414 |
+
try:
|
| 415 |
+
if int(d.get("hostapi", -1)) != wasapi_idx:
|
| 416 |
+
continue
|
| 417 |
+
if int(d.get("max_input_channels", 0)) <= 0:
|
| 418 |
+
continue
|
| 419 |
+
name = str(d.get("name", "")).lower()
|
| 420 |
+
if "loopback" in name or "(loopback)" in name:
|
| 421 |
+
loopbacks.append(i)
|
| 422 |
+
except Exception:
|
| 423 |
+
continue
|
| 424 |
+
if not loopbacks:
|
| 425 |
+
return None
|
| 426 |
+
|
| 427 |
+
# Prefer loopback device that matches the default output device name
|
| 428 |
+
if out_name:
|
| 429 |
+
out_stem = out_name.split("(")[0].strip()
|
| 430 |
+
if out_stem:
|
| 431 |
+
for i in loopbacks:
|
| 432 |
+
try:
|
| 433 |
+
name = str(devs[i].get("name", "")).lower()
|
| 434 |
+
if out_stem in name:
|
| 435 |
+
return i
|
| 436 |
+
except Exception:
|
| 437 |
+
continue
|
| 438 |
+
|
| 439 |
+
# Otherwise choose best score (avoid HDMI loopback variants when multiple exist)
|
| 440 |
+
best = None
|
| 441 |
+
best_score = -10_000
|
| 442 |
+
for i in loopbacks:
|
| 443 |
+
try:
|
| 444 |
+
nm = str(devs[i].get("name", ""))
|
| 445 |
+
scv = name_score_audio_device(nm)
|
| 446 |
+
if scv > best_score:
|
| 447 |
+
best_score = scv
|
| 448 |
+
best = i
|
| 449 |
+
except Exception:
|
| 450 |
+
continue
|
| 451 |
+
return best if best is not None else loopbacks[0]
|
| 452 |
+
|
| 453 |
+
def _pick_output_device(self) -> Optional[int]:
|
| 454 |
+
if sd is None or not _WIN:
|
| 455 |
+
return None
|
| 456 |
+
wasapi_idx = self._wasapi_idx()
|
| 457 |
+
if wasapi_idx is None:
|
| 458 |
+
return None
|
| 459 |
+
try:
|
| 460 |
+
devs = sd.query_devices()
|
| 461 |
+
except Exception:
|
| 462 |
+
return None
|
| 463 |
+
|
| 464 |
+
outs: List[int] = []
|
| 465 |
+
for i, d in enumerate(devs):
|
| 466 |
+
try:
|
| 467 |
+
if int(d.get("hostapi", -1)) == wasapi_idx and int(d.get("max_output_channels", 0)) > 0:
|
| 468 |
+
outs.append(i)
|
| 469 |
+
except Exception:
|
| 470 |
+
continue
|
| 471 |
+
if not outs:
|
| 472 |
+
return None
|
| 473 |
+
|
| 474 |
+
# Prefer default output unless it looks like HDMI/display; then pick best-scored output.
|
| 475 |
+
try:
|
| 476 |
+
out_def = int(sd.default.device[1])
|
| 477 |
+
if out_def in outs:
|
| 478 |
+
def_name = str(devs[out_def].get("name", ""))
|
| 479 |
+
if not looks_bad_default_endpoint(def_name):
|
| 480 |
+
return out_def
|
| 481 |
+
except Exception:
|
| 482 |
+
pass
|
| 483 |
+
|
| 484 |
+
best = None
|
| 485 |
+
best_score = -10_000
|
| 486 |
+
for i in outs:
|
| 487 |
+
try:
|
| 488 |
+
nm = str(devs[i].get("name", ""))
|
| 489 |
+
scv = name_score_audio_device(nm)
|
| 490 |
+
if scv > best_score:
|
| 491 |
+
best_score = scv
|
| 492 |
+
best = i
|
| 493 |
+
except Exception:
|
| 494 |
+
continue
|
| 495 |
+
return best if best is not None else outs[0]
|
| 496 |
+
|
| 497 |
+
def start(self) -> None:
|
| 498 |
+
if self._th or sd is None or not _WIN:
|
| 499 |
+
return
|
| 500 |
+
|
| 501 |
+
dev = self._pick_loopback_input_device()
|
| 502 |
+
using_loopback_input = True
|
| 503 |
+
if dev is None:
|
| 504 |
+
dev = self._pick_output_device()
|
| 505 |
+
using_loopback_input = False
|
| 506 |
+
if dev is None:
|
| 507 |
+
logging.info("[SD Loopback] no WASAPI device found.")
|
| 508 |
+
return
|
| 509 |
+
|
| 510 |
+
self._dev_index = dev
|
| 511 |
+
try:
|
| 512 |
+
devinfo = sd.query_devices(dev)
|
| 513 |
+
devname = str(devinfo.get("name", "?"))
|
| 514 |
+
max_in = int(devinfo.get("max_input_channels", 0) or 0)
|
| 515 |
+
max_out = int(devinfo.get("max_output_channels", 0) or 0)
|
| 516 |
+
dev_sr = float(devinfo.get("default_samplerate", self.sr) or self.sr)
|
| 517 |
+
except Exception:
|
| 518 |
+
devname, max_in, max_out, dev_sr = f"dev#{dev}", 0, 2, float(self.sr)
|
| 519 |
+
|
| 520 |
+
extra = None
|
| 521 |
+
try:
|
| 522 |
+
extra = sd.WasapiSettings(loopback=True)
|
| 523 |
+
except Exception:
|
| 524 |
+
extra = None
|
| 525 |
+
self._extra = extra
|
| 526 |
+
|
| 527 |
+
if using_loopback_input:
|
| 528 |
+
self._chosen = f"sd/wasapi loopback-in: {devname}"
|
| 529 |
+
ch_max = max(1, max_in)
|
| 530 |
+
else:
|
| 531 |
+
self._chosen = f"sd/wasapi loopback: {devname}"
|
| 532 |
+
ch_max = max(1, max_out)
|
| 533 |
+
|
| 534 |
+
sr_candidates: List[int] = []
|
| 535 |
+
for s in [self.sr, int(dev_sr), 48000, 44100]:
|
| 536 |
+
if s > 8000 and s not in sr_candidates:
|
| 537 |
+
sr_candidates.append(int(s))
|
| 538 |
+
|
| 539 |
+
ch_candidates: List[int] = []
|
| 540 |
+
for c in [2, 1]:
|
| 541 |
+
if c <= ch_max:
|
| 542 |
+
ch_candidates.append(c)
|
| 543 |
+
if not ch_candidates:
|
| 544 |
+
ch_candidates = [1]
|
| 545 |
+
|
| 546 |
+
def cb(indata, frames, time_info, status): # noqa: ANN001
|
| 547 |
+
try:
|
| 548 |
+
block = np.asarray(indata, dtype=np.float32)
|
| 549 |
+
self.win.push(time.time(), rms_dbfs(block))
|
| 550 |
+
with self._lb_lock:
|
| 551 |
+
self._last_block = block.copy()
|
| 552 |
+
except Exception:
|
| 553 |
+
pass
|
| 554 |
+
|
| 555 |
+
def run():
|
| 556 |
+
try:
|
| 557 |
+
last_err = None
|
| 558 |
+
stream = None
|
| 559 |
+
|
| 560 |
+
for sr_try in sr_candidates:
|
| 561 |
+
for ch_try in ch_candidates:
|
| 562 |
+
try:
|
| 563 |
+
frames = int(round(self.frame_s * sr_try))
|
| 564 |
+
stream = sd.InputStream(
|
| 565 |
+
samplerate=sr_try,
|
| 566 |
+
channels=ch_try,
|
| 567 |
+
dtype="float32",
|
| 568 |
+
blocksize=frames,
|
| 569 |
+
device=self._dev_index,
|
| 570 |
+
extra_settings=self._extra if _WIN else None,
|
| 571 |
+
callback=cb,
|
| 572 |
+
)
|
| 573 |
+
self.sr = int(sr_try)
|
| 574 |
+
self.frames = int(frames)
|
| 575 |
+
self.ok = True
|
| 576 |
+
logging.info("[SD Loopback] opened sr=%s ch=%s (%s)", sr_try, ch_try, self._chosen)
|
| 577 |
+
break
|
| 578 |
+
except Exception as e:
|
| 579 |
+
last_err = e
|
| 580 |
+
stream = None
|
| 581 |
+
if stream is not None:
|
| 582 |
+
break
|
| 583 |
+
|
| 584 |
+
if stream is None:
|
| 585 |
+
logging.info("[SD Loopback] init error: %r", last_err)
|
| 586 |
+
self.ok = False
|
| 587 |
+
return
|
| 588 |
+
|
| 589 |
+
with stream:
|
| 590 |
+
while not self._stop.is_set():
|
| 591 |
+
time.sleep(0.25)
|
| 592 |
+
except Exception as e:
|
| 593 |
+
logging.info("[SD Loopback] thread error: %r", e)
|
| 594 |
+
self.ok = False
|
| 595 |
+
|
| 596 |
+
self._th = threading.Thread(target=run, name="SDLoopback", daemon=True)
|
| 597 |
+
self._th.start()
|
| 598 |
+
|
| 599 |
+
def stop(self) -> None:
|
| 600 |
+
self._stop.set()
|
| 601 |
+
if self._th:
|
| 602 |
+
self._th.join(timeout=1.5)
|
| 603 |
+
|
| 604 |
+
|
| 605 |
+
class StereoMixSampler_SD(SamplerBase):
|
| 606 |
+
"""
|
| 607 |
+
Capture from an *input* device that looks like "Stereo Mix"/"What U Hear".
|
| 608 |
+
|
| 609 |
+
Use CALLBACK mode so we don't depend on PortAudio's blocking API support.
|
| 610 |
+
"""
|
| 611 |
+
|
| 612 |
+
def __init__(self, sr=DEFAULT_SR, frame_s=DEFAULT_FRAME_S, history_s=150.0):
|
| 613 |
+
self.sr = int(sr)
|
| 614 |
+
self.frame_s = float(frame_s)
|
| 615 |
+
self.frames = int(round(self.frame_s * self.sr))
|
| 616 |
+
self.win = PercentileWindow(frame_s, history_s)
|
| 617 |
+
|
| 618 |
+
self.ok = False
|
| 619 |
+
self._stop = threading.Event()
|
| 620 |
+
self._th: Optional[threading.Thread] = None
|
| 621 |
+
self._last_block: Optional[np.ndarray] = None
|
| 622 |
+
self._lb_lock = threading.Lock()
|
| 623 |
+
|
| 624 |
+
self._chosen: Optional[str] = None
|
| 625 |
+
self._dev_index: Optional[int] = None
|
| 626 |
+
|
| 627 |
+
def chosen_name(self) -> Optional[str]:
|
| 628 |
+
return self._chosen if self.ok else None
|
| 629 |
+
|
| 630 |
+
def get_last_block(self) -> Optional[np.ndarray]:
|
| 631 |
+
with self._lb_lock:
|
| 632 |
+
return None if self._last_block is None else self._last_block.copy()
|
| 633 |
+
|
| 634 |
+
def _pick_device(self) -> Optional[int]:
|
| 635 |
+
if sd is None:
|
| 636 |
+
return None
|
| 637 |
+
try:
|
| 638 |
+
devs = sd.query_devices()
|
| 639 |
+
except Exception:
|
| 640 |
+
return None
|
| 641 |
+
|
| 642 |
+
needles = ["stereo mix", "what u hear", "what you hear"]
|
| 643 |
+
hits: List[int] = []
|
| 644 |
+
for i, d in enumerate(devs):
|
| 645 |
+
try:
|
| 646 |
+
name = str(d.get("name", "")).lower()
|
| 647 |
+
max_in = int(d.get("max_input_channels", 0))
|
| 648 |
+
if max_in <= 0:
|
| 649 |
+
continue
|
| 650 |
+
if any(n in name for n in needles):
|
| 651 |
+
hits.append(i)
|
| 652 |
+
except Exception:
|
| 653 |
+
continue
|
| 654 |
+
|
| 655 |
+
if not hits:
|
| 656 |
+
return None
|
| 657 |
+
|
| 658 |
+
# Prefer higher score names (realtek tends to be correct)
|
| 659 |
+
best = None
|
| 660 |
+
best_score = -10_000
|
| 661 |
+
for i in hits:
|
| 662 |
+
try:
|
| 663 |
+
nm = str(devs[i].get("name", ""))
|
| 664 |
+
scv = name_score_audio_device(nm)
|
| 665 |
+
if scv > best_score:
|
| 666 |
+
best_score = scv
|
| 667 |
+
best = i
|
| 668 |
+
except Exception:
|
| 669 |
+
continue
|
| 670 |
+
return best if best is not None else hits[0]
|
| 671 |
+
|
| 672 |
+
def start(self) -> None:
|
| 673 |
+
if self._th or sd is None:
|
| 674 |
+
return
|
| 675 |
+
dev = self._pick_device()
|
| 676 |
+
if dev is None:
|
| 677 |
+
return
|
| 678 |
+
self._dev_index = dev
|
| 679 |
+
|
| 680 |
+
try:
|
| 681 |
+
devinfo = sd.query_devices(dev)
|
| 682 |
+
devname = str(devinfo.get("name", "?"))
|
| 683 |
+
max_in = int(devinfo.get("max_input_channels", 1) or 1)
|
| 684 |
+
dev_sr = float(devinfo.get("default_samplerate", self.sr) or self.sr)
|
| 685 |
+
except Exception:
|
| 686 |
+
devname, max_in, dev_sr = f"dev#{dev}", 1, float(self.sr)
|
| 687 |
+
|
| 688 |
+
self._chosen = f"sd/input: {devname}"
|
| 689 |
+
|
| 690 |
+
sr_candidates: List[int] = []
|
| 691 |
+
for s in [self.sr, int(dev_sr), 48000, 44100]:
|
| 692 |
+
if s > 8000 and s not in sr_candidates:
|
| 693 |
+
sr_candidates.append(int(s))
|
| 694 |
+
|
| 695 |
+
ch_candidates = [c for c in [2, 1] if c <= max_in] or [1]
|
| 696 |
+
|
| 697 |
+
def cb(indata, frames, time_info, status): # noqa: ANN001
|
| 698 |
+
try:
|
| 699 |
+
block = np.asarray(indata, dtype=np.float32)
|
| 700 |
+
self.win.push(time.time(), rms_dbfs(block))
|
| 701 |
+
with self._lb_lock:
|
| 702 |
+
self._last_block = block.copy()
|
| 703 |
+
except Exception:
|
| 704 |
+
pass
|
| 705 |
+
|
| 706 |
+
def run():
|
| 707 |
+
last_err = None
|
| 708 |
+
stream = None
|
| 709 |
+
|
| 710 |
+
for sr_try in sr_candidates:
|
| 711 |
+
for ch_try in ch_candidates:
|
| 712 |
+
try:
|
| 713 |
+
frames = int(round(self.frame_s * sr_try))
|
| 714 |
+
stream = sd.InputStream(
|
| 715 |
+
samplerate=sr_try,
|
| 716 |
+
channels=ch_try,
|
| 717 |
+
dtype="float32",
|
| 718 |
+
blocksize=frames,
|
| 719 |
+
device=self._dev_index,
|
| 720 |
+
callback=cb,
|
| 721 |
+
)
|
| 722 |
+
self.sr = int(sr_try)
|
| 723 |
+
self.frames = int(frames)
|
| 724 |
+
self.ok = True
|
| 725 |
+
logging.info("[StereoMix] opened sr=%s ch=%s (%s)", sr_try, ch_try, self._chosen)
|
| 726 |
+
break
|
| 727 |
+
except Exception as e:
|
| 728 |
+
last_err = e
|
| 729 |
+
stream = None
|
| 730 |
+
if stream is not None:
|
| 731 |
+
break
|
| 732 |
+
|
| 733 |
+
if stream is None:
|
| 734 |
+
logging.info("[StereoMix] init error: %r", last_err)
|
| 735 |
+
self.ok = False
|
| 736 |
+
return
|
| 737 |
+
|
| 738 |
+
try:
|
| 739 |
+
with stream:
|
| 740 |
+
while not self._stop.is_set():
|
| 741 |
+
time.sleep(0.25)
|
| 742 |
+
except Exception as e:
|
| 743 |
+
logging.info("[StereoMix] thread error: %r", e)
|
| 744 |
+
self.ok = False
|
| 745 |
+
|
| 746 |
+
self._th = threading.Thread(target=run, name="StereoMix", daemon=True)
|
| 747 |
+
self._th.start()
|
| 748 |
+
|
| 749 |
+
def stop(self) -> None:
|
| 750 |
+
self._stop.set()
|
| 751 |
+
if self._th:
|
| 752 |
+
self._th.join(timeout=1.5)
|
| 753 |
+
|
| 754 |
+
|
| 755 |
+
class LoopbackSampler_SC(SamplerBase):
|
| 756 |
+
"""python-soundcard loopback (can pick the "wrong" speaker on multi-output systems)."""
|
| 757 |
+
|
| 758 |
+
def __init__(self, sr: int = DEFAULT_SR, frame_s: float = DEFAULT_FRAME_S, history_s: float = 150.0, dev_name: Optional[str] = None):
|
| 759 |
+
self.ok = False
|
| 760 |
+
self.sr = int(sr)
|
| 761 |
+
self.frame_s = float(frame_s)
|
| 762 |
+
self.frames = int(round(self.frame_s * self.sr))
|
| 763 |
+
self.win = PercentileWindow(self.frame_s, history_s)
|
| 764 |
+
self.stop_evt = threading.Event()
|
| 765 |
+
self.th: Optional[threading.Thread] = None
|
| 766 |
+
self._last_block: Optional[np.ndarray] = None
|
| 767 |
+
self._lb_lock = threading.Lock()
|
| 768 |
+
self._chosen_name: Optional[str] = None
|
| 769 |
+
self._dev_name = dev_name
|
| 770 |
+
|
| 771 |
+
def chosen_name(self) -> Optional[str]:
|
| 772 |
+
return self._chosen_name if self.ok else None
|
| 773 |
+
|
| 774 |
+
def get_last_block(self) -> Optional[np.ndarray]:
|
| 775 |
+
with self._lb_lock:
|
| 776 |
+
return None if self._last_block is None else self._last_block.copy()
|
| 777 |
+
|
| 778 |
+
def _speaker_score(self, name: str) -> int:
|
| 779 |
+
return name_score_audio_device(name)
|
| 780 |
+
|
| 781 |
+
def _pick_recorder(self):
|
| 782 |
+
"""
|
| 783 |
+
python-soundcard loopback.
|
| 784 |
+
|
| 785 |
+
Change vs older versions:
|
| 786 |
+
- We do NOT always prioritize sc.default_speaker() if it looks like HDMI/display/etc.
|
| 787 |
+
Instead we score endpoints and choose the best likely-real speaker.
|
| 788 |
+
"""
|
| 789 |
+
if sc is None:
|
| 790 |
+
return None
|
| 791 |
+
|
| 792 |
+
speakers: List[Any] = []
|
| 793 |
+
try:
|
| 794 |
+
speakers = list(sc.all_speakers())
|
| 795 |
+
except Exception:
|
| 796 |
+
speakers = []
|
| 797 |
+
|
| 798 |
+
# If dev_name supplied, try it first.
|
| 799 |
+
if self._dev_name:
|
| 800 |
+
for spk in speakers:
|
| 801 |
+
try:
|
| 802 |
+
if str(getattr(spk, "name", "")) == str(self._dev_name):
|
| 803 |
+
try:
|
| 804 |
+
mic = sc.get_microphone(id=str(spk.name), include_loopback=True)
|
| 805 |
+
self._chosen_name = f"soundcard loopback: {mic.name}"
|
| 806 |
+
for ch in (2, 1):
|
| 807 |
+
try:
|
| 808 |
+
rec = mic.recorder(samplerate=self.sr, channels=ch)
|
| 809 |
+
return rec
|
| 810 |
+
except Exception:
|
| 811 |
+
continue
|
| 812 |
+
except Exception:
|
| 813 |
+
pass
|
| 814 |
+
except Exception:
|
| 815 |
+
continue
|
| 816 |
+
|
| 817 |
+
default_first: List[Any] = []
|
| 818 |
+
try:
|
| 819 |
+
d = sc.default_speaker()
|
| 820 |
+
dname = str(getattr(d, "name", ""))
|
| 821 |
+
if not looks_bad_default_endpoint(dname):
|
| 822 |
+
default_first = [d]
|
| 823 |
+
speakers = [s for s in speakers if getattr(s, "name", None) != getattr(d, "name", None)]
|
| 824 |
+
else:
|
| 825 |
+
# Bad default endpoint: do NOT force it to the front.
|
| 826 |
+
default_first = []
|
| 827 |
+
except Exception:
|
| 828 |
+
default_first = []
|
| 829 |
+
|
| 830 |
+
speakers_sorted = sorted(
|
| 831 |
+
speakers,
|
| 832 |
+
key=lambda s: self._speaker_score(getattr(s, "name", "")),
|
| 833 |
+
reverse=True,
|
| 834 |
+
)
|
| 835 |
+
|
| 836 |
+
candidates = (default_first + speakers_sorted)[:14]
|
| 837 |
+
|
| 838 |
+
for spk in candidates:
|
| 839 |
+
try:
|
| 840 |
+
mic = sc.get_microphone(id=str(spk.name), include_loopback=True)
|
| 841 |
+
self._chosen_name = f"soundcard loopback: {mic.name}"
|
| 842 |
+
for ch in (2, 1):
|
| 843 |
+
try:
|
| 844 |
+
rec = mic.recorder(samplerate=self.sr, channels=ch)
|
| 845 |
+
return rec
|
| 846 |
+
except Exception:
|
| 847 |
+
continue
|
| 848 |
+
except Exception:
|
| 849 |
+
continue
|
| 850 |
+
|
| 851 |
+
return None
|
| 852 |
+
|
| 853 |
+
def start(self) -> None:
|
| 854 |
+
if self.th or sc is None:
|
| 855 |
+
return
|
| 856 |
+
rec = self._pick_recorder()
|
| 857 |
+
if rec is None:
|
| 858 |
+
return
|
| 859 |
+
|
| 860 |
+
def run():
|
| 861 |
+
try:
|
| 862 |
+
with rec:
|
| 863 |
+
while not self.stop_evt.is_set():
|
| 864 |
+
try:
|
| 865 |
+
block = rec.record(self.frames)
|
| 866 |
+
block = np.asarray(block, dtype=np.float32)
|
| 867 |
+
self.win.push(time.time(), rms_dbfs(block))
|
| 868 |
+
with self._lb_lock:
|
| 869 |
+
self._last_block = block.copy()
|
| 870 |
+
except Exception:
|
| 871 |
+
time.sleep(0.05)
|
| 872 |
+
except Exception:
|
| 873 |
+
pass
|
| 874 |
+
|
| 875 |
+
self.th = threading.Thread(target=run, name="SCLoopback", daemon=True)
|
| 876 |
+
self.th.start()
|
| 877 |
+
self.ok = True
|
| 878 |
+
logging.info("[soundcard loopback] running: %s", self._chosen_name)
|
| 879 |
+
|
| 880 |
+
def stop(self) -> None:
|
| 881 |
+
self.stop_evt.set()
|
| 882 |
+
if self.th:
|
| 883 |
+
self.th.join(timeout=1.5)
|
| 884 |
+
|
| 885 |
+
|
| 886 |
+
class PycawPeakSampler(SamplerBase):
|
| 887 |
+
"""
|
| 888 |
+
Reliable-ish fallback: system output peak meter via Pycaw.
|
| 889 |
+
|
| 890 |
+
Notes:
|
| 891 |
+
- This sampler does NOT provide raw audio blocks (so VAD is disabled).
|
| 892 |
+
- Some systems throw intermittent COM errors on GetPeakValue(). We keep emitting samples
|
| 893 |
+
(using last known value) and aggressively re-acquire the meter to self-heal.
|
| 894 |
+
|
| 895 |
+
v0.10.11: relaxed "degraded" threshold so we don't force-switch too aggressively.
|
| 896 |
+
"""
|
| 897 |
+
|
| 898 |
+
def __init__(self, frame_s=DEFAULT_FRAME_S, history_s=150.0):
|
| 899 |
+
self.frame_s = float(frame_s)
|
| 900 |
+
self.win = PercentileWindow(frame_s, history_s)
|
| 901 |
+
self._stop = threading.Event()
|
| 902 |
+
self._th: Optional[threading.Thread] = None
|
| 903 |
+
self._ok = False
|
| 904 |
+
|
| 905 |
+
self._mu = threading.Lock()
|
| 906 |
+
self._succ = 0
|
| 907 |
+
self._fail = 0
|
| 908 |
+
self._fail_streak = 0
|
| 909 |
+
self._last_ok_ts = 0.0
|
| 910 |
+
|
| 911 |
+
def chosen_name(self) -> Optional[str]:
|
| 912 |
+
return "pycaw peak meter" if self._ok else None
|
| 913 |
+
|
| 914 |
+
def is_degraded(self) -> bool:
|
| 915 |
+
with self._mu:
|
| 916 |
+
if not self._ok:
|
| 917 |
+
return True
|
| 918 |
+
now = time.time()
|
| 919 |
+
# v0.10.11: be less trigger-happy.
|
| 920 |
+
# Only declare degraded if we haven't had a successful read in a long time AND fail streak is huge.
|
| 921 |
+
if (now - self._last_ok_ts) > 60.0 and self._fail_streak >= 500:
|
| 922 |
+
return True
|
| 923 |
+
return False
|
| 924 |
+
|
| 925 |
+
def start(self) -> None:
|
| 926 |
+
if self._th or not _WIN:
|
| 927 |
+
return
|
| 928 |
+
|
| 929 |
+
def run():
|
| 930 |
+
meter = None
|
| 931 |
+
last_db = -100.0
|
| 932 |
+
|
| 933 |
+
def acquire():
|
| 934 |
+
nonlocal meter
|
| 935 |
+
try:
|
| 936 |
+
import ctypes
|
| 937 |
+
from ctypes import POINTER
|
| 938 |
+
from pycaw.pycaw import AudioUtilities, IAudioMeterInformation
|
| 939 |
+
from comtypes import CLSCTX_ALL
|
| 940 |
+
|
| 941 |
+
dev = AudioUtilities.GetSpeakers()
|
| 942 |
+
iface = dev.Activate(IAudioMeterInformation._iid_, CLSCTX_ALL, None)
|
| 943 |
+
meter = ctypes.cast(iface, POINTER(IAudioMeterInformation))
|
| 944 |
+
return True
|
| 945 |
+
except Exception as e:
|
| 946 |
+
logging.info("[PycawMeter] acquire failed: %r", e)
|
| 947 |
+
meter = None
|
| 948 |
+
return False
|
| 949 |
+
|
| 950 |
+
CoUninitialize = None
|
| 951 |
+
try:
|
| 952 |
+
try:
|
| 953 |
+
from comtypes import CoInitializeEx, CoUninitialize as _CoUninitialize, COINIT_MULTITHREADED
|
| 954 |
+
CoUninitialize = _CoUninitialize
|
| 955 |
+
CoInitializeEx(COINIT_MULTITHREADED)
|
| 956 |
+
except Exception:
|
| 957 |
+
from comtypes import CoInitialize, CoUninitialize as _CoUninitialize
|
| 958 |
+
CoUninitialize = _CoUninitialize
|
| 959 |
+
CoInitialize()
|
| 960 |
+
|
| 961 |
+
try:
|
| 962 |
+
ok = acquire()
|
| 963 |
+
self._ok = bool(ok)
|
| 964 |
+
if self._ok:
|
| 965 |
+
logging.info("[PycawMeter] running.")
|
| 966 |
+
|
| 967 |
+
last_log = 0.0
|
| 968 |
+
while not self._stop.is_set():
|
| 969 |
+
db = last_db
|
| 970 |
+
try:
|
| 971 |
+
if meter is None:
|
| 972 |
+
acquire()
|
| 973 |
+
|
| 974 |
+
if meter is not None:
|
| 975 |
+
import ctypes
|
| 976 |
+
from ctypes import byref, c_float
|
| 977 |
+
|
| 978 |
+
v = c_float()
|
| 979 |
+
meter.GetPeakValue(byref(v))
|
| 980 |
+
peak = float(v.value)
|
| 981 |
+
if peak <= 0.0 or not math.isfinite(peak):
|
| 982 |
+
db = -100.0
|
| 983 |
+
else:
|
| 984 |
+
db = 20.0 * math.log10(max(1e-9, peak))
|
| 985 |
+
last_db = db
|
| 986 |
+
|
| 987 |
+
with self._mu:
|
| 988 |
+
self._succ += 1
|
| 989 |
+
self._fail_streak = 0
|
| 990 |
+
self._last_ok_ts = time.time()
|
| 991 |
+
else:
|
| 992 |
+
raise RuntimeError("meter not acquired")
|
| 993 |
+
except Exception:
|
| 994 |
+
with self._mu:
|
| 995 |
+
self._fail += 1
|
| 996 |
+
self._fail_streak += 1
|
| 997 |
+
fs = self._fail_streak
|
| 998 |
+
|
| 999 |
+
if fs in (1, 10, 25, 50, 100, 200) or (time.time() - last_log) > 15.0:
|
| 1000 |
+
last_log = time.time()
|
| 1001 |
+
logging.info("[PycawMeter] read error (x%s) — continuing.", fs)
|
| 1002 |
+
|
| 1003 |
+
# keep trying to reacquire periodically, but don't force-switch early
|
| 1004 |
+
if fs in (3, 10, 25, 50, 100, 200, 350) or (time.time() - self._last_ok_ts) > 10.0:
|
| 1005 |
+
acquire()
|
| 1006 |
+
|
| 1007 |
+
# ALWAYS push a sample (even last known) so the controller sees "alive"
|
| 1008 |
+
self.win.push(time.time(), db)
|
| 1009 |
+
time.sleep(self.frame_s)
|
| 1010 |
+
finally:
|
| 1011 |
+
# IMPORTANT: drop COM interface refs BEFORE CoUninitialize
|
| 1012 |
+
try:
|
| 1013 |
+
meter = None
|
| 1014 |
+
gc.collect()
|
| 1015 |
+
except Exception:
|
| 1016 |
+
pass
|
| 1017 |
+
try:
|
| 1018 |
+
if CoUninitialize is not None:
|
| 1019 |
+
CoUninitialize()
|
| 1020 |
+
except Exception:
|
| 1021 |
+
pass
|
| 1022 |
+
except Exception as e:
|
| 1023 |
+
logging.info("[PycawMeter] init error: %r", e)
|
| 1024 |
+
|
| 1025 |
+
self._th = threading.Thread(target=run, name="PycawMeter", daemon=True)
|
| 1026 |
+
self._th.start()
|
| 1027 |
+
|
| 1028 |
+
def stop(self) -> None:
|
| 1029 |
+
self._stop.set()
|
| 1030 |
+
if self._th:
|
| 1031 |
+
self._th.join(timeout=2.5)
|
| 1032 |
+
|
| 1033 |
+
|
| 1034 |
+
class MeterSampler(SamplerBase):
|
| 1035 |
+
"""
|
| 1036 |
+
Last-resort COM meter via CreateObject("MMDeviceEnumerator") and IAudioMeterInformation.
|
| 1037 |
+
"""
|
| 1038 |
+
|
| 1039 |
+
def __init__(self, frame_s=DEFAULT_FRAME_S, history_s=150.0):
|
| 1040 |
+
self.frame_s = float(frame_s)
|
| 1041 |
+
self.win = PercentileWindow(frame_s, history_s)
|
| 1042 |
+
self._ok = False
|
| 1043 |
+
self._stop = threading.Event()
|
| 1044 |
+
self._th: Optional[threading.Thread] = None
|
| 1045 |
+
|
| 1046 |
+
self._mu = threading.Lock()
|
| 1047 |
+
self._fail_streak = 0
|
| 1048 |
+
self._last_ok_ts = 0.0
|
| 1049 |
+
|
| 1050 |
+
def chosen_name(self) -> Optional[str]:
|
| 1051 |
+
return "endpoint peak meter" if self._ok else None
|
| 1052 |
+
|
| 1053 |
+
def is_degraded(self) -> bool:
|
| 1054 |
+
with self._mu:
|
| 1055 |
+
if not self._ok:
|
| 1056 |
+
return True
|
| 1057 |
+
# slightly relaxed vs old: require longer time with no ok and a big fail streak
|
| 1058 |
+
if (time.time() - self._last_ok_ts) > 60.0 and self._fail_streak >= 500:
|
| 1059 |
+
return True
|
| 1060 |
+
return False
|
| 1061 |
+
|
| 1062 |
+
def start(self) -> None:
|
| 1063 |
+
if self._th or not _WIN:
|
| 1064 |
+
return
|
| 1065 |
+
|
| 1066 |
+
def run():
|
| 1067 |
+
meter = None
|
| 1068 |
+
last_db = -100.0
|
| 1069 |
+
|
| 1070 |
+
def acquire():
|
| 1071 |
+
nonlocal meter
|
| 1072 |
+
try:
|
| 1073 |
+
import ctypes
|
| 1074 |
+
from ctypes import POINTER, byref, c_float, c_int, c_void_p, c_ulong
|
| 1075 |
+
from comtypes import (
|
| 1076 |
+
IUnknown, GUID, HRESULT, COMMETHOD,
|
| 1077 |
+
CLSCTX_ALL,
|
| 1078 |
+
)
|
| 1079 |
+
from comtypes.client import CreateObject
|
| 1080 |
+
|
| 1081 |
+
eRender = 0
|
| 1082 |
+
eMultimedia = 1
|
| 1083 |
+
|
| 1084 |
+
class IMMDevice(IUnknown):
|
| 1085 |
+
_iid_ = GUID('{D666063F-1587-4E43-81F1-B948E807363F}')
|
| 1086 |
+
_methods_ = [
|
| 1087 |
+
COMMETHOD([], HRESULT, 'Activate',
|
| 1088 |
+
(['in'], GUID, 'iid'),
|
| 1089 |
+
(['in'], c_ulong, 'dwClsCtx'),
|
| 1090 |
+
(['in'], c_void_p, 'pActivationParams'),
|
| 1091 |
+
(['out'], POINTER(c_void_p), 'ppInterface')),
|
| 1092 |
+
]
|
| 1093 |
+
|
| 1094 |
+
class IMMDeviceEnumerator(IUnknown):
|
| 1095 |
+
_iid_ = GUID('{A95664D2-9614-4F35-A746-DE8DB63617E6}')
|
| 1096 |
+
_methods_ = [
|
| 1097 |
+
COMMETHOD([], HRESULT, 'GetDefaultAudioEndpoint',
|
| 1098 |
+
(['in'], c_int, 'dataFlow'),
|
| 1099 |
+
(['in'], c_int, 'role'),
|
| 1100 |
+
(['out'], POINTER(POINTER(IMMDevice)), 'ppDevice')),
|
| 1101 |
+
]
|
| 1102 |
+
|
| 1103 |
+
class IAudioMeterInformation(IUnknown):
|
| 1104 |
+
_iid_ = GUID('{C02216F6-8C67-4B5B-9D00-D008E73E0064}')
|
| 1105 |
+
_methods_ = [
|
| 1106 |
+
COMMETHOD([], HRESULT, 'GetPeakValue',
|
| 1107 |
+
(['out'], POINTER(c_float), 'pfPeak')),
|
| 1108 |
+
]
|
| 1109 |
+
|
| 1110 |
+
enum = CreateObject("MMDeviceEnumerator", interface=IMMDeviceEnumerator)
|
| 1111 |
+
dev = POINTER(IMMDevice)()
|
| 1112 |
+
hr = enum.GetDefaultAudioEndpoint(eRender, eMultimedia, byref(dev))
|
| 1113 |
+
if hr:
|
| 1114 |
+
raise OSError(f"GetDefaultAudioEndpoint failed hr=0x{hr:08X}")
|
| 1115 |
+
ptr = c_void_p()
|
| 1116 |
+
hr = dev.Activate(IAudioMeterInformation._iid_, CLSCTX_ALL, None, byref(ptr))
|
| 1117 |
+
if hr:
|
| 1118 |
+
raise OSError(f"Activate(IAudioMeterInformation) failed hr=0x{hr:08X}")
|
| 1119 |
+
|
| 1120 |
+
meter = ctypes.cast(ptr, POINTER(IAudioMeterInformation))
|
| 1121 |
+
return True
|
| 1122 |
+
except Exception as e:
|
| 1123 |
+
logging.info("[Meter] acquire failed: %r", e)
|
| 1124 |
+
meter = None
|
| 1125 |
+
return False
|
| 1126 |
+
|
| 1127 |
+
CoUninitialize = None
|
| 1128 |
+
try:
|
| 1129 |
+
try:
|
| 1130 |
+
from comtypes import CoInitializeEx, CoUninitialize as _CoUninitialize, COINIT_MULTITHREADED
|
| 1131 |
+
CoUninitialize = _CoUninitialize
|
| 1132 |
+
CoInitializeEx(COINIT_MULTITHREADED)
|
| 1133 |
+
except Exception:
|
| 1134 |
+
from comtypes import CoInitialize, CoUninitialize as _CoUninitialize
|
| 1135 |
+
CoUninitialize = _CoUninitialize
|
| 1136 |
+
CoInitialize()
|
| 1137 |
+
|
| 1138 |
+
try:
|
| 1139 |
+
ok = acquire()
|
| 1140 |
+
self._ok = bool(ok)
|
| 1141 |
+
if self._ok:
|
| 1142 |
+
logging.info("[Meter] running (COM peak).")
|
| 1143 |
+
|
| 1144 |
+
last_log = 0.0
|
| 1145 |
+
while not self._stop.is_set():
|
| 1146 |
+
db = last_db
|
| 1147 |
+
try:
|
| 1148 |
+
if meter is None:
|
| 1149 |
+
acquire()
|
| 1150 |
+
|
| 1151 |
+
if meter is not None:
|
| 1152 |
+
from ctypes import byref, c_float
|
| 1153 |
+
v = c_float()
|
| 1154 |
+
meter.GetPeakValue(byref(v))
|
| 1155 |
+
peak = float(v.value)
|
| 1156 |
+
if peak <= 0.0 or not math.isfinite(peak):
|
| 1157 |
+
db = -100.0
|
| 1158 |
+
else:
|
| 1159 |
+
db = 20.0 * math.log10(max(1e-9, peak))
|
| 1160 |
+
last_db = db
|
| 1161 |
+
|
| 1162 |
+
with self._mu:
|
| 1163 |
+
self._fail_streak = 0
|
| 1164 |
+
self._last_ok_ts = time.time()
|
| 1165 |
+
else:
|
| 1166 |
+
raise RuntimeError("meter not acquired")
|
| 1167 |
+
except Exception:
|
| 1168 |
+
with self._mu:
|
| 1169 |
+
self._fail_streak += 1
|
| 1170 |
+
fs = self._fail_streak
|
| 1171 |
+
|
| 1172 |
+
if fs in (1, 10, 25, 50, 100, 200) or (time.time() - last_log) > 15.0:
|
| 1173 |
+
last_log = time.time()
|
| 1174 |
+
logging.info("[Meter] read error (x%s) — continuing.", fs)
|
| 1175 |
+
|
| 1176 |
+
if fs in (3, 10, 25, 50, 100, 200, 350):
|
| 1177 |
+
acquire()
|
| 1178 |
+
|
| 1179 |
+
self.win.push(time.time(), db)
|
| 1180 |
+
time.sleep(self.frame_s)
|
| 1181 |
+
finally:
|
| 1182 |
+
# IMPORTANT: drop COM interface refs BEFORE CoUninitialize
|
| 1183 |
+
try:
|
| 1184 |
+
meter = None
|
| 1185 |
+
gc.collect()
|
| 1186 |
+
except Exception:
|
| 1187 |
+
pass
|
| 1188 |
+
try:
|
| 1189 |
+
if CoUninitialize is not None:
|
| 1190 |
+
CoUninitialize()
|
| 1191 |
+
except Exception:
|
| 1192 |
+
pass
|
| 1193 |
+
except Exception as e:
|
| 1194 |
+
logging.info("[Meter] init error: %r", e)
|
| 1195 |
+
|
| 1196 |
+
self._th = threading.Thread(target=run, name="MeterCOM", daemon=True)
|
| 1197 |
+
self._th.start()
|
| 1198 |
+
|
| 1199 |
+
def stop(self) -> None:
|
| 1200 |
+
self._stop.set()
|
| 1201 |
+
if self._th:
|
| 1202 |
+
self._th.join(timeout=2.5)
|
| 1203 |
+
|
| 1204 |
+
|
| 1205 |
+
# ------------------ volume backends ------------------
|
| 1206 |
+
|
| 1207 |
+
class VolBackend:
|
| 1208 |
+
def get(self) -> float:
|
| 1209 |
+
raise NotImplementedError
|
| 1210 |
+
|
| 1211 |
+
def set(self, s: float) -> None:
|
| 1212 |
+
raise NotImplementedError
|
| 1213 |
+
|
| 1214 |
+
|
| 1215 |
+
class WinVolSTA(VolBackend):
|
| 1216 |
+
"""System master volume via pycaw on a dedicated COM thread."""
|
| 1217 |
+
|
| 1218 |
+
def __init__(self):
|
| 1219 |
+
self._q: queue.Queue = queue.Queue()
|
| 1220 |
+
self._ready = threading.Event()
|
| 1221 |
+
self._stop = threading.Event()
|
| 1222 |
+
self._th = threading.Thread(target=self._run, name="WinVolCOM", daemon=True)
|
| 1223 |
+
self._th.start()
|
| 1224 |
+
if not self._ready.wait(timeout=2.5):
|
| 1225 |
+
raise RuntimeError("WinVolSTA COM init timed out")
|
| 1226 |
+
|
| 1227 |
+
def _run(self):
|
| 1228 |
+
dev = None
|
| 1229 |
+
iface = None
|
| 1230 |
+
ep = None
|
| 1231 |
+
CoUninitialize = None
|
| 1232 |
+
try:
|
| 1233 |
+
from comtypes import CoInitialize, CoUninitialize as _CoUninitialize, CLSCTX_ALL # type: ignore
|
| 1234 |
+
from ctypes import POINTER, cast
|
| 1235 |
+
from pycaw.pycaw import AudioUtilities, IAudioEndpointVolume # type: ignore
|
| 1236 |
+
|
| 1237 |
+
CoUninitialize = _CoUninitialize
|
| 1238 |
+
|
| 1239 |
+
CoInitialize()
|
| 1240 |
+
try:
|
| 1241 |
+
dev = AudioUtilities.GetSpeakers()
|
| 1242 |
+
iface = dev.Activate(IAudioEndpointVolume._iid_, CLSCTX_ALL, None)
|
| 1243 |
+
ep = cast(iface, POINTER(IAudioEndpointVolume))
|
| 1244 |
+
self._ready.set()
|
| 1245 |
+
|
| 1246 |
+
while not self._stop.is_set():
|
| 1247 |
+
try:
|
| 1248 |
+
op, val, ack = self._q.get(timeout=0.1)
|
| 1249 |
+
except queue.Empty:
|
| 1250 |
+
continue
|
| 1251 |
+
try:
|
| 1252 |
+
if op == "get":
|
| 1253 |
+
ack.set_result(float(ep.GetMasterVolumeLevelScalar()))
|
| 1254 |
+
elif op == "set":
|
| 1255 |
+
ep.SetMasterVolumeLevelScalar(clamp(float(val), 0.0, 1.0), None)
|
| 1256 |
+
ack.set_result(True)
|
| 1257 |
+
elif op == "quit":
|
| 1258 |
+
ack.set_result(True)
|
| 1259 |
+
break
|
| 1260 |
+
except Exception as e:
|
| 1261 |
+
ack.set_exception(e)
|
| 1262 |
+
finally:
|
| 1263 |
+
# IMPORTANT: drop COM interface refs BEFORE CoUninitialize
|
| 1264 |
+
try:
|
| 1265 |
+
ep = None
|
| 1266 |
+
iface = None
|
| 1267 |
+
dev = None
|
| 1268 |
+
gc.collect()
|
| 1269 |
+
except Exception:
|
| 1270 |
+
pass
|
| 1271 |
+
try:
|
| 1272 |
+
if CoUninitialize is not None:
|
| 1273 |
+
CoUninitialize()
|
| 1274 |
+
except Exception:
|
| 1275 |
+
pass
|
| 1276 |
+
except Exception as e:
|
| 1277 |
+
self._ready.set()
|
| 1278 |
+
try:
|
| 1279 |
+
while True:
|
| 1280 |
+
op, val, ack = self._q.get_nowait()
|
| 1281 |
+
ack.set_exception(e)
|
| 1282 |
+
except queue.Empty:
|
| 1283 |
+
pass
|
| 1284 |
+
|
| 1285 |
+
class _Ack:
|
| 1286 |
+
def __init__(self):
|
| 1287 |
+
self._ev = threading.Event()
|
| 1288 |
+
self._res = None
|
| 1289 |
+
self._exc: Optional[BaseException] = None
|
| 1290 |
+
|
| 1291 |
+
def set_result(self, r):
|
| 1292 |
+
self._res = r
|
| 1293 |
+
self._ev.set()
|
| 1294 |
+
|
| 1295 |
+
def set_exception(self, e: BaseException):
|
| 1296 |
+
self._exc = e
|
| 1297 |
+
self._ev.set()
|
| 1298 |
+
|
| 1299 |
+
def wait(self, timeout=None):
|
| 1300 |
+
ok = self._ev.wait(timeout)
|
| 1301 |
+
if not ok:
|
| 1302 |
+
raise TimeoutError("WinVolSTA RPC timed out")
|
| 1303 |
+
if self._exc:
|
| 1304 |
+
raise self._exc
|
| 1305 |
+
return self._res
|
| 1306 |
+
|
| 1307 |
+
def _rpc(self, op: str, val=None, timeout=2.0):
|
| 1308 |
+
ack = WinVolSTA._Ack()
|
| 1309 |
+
self._q.put((op, val, ack))
|
| 1310 |
+
return ack.wait(timeout=timeout)
|
| 1311 |
+
|
| 1312 |
+
def get(self) -> float:
|
| 1313 |
+
try:
|
| 1314 |
+
return float(self._rpc("get"))
|
| 1315 |
+
except Exception:
|
| 1316 |
+
return 0.5
|
| 1317 |
+
|
| 1318 |
+
def set(self, s: float) -> None:
|
| 1319 |
+
try:
|
| 1320 |
+
self._rpc("set", s)
|
| 1321 |
+
except Exception:
|
| 1322 |
+
pass
|
| 1323 |
+
|
| 1324 |
+
def close(self):
|
| 1325 |
+
try:
|
| 1326 |
+
self._rpc("quit", timeout=1.5)
|
| 1327 |
+
except Exception:
|
| 1328 |
+
pass
|
| 1329 |
+
self._stop.set()
|
| 1330 |
+
try:
|
| 1331 |
+
if self._th and self._th.is_alive():
|
| 1332 |
+
self._th.join(timeout=2.5)
|
| 1333 |
+
except Exception:
|
| 1334 |
+
pass
|
| 1335 |
+
|
| 1336 |
+
|
| 1337 |
+
class DryVol(VolBackend):
|
| 1338 |
+
def __init__(self):
|
| 1339 |
+
self._s = 0.4
|
| 1340 |
+
|
| 1341 |
+
def get(self) -> float:
|
| 1342 |
+
return self._s
|
| 1343 |
+
|
| 1344 |
+
def set(self, s: float) -> None:
|
| 1345 |
+
self._s = clamp(float(s), 0.0, 1.0)
|
| 1346 |
+
|
| 1347 |
+
|
| 1348 |
+
def choose_backend(force_dry: bool = False) -> VolBackend:
|
| 1349 |
+
if not _WIN or force_dry:
|
| 1350 |
+
logging.info("[Vol] Using DryVol (no system changes).")
|
| 1351 |
+
return DryVol()
|
| 1352 |
+
try:
|
| 1353 |
+
bk = WinVolSTA()
|
| 1354 |
+
logging.info("[Vol] Using WinVolSTA (COM thread).")
|
| 1355 |
+
return bk
|
| 1356 |
+
except Exception as e:
|
| 1357 |
+
logging.info("[Vol] Falling back to DryVol: %r", e)
|
| 1358 |
+
return DryVol()
|
| 1359 |
+
|
| 1360 |
+
|
| 1361 |
+
# ------------------ learner ------------------
|
| 1362 |
+
|
| 1363 |
+
class Learner:
|
| 1364 |
+
def __init__(self, path: str, min_events=6, q=0.70):
|
| 1365 |
+
self.path = path
|
| 1366 |
+
self.min_events = int(min_events)
|
| 1367 |
+
self.q = float(q)
|
| 1368 |
+
self.global_downs: Deque[float] = deque(maxlen=600)
|
| 1369 |
+
self.hour_downs: Dict[int, Deque[float]] = {h: deque(maxlen=300) for h in range(24)}
|
| 1370 |
+
self._mu = threading.Lock()
|
| 1371 |
+
self.load()
|
| 1372 |
+
|
| 1373 |
+
def load(self):
|
| 1374 |
+
if not os.path.exists(self.path):
|
| 1375 |
+
return
|
| 1376 |
+
try:
|
| 1377 |
+
with open(self.path, "r", encoding="utf-8") as f:
|
| 1378 |
+
data = json.load(f)
|
| 1379 |
+
except Exception as e:
|
| 1380 |
+
logging.info("[Learner] load error: %r", e)
|
| 1381 |
+
return
|
| 1382 |
+
|
| 1383 |
+
with self._mu:
|
| 1384 |
+
self.global_downs.clear()
|
| 1385 |
+
for h in range(24):
|
| 1386 |
+
self.hour_downs[h].clear()
|
| 1387 |
+
|
| 1388 |
+
g_src = data.get("global_downs", [])
|
| 1389 |
+
if isinstance(g_src, list):
|
| 1390 |
+
for x in g_src[-600:]:
|
| 1391 |
+
try:
|
| 1392 |
+
self.global_downs.append(float(x))
|
| 1393 |
+
except Exception:
|
| 1394 |
+
pass
|
| 1395 |
+
|
| 1396 |
+
h_src = data.get("hour_downs", {})
|
| 1397 |
+
if isinstance(h_src, dict):
|
| 1398 |
+
for k, arr in h_src.items():
|
| 1399 |
+
try:
|
| 1400 |
+
h = int(k)
|
| 1401 |
+
if 0 <= h <= 23 and isinstance(arr, list):
|
| 1402 |
+
for x in arr[-300:]:
|
| 1403 |
+
try:
|
| 1404 |
+
self.hour_downs[h].append(float(x))
|
| 1405 |
+
except Exception:
|
| 1406 |
+
pass
|
| 1407 |
+
except Exception:
|
| 1408 |
+
continue
|
| 1409 |
+
|
| 1410 |
+
def save(self):
|
| 1411 |
+
try:
|
| 1412 |
+
with self._mu:
|
| 1413 |
+
out = {
|
| 1414 |
+
"global_downs": list(self.global_downs),
|
| 1415 |
+
"hour_downs": {str(h): list(self.hour_downs[h]) for h in range(24)},
|
| 1416 |
+
}
|
| 1417 |
+
tmp = self.path + ".tmp"
|
| 1418 |
+
with open(tmp, "w", encoding="utf-8") as f:
|
| 1419 |
+
json.dump(out, f)
|
| 1420 |
+
os.replace(tmp, self.path)
|
| 1421 |
+
except Exception as e:
|
| 1422 |
+
logging.info("[Learner] save error: %r", e)
|
| 1423 |
+
|
| 1424 |
+
@staticmethod
|
| 1425 |
+
def _percentile(vals: List[float], q: float) -> float:
|
| 1426 |
+
if not vals:
|
| 1427 |
+
return -100.0
|
| 1428 |
+
s = sorted(vals)
|
| 1429 |
+
k = int(round((len(s) - 1) * clamp(q, 0.0, 1.0)))
|
| 1430 |
+
return float(s[k])
|
| 1431 |
+
|
| 1432 |
+
def record_down(self, db_at: float, hour: int):
|
| 1433 |
+
with self._mu:
|
| 1434 |
+
self.global_downs.append(float(db_at))
|
| 1435 |
+
if 0 <= hour <= 23:
|
| 1436 |
+
self.hour_downs[hour].append(float(db_at))
|
| 1437 |
+
|
| 1438 |
+
def threshold(self, hour: int) -> Optional[float]:
|
| 1439 |
+
with self._mu:
|
| 1440 |
+
per = self.hour_downs.get(hour, deque())
|
| 1441 |
+
g = self.global_downs
|
| 1442 |
+
|
| 1443 |
+
if len(per) >= self.min_events:
|
| 1444 |
+
q_use = 0.75 if len(per) > 20 else self.q
|
| 1445 |
+
return self._percentile(list(per), q_use)
|
| 1446 |
+
|
| 1447 |
+
if len(g) >= self.min_events:
|
| 1448 |
+
q_use = 0.75 if len(g) > 20 else self.q
|
| 1449 |
+
return self._percentile(list(g), q_use)
|
| 1450 |
+
|
| 1451 |
+
return None
|
| 1452 |
+
|
| 1453 |
+
def counts(self) -> Tuple[int, Dict[int, int]]:
|
| 1454 |
+
with self._mu:
|
| 1455 |
+
return len(self.global_downs), {h: len(self.hour_downs[h]) for h in range(24)}
|
| 1456 |
+
|
| 1457 |
+
def reset(self):
|
| 1458 |
+
with self._mu:
|
| 1459 |
+
self.global_downs.clear()
|
| 1460 |
+
for h in range(24):
|
| 1461 |
+
self.hour_downs[h].clear()
|
| 1462 |
+
self.save()
|
| 1463 |
+
|
| 1464 |
+
|
| 1465 |
+
# ------------------ speech gate ------------------
|
| 1466 |
+
|
| 1467 |
+
class SpeechGate:
|
| 1468 |
+
def __init__(self, fs_capture: int, frame_ms: int = 20, aggressiveness: int = 2, ema_alpha: float = 0.35):
|
| 1469 |
+
self.fs_cap = int(fs_capture)
|
| 1470 |
+
self.frame_ms = int(frame_ms)
|
| 1471 |
+
self._ema = 0.0
|
| 1472 |
+
self._alpha = float(clamp(ema_alpha, 0.0, 1.0))
|
| 1473 |
+
self._have_vad = _HAVE_WEBRTCVAD
|
| 1474 |
+
if self._have_vad:
|
| 1475 |
+
self.vad = webrtcvad.Vad(int(clamp(aggressiveness, 0, 3)))
|
| 1476 |
+
|
| 1477 |
+
def _to_16k_pcm16(self, x: np.ndarray) -> Tuple[bytes, int]:
|
| 1478 |
+
if x.ndim > 1:
|
| 1479 |
+
x = x.mean(axis=1)
|
| 1480 |
+
fs16 = 16000
|
| 1481 |
+
if self.fs_cap == 48000:
|
| 1482 |
+
x = x[::3]
|
| 1483 |
+
else:
|
| 1484 |
+
idx = np.linspace(0, len(x) - 1, int(len(x) * fs16 / self.fs_cap))
|
| 1485 |
+
x = np.interp(idx, np.arange(len(x)), x).astype(np.float32)
|
| 1486 |
+
x = np.clip(x, -1.0, 1.0)
|
| 1487 |
+
return (x * 32767.0).astype(np.int16).tobytes(), fs16
|
| 1488 |
+
|
| 1489 |
+
def _heuristic_prob(self, block: np.ndarray) -> float:
|
| 1490 |
+
if block.ndim > 1:
|
| 1491 |
+
x = block.mean(axis=1).astype(np.float32, copy=False)
|
| 1492 |
+
else:
|
| 1493 |
+
x = block.astype(np.float32, copy=False)
|
| 1494 |
+
|
| 1495 |
+
e_db = 20.0 * math.log10(max(1e-9, float(np.sqrt(np.mean(x * x)))))
|
| 1496 |
+
if e_db <= -55.0 or len(x) < 512:
|
| 1497 |
+
return 0.0
|
| 1498 |
+
|
| 1499 |
+
zc = float(np.mean((x[1:] * x[:-1]) < 0.0))
|
| 1500 |
+
X = np.fft.rfft(x * np.hanning(len(x)))
|
| 1501 |
+
mag = np.abs(X) + 1e-9
|
| 1502 |
+
freqs = np.fft.rfftfreq(len(x), 1.0 / self.fs_cap)
|
| 1503 |
+
hf = float(mag[freqs >= 2000].sum() / mag.sum())
|
| 1504 |
+
return 1.0 if (0.03 <= zc <= 0.25) and (0.05 <= hf <= 0.60) else 0.0
|
| 1505 |
+
|
| 1506 |
+
def prob(self, block: Optional[np.ndarray]) -> float:
|
| 1507 |
+
if block is None or getattr(block, "size", 0) == 0:
|
| 1508 |
+
self._ema = (1.0 - self._alpha) * self._ema
|
| 1509 |
+
return self._ema
|
| 1510 |
+
|
| 1511 |
+
if self._have_vad:
|
| 1512 |
+
try:
|
| 1513 |
+
pcm16, fs16 = self._to_16k_pcm16(block)
|
| 1514 |
+
frame_len = int((self.frame_ms / 1000.0) * fs16)
|
| 1515 |
+
hits = 0
|
| 1516 |
+
total = 0
|
| 1517 |
+
step = frame_len * 2
|
| 1518 |
+
for i in range(0, len(pcm16), step):
|
| 1519 |
+
frame = pcm16[i: i + step]
|
| 1520 |
+
if len(frame) < step:
|
| 1521 |
+
break
|
| 1522 |
+
total += 1
|
| 1523 |
+
if self.vad.is_speech(frame, fs16):
|
| 1524 |
+
hits += 1
|
| 1525 |
+
raw = (hits / total) if total else 0.0
|
| 1526 |
+
except Exception:
|
| 1527 |
+
raw = 0.0
|
| 1528 |
+
else:
|
| 1529 |
+
raw = self._heuristic_prob(block)
|
| 1530 |
+
|
| 1531 |
+
self._ema = self._alpha * raw + (1.0 - self._alpha) * self._ema
|
| 1532 |
+
return self._ema
|
| 1533 |
+
|
| 1534 |
+
|
| 1535 |
+
# ------------------ volume poller ------------------
|
| 1536 |
+
|
| 1537 |
+
class VolumePoller:
|
| 1538 |
+
def __init__(self, bk, poll_s=0.05, min_step=0.005):
|
| 1539 |
+
self.bk = bk
|
| 1540 |
+
self.poll_s = float(poll_s)
|
| 1541 |
+
self.min_step = float(min_step)
|
| 1542 |
+
self._stop = threading.Event()
|
| 1543 |
+
self._thr: Optional[threading.Thread] = None
|
| 1544 |
+
self._prev = self.bk.get()
|
| 1545 |
+
self._callbacks: List[Callable[[float, float, float], None]] = []
|
| 1546 |
+
|
| 1547 |
+
def on_change(self, fn: Callable[[float, float, float], None]):
|
| 1548 |
+
self._callbacks.append(fn)
|
| 1549 |
+
|
| 1550 |
+
def start(self):
|
| 1551 |
+
if self._thr:
|
| 1552 |
+
return
|
| 1553 |
+
|
| 1554 |
+
def run():
|
| 1555 |
+
while not self._stop.is_set():
|
| 1556 |
+
time.sleep(self.poll_s)
|
| 1557 |
+
try:
|
| 1558 |
+
cur = self.bk.get()
|
| 1559 |
+
except Exception:
|
| 1560 |
+
continue
|
| 1561 |
+
prev = self._prev
|
| 1562 |
+
if abs(cur - prev) >= self.min_step:
|
| 1563 |
+
ts = time.time()
|
| 1564 |
+
for fn in self._callbacks:
|
| 1565 |
+
try:
|
| 1566 |
+
fn(ts, prev, cur)
|
| 1567 |
+
except Exception:
|
| 1568 |
+
pass
|
| 1569 |
+
self._prev = cur
|
| 1570 |
+
|
| 1571 |
+
self._thr = threading.Thread(target=run, name="VolPoll", daemon=True)
|
| 1572 |
+
self._thr.start()
|
| 1573 |
+
|
| 1574 |
+
def stop(self):
|
| 1575 |
+
self._stop.set()
|
| 1576 |
+
if self._thr:
|
| 1577 |
+
self._thr.join(timeout=1.5)
|
| 1578 |
+
|
| 1579 |
+
|
| 1580 |
+
# ------------------ controller ------------------
|
| 1581 |
+
|
| 1582 |
+
class AutoVolController:
|
| 1583 |
+
def __init__(self, model_path: str, events_path: str, force_dryvol: bool = False):
|
| 1584 |
+
self.model_path = model_path
|
| 1585 |
+
self.events_path = events_path
|
| 1586 |
+
|
| 1587 |
+
self.FRAME_S = DEFAULT_FRAME_S
|
| 1588 |
+
self.BASELINE_WIN_S = 45.0
|
| 1589 |
+
self.SHORT_WIN_S = 1.0
|
| 1590 |
+
|
| 1591 |
+
self.OVER_MARGIN_DB = 1.2
|
| 1592 |
+
self.ATTACK_DB_MAX = 1.6
|
| 1593 |
+
self.RELEASE_DB_MAX = 0.45
|
| 1594 |
+
self.MIN_VOL = 0.03
|
| 1595 |
+
|
| 1596 |
+
self.SPEECH_UP_DB = 2.0
|
| 1597 |
+
self.NOSPEECH_DOWN_DB = -2.0
|
| 1598 |
+
|
| 1599 |
+
self.IGNORE_OWN_SET_S = 0.8
|
| 1600 |
+
self.USER_DOWN_COOLDOWN_S = 1.2
|
| 1601 |
+
self.SET_COOLDOWN_S = 1.6
|
| 1602 |
+
self.STARTUP_OBS_S = 6.0
|
| 1603 |
+
|
| 1604 |
+
self.NO_SAMPLE_GRACE_S = 8.0
|
| 1605 |
+
self.SWITCH_COOLDOWN_S = 15.0
|
| 1606 |
+
|
| 1607 |
+
# v0.10.11: selection preflight and backoff (reduces infinite sampler cycling)
|
| 1608 |
+
self.SAMPLER_PREFLIGHT_S = 4.5
|
| 1609 |
+
self.SAMPLER_BACKOFF_BASE_S = 25.0
|
| 1610 |
+
self.SAMPLER_BACKOFF_MAX_S = 15 * 60.0
|
| 1611 |
+
|
| 1612 |
+
self._stop = threading.Event()
|
| 1613 |
+
self._paused = threading.Event()
|
| 1614 |
+
self._observe = threading.Event() # observe-only mode (no volume changes)
|
| 1615 |
+
self._thread: Optional[threading.Thread] = None
|
| 1616 |
+
self._last_set_ts = 0.0
|
| 1617 |
+
self._last_user_down_ts = 0.0
|
| 1618 |
+
self._startup_ts = time.time()
|
| 1619 |
+
|
| 1620 |
+
self.observe_only = False
|
| 1621 |
+
|
| 1622 |
+
self._last_th: Optional[float] = None
|
| 1623 |
+
self._last_p85 = -100.0
|
| 1624 |
+
self._last_p95 = -100.0
|
| 1625 |
+
self._speech = 0.0
|
| 1626 |
+
self._flash_duck_until = 0.0
|
| 1627 |
+
|
| 1628 |
+
self._signal_state = "INIT"
|
| 1629 |
+
self._last_sample_ts = time.time()
|
| 1630 |
+
self._last_switch_ts = 0.0
|
| 1631 |
+
|
| 1632 |
+
self.bk = choose_backend(force_dry=force_dryvol)
|
| 1633 |
+
self.learner = Learner(path=self.model_path)
|
| 1634 |
+
self._downs_total = self.learner.counts()[0]
|
| 1635 |
+
|
| 1636 |
+
try:
|
| 1637 |
+
self.events = open(self.events_path, "a", encoding="utf-8")
|
| 1638 |
+
except Exception as e:
|
| 1639 |
+
logging.info("[AutoVol] cannot open events file: %r", e)
|
| 1640 |
+
self.events = None
|
| 1641 |
+
|
| 1642 |
+
self.resting = self.bk.get()
|
| 1643 |
+
self.current = self.resting
|
| 1644 |
+
|
| 1645 |
+
self.poll = VolumePoller(self.bk, poll_s=0.05, min_step=0.005)
|
| 1646 |
+
self.poll.on_change(self._on_user_change)
|
| 1647 |
+
|
| 1648 |
+
self.vad = SpeechGate(fs_capture=48000, frame_ms=20, aggressiveness=2, ema_alpha=0.35)
|
| 1649 |
+
|
| 1650 |
+
self._samplers: List[SamplerBase] = [
|
| 1651 |
+
LoopbackSampler_SD(sr=48000, frame_s=self.FRAME_S, history_s=150.0),
|
| 1652 |
+
LoopbackSampler_SC(sr=48000, frame_s=self.FRAME_S, history_s=150.0),
|
| 1653 |
+
PycawPeakSampler(frame_s=self.FRAME_S, history_s=150.0),
|
| 1654 |
+
StereoMixSampler_SD(sr=48000, frame_s=self.FRAME_S, history_s=150.0),
|
| 1655 |
+
MeterSampler(frame_s=self.FRAME_S, history_s=150.0),
|
| 1656 |
+
]
|
| 1657 |
+
|
| 1658 |
+
self.sampler: Optional[SamplerBase] = None
|
| 1659 |
+
self._sampler_idx = -1
|
| 1660 |
+
|
| 1661 |
+
# v0.10.11: per-sampler backoff
|
| 1662 |
+
self._sampler_fail: Dict[str, Dict[str, float]] = {}
|
| 1663 |
+
|
| 1664 |
+
self._switch_sampler(reason="startup")
|
| 1665 |
+
|
| 1666 |
+
bk_name = "WinVolSTA" if isinstance(self.bk, WinVolSTA) else "DryVol"
|
| 1667 |
+
src = self.sampler.chosen_name() if self.sampler else "none"
|
| 1668 |
+
logging.info("[AutoVol] backend=%s sampler=%s model=%s events=%s", bk_name, src, self.model_path, self.events_path)
|
| 1669 |
+
|
| 1670 |
+
@property
|
| 1671 |
+
def observe_only(self) -> bool:
|
| 1672 |
+
"""If True, AutoVol will not change system volume (it still learns + shows stats)."""
|
| 1673 |
+
return bool(self._observe.is_set())
|
| 1674 |
+
|
| 1675 |
+
@observe_only.setter
|
| 1676 |
+
def observe_only(self, v: bool) -> None:
|
| 1677 |
+
if bool(v):
|
| 1678 |
+
self._observe.set()
|
| 1679 |
+
else:
|
| 1680 |
+
self._observe.clear()
|
| 1681 |
+
|
| 1682 |
+
def _write_event(self, obj: Dict[str, Any]) -> None:
|
| 1683 |
+
try:
|
| 1684 |
+
if self.events:
|
| 1685 |
+
self.events.write(json.dumps(obj) + "\n")
|
| 1686 |
+
self.events.flush()
|
| 1687 |
+
except Exception:
|
| 1688 |
+
pass
|
| 1689 |
+
|
| 1690 |
+
def _sampler_stats(self, window_s: float) -> Stats:
|
| 1691 |
+
if self.sampler is not None and hasattr(self.sampler, "win"):
|
| 1692 |
+
try:
|
| 1693 |
+
return getattr(self.sampler, "win").stats(window_s)
|
| 1694 |
+
except Exception:
|
| 1695 |
+
pass
|
| 1696 |
+
return Stats(-100.0, -100.0, -100.0, -100.0, 0)
|
| 1697 |
+
|
| 1698 |
+
def _sampler_backoff_until(self, key: str) -> float:
|
| 1699 |
+
st = self._sampler_fail.get(key, {})
|
| 1700 |
+
return float(st.get("until", 0.0))
|
| 1701 |
+
|
| 1702 |
+
def _mark_sampler_fail(self, key: str) -> None:
|
| 1703 |
+
now = time.time()
|
| 1704 |
+
st = self._sampler_fail.get(key)
|
| 1705 |
+
if not st:
|
| 1706 |
+
st = {"fails": 0.0, "until": 0.0}
|
| 1707 |
+
self._sampler_fail[key] = st
|
| 1708 |
+
st["fails"] = float(st.get("fails", 0.0) + 1.0)
|
| 1709 |
+
fails = st["fails"]
|
| 1710 |
+
backoff = min(self.SAMPLER_BACKOFF_MAX_S, self.SAMPLER_BACKOFF_BASE_S * (2.0 ** max(0.0, fails - 1.0)))
|
| 1711 |
+
st["until"] = now + backoff
|
| 1712 |
+
|
| 1713 |
+
def _switch_sampler(self, reason: str) -> None:
|
| 1714 |
+
try:
|
| 1715 |
+
if self.sampler:
|
| 1716 |
+
self.sampler.stop()
|
| 1717 |
+
except Exception:
|
| 1718 |
+
pass
|
| 1719 |
+
|
| 1720 |
+
picked = None
|
| 1721 |
+
best_name = None
|
| 1722 |
+
|
| 1723 |
+
n_samplers = max(1, len(self._samplers))
|
| 1724 |
+
now = time.time()
|
| 1725 |
+
|
| 1726 |
+
for _ in range(n_samplers):
|
| 1727 |
+
self._sampler_idx = (self._sampler_idx + 1) % n_samplers
|
| 1728 |
+
cand = self._samplers[self._sampler_idx]
|
| 1729 |
+
key = cand.sampler_key()
|
| 1730 |
+
|
| 1731 |
+
# v0.10.11: skip samplers in backoff
|
| 1732 |
+
if now < self._sampler_backoff_until(key):
|
| 1733 |
+
continue
|
| 1734 |
+
|
| 1735 |
+
try:
|
| 1736 |
+
cand.start()
|
| 1737 |
+
except Exception:
|
| 1738 |
+
pass
|
| 1739 |
+
|
| 1740 |
+
# v0.10.11: preflight must see actual sample flow (n>0)
|
| 1741 |
+
t0 = time.time()
|
| 1742 |
+
ok_flow = False
|
| 1743 |
+
while time.time() - t0 < self.SAMPLER_PREFLIGHT_S:
|
| 1744 |
+
try:
|
| 1745 |
+
if cand.samples_recent(1.2):
|
| 1746 |
+
ok_flow = True
|
| 1747 |
+
break
|
| 1748 |
+
except Exception:
|
| 1749 |
+
pass
|
| 1750 |
+
time.sleep(0.2)
|
| 1751 |
+
|
| 1752 |
+
nm = cand.chosen_name()
|
| 1753 |
+
if ok_flow:
|
| 1754 |
+
picked = cand
|
| 1755 |
+
best_name = nm or key
|
| 1756 |
+
break
|
| 1757 |
+
|
| 1758 |
+
# preflight failed -> stop and backoff this sampler
|
| 1759 |
+
try:
|
| 1760 |
+
cand.stop()
|
| 1761 |
+
except Exception:
|
| 1762 |
+
pass
|
| 1763 |
+
self._mark_sampler_fail(key)
|
| 1764 |
+
|
| 1765 |
+
self.sampler = picked
|
| 1766 |
+
self._last_switch_ts = time.time()
|
| 1767 |
+
|
| 1768 |
+
if self.sampler:
|
| 1769 |
+
logging.info("[Sampler] switched -> %s (%s)", self.sampler.chosen_name() or best_name or self.sampler.sampler_key(), reason)
|
| 1770 |
+
self._signal_state = f"SWITCH({reason})"
|
| 1771 |
+
else:
|
| 1772 |
+
logging.info("[Sampler] no viable sampler found (%s).", reason)
|
| 1773 |
+
self._signal_state = "NO SAMPLER"
|
| 1774 |
+
|
| 1775 |
+
def _update_signal_health(self) -> None:
|
| 1776 |
+
now = time.time()
|
| 1777 |
+
|
| 1778 |
+
if self.sampler is not None:
|
| 1779 |
+
deg = getattr(self.sampler, "is_degraded", None)
|
| 1780 |
+
if callable(deg):
|
| 1781 |
+
try:
|
| 1782 |
+
if bool(deg()) and (now - self._last_switch_ts) >= self.SWITCH_COOLDOWN_S:
|
| 1783 |
+
self._signal_state = "DEGRADED"
|
| 1784 |
+
self._switch_sampler(reason="degraded")
|
| 1785 |
+
return
|
| 1786 |
+
except Exception:
|
| 1787 |
+
pass
|
| 1788 |
+
|
| 1789 |
+
st = self._sampler_stats(1.5)
|
| 1790 |
+
if st.n > 0:
|
| 1791 |
+
self._last_sample_ts = now
|
| 1792 |
+
if (
|
| 1793 |
+
self._signal_state in ("INIT", "NO SAMPLES", "NO SAMPLER")
|
| 1794 |
+
or self._signal_state.startswith("SWITCH")
|
| 1795 |
+
or self._signal_state == "DEGRADED"
|
| 1796 |
+
):
|
| 1797 |
+
self._signal_state = "LIVE"
|
| 1798 |
+
return
|
| 1799 |
+
|
| 1800 |
+
if (now - self._last_sample_ts) > self.NO_SAMPLE_GRACE_S:
|
| 1801 |
+
self._signal_state = "NO SAMPLES"
|
| 1802 |
+
if (now - self._last_switch_ts) >= self.SWITCH_COOLDOWN_S:
|
| 1803 |
+
self._switch_sampler(reason="no-samples")
|
| 1804 |
+
|
| 1805 |
+
def vol_set(self, new_scalar: float, why: str = "auto") -> None:
|
| 1806 |
+
new_scalar = clamp(new_scalar, self.MIN_VOL, 1.0)
|
| 1807 |
+
self.bk.set(new_scalar)
|
| 1808 |
+
self.current = new_scalar
|
| 1809 |
+
now = time.time()
|
| 1810 |
+
self._last_set_ts = now
|
| 1811 |
+
self._flash_duck_until = now + 2.2
|
| 1812 |
+
|
| 1813 |
+
self._write_event({
|
| 1814 |
+
"ts": round(now, 3),
|
| 1815 |
+
"type": "AUTO_SET",
|
| 1816 |
+
"why": why,
|
| 1817 |
+
"vol": round(new_scalar, 3),
|
| 1818 |
+
"th_db": None if self._last_th is None else round(self._last_th, 2),
|
| 1819 |
+
"p85_db": round(self._last_p85, 2),
|
| 1820 |
+
"p95_db": round(self._last_p95, 2),
|
| 1821 |
+
"signal": self._signal_state,
|
| 1822 |
+
"sampler": self.sampler.chosen_name() if self.sampler else None,
|
| 1823 |
+
})
|
| 1824 |
+
|
| 1825 |
+
def _on_user_change(self, ts: float, old: float, new: float):
|
| 1826 |
+
if ts - self._last_set_ts <= self.IGNORE_OWN_SET_S:
|
| 1827 |
+
return
|
| 1828 |
+
|
| 1829 |
+
self.resting = new
|
| 1830 |
+
self.current = new
|
| 1831 |
+
|
| 1832 |
+
if self._paused.is_set():
|
| 1833 |
+
return
|
| 1834 |
+
|
| 1835 |
+
st = self._sampler_stats(self.SHORT_WIN_S)
|
| 1836 |
+
hour = time.localtime(ts).tm_hour
|
| 1837 |
+
db_at = st.p85
|
| 1838 |
+
|
| 1839 |
+
self._write_event({
|
| 1840 |
+
"ts": round(ts, 3),
|
| 1841 |
+
"type": "USER_SET",
|
| 1842 |
+
"hour": hour,
|
| 1843 |
+
"dir": "DOWN" if new < old else "UP",
|
| 1844 |
+
"p85_db": round(db_at, 2),
|
| 1845 |
+
"old": round(old, 3),
|
| 1846 |
+
"new": round(new, 3),
|
| 1847 |
+
"signal": self._signal_state,
|
| 1848 |
+
"sampler": self.sampler.chosen_name() if self.sampler else None,
|
| 1849 |
+
})
|
| 1850 |
+
|
| 1851 |
+
if (
|
| 1852 |
+
new < old
|
| 1853 |
+
and st.n >= 1
|
| 1854 |
+
and (ts - self._last_user_down_ts) > self.USER_DOWN_COOLDOWN_S
|
| 1855 |
+
):
|
| 1856 |
+
self.learner.record_down(db_at, hour)
|
| 1857 |
+
self._last_user_down_ts = ts
|
| 1858 |
+
self._downs_total += 1
|
| 1859 |
+
self.learner.save()
|
| 1860 |
+
|
| 1861 |
+
def start(self):
|
| 1862 |
+
self.poll.start()
|
| 1863 |
+
if self._thread:
|
| 1864 |
+
return
|
| 1865 |
+
self._thread = threading.Thread(target=self._run, name="AutoVolLoop", daemon=True)
|
| 1866 |
+
self._thread.start()
|
| 1867 |
+
|
| 1868 |
+
def stop(self):
|
| 1869 |
+
self._stop.set()
|
| 1870 |
+
try:
|
| 1871 |
+
self.poll.stop()
|
| 1872 |
+
except Exception:
|
| 1873 |
+
pass
|
| 1874 |
+
try:
|
| 1875 |
+
if isinstance(self.bk, WinVolSTA):
|
| 1876 |
+
self.bk.close()
|
| 1877 |
+
except Exception:
|
| 1878 |
+
pass
|
| 1879 |
+
try:
|
| 1880 |
+
if self.sampler:
|
| 1881 |
+
self.sampler.stop()
|
| 1882 |
+
except Exception:
|
| 1883 |
+
pass
|
| 1884 |
+
try:
|
| 1885 |
+
self.learner.save()
|
| 1886 |
+
if self.events:
|
| 1887 |
+
self.events.close()
|
| 1888 |
+
except Exception:
|
| 1889 |
+
pass
|
| 1890 |
+
if self._thread:
|
| 1891 |
+
self._thread.join(timeout=1.5)
|
| 1892 |
+
|
| 1893 |
+
def pause(self, do_pause: bool):
|
| 1894 |
+
if do_pause:
|
| 1895 |
+
self._paused.set()
|
| 1896 |
+
if abs(self.current - self.resting) > 1e-3:
|
| 1897 |
+
self.vol_set(self.resting, why="pause->restore")
|
| 1898 |
+
else:
|
| 1899 |
+
self._paused.clear()
|
| 1900 |
+
|
| 1901 |
+
def reset_learning(self):
|
| 1902 |
+
try:
|
| 1903 |
+
self.learner.reset()
|
| 1904 |
+
self._downs_total = 0
|
| 1905 |
+
except Exception:
|
| 1906 |
+
pass
|
| 1907 |
+
|
| 1908 |
+
def open_data_folder(self, data_dir: str):
|
| 1909 |
+
try:
|
| 1910 |
+
if _WIN:
|
| 1911 |
+
os.startfile(data_dir) # type: ignore[attr-defined]
|
| 1912 |
+
elif sys.platform == "darwin":
|
| 1913 |
+
subprocess.Popen(["open", data_dir])
|
| 1914 |
+
else:
|
| 1915 |
+
subprocess.Popen(["xdg-open", data_dir])
|
| 1916 |
+
except Exception:
|
| 1917 |
+
pass
|
| 1918 |
+
|
| 1919 |
+
def stats_text_short(self) -> str:
|
| 1920 |
+
mode = "P" if self._paused.is_set() else ("O" if self.observe_only or (time.time() - self._startup_ts < self.STARTUP_OBS_S) else "L")
|
| 1921 |
+
th_txt = f"{self._last_th:.0f}" if self._last_th is not None else "—"
|
| 1922 |
+
src = self.sampler.chosen_name() if self.sampler else "none"
|
| 1923 |
+
return f"{self._signal_state} {mode} vol:{self.current:.2f} p85:{self._last_p85:.0f} th:{th_txt} d:{self._downs_total} ({src})"
|
| 1924 |
+
|
| 1925 |
+
def stats_text_long(self) -> str:
|
| 1926 |
+
tag = "vad" if _HAVE_WEBRTCVAD else "lite"
|
| 1927 |
+
th_txt = f"{self._last_th:.1f}dB" if (self._last_th is not None) else "—"
|
| 1928 |
+
mode_txt = "PAUSED" if self._paused.is_set() else ("OBSERVE" if self.observe_only or (time.time() - self._startup_ts < self.STARTUP_OBS_S) else "LIVE")
|
| 1929 |
+
duck_txt = " ↓" if (time.time() < self._flash_duck_until) else ""
|
| 1930 |
+
src = self.sampler.chosen_name() if self.sampler else "none"
|
| 1931 |
+
return f"{self._signal_state} | {mode_txt}{duck_txt} | downs:{self._downs_total} | p85:{self._last_p85:.1f} | p95:{self._last_p95:.1f} | th:{th_txt} | vol:{self.current:.2f} | sp:{self._speech:.2f}({tag}) | src:{src}"
|
| 1932 |
+
|
| 1933 |
+
def _maybe_promote_sampler(self, now: float) -> None:
|
| 1934 |
+
# This method exists in some builds; keep it safe even if called.
|
| 1935 |
+
if self._paused.is_set() or self._observe.is_set():
|
| 1936 |
+
return
|
| 1937 |
+
|
| 1938 |
+
def _run(self):
|
| 1939 |
+
last_save = time.time()
|
| 1940 |
+
|
| 1941 |
+
while not self._stop.is_set():
|
| 1942 |
+
time.sleep(0.25)
|
| 1943 |
+
now = time.time()
|
| 1944 |
+
|
| 1945 |
+
actual = self.bk.get()
|
| 1946 |
+
if abs(actual - self.current) > 0.05:
|
| 1947 |
+
self.resting = actual
|
| 1948 |
+
self.current = actual
|
| 1949 |
+
|
| 1950 |
+
self._update_signal_health()
|
| 1951 |
+
if self._signal_state in ("NO SAMPLER", "NO SAMPLES"):
|
| 1952 |
+
continue
|
| 1953 |
+
|
| 1954 |
+
if self._paused.is_set() or self.observe_only or (now - self._startup_ts < self.STARTUP_OBS_S):
|
| 1955 |
+
continue
|
| 1956 |
+
|
| 1957 |
+
if not self.sampler:
|
| 1958 |
+
continue
|
| 1959 |
+
|
| 1960 |
+
base = self._sampler_stats(self.BASELINE_WIN_S)
|
| 1961 |
+
cur = self._sampler_stats(self.SHORT_WIN_S)
|
| 1962 |
+
self._last_p85 = cur.p85
|
| 1963 |
+
self._last_p95 = cur.p95
|
| 1964 |
+
|
| 1965 |
+
if cur.n < 1:
|
| 1966 |
+
continue
|
| 1967 |
+
|
| 1968 |
+
hour = time.localtime().tm_hour
|
| 1969 |
+
th = self.learner.threshold(hour)
|
| 1970 |
+
if th is None:
|
| 1971 |
+
th = max(base.p70, -45.0) + 6.0
|
| 1972 |
+
self._last_th = th
|
| 1973 |
+
|
| 1974 |
+
over85 = cur.p85 - th
|
| 1975 |
+
if (now - self._last_set_ts) >= self.SET_COOLDOWN_S and over85 > self.OVER_MARGIN_DB:
|
| 1976 |
+
step_db = clamp(over85 * 0.35, 0.25, self.ATTACK_DB_MAX)
|
| 1977 |
+
self.vol_set(self.current * db_to_lin(-step_db), why="steady_over85")
|
| 1978 |
+
continue
|
| 1979 |
+
|
| 1980 |
+
over95 = cur.p95 - th
|
| 1981 |
+
if (now - self._last_set_ts) >= self.SET_COOLDOWN_S and over95 > (self.OVER_MARGIN_DB + 1.8):
|
| 1982 |
+
step_db = clamp(over95 * 0.55, 0.6, 2.8)
|
| 1983 |
+
self.vol_set(self.current * db_to_lin(-step_db), why="spike_over95")
|
| 1984 |
+
continue
|
| 1985 |
+
|
| 1986 |
+
block = None
|
| 1987 |
+
try:
|
| 1988 |
+
block = self.sampler.get_last_block()
|
| 1989 |
+
except Exception:
|
| 1990 |
+
block = None
|
| 1991 |
+
|
| 1992 |
+
if block is not None and getattr(block, "size", 0) > 0:
|
| 1993 |
+
sp_prob = self.vad.prob(block)
|
| 1994 |
+
self._speech = 0.6 * sp_prob + 0.4 * self._speech
|
| 1995 |
+
|
| 1996 |
+
if (now - self._last_set_ts) >= self.SET_COOLDOWN_S:
|
| 1997 |
+
target = self.resting
|
| 1998 |
+
if self._speech >= 0.55:
|
| 1999 |
+
target = min(1.0, self.resting * db_to_lin(self.SPEECH_UP_DB))
|
| 2000 |
+
else:
|
| 2001 |
+
target = max(self.MIN_VOL, self.resting * db_to_lin(self.NOSPEECH_DOWN_DB))
|
| 2002 |
+
|
| 2003 |
+
if abs(target - self.current) > 0.015:
|
| 2004 |
+
step_up = db_to_lin(self.RELEASE_DB_MAX)
|
| 2005 |
+
step_dn = db_to_lin(-self.RELEASE_DB_MAX)
|
| 2006 |
+
if target > self.current:
|
| 2007 |
+
new = min(target, self.current * step_up)
|
| 2008 |
+
else:
|
| 2009 |
+
new = max(target, self.current * step_dn)
|
| 2010 |
+
self.vol_set(new, why="speech_gate")
|
| 2011 |
+
else:
|
| 2012 |
+
self.vad.prob(None)
|
| 2013 |
+
self._speech = 0.0
|
| 2014 |
+
|
| 2015 |
+
if now - last_save >= 25.0:
|
| 2016 |
+
last_save = now
|
| 2017 |
+
self.learner.save()
|
| 2018 |
+
|
| 2019 |
+
|
| 2020 |
+
# ------------------ tray ------------------
|
| 2021 |
+
|
| 2022 |
+
def make_icon(color_fg=(255, 255, 255, 255), color_bg=(0, 0, 0, 0)) -> Image.Image:
|
| 2023 |
+
W, H = 64, 64
|
| 2024 |
+
img = Image.new("RGBA", (W, H), color_bg)
|
| 2025 |
+
d = ImageDraw.Draw(img)
|
| 2026 |
+
d.rectangle([12, 24, 24, 40], fill=color_fg)
|
| 2027 |
+
d.polygon([(24, 24), (36, 16), (36, 48), (24, 40)], fill=color_fg)
|
| 2028 |
+
d.arc([38, 18, 58, 46], start=315, end=45, width=3, fill=color_fg)
|
| 2029 |
+
d.arc([42, 14, 62, 50], start=315, end=45, width=2, fill=color_fg)
|
| 2030 |
+
return img
|
| 2031 |
+
|
| 2032 |
+
|
| 2033 |
+
def resolve_paths(model_filename: str, events_filename: str) -> Tuple[str, str, str]:
|
| 2034 |
+
data_dir = _default_data_dir()
|
| 2035 |
+
os.makedirs(data_dir, exist_ok=True)
|
| 2036 |
+
model_path = model_filename if os.path.isabs(model_filename) else os.path.join(data_dir, model_filename)
|
| 2037 |
+
events_path = events_filename if os.path.isabs(events_filename) else os.path.join(data_dir, events_filename)
|
| 2038 |
+
return data_dir, model_path, events_path
|
| 2039 |
+
|
| 2040 |
+
|
| 2041 |
+
def run_tray():
|
| 2042 |
+
ap = argparse.ArgumentParser(add_help=True)
|
| 2043 |
+
ap.add_argument("--model", default="autovol_learn.json")
|
| 2044 |
+
ap.add_argument("--events", default="autovol_events.jsonl")
|
| 2045 |
+
ap.add_argument("--force-dryvol", action="store_true", help="don't touch system volume (debug)")
|
| 2046 |
+
ap.add_argument("--observe", action="store_true", help="start in observe-only mode (no volume changes)")
|
| 2047 |
+
ap.add_argument("--reset", action="store_true", help="reset learned downs before starting")
|
| 2048 |
+
ap.add_argument("--no-autoinstall", action="store_true", help="disable auto-install of missing deps")
|
| 2049 |
+
args = ap.parse_args()
|
| 2050 |
+
|
| 2051 |
+
data_dir, model_path, events_path = resolve_paths(args.model, args.events)
|
| 2052 |
+
log_path = setup_logging(data_dir)
|
| 2053 |
+
logging.info("Log file: %s", log_path)
|
| 2054 |
+
|
| 2055 |
+
ctl = AutoVolController(model_path=model_path, events_path=events_path, force_dryvol=args.force_dryvol)
|
| 2056 |
+
if args.reset:
|
| 2057 |
+
ctl.reset_learning()
|
| 2058 |
+
logging.info("Learning reset.")
|
| 2059 |
+
ctl.observe_only = bool(args.observe)
|
| 2060 |
+
ctl.start()
|
| 2061 |
+
|
| 2062 |
+
icon_img = make_icon()
|
| 2063 |
+
icon = pystray.Icon("AutoVol", icon=icon_img, title="AutoVol")
|
| 2064 |
+
|
| 2065 |
+
def update_title():
|
| 2066 |
+
icon.title = safe_tooltip("AutoVol — " + ctl.stats_text_short())
|
| 2067 |
+
|
| 2068 |
+
def on_pause(_icon, _item):
|
| 2069 |
+
ctl.pause(not ctl._paused.is_set())
|
| 2070 |
+
update_title()
|
| 2071 |
+
|
| 2072 |
+
def on_toggle_observe(_icon, _item):
|
| 2073 |
+
ctl.observe_only = not ctl.observe_only
|
| 2074 |
+
update_title()
|
| 2075 |
+
|
| 2076 |
+
def on_reset(_icon, _item):
|
| 2077 |
+
ctl.reset_learning()
|
| 2078 |
+
update_title()
|
| 2079 |
+
|
| 2080 |
+
def on_open(_icon, _item):
|
| 2081 |
+
ctl.open_data_folder(data_dir)
|
| 2082 |
+
|
| 2083 |
+
def on_quit(icon_obj, _item):
|
| 2084 |
+
try:
|
| 2085 |
+
ctl.stop()
|
| 2086 |
+
finally:
|
| 2087 |
+
icon_obj.stop()
|
| 2088 |
+
|
| 2089 |
+
menu = Menu(
|
| 2090 |
+
Item(lambda _item: safe_tooltip("Status: " + ctl.stats_text_long(), max_len=120), None, enabled=False),
|
| 2091 |
+
Item(lambda _item: "Observe only (no changes)", on_toggle_observe, checked=lambda _item: ctl.observe_only),
|
| 2092 |
+
Item(lambda _item: "Resume" if ctl._paused.is_set() else "Pause", on_pause),
|
| 2093 |
+
Item("Reset learning", on_reset),
|
| 2094 |
+
Item("Open data folder", on_open),
|
| 2095 |
+
Item("Quit", on_quit),
|
| 2096 |
+
)
|
| 2097 |
+
icon.menu = menu
|
| 2098 |
+
|
| 2099 |
+
def refresher():
|
| 2100 |
+
while not ctl._stop.is_set():
|
| 2101 |
+
update_title()
|
| 2102 |
+
time.sleep(1.8)
|
| 2103 |
+
|
| 2104 |
+
threading.Thread(target=refresher, name="TrayRefresh", daemon=True).start()
|
| 2105 |
+
|
| 2106 |
+
logging.info("[AutoVol] tray up — check system tray.")
|
| 2107 |
+
update_title()
|
| 2108 |
+
icon.run()
|
| 2109 |
+
|
| 2110 |
+
|
| 2111 |
+
if __name__ == "__main__":
|
| 2112 |
+
try:
|
| 2113 |
+
run_tray()
|
| 2114 |
+
except KeyboardInterrupt:
|
| 2115 |
+
pass
|
| 2116 |
+
except Exception as e:
|
| 2117 |
+
try:
|
| 2118 |
+
dd = _default_data_dir()
|
| 2119 |
+
os.makedirs(dd, exist_ok=True)
|
| 2120 |
+
with open(os.path.join(dd, "autovol_crash.txt"), "w", encoding="utf-8") as f:
|
| 2121 |
+
f.write(repr(e) + "\n\n")
|
| 2122 |
+
f.write(traceback.format_exc())
|
| 2123 |
+
except Exception:
|
| 2124 |
+
pass
|
| 2125 |
+
raise
|