|
|
|
|
|
|
| """
|
| AutoVol (Tray) — zero-config, self-healing auto volume learner.
|
|
|
| What it tries to do:
|
| - Watch "how loud the system audio is" (best effort: real loopback audio; fallback: peak meter).
|
| - Learn when you turn volume down (stores the loudness level at that moment).
|
| - Next time it detects you're above your learned loudness threshold, it gently ducks volume.
|
|
|
| v0.10.11 fixes vs v0.10.10 (quality-of-life + fewer “sampler thrash” loops):
|
| - BETTER: Smarter audio-device picking (especially avoids HDMI/Display endpoints when possible).
|
| * soundcard loopback no longer blindly prefers a “bad” default speaker (HDMI/display/etc).
|
| * sounddevice WASAPI output selection uses a score-based pick, not just default output.
|
| - BETTER: Sampler selection preflight now requires actual sample flow (recent window n>0),
|
| not just “stream opened”. This prevents picking a sampler that’s dead-on-arrival.
|
| - BETTER: Adds per-sampler exponential backoff when a sampler repeatedly fails preflight,
|
| so the system doesn’t rotate through the same broken sources every ~15s forever.
|
| - BETTER: Pycaw “degraded” threshold relaxed so it keeps trying longer on flaky COM systems
|
| instead of force-switching too aggressively.
|
| - KEEP: Prior COM-finalizer safety and WinVolSTA thread join behavior.
|
|
|
| Run:
|
| python autovol_tray.py
|
|
|
| Data dir (Windows):
|
| %LOCALAPPDATA%\\AutoVol
|
| """
|
|
|
| from __future__ import annotations
|
|
|
| import os
|
| import sys
|
| import math
|
| import time
|
| import json
|
| import platform
|
| import threading
|
| import argparse
|
| import queue
|
| import subprocess
|
| import traceback
|
| import logging
|
| import gc
|
| from logging.handlers import RotatingFileHandler
|
| from typing import Deque, Dict, List, Optional, Tuple, Callable, Any
|
| from collections import deque
|
| from dataclasses import dataclass
|
|
|
| __version__ = "0.10.11"
|
| _WIN = platform.system().lower().startswith("win")
|
|
|
| DEFAULT_SR = 48000
|
| DEFAULT_FRAME_S = 0.20
|
| DEFAULT_FRAMES = int(round(DEFAULT_SR * DEFAULT_FRAME_S))
|
|
|
|
|
|
|
| _NO_AUTOINSTALL = ("--no-autoinstall" in sys.argv)
|
|
|
|
|
| def _pip_install(pkgs: List[str]) -> bool:
|
| """Best-effort dependency install.
|
|
|
| If you're NOT in a venv, install into per-user site-packages (avoids admin/permission issues).
|
| If you're in a venv, install into the venv as normal.
|
| """
|
| try:
|
| in_venv = (getattr(sys, "base_prefix", sys.prefix) != sys.prefix) or bool(os.environ.get("VIRTUAL_ENV"))
|
| cmd = [sys.executable, "-m", "pip", "install", "--upgrade"]
|
| if not in_venv:
|
| cmd.append("--user")
|
| cmd += pkgs
|
| p = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
|
| if p.returncode != 0:
|
| logging.info("[deps] pip failed (%s):\n%s", p.returncode, p.stdout[-3000:])
|
| return (p.returncode == 0)
|
| except Exception:
|
| return False
|
|
|
|
|
| def _ensure_deps(auto_install: bool = True) -> None:
|
| need: List[str] = []
|
|
|
| try:
|
| import numpy
|
| except Exception:
|
| need.append("numpy")
|
|
|
| try:
|
| import PIL
|
| except Exception:
|
| need.append("Pillow")
|
|
|
| try:
|
| import pystray
|
| except Exception:
|
| need.append("pystray")
|
|
|
| if _WIN:
|
| try:
|
| import comtypes
|
| except Exception:
|
| need.append("comtypes")
|
| try:
|
| import pycaw
|
| except Exception:
|
| need.append("pycaw")
|
| try:
|
| import win32api
|
| except Exception:
|
| need.append("pywin32")
|
|
|
| try:
|
| import sounddevice
|
| except Exception:
|
| need.append("sounddevice")
|
|
|
|
|
| try:
|
| import soundcard
|
| except Exception:
|
| if auto_install:
|
| need.append("soundcard")
|
|
|
|
|
| try:
|
| import webrtcvad
|
| except Exception:
|
| pass
|
|
|
| if need and auto_install:
|
| _pip_install(need)
|
|
|
|
|
|
|
| try:
|
| _ensure_deps(auto_install=(not _NO_AUTOINSTALL))
|
| except Exception:
|
| pass
|
|
|
|
|
| import numpy as np
|
|
|
| try:
|
| import sounddevice as sd
|
| except Exception:
|
| sd = None
|
|
|
| try:
|
| import soundcard as sc
|
| except Exception:
|
| sc = None
|
|
|
| try:
|
| import webrtcvad
|
| _HAVE_WEBRTCVAD = True
|
| except Exception:
|
| webrtcvad = None
|
| _HAVE_WEBRTCVAD = False
|
|
|
| import pystray
|
| from pystray import MenuItem as Item, Menu
|
| from PIL import Image, ImageDraw
|
|
|
|
|
|
|
|
|
| def _default_data_dir() -> str:
|
| if _WIN and "LOCALAPPDATA" in os.environ:
|
| return os.path.join(os.environ["LOCALAPPDATA"], "AutoVol")
|
| return os.path.abspath(".")
|
|
|
|
|
| def setup_logging(data_dir: str) -> str:
|
| os.makedirs(data_dir, exist_ok=True)
|
| log_path = os.path.join(data_dir, "autovol.log")
|
|
|
| logger = logging.getLogger()
|
| logger.setLevel(logging.INFO)
|
|
|
| fmt = logging.Formatter("%(asctime)s %(levelname)s %(threadName)s %(message)s")
|
| fh = RotatingFileHandler(log_path, maxBytes=512_000, backupCount=2, encoding="utf-8")
|
| fh.setFormatter(fmt)
|
| sh = logging.StreamHandler(sys.stdout)
|
| sh.setFormatter(fmt)
|
|
|
| logger.handlers = []
|
| logger.addHandler(fh)
|
| logger.addHandler(sh)
|
|
|
| logging.info("AutoVol starting v%s (win=%s) data_dir=%s", __version__, _WIN, data_dir)
|
| logging.info("Args: %s", " ".join(sys.argv))
|
| if _NO_AUTOINSTALL:
|
| logging.info("Auto-install deps: DISABLED (--no-autoinstall)")
|
| return log_path
|
|
|
|
|
|
|
|
|
| _BAD_AUDIO_TOKENS = [
|
| "hdmi", "display", "nvidia", "amd", "intel", "dp audio", "display audio", "vf", "virtual",
|
| "monitor", "sonic", "nahimic", "remote", "wireless display",
|
| ]
|
|
|
| _GOOD_AUDIO_TOKENS = [
|
| "realtek", "speakers", "speaker", "headphones", "headphone", "usb", "dac", "analog", "line out",
|
| ]
|
|
|
|
|
| def clamp(x: float, lo: float, hi: float) -> float:
|
| return max(lo, min(hi, x))
|
|
|
|
|
| def db_to_lin(db: float) -> float:
|
| return 10.0 ** (db / 20.0)
|
|
|
|
|
| def rms_dbfs(x: np.ndarray, eps: float = 1e-12) -> float:
|
| if x is None or getattr(x, "size", 0) == 0:
|
| return -100.0
|
| if x.ndim == 2 and x.shape[1] > 1:
|
| x = x.mean(axis=1)
|
| rms = float(np.sqrt(np.mean(np.square(x), dtype=np.float64)))
|
| if not np.isfinite(rms) or rms <= eps:
|
| return -100.0
|
| db = 20.0 * math.log10(max(eps, rms))
|
| return float(max(min(db, 0.0), -100.0))
|
|
|
|
|
| def safe_tooltip(s: str, max_len: int = 120) -> str:
|
| """
|
| Windows NOTIFYICONDATAW tooltip limit is 128 WCHAR incl null.
|
| Keep it comfortably below to avoid pystray ValueError.
|
| """
|
| s = s.replace("\n", " ").strip()
|
| if len(s) <= max_len:
|
| return s
|
| return s[: max_len - 1] + "…"
|
|
|
|
|
| def name_score_audio_device(name: str) -> int:
|
| """
|
| Heuristic: prefer likely-real speaker endpoints, avoid HDMI/display/virtual endpoints.
|
| """
|
| n = (name or "").lower()
|
| score = 0
|
| for t in _GOOD_AUDIO_TOKENS:
|
| if t in n:
|
| score += 12
|
| for t in _BAD_AUDIO_TOKENS:
|
| if t in n:
|
| score -= 18
|
| if "realtek" in n:
|
| score += 25
|
| if "speaker" in n:
|
| score += 10
|
| if "headphone" in n:
|
| score += 8
|
| if "usb" in n:
|
| score += 6
|
| return score
|
|
|
|
|
| def looks_bad_default_endpoint(name: str) -> bool:
|
| n = (name or "").lower()
|
| if any(t in n for t in _BAD_AUDIO_TOKENS):
|
| return True
|
|
|
| return name_score_audio_device(name) < -5
|
|
|
|
|
| @dataclass
|
| class Stats:
|
| p50: float
|
| p70: float
|
| p85: float
|
| p95: float
|
| n: int
|
|
|
|
|
| class PercentileWindow:
|
| def __init__(self, frame_s: float, history_s: float):
|
| self.frame_s = float(frame_s)
|
| self.buf: Deque[Tuple[float, float]] = deque(maxlen=int(history_s / frame_s) + 16)
|
| self.lock = threading.Lock()
|
|
|
| def push(self, ts: float, db: float) -> None:
|
| with self.lock:
|
| self.buf.append((ts, db))
|
|
|
| def stats(self, window_s: float) -> Stats:
|
| cutoff = time.time() - float(window_s)
|
| with self.lock:
|
| vals = [db for (ts, db) in self.buf if ts >= cutoff]
|
| if not vals:
|
| return Stats(-100.0, -100.0, -100.0, -100.0, 0)
|
| vals.sort()
|
|
|
| def pct(p: float) -> float:
|
| k = int(round((len(vals) - 1) * clamp(p, 0.0, 1.0)))
|
| return float(vals[k])
|
|
|
| return Stats(p50=pct(0.50), p70=pct(0.70), p85=pct(0.85), p95=pct(0.95), n=len(vals))
|
|
|
|
|
|
|
|
|
| class SamplerBase:
|
| """
|
| Samplers should be "alive" even during silence.
|
| Health is: are samples arriving (n>0), not whether audio is loud.
|
| """
|
| def chosen_name(self) -> Optional[str]:
|
| return None
|
|
|
| def start(self) -> None:
|
| pass
|
|
|
| def stop(self) -> None:
|
| pass
|
|
|
| def get_last_block(self) -> Optional[np.ndarray]:
|
| return None
|
|
|
| def samples_recent(self, window_s: float = 1.5) -> bool:
|
| try:
|
| win = getattr(self, "win", None)
|
| if win is None:
|
| return False
|
| st = win.stats(window_s)
|
| return st.n > 0
|
| except Exception:
|
| return False
|
|
|
| def sampler_key(self) -> str:
|
| return self.__class__.__name__
|
|
|
|
|
| class LoopbackSampler_SD(SamplerBase):
|
| """
|
| sounddevice WASAPI loopback.
|
|
|
| Key detail: some PortAudio/WASAPI builds on Windows do NOT support the blocking API
|
| (you'll see: "Blocking API not supported yet"). To self-heal across machines, we run
|
| the stream in CALLBACK mode and never call stream.read().
|
|
|
| Strategy:
|
| - Prefer explicit "(loopback)" INPUT devices when present.
|
| - Otherwise, try output devices with WasapiSettings(loopback=True).
|
| - Score devices to avoid HDMI/display endpoints when possible.
|
| """
|
|
|
| def __init__(self, sr=DEFAULT_SR, frame_s=DEFAULT_FRAME_S, history_s=150.0):
|
| self.sr = int(sr)
|
| self.frame_s = float(frame_s)
|
| self.frames = int(round(self.frame_s * self.sr))
|
| self.win = PercentileWindow(frame_s, history_s)
|
|
|
| self.ok = False
|
| self._stop = threading.Event()
|
| self._th: Optional[threading.Thread] = None
|
| self._last_block: Optional[np.ndarray] = None
|
| self._lb_lock = threading.Lock()
|
|
|
| self._chosen: Optional[str] = None
|
| self._dev_index: Optional[int] = None
|
| self._extra = None
|
|
|
| def chosen_name(self) -> Optional[str]:
|
| return self._chosen if self.ok else None
|
|
|
| def get_last_block(self) -> Optional[np.ndarray]:
|
| with self._lb_lock:
|
| return None if self._last_block is None else self._last_block.copy()
|
|
|
| def _wasapi_idx(self) -> Optional[int]:
|
| if sd is None:
|
| return None
|
| try:
|
| hostapis = sd.query_hostapis()
|
| for i, h in enumerate(hostapis):
|
| if "wasapi" in str(h.get("name", "")).lower():
|
| return i
|
| except Exception:
|
| return None
|
| return None
|
|
|
| def _pick_loopback_input_device(self) -> Optional[int]:
|
| """
|
| Many systems expose loopback capture as a dedicated *input* device with "(loopback)" in name.
|
| If present, prefer it.
|
| """
|
| if sd is None or not _WIN:
|
| return None
|
| wasapi_idx = self._wasapi_idx()
|
| if wasapi_idx is None:
|
| return None
|
| try:
|
| devs = sd.query_devices()
|
| except Exception:
|
| return None
|
|
|
| out_name = ""
|
| try:
|
| out_idx = int(sd.default.device[1])
|
| out_name = str(sd.query_devices(out_idx).get("name", "")).lower()
|
| except Exception:
|
| out_name = ""
|
|
|
| loopbacks: List[int] = []
|
| for i, d in enumerate(devs):
|
| try:
|
| if int(d.get("hostapi", -1)) != wasapi_idx:
|
| continue
|
| if int(d.get("max_input_channels", 0)) <= 0:
|
| continue
|
| name = str(d.get("name", "")).lower()
|
| if "loopback" in name or "(loopback)" in name:
|
| loopbacks.append(i)
|
| except Exception:
|
| continue
|
| if not loopbacks:
|
| return None
|
|
|
|
|
| if out_name:
|
| out_stem = out_name.split("(")[0].strip()
|
| if out_stem:
|
| for i in loopbacks:
|
| try:
|
| name = str(devs[i].get("name", "")).lower()
|
| if out_stem in name:
|
| return i
|
| except Exception:
|
| continue
|
|
|
|
|
| best = None
|
| best_score = -10_000
|
| for i in loopbacks:
|
| try:
|
| nm = str(devs[i].get("name", ""))
|
| scv = name_score_audio_device(nm)
|
| if scv > best_score:
|
| best_score = scv
|
| best = i
|
| except Exception:
|
| continue
|
| return best if best is not None else loopbacks[0]
|
|
|
| def _pick_output_device(self) -> Optional[int]:
|
| if sd is None or not _WIN:
|
| return None
|
| wasapi_idx = self._wasapi_idx()
|
| if wasapi_idx is None:
|
| return None
|
| try:
|
| devs = sd.query_devices()
|
| except Exception:
|
| return None
|
|
|
| outs: List[int] = []
|
| for i, d in enumerate(devs):
|
| try:
|
| if int(d.get("hostapi", -1)) == wasapi_idx and int(d.get("max_output_channels", 0)) > 0:
|
| outs.append(i)
|
| except Exception:
|
| continue
|
| if not outs:
|
| return None
|
|
|
|
|
| try:
|
| out_def = int(sd.default.device[1])
|
| if out_def in outs:
|
| def_name = str(devs[out_def].get("name", ""))
|
| if not looks_bad_default_endpoint(def_name):
|
| return out_def
|
| except Exception:
|
| pass
|
|
|
| best = None
|
| best_score = -10_000
|
| for i in outs:
|
| try:
|
| nm = str(devs[i].get("name", ""))
|
| scv = name_score_audio_device(nm)
|
| if scv > best_score:
|
| best_score = scv
|
| best = i
|
| except Exception:
|
| continue
|
| return best if best is not None else outs[0]
|
|
|
| def start(self) -> None:
|
| if self._th or sd is None or not _WIN:
|
| return
|
|
|
| dev = self._pick_loopback_input_device()
|
| using_loopback_input = True
|
| if dev is None:
|
| dev = self._pick_output_device()
|
| using_loopback_input = False
|
| if dev is None:
|
| logging.info("[SD Loopback] no WASAPI device found.")
|
| return
|
|
|
| self._dev_index = dev
|
| try:
|
| devinfo = sd.query_devices(dev)
|
| devname = str(devinfo.get("name", "?"))
|
| max_in = int(devinfo.get("max_input_channels", 0) or 0)
|
| max_out = int(devinfo.get("max_output_channels", 0) or 0)
|
| dev_sr = float(devinfo.get("default_samplerate", self.sr) or self.sr)
|
| except Exception:
|
| devname, max_in, max_out, dev_sr = f"dev#{dev}", 0, 2, float(self.sr)
|
|
|
| extra = None
|
| try:
|
| extra = sd.WasapiSettings(loopback=True)
|
| except Exception:
|
| extra = None
|
| self._extra = extra
|
|
|
| if using_loopback_input:
|
| self._chosen = f"sd/wasapi loopback-in: {devname}"
|
| ch_max = max(1, max_in)
|
| else:
|
| self._chosen = f"sd/wasapi loopback: {devname}"
|
| ch_max = max(1, max_out)
|
|
|
| sr_candidates: List[int] = []
|
| for s in [self.sr, int(dev_sr), 48000, 44100]:
|
| if s > 8000 and s not in sr_candidates:
|
| sr_candidates.append(int(s))
|
|
|
| ch_candidates: List[int] = []
|
| for c in [2, 1]:
|
| if c <= ch_max:
|
| ch_candidates.append(c)
|
| if not ch_candidates:
|
| ch_candidates = [1]
|
|
|
| def cb(indata, frames, time_info, status):
|
| try:
|
| block = np.asarray(indata, dtype=np.float32)
|
| self.win.push(time.time(), rms_dbfs(block))
|
| with self._lb_lock:
|
| self._last_block = block.copy()
|
| except Exception:
|
| pass
|
|
|
| def run():
|
| try:
|
| last_err = None
|
| stream = None
|
|
|
| for sr_try in sr_candidates:
|
| for ch_try in ch_candidates:
|
| try:
|
| frames = int(round(self.frame_s * sr_try))
|
| stream = sd.InputStream(
|
| samplerate=sr_try,
|
| channels=ch_try,
|
| dtype="float32",
|
| blocksize=frames,
|
| device=self._dev_index,
|
| extra_settings=self._extra if _WIN else None,
|
| callback=cb,
|
| )
|
| self.sr = int(sr_try)
|
| self.frames = int(frames)
|
| self.ok = True
|
| logging.info("[SD Loopback] opened sr=%s ch=%s (%s)", sr_try, ch_try, self._chosen)
|
| break
|
| except Exception as e:
|
| last_err = e
|
| stream = None
|
| if stream is not None:
|
| break
|
|
|
| if stream is None:
|
| logging.info("[SD Loopback] init error: %r", last_err)
|
| self.ok = False
|
| return
|
|
|
| with stream:
|
| while not self._stop.is_set():
|
| time.sleep(0.25)
|
| except Exception as e:
|
| logging.info("[SD Loopback] thread error: %r", e)
|
| self.ok = False
|
|
|
| self._th = threading.Thread(target=run, name="SDLoopback", daemon=True)
|
| self._th.start()
|
|
|
| def stop(self) -> None:
|
| self._stop.set()
|
| if self._th:
|
| self._th.join(timeout=1.5)
|
|
|
|
|
| class StereoMixSampler_SD(SamplerBase):
|
| """
|
| Capture from an *input* device that looks like "Stereo Mix"/"What U Hear".
|
|
|
| Use CALLBACK mode so we don't depend on PortAudio's blocking API support.
|
| """
|
|
|
| def __init__(self, sr=DEFAULT_SR, frame_s=DEFAULT_FRAME_S, history_s=150.0):
|
| self.sr = int(sr)
|
| self.frame_s = float(frame_s)
|
| self.frames = int(round(self.frame_s * self.sr))
|
| self.win = PercentileWindow(frame_s, history_s)
|
|
|
| self.ok = False
|
| self._stop = threading.Event()
|
| self._th: Optional[threading.Thread] = None
|
| self._last_block: Optional[np.ndarray] = None
|
| self._lb_lock = threading.Lock()
|
|
|
| self._chosen: Optional[str] = None
|
| self._dev_index: Optional[int] = None
|
|
|
| def chosen_name(self) -> Optional[str]:
|
| return self._chosen if self.ok else None
|
|
|
| def get_last_block(self) -> Optional[np.ndarray]:
|
| with self._lb_lock:
|
| return None if self._last_block is None else self._last_block.copy()
|
|
|
| def _pick_device(self) -> Optional[int]:
|
| if sd is None:
|
| return None
|
| try:
|
| devs = sd.query_devices()
|
| except Exception:
|
| return None
|
|
|
| needles = ["stereo mix", "what u hear", "what you hear"]
|
| hits: List[int] = []
|
| for i, d in enumerate(devs):
|
| try:
|
| name = str(d.get("name", "")).lower()
|
| max_in = int(d.get("max_input_channels", 0))
|
| if max_in <= 0:
|
| continue
|
| if any(n in name for n in needles):
|
| hits.append(i)
|
| except Exception:
|
| continue
|
|
|
| if not hits:
|
| return None
|
|
|
|
|
| best = None
|
| best_score = -10_000
|
| for i in hits:
|
| try:
|
| nm = str(devs[i].get("name", ""))
|
| scv = name_score_audio_device(nm)
|
| if scv > best_score:
|
| best_score = scv
|
| best = i
|
| except Exception:
|
| continue
|
| return best if best is not None else hits[0]
|
|
|
| def start(self) -> None:
|
| if self._th or sd is None:
|
| return
|
| dev = self._pick_device()
|
| if dev is None:
|
| return
|
| self._dev_index = dev
|
|
|
| try:
|
| devinfo = sd.query_devices(dev)
|
| devname = str(devinfo.get("name", "?"))
|
| max_in = int(devinfo.get("max_input_channels", 1) or 1)
|
| dev_sr = float(devinfo.get("default_samplerate", self.sr) or self.sr)
|
| except Exception:
|
| devname, max_in, dev_sr = f"dev#{dev}", 1, float(self.sr)
|
|
|
| self._chosen = f"sd/input: {devname}"
|
|
|
| sr_candidates: List[int] = []
|
| for s in [self.sr, int(dev_sr), 48000, 44100]:
|
| if s > 8000 and s not in sr_candidates:
|
| sr_candidates.append(int(s))
|
|
|
| ch_candidates = [c for c in [2, 1] if c <= max_in] or [1]
|
|
|
| def cb(indata, frames, time_info, status):
|
| try:
|
| block = np.asarray(indata, dtype=np.float32)
|
| self.win.push(time.time(), rms_dbfs(block))
|
| with self._lb_lock:
|
| self._last_block = block.copy()
|
| except Exception:
|
| pass
|
|
|
| def run():
|
| last_err = None
|
| stream = None
|
|
|
| for sr_try in sr_candidates:
|
| for ch_try in ch_candidates:
|
| try:
|
| frames = int(round(self.frame_s * sr_try))
|
| stream = sd.InputStream(
|
| samplerate=sr_try,
|
| channels=ch_try,
|
| dtype="float32",
|
| blocksize=frames,
|
| device=self._dev_index,
|
| callback=cb,
|
| )
|
| self.sr = int(sr_try)
|
| self.frames = int(frames)
|
| self.ok = True
|
| logging.info("[StereoMix] opened sr=%s ch=%s (%s)", sr_try, ch_try, self._chosen)
|
| break
|
| except Exception as e:
|
| last_err = e
|
| stream = None
|
| if stream is not None:
|
| break
|
|
|
| if stream is None:
|
| logging.info("[StereoMix] init error: %r", last_err)
|
| self.ok = False
|
| return
|
|
|
| try:
|
| with stream:
|
| while not self._stop.is_set():
|
| time.sleep(0.25)
|
| except Exception as e:
|
| logging.info("[StereoMix] thread error: %r", e)
|
| self.ok = False
|
|
|
| self._th = threading.Thread(target=run, name="StereoMix", daemon=True)
|
| self._th.start()
|
|
|
| def stop(self) -> None:
|
| self._stop.set()
|
| if self._th:
|
| self._th.join(timeout=1.5)
|
|
|
|
|
| class LoopbackSampler_SC(SamplerBase):
|
| """python-soundcard loopback (can pick the "wrong" speaker on multi-output systems)."""
|
|
|
| def __init__(self, sr: int = DEFAULT_SR, frame_s: float = DEFAULT_FRAME_S, history_s: float = 150.0, dev_name: Optional[str] = None):
|
| self.ok = False
|
| self.sr = int(sr)
|
| self.frame_s = float(frame_s)
|
| self.frames = int(round(self.frame_s * self.sr))
|
| self.win = PercentileWindow(self.frame_s, history_s)
|
| self.stop_evt = threading.Event()
|
| self.th: Optional[threading.Thread] = None
|
| self._last_block: Optional[np.ndarray] = None
|
| self._lb_lock = threading.Lock()
|
| self._chosen_name: Optional[str] = None
|
| self._dev_name = dev_name
|
|
|
| def chosen_name(self) -> Optional[str]:
|
| return self._chosen_name if self.ok else None
|
|
|
| def get_last_block(self) -> Optional[np.ndarray]:
|
| with self._lb_lock:
|
| return None if self._last_block is None else self._last_block.copy()
|
|
|
| def _speaker_score(self, name: str) -> int:
|
| return name_score_audio_device(name)
|
|
|
| def _pick_recorder(self):
|
| """
|
| python-soundcard loopback.
|
|
|
| Change vs older versions:
|
| - We do NOT always prioritize sc.default_speaker() if it looks like HDMI/display/etc.
|
| Instead we score endpoints and choose the best likely-real speaker.
|
| """
|
| if sc is None:
|
| return None
|
|
|
| speakers: List[Any] = []
|
| try:
|
| speakers = list(sc.all_speakers())
|
| except Exception:
|
| speakers = []
|
|
|
|
|
| if self._dev_name:
|
| for spk in speakers:
|
| try:
|
| if str(getattr(spk, "name", "")) == str(self._dev_name):
|
| try:
|
| mic = sc.get_microphone(id=str(spk.name), include_loopback=True)
|
| self._chosen_name = f"soundcard loopback: {mic.name}"
|
| for ch in (2, 1):
|
| try:
|
| rec = mic.recorder(samplerate=self.sr, channels=ch)
|
| return rec
|
| except Exception:
|
| continue
|
| except Exception:
|
| pass
|
| except Exception:
|
| continue
|
|
|
| default_first: List[Any] = []
|
| try:
|
| d = sc.default_speaker()
|
| dname = str(getattr(d, "name", ""))
|
| if not looks_bad_default_endpoint(dname):
|
| default_first = [d]
|
| speakers = [s for s in speakers if getattr(s, "name", None) != getattr(d, "name", None)]
|
| else:
|
|
|
| default_first = []
|
| except Exception:
|
| default_first = []
|
|
|
| speakers_sorted = sorted(
|
| speakers,
|
| key=lambda s: self._speaker_score(getattr(s, "name", "")),
|
| reverse=True,
|
| )
|
|
|
| candidates = (default_first + speakers_sorted)[:14]
|
|
|
| for spk in candidates:
|
| try:
|
| mic = sc.get_microphone(id=str(spk.name), include_loopback=True)
|
| self._chosen_name = f"soundcard loopback: {mic.name}"
|
| for ch in (2, 1):
|
| try:
|
| rec = mic.recorder(samplerate=self.sr, channels=ch)
|
| return rec
|
| except Exception:
|
| continue
|
| except Exception:
|
| continue
|
|
|
| return None
|
|
|
| def start(self) -> None:
|
| if self.th or sc is None:
|
| return
|
| rec = self._pick_recorder()
|
| if rec is None:
|
| return
|
|
|
| def run():
|
| try:
|
| with rec:
|
| while not self.stop_evt.is_set():
|
| try:
|
| block = rec.record(self.frames)
|
| block = np.asarray(block, dtype=np.float32)
|
| self.win.push(time.time(), rms_dbfs(block))
|
| with self._lb_lock:
|
| self._last_block = block.copy()
|
| except Exception:
|
| time.sleep(0.05)
|
| except Exception:
|
| pass
|
|
|
| self.th = threading.Thread(target=run, name="SCLoopback", daemon=True)
|
| self.th.start()
|
| self.ok = True
|
| logging.info("[soundcard loopback] running: %s", self._chosen_name)
|
|
|
| def stop(self) -> None:
|
| self.stop_evt.set()
|
| if self.th:
|
| self.th.join(timeout=1.5)
|
|
|
|
|
| class PycawPeakSampler(SamplerBase):
|
| """
|
| Reliable-ish fallback: system output peak meter via Pycaw.
|
|
|
| Notes:
|
| - This sampler does NOT provide raw audio blocks (so VAD is disabled).
|
| - Some systems throw intermittent COM errors on GetPeakValue(). We keep emitting samples
|
| (using last known value) and aggressively re-acquire the meter to self-heal.
|
|
|
| v0.10.11: relaxed "degraded" threshold so we don't force-switch too aggressively.
|
| """
|
|
|
| def __init__(self, frame_s=DEFAULT_FRAME_S, history_s=150.0):
|
| self.frame_s = float(frame_s)
|
| self.win = PercentileWindow(frame_s, history_s)
|
| self._stop = threading.Event()
|
| self._th: Optional[threading.Thread] = None
|
| self._ok = False
|
|
|
| self._mu = threading.Lock()
|
| self._succ = 0
|
| self._fail = 0
|
| self._fail_streak = 0
|
| self._last_ok_ts = 0.0
|
|
|
| def chosen_name(self) -> Optional[str]:
|
| return "pycaw peak meter" if self._ok else None
|
|
|
| def is_degraded(self) -> bool:
|
| with self._mu:
|
| if not self._ok:
|
| return True
|
| now = time.time()
|
|
|
|
|
| if (now - self._last_ok_ts) > 60.0 and self._fail_streak >= 500:
|
| return True
|
| return False
|
|
|
| def start(self) -> None:
|
| if self._th or not _WIN:
|
| return
|
|
|
| def run():
|
| meter = None
|
| last_db = -100.0
|
|
|
| def acquire():
|
| nonlocal meter
|
| try:
|
| import ctypes
|
| from ctypes import POINTER
|
| from pycaw.pycaw import AudioUtilities, IAudioMeterInformation
|
| from comtypes import CLSCTX_ALL
|
|
|
| dev = AudioUtilities.GetSpeakers()
|
| iface = dev.Activate(IAudioMeterInformation._iid_, CLSCTX_ALL, None)
|
| meter = ctypes.cast(iface, POINTER(IAudioMeterInformation))
|
| return True
|
| except Exception as e:
|
| logging.info("[PycawMeter] acquire failed: %r", e)
|
| meter = None
|
| return False
|
|
|
| CoUninitialize = None
|
| try:
|
| try:
|
| from comtypes import CoInitializeEx, CoUninitialize as _CoUninitialize, COINIT_MULTITHREADED
|
| CoUninitialize = _CoUninitialize
|
| CoInitializeEx(COINIT_MULTITHREADED)
|
| except Exception:
|
| from comtypes import CoInitialize, CoUninitialize as _CoUninitialize
|
| CoUninitialize = _CoUninitialize
|
| CoInitialize()
|
|
|
| try:
|
| ok = acquire()
|
| self._ok = bool(ok)
|
| if self._ok:
|
| logging.info("[PycawMeter] running.")
|
|
|
| last_log = 0.0
|
| while not self._stop.is_set():
|
| db = last_db
|
| try:
|
| if meter is None:
|
| acquire()
|
|
|
| if meter is not None:
|
| import ctypes
|
| from ctypes import byref, c_float
|
|
|
| v = c_float()
|
| meter.GetPeakValue(byref(v))
|
| peak = float(v.value)
|
| if peak <= 0.0 or not math.isfinite(peak):
|
| db = -100.0
|
| else:
|
| db = 20.0 * math.log10(max(1e-9, peak))
|
| last_db = db
|
|
|
| with self._mu:
|
| self._succ += 1
|
| self._fail_streak = 0
|
| self._last_ok_ts = time.time()
|
| else:
|
| raise RuntimeError("meter not acquired")
|
| except Exception:
|
| with self._mu:
|
| self._fail += 1
|
| self._fail_streak += 1
|
| fs = self._fail_streak
|
|
|
| if fs in (1, 10, 25, 50, 100, 200) or (time.time() - last_log) > 15.0:
|
| last_log = time.time()
|
| logging.info("[PycawMeter] read error (x%s) — continuing.", fs)
|
|
|
|
|
| if fs in (3, 10, 25, 50, 100, 200, 350) or (time.time() - self._last_ok_ts) > 10.0:
|
| acquire()
|
|
|
|
|
| self.win.push(time.time(), db)
|
| time.sleep(self.frame_s)
|
| finally:
|
|
|
| try:
|
| meter = None
|
| gc.collect()
|
| except Exception:
|
| pass
|
| try:
|
| if CoUninitialize is not None:
|
| CoUninitialize()
|
| except Exception:
|
| pass
|
| except Exception as e:
|
| logging.info("[PycawMeter] init error: %r", e)
|
|
|
| self._th = threading.Thread(target=run, name="PycawMeter", daemon=True)
|
| self._th.start()
|
|
|
| def stop(self) -> None:
|
| self._stop.set()
|
| if self._th:
|
| self._th.join(timeout=2.5)
|
|
|
|
|
| class MeterSampler(SamplerBase):
|
| """
|
| Last-resort COM meter via CreateObject("MMDeviceEnumerator") and IAudioMeterInformation.
|
| """
|
|
|
| def __init__(self, frame_s=DEFAULT_FRAME_S, history_s=150.0):
|
| self.frame_s = float(frame_s)
|
| self.win = PercentileWindow(frame_s, history_s)
|
| self._ok = False
|
| self._stop = threading.Event()
|
| self._th: Optional[threading.Thread] = None
|
|
|
| self._mu = threading.Lock()
|
| self._fail_streak = 0
|
| self._last_ok_ts = 0.0
|
|
|
| def chosen_name(self) -> Optional[str]:
|
| return "endpoint peak meter" if self._ok else None
|
|
|
| def is_degraded(self) -> bool:
|
| with self._mu:
|
| if not self._ok:
|
| return True
|
|
|
| if (time.time() - self._last_ok_ts) > 60.0 and self._fail_streak >= 500:
|
| return True
|
| return False
|
|
|
| def start(self) -> None:
|
| if self._th or not _WIN:
|
| return
|
|
|
| def run():
|
| meter = None
|
| last_db = -100.0
|
|
|
| def acquire():
|
| nonlocal meter
|
| try:
|
| import ctypes
|
| from ctypes import POINTER, byref, c_float, c_int, c_void_p, c_ulong
|
| from comtypes import (
|
| IUnknown, GUID, HRESULT, COMMETHOD,
|
| CLSCTX_ALL,
|
| )
|
| from comtypes.client import CreateObject
|
|
|
| eRender = 0
|
| eMultimedia = 1
|
|
|
| class IMMDevice(IUnknown):
|
| _iid_ = GUID('{D666063F-1587-4E43-81F1-B948E807363F}')
|
| _methods_ = [
|
| COMMETHOD([], HRESULT, 'Activate',
|
| (['in'], GUID, 'iid'),
|
| (['in'], c_ulong, 'dwClsCtx'),
|
| (['in'], c_void_p, 'pActivationParams'),
|
| (['out'], POINTER(c_void_p), 'ppInterface')),
|
| ]
|
|
|
| class IMMDeviceEnumerator(IUnknown):
|
| _iid_ = GUID('{A95664D2-9614-4F35-A746-DE8DB63617E6}')
|
| _methods_ = [
|
| COMMETHOD([], HRESULT, 'GetDefaultAudioEndpoint',
|
| (['in'], c_int, 'dataFlow'),
|
| (['in'], c_int, 'role'),
|
| (['out'], POINTER(POINTER(IMMDevice)), 'ppDevice')),
|
| ]
|
|
|
| class IAudioMeterInformation(IUnknown):
|
| _iid_ = GUID('{C02216F6-8C67-4B5B-9D00-D008E73E0064}')
|
| _methods_ = [
|
| COMMETHOD([], HRESULT, 'GetPeakValue',
|
| (['out'], POINTER(c_float), 'pfPeak')),
|
| ]
|
|
|
| enum = CreateObject("MMDeviceEnumerator", interface=IMMDeviceEnumerator)
|
| dev = POINTER(IMMDevice)()
|
| hr = enum.GetDefaultAudioEndpoint(eRender, eMultimedia, byref(dev))
|
| if hr:
|
| raise OSError(f"GetDefaultAudioEndpoint failed hr=0x{hr:08X}")
|
| ptr = c_void_p()
|
| hr = dev.Activate(IAudioMeterInformation._iid_, CLSCTX_ALL, None, byref(ptr))
|
| if hr:
|
| raise OSError(f"Activate(IAudioMeterInformation) failed hr=0x{hr:08X}")
|
|
|
| meter = ctypes.cast(ptr, POINTER(IAudioMeterInformation))
|
| return True
|
| except Exception as e:
|
| logging.info("[Meter] acquire failed: %r", e)
|
| meter = None
|
| return False
|
|
|
| CoUninitialize = None
|
| try:
|
| try:
|
| from comtypes import CoInitializeEx, CoUninitialize as _CoUninitialize, COINIT_MULTITHREADED
|
| CoUninitialize = _CoUninitialize
|
| CoInitializeEx(COINIT_MULTITHREADED)
|
| except Exception:
|
| from comtypes import CoInitialize, CoUninitialize as _CoUninitialize
|
| CoUninitialize = _CoUninitialize
|
| CoInitialize()
|
|
|
| try:
|
| ok = acquire()
|
| self._ok = bool(ok)
|
| if self._ok:
|
| logging.info("[Meter] running (COM peak).")
|
|
|
| last_log = 0.0
|
| while not self._stop.is_set():
|
| db = last_db
|
| try:
|
| if meter is None:
|
| acquire()
|
|
|
| if meter is not None:
|
| from ctypes import byref, c_float
|
| v = c_float()
|
| meter.GetPeakValue(byref(v))
|
| peak = float(v.value)
|
| if peak <= 0.0 or not math.isfinite(peak):
|
| db = -100.0
|
| else:
|
| db = 20.0 * math.log10(max(1e-9, peak))
|
| last_db = db
|
|
|
| with self._mu:
|
| self._fail_streak = 0
|
| self._last_ok_ts = time.time()
|
| else:
|
| raise RuntimeError("meter not acquired")
|
| except Exception:
|
| with self._mu:
|
| self._fail_streak += 1
|
| fs = self._fail_streak
|
|
|
| if fs in (1, 10, 25, 50, 100, 200) or (time.time() - last_log) > 15.0:
|
| last_log = time.time()
|
| logging.info("[Meter] read error (x%s) — continuing.", fs)
|
|
|
| if fs in (3, 10, 25, 50, 100, 200, 350):
|
| acquire()
|
|
|
| self.win.push(time.time(), db)
|
| time.sleep(self.frame_s)
|
| finally:
|
|
|
| try:
|
| meter = None
|
| gc.collect()
|
| except Exception:
|
| pass
|
| try:
|
| if CoUninitialize is not None:
|
| CoUninitialize()
|
| except Exception:
|
| pass
|
| except Exception as e:
|
| logging.info("[Meter] init error: %r", e)
|
|
|
| self._th = threading.Thread(target=run, name="MeterCOM", daemon=True)
|
| self._th.start()
|
|
|
| def stop(self) -> None:
|
| self._stop.set()
|
| if self._th:
|
| self._th.join(timeout=2.5)
|
|
|
|
|
|
|
|
|
| class VolBackend:
|
| def get(self) -> float:
|
| raise NotImplementedError
|
|
|
| def set(self, s: float) -> None:
|
| raise NotImplementedError
|
|
|
|
|
| class WinVolSTA(VolBackend):
|
| """System master volume via pycaw on a dedicated COM thread."""
|
|
|
| def __init__(self):
|
| self._q: queue.Queue = queue.Queue()
|
| self._ready = threading.Event()
|
| self._stop = threading.Event()
|
| self._th = threading.Thread(target=self._run, name="WinVolCOM", daemon=True)
|
| self._th.start()
|
| if not self._ready.wait(timeout=2.5):
|
| raise RuntimeError("WinVolSTA COM init timed out")
|
|
|
| def _run(self):
|
| dev = None
|
| iface = None
|
| ep = None
|
| CoUninitialize = None
|
| try:
|
| from comtypes import CoInitialize, CoUninitialize as _CoUninitialize, CLSCTX_ALL
|
| from ctypes import POINTER, cast
|
| from pycaw.pycaw import AudioUtilities, IAudioEndpointVolume
|
|
|
| CoUninitialize = _CoUninitialize
|
|
|
| CoInitialize()
|
| try:
|
| dev = AudioUtilities.GetSpeakers()
|
| iface = dev.Activate(IAudioEndpointVolume._iid_, CLSCTX_ALL, None)
|
| ep = cast(iface, POINTER(IAudioEndpointVolume))
|
| self._ready.set()
|
|
|
| while not self._stop.is_set():
|
| try:
|
| op, val, ack = self._q.get(timeout=0.1)
|
| except queue.Empty:
|
| continue
|
| try:
|
| if op == "get":
|
| ack.set_result(float(ep.GetMasterVolumeLevelScalar()))
|
| elif op == "set":
|
| ep.SetMasterVolumeLevelScalar(clamp(float(val), 0.0, 1.0), None)
|
| ack.set_result(True)
|
| elif op == "quit":
|
| ack.set_result(True)
|
| break
|
| except Exception as e:
|
| ack.set_exception(e)
|
| finally:
|
|
|
| try:
|
| ep = None
|
| iface = None
|
| dev = None
|
| gc.collect()
|
| except Exception:
|
| pass
|
| try:
|
| if CoUninitialize is not None:
|
| CoUninitialize()
|
| except Exception:
|
| pass
|
| except Exception as e:
|
| self._ready.set()
|
| try:
|
| while True:
|
| op, val, ack = self._q.get_nowait()
|
| ack.set_exception(e)
|
| except queue.Empty:
|
| pass
|
|
|
| class _Ack:
|
| def __init__(self):
|
| self._ev = threading.Event()
|
| self._res = None
|
| self._exc: Optional[BaseException] = None
|
|
|
| def set_result(self, r):
|
| self._res = r
|
| self._ev.set()
|
|
|
| def set_exception(self, e: BaseException):
|
| self._exc = e
|
| self._ev.set()
|
|
|
| def wait(self, timeout=None):
|
| ok = self._ev.wait(timeout)
|
| if not ok:
|
| raise TimeoutError("WinVolSTA RPC timed out")
|
| if self._exc:
|
| raise self._exc
|
| return self._res
|
|
|
| def _rpc(self, op: str, val=None, timeout=2.0):
|
| ack = WinVolSTA._Ack()
|
| self._q.put((op, val, ack))
|
| return ack.wait(timeout=timeout)
|
|
|
| def get(self) -> float:
|
| try:
|
| return float(self._rpc("get"))
|
| except Exception:
|
| return 0.5
|
|
|
| def set(self, s: float) -> None:
|
| try:
|
| self._rpc("set", s)
|
| except Exception:
|
| pass
|
|
|
| def close(self):
|
| try:
|
| self._rpc("quit", timeout=1.5)
|
| except Exception:
|
| pass
|
| self._stop.set()
|
| try:
|
| if self._th and self._th.is_alive():
|
| self._th.join(timeout=2.5)
|
| except Exception:
|
| pass
|
|
|
|
|
| class DryVol(VolBackend):
|
| def __init__(self):
|
| self._s = 0.4
|
|
|
| def get(self) -> float:
|
| return self._s
|
|
|
| def set(self, s: float) -> None:
|
| self._s = clamp(float(s), 0.0, 1.0)
|
|
|
|
|
| def choose_backend(force_dry: bool = False) -> VolBackend:
|
| if not _WIN or force_dry:
|
| logging.info("[Vol] Using DryVol (no system changes).")
|
| return DryVol()
|
| try:
|
| bk = WinVolSTA()
|
| logging.info("[Vol] Using WinVolSTA (COM thread).")
|
| return bk
|
| except Exception as e:
|
| logging.info("[Vol] Falling back to DryVol: %r", e)
|
| return DryVol()
|
|
|
|
|
|
|
|
|
| class Learner:
|
| def __init__(self, path: str, min_events=6, q=0.70):
|
| self.path = path
|
| self.min_events = int(min_events)
|
| self.q = float(q)
|
| self.global_downs: Deque[float] = deque(maxlen=600)
|
| self.hour_downs: Dict[int, Deque[float]] = {h: deque(maxlen=300) for h in range(24)}
|
| self._mu = threading.Lock()
|
| self.load()
|
|
|
| def load(self):
|
| if not os.path.exists(self.path):
|
| return
|
| try:
|
| with open(self.path, "r", encoding="utf-8") as f:
|
| data = json.load(f)
|
| except Exception as e:
|
| logging.info("[Learner] load error: %r", e)
|
| return
|
|
|
| with self._mu:
|
| self.global_downs.clear()
|
| for h in range(24):
|
| self.hour_downs[h].clear()
|
|
|
| g_src = data.get("global_downs", [])
|
| if isinstance(g_src, list):
|
| for x in g_src[-600:]:
|
| try:
|
| self.global_downs.append(float(x))
|
| except Exception:
|
| pass
|
|
|
| h_src = data.get("hour_downs", {})
|
| if isinstance(h_src, dict):
|
| for k, arr in h_src.items():
|
| try:
|
| h = int(k)
|
| if 0 <= h <= 23 and isinstance(arr, list):
|
| for x in arr[-300:]:
|
| try:
|
| self.hour_downs[h].append(float(x))
|
| except Exception:
|
| pass
|
| except Exception:
|
| continue
|
|
|
| def save(self):
|
| try:
|
| with self._mu:
|
| out = {
|
| "global_downs": list(self.global_downs),
|
| "hour_downs": {str(h): list(self.hour_downs[h]) for h in range(24)},
|
| }
|
| tmp = self.path + ".tmp"
|
| with open(tmp, "w", encoding="utf-8") as f:
|
| json.dump(out, f)
|
| os.replace(tmp, self.path)
|
| except Exception as e:
|
| logging.info("[Learner] save error: %r", e)
|
|
|
| @staticmethod
|
| def _percentile(vals: List[float], q: float) -> float:
|
| if not vals:
|
| return -100.0
|
| s = sorted(vals)
|
| k = int(round((len(s) - 1) * clamp(q, 0.0, 1.0)))
|
| return float(s[k])
|
|
|
| def record_down(self, db_at: float, hour: int):
|
| with self._mu:
|
| self.global_downs.append(float(db_at))
|
| if 0 <= hour <= 23:
|
| self.hour_downs[hour].append(float(db_at))
|
|
|
| def threshold(self, hour: int) -> Optional[float]:
|
| with self._mu:
|
| per = self.hour_downs.get(hour, deque())
|
| g = self.global_downs
|
|
|
| if len(per) >= self.min_events:
|
| q_use = 0.75 if len(per) > 20 else self.q
|
| return self._percentile(list(per), q_use)
|
|
|
| if len(g) >= self.min_events:
|
| q_use = 0.75 if len(g) > 20 else self.q
|
| return self._percentile(list(g), q_use)
|
|
|
| return None
|
|
|
| def counts(self) -> Tuple[int, Dict[int, int]]:
|
| with self._mu:
|
| return len(self.global_downs), {h: len(self.hour_downs[h]) for h in range(24)}
|
|
|
| def reset(self):
|
| with self._mu:
|
| self.global_downs.clear()
|
| for h in range(24):
|
| self.hour_downs[h].clear()
|
| self.save()
|
|
|
|
|
|
|
|
|
| class SpeechGate:
|
| def __init__(self, fs_capture: int, frame_ms: int = 20, aggressiveness: int = 2, ema_alpha: float = 0.35):
|
| self.fs_cap = int(fs_capture)
|
| self.frame_ms = int(frame_ms)
|
| self._ema = 0.0
|
| self._alpha = float(clamp(ema_alpha, 0.0, 1.0))
|
| self._have_vad = _HAVE_WEBRTCVAD
|
| if self._have_vad:
|
| self.vad = webrtcvad.Vad(int(clamp(aggressiveness, 0, 3)))
|
|
|
| def _to_16k_pcm16(self, x: np.ndarray) -> Tuple[bytes, int]:
|
| if x.ndim > 1:
|
| x = x.mean(axis=1)
|
| fs16 = 16000
|
| if self.fs_cap == 48000:
|
| x = x[::3]
|
| else:
|
| idx = np.linspace(0, len(x) - 1, int(len(x) * fs16 / self.fs_cap))
|
| x = np.interp(idx, np.arange(len(x)), x).astype(np.float32)
|
| x = np.clip(x, -1.0, 1.0)
|
| return (x * 32767.0).astype(np.int16).tobytes(), fs16
|
|
|
| def _heuristic_prob(self, block: np.ndarray) -> float:
|
| if block.ndim > 1:
|
| x = block.mean(axis=1).astype(np.float32, copy=False)
|
| else:
|
| x = block.astype(np.float32, copy=False)
|
|
|
| e_db = 20.0 * math.log10(max(1e-9, float(np.sqrt(np.mean(x * x)))))
|
| if e_db <= -55.0 or len(x) < 512:
|
| return 0.0
|
|
|
| zc = float(np.mean((x[1:] * x[:-1]) < 0.0))
|
| X = np.fft.rfft(x * np.hanning(len(x)))
|
| mag = np.abs(X) + 1e-9
|
| freqs = np.fft.rfftfreq(len(x), 1.0 / self.fs_cap)
|
| hf = float(mag[freqs >= 2000].sum() / mag.sum())
|
| return 1.0 if (0.03 <= zc <= 0.25) and (0.05 <= hf <= 0.60) else 0.0
|
|
|
| def prob(self, block: Optional[np.ndarray]) -> float:
|
| if block is None or getattr(block, "size", 0) == 0:
|
| self._ema = (1.0 - self._alpha) * self._ema
|
| return self._ema
|
|
|
| if self._have_vad:
|
| try:
|
| pcm16, fs16 = self._to_16k_pcm16(block)
|
| frame_len = int((self.frame_ms / 1000.0) * fs16)
|
| hits = 0
|
| total = 0
|
| step = frame_len * 2
|
| for i in range(0, len(pcm16), step):
|
| frame = pcm16[i: i + step]
|
| if len(frame) < step:
|
| break
|
| total += 1
|
| if self.vad.is_speech(frame, fs16):
|
| hits += 1
|
| raw = (hits / total) if total else 0.0
|
| except Exception:
|
| raw = 0.0
|
| else:
|
| raw = self._heuristic_prob(block)
|
|
|
| self._ema = self._alpha * raw + (1.0 - self._alpha) * self._ema
|
| return self._ema
|
|
|
|
|
|
|
|
|
| class VolumePoller:
|
| def __init__(self, bk, poll_s=0.05, min_step=0.005):
|
| self.bk = bk
|
| self.poll_s = float(poll_s)
|
| self.min_step = float(min_step)
|
| self._stop = threading.Event()
|
| self._thr: Optional[threading.Thread] = None
|
| self._prev = self.bk.get()
|
| self._callbacks: List[Callable[[float, float, float], None]] = []
|
|
|
| def on_change(self, fn: Callable[[float, float, float], None]):
|
| self._callbacks.append(fn)
|
|
|
| def start(self):
|
| if self._thr:
|
| return
|
|
|
| def run():
|
| while not self._stop.is_set():
|
| time.sleep(self.poll_s)
|
| try:
|
| cur = self.bk.get()
|
| except Exception:
|
| continue
|
| prev = self._prev
|
| if abs(cur - prev) >= self.min_step:
|
| ts = time.time()
|
| for fn in self._callbacks:
|
| try:
|
| fn(ts, prev, cur)
|
| except Exception:
|
| pass
|
| self._prev = cur
|
|
|
| self._thr = threading.Thread(target=run, name="VolPoll", daemon=True)
|
| self._thr.start()
|
|
|
| def stop(self):
|
| self._stop.set()
|
| if self._thr:
|
| self._thr.join(timeout=1.5)
|
|
|
|
|
|
|
|
|
| class AutoVolController:
|
| def __init__(self, model_path: str, events_path: str, force_dryvol: bool = False):
|
| self.model_path = model_path
|
| self.events_path = events_path
|
|
|
| self.FRAME_S = DEFAULT_FRAME_S
|
| self.BASELINE_WIN_S = 45.0
|
| self.SHORT_WIN_S = 1.0
|
|
|
| self.OVER_MARGIN_DB = 1.2
|
| self.ATTACK_DB_MAX = 1.6
|
| self.RELEASE_DB_MAX = 0.45
|
| self.MIN_VOL = 0.03
|
|
|
| self.SPEECH_UP_DB = 2.0
|
| self.NOSPEECH_DOWN_DB = -2.0
|
|
|
| self.IGNORE_OWN_SET_S = 0.8
|
| self.USER_DOWN_COOLDOWN_S = 1.2
|
| self.SET_COOLDOWN_S = 1.6
|
| self.STARTUP_OBS_S = 6.0
|
|
|
| self.NO_SAMPLE_GRACE_S = 8.0
|
| self.SWITCH_COOLDOWN_S = 15.0
|
|
|
|
|
| self.SAMPLER_PREFLIGHT_S = 4.5
|
| self.SAMPLER_BACKOFF_BASE_S = 25.0
|
| self.SAMPLER_BACKOFF_MAX_S = 15 * 60.0
|
|
|
| self._stop = threading.Event()
|
| self._paused = threading.Event()
|
| self._observe = threading.Event()
|
| self._thread: Optional[threading.Thread] = None
|
| self._last_set_ts = 0.0
|
| self._last_user_down_ts = 0.0
|
| self._startup_ts = time.time()
|
|
|
| self.observe_only = False
|
|
|
| self._last_th: Optional[float] = None
|
| self._last_p85 = -100.0
|
| self._last_p95 = -100.0
|
| self._speech = 0.0
|
| self._flash_duck_until = 0.0
|
|
|
| self._signal_state = "INIT"
|
| self._last_sample_ts = time.time()
|
| self._last_switch_ts = 0.0
|
|
|
| self.bk = choose_backend(force_dry=force_dryvol)
|
| self.learner = Learner(path=self.model_path)
|
| self._downs_total = self.learner.counts()[0]
|
|
|
| try:
|
| self.events = open(self.events_path, "a", encoding="utf-8")
|
| except Exception as e:
|
| logging.info("[AutoVol] cannot open events file: %r", e)
|
| self.events = None
|
|
|
| self.resting = self.bk.get()
|
| self.current = self.resting
|
|
|
| self.poll = VolumePoller(self.bk, poll_s=0.05, min_step=0.005)
|
| self.poll.on_change(self._on_user_change)
|
|
|
| self.vad = SpeechGate(fs_capture=48000, frame_ms=20, aggressiveness=2, ema_alpha=0.35)
|
|
|
| self._samplers: List[SamplerBase] = [
|
| LoopbackSampler_SD(sr=48000, frame_s=self.FRAME_S, history_s=150.0),
|
| LoopbackSampler_SC(sr=48000, frame_s=self.FRAME_S, history_s=150.0),
|
| PycawPeakSampler(frame_s=self.FRAME_S, history_s=150.0),
|
| StereoMixSampler_SD(sr=48000, frame_s=self.FRAME_S, history_s=150.0),
|
| MeterSampler(frame_s=self.FRAME_S, history_s=150.0),
|
| ]
|
|
|
| self.sampler: Optional[SamplerBase] = None
|
| self._sampler_idx = -1
|
|
|
|
|
| self._sampler_fail: Dict[str, Dict[str, float]] = {}
|
|
|
| self._switch_sampler(reason="startup")
|
|
|
| bk_name = "WinVolSTA" if isinstance(self.bk, WinVolSTA) else "DryVol"
|
| src = self.sampler.chosen_name() if self.sampler else "none"
|
| logging.info("[AutoVol] backend=%s sampler=%s model=%s events=%s", bk_name, src, self.model_path, self.events_path)
|
|
|
| @property
|
| def observe_only(self) -> bool:
|
| """If True, AutoVol will not change system volume (it still learns + shows stats)."""
|
| return bool(self._observe.is_set())
|
|
|
| @observe_only.setter
|
| def observe_only(self, v: bool) -> None:
|
| if bool(v):
|
| self._observe.set()
|
| else:
|
| self._observe.clear()
|
|
|
| def _write_event(self, obj: Dict[str, Any]) -> None:
|
| try:
|
| if self.events:
|
| self.events.write(json.dumps(obj) + "\n")
|
| self.events.flush()
|
| except Exception:
|
| pass
|
|
|
| def _sampler_stats(self, window_s: float) -> Stats:
|
| if self.sampler is not None and hasattr(self.sampler, "win"):
|
| try:
|
| return getattr(self.sampler, "win").stats(window_s)
|
| except Exception:
|
| pass
|
| return Stats(-100.0, -100.0, -100.0, -100.0, 0)
|
|
|
| def _sampler_backoff_until(self, key: str) -> float:
|
| st = self._sampler_fail.get(key, {})
|
| return float(st.get("until", 0.0))
|
|
|
| def _mark_sampler_fail(self, key: str) -> None:
|
| now = time.time()
|
| st = self._sampler_fail.get(key)
|
| if not st:
|
| st = {"fails": 0.0, "until": 0.0}
|
| self._sampler_fail[key] = st
|
| st["fails"] = float(st.get("fails", 0.0) + 1.0)
|
| fails = st["fails"]
|
| backoff = min(self.SAMPLER_BACKOFF_MAX_S, self.SAMPLER_BACKOFF_BASE_S * (2.0 ** max(0.0, fails - 1.0)))
|
| st["until"] = now + backoff
|
|
|
| def _switch_sampler(self, reason: str) -> None:
|
| try:
|
| if self.sampler:
|
| self.sampler.stop()
|
| except Exception:
|
| pass
|
|
|
| picked = None
|
| best_name = None
|
|
|
| n_samplers = max(1, len(self._samplers))
|
| now = time.time()
|
|
|
| for _ in range(n_samplers):
|
| self._sampler_idx = (self._sampler_idx + 1) % n_samplers
|
| cand = self._samplers[self._sampler_idx]
|
| key = cand.sampler_key()
|
|
|
|
|
| if now < self._sampler_backoff_until(key):
|
| continue
|
|
|
| try:
|
| cand.start()
|
| except Exception:
|
| pass
|
|
|
|
|
| t0 = time.time()
|
| ok_flow = False
|
| while time.time() - t0 < self.SAMPLER_PREFLIGHT_S:
|
| try:
|
| if cand.samples_recent(1.2):
|
| ok_flow = True
|
| break
|
| except Exception:
|
| pass
|
| time.sleep(0.2)
|
|
|
| nm = cand.chosen_name()
|
| if ok_flow:
|
| picked = cand
|
| best_name = nm or key
|
| break
|
|
|
|
|
| try:
|
| cand.stop()
|
| except Exception:
|
| pass
|
| self._mark_sampler_fail(key)
|
|
|
| self.sampler = picked
|
| self._last_switch_ts = time.time()
|
|
|
| if self.sampler:
|
| logging.info("[Sampler] switched -> %s (%s)", self.sampler.chosen_name() or best_name or self.sampler.sampler_key(), reason)
|
| self._signal_state = f"SWITCH({reason})"
|
| else:
|
| logging.info("[Sampler] no viable sampler found (%s).", reason)
|
| self._signal_state = "NO SAMPLER"
|
|
|
| def _update_signal_health(self) -> None:
|
| now = time.time()
|
|
|
| if self.sampler is not None:
|
| deg = getattr(self.sampler, "is_degraded", None)
|
| if callable(deg):
|
| try:
|
| if bool(deg()) and (now - self._last_switch_ts) >= self.SWITCH_COOLDOWN_S:
|
| self._signal_state = "DEGRADED"
|
| self._switch_sampler(reason="degraded")
|
| return
|
| except Exception:
|
| pass
|
|
|
| st = self._sampler_stats(1.5)
|
| if st.n > 0:
|
| self._last_sample_ts = now
|
| if (
|
| self._signal_state in ("INIT", "NO SAMPLES", "NO SAMPLER")
|
| or self._signal_state.startswith("SWITCH")
|
| or self._signal_state == "DEGRADED"
|
| ):
|
| self._signal_state = "LIVE"
|
| return
|
|
|
| if (now - self._last_sample_ts) > self.NO_SAMPLE_GRACE_S:
|
| self._signal_state = "NO SAMPLES"
|
| if (now - self._last_switch_ts) >= self.SWITCH_COOLDOWN_S:
|
| self._switch_sampler(reason="no-samples")
|
|
|
| def vol_set(self, new_scalar: float, why: str = "auto") -> None:
|
| new_scalar = clamp(new_scalar, self.MIN_VOL, 1.0)
|
| self.bk.set(new_scalar)
|
| self.current = new_scalar
|
| now = time.time()
|
| self._last_set_ts = now
|
| self._flash_duck_until = now + 2.2
|
|
|
| self._write_event({
|
| "ts": round(now, 3),
|
| "type": "AUTO_SET",
|
| "why": why,
|
| "vol": round(new_scalar, 3),
|
| "th_db": None if self._last_th is None else round(self._last_th, 2),
|
| "p85_db": round(self._last_p85, 2),
|
| "p95_db": round(self._last_p95, 2),
|
| "signal": self._signal_state,
|
| "sampler": self.sampler.chosen_name() if self.sampler else None,
|
| })
|
|
|
| def _on_user_change(self, ts: float, old: float, new: float):
|
| if ts - self._last_set_ts <= self.IGNORE_OWN_SET_S:
|
| return
|
|
|
| self.resting = new
|
| self.current = new
|
|
|
| if self._paused.is_set():
|
| return
|
|
|
| st = self._sampler_stats(self.SHORT_WIN_S)
|
| hour = time.localtime(ts).tm_hour
|
| db_at = st.p85
|
|
|
| self._write_event({
|
| "ts": round(ts, 3),
|
| "type": "USER_SET",
|
| "hour": hour,
|
| "dir": "DOWN" if new < old else "UP",
|
| "p85_db": round(db_at, 2),
|
| "old": round(old, 3),
|
| "new": round(new, 3),
|
| "signal": self._signal_state,
|
| "sampler": self.sampler.chosen_name() if self.sampler else None,
|
| })
|
|
|
| if (
|
| new < old
|
| and st.n >= 1
|
| and (ts - self._last_user_down_ts) > self.USER_DOWN_COOLDOWN_S
|
| ):
|
| self.learner.record_down(db_at, hour)
|
| self._last_user_down_ts = ts
|
| self._downs_total += 1
|
| self.learner.save()
|
|
|
| def start(self):
|
| self.poll.start()
|
| if self._thread:
|
| return
|
| self._thread = threading.Thread(target=self._run, name="AutoVolLoop", daemon=True)
|
| self._thread.start()
|
|
|
| def stop(self):
|
| self._stop.set()
|
| try:
|
| self.poll.stop()
|
| except Exception:
|
| pass
|
| try:
|
| if isinstance(self.bk, WinVolSTA):
|
| self.bk.close()
|
| except Exception:
|
| pass
|
| try:
|
| if self.sampler:
|
| self.sampler.stop()
|
| except Exception:
|
| pass
|
| try:
|
| self.learner.save()
|
| if self.events:
|
| self.events.close()
|
| except Exception:
|
| pass
|
| if self._thread:
|
| self._thread.join(timeout=1.5)
|
|
|
| def pause(self, do_pause: bool):
|
| if do_pause:
|
| self._paused.set()
|
| if abs(self.current - self.resting) > 1e-3:
|
| self.vol_set(self.resting, why="pause->restore")
|
| else:
|
| self._paused.clear()
|
|
|
| def reset_learning(self):
|
| try:
|
| self.learner.reset()
|
| self._downs_total = 0
|
| except Exception:
|
| pass
|
|
|
| def open_data_folder(self, data_dir: str):
|
| try:
|
| if _WIN:
|
| os.startfile(data_dir)
|
| elif sys.platform == "darwin":
|
| subprocess.Popen(["open", data_dir])
|
| else:
|
| subprocess.Popen(["xdg-open", data_dir])
|
| except Exception:
|
| pass
|
|
|
| def stats_text_short(self) -> str:
|
| 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")
|
| th_txt = f"{self._last_th:.0f}" if self._last_th is not None else "—"
|
| src = self.sampler.chosen_name() if self.sampler else "none"
|
| return f"{self._signal_state} {mode} vol:{self.current:.2f} p85:{self._last_p85:.0f} th:{th_txt} d:{self._downs_total} ({src})"
|
|
|
| def stats_text_long(self) -> str:
|
| tag = "vad" if _HAVE_WEBRTCVAD else "lite"
|
| th_txt = f"{self._last_th:.1f}dB" if (self._last_th is not None) else "—"
|
| 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")
|
| duck_txt = " ↓" if (time.time() < self._flash_duck_until) else ""
|
| src = self.sampler.chosen_name() if self.sampler else "none"
|
| 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}"
|
|
|
| def _maybe_promote_sampler(self, now: float) -> None:
|
|
|
| if self._paused.is_set() or self._observe.is_set():
|
| return
|
|
|
| def _run(self):
|
| last_save = time.time()
|
|
|
| while not self._stop.is_set():
|
| time.sleep(0.25)
|
| now = time.time()
|
|
|
| actual = self.bk.get()
|
| if abs(actual - self.current) > 0.05:
|
| self.resting = actual
|
| self.current = actual
|
|
|
| self._update_signal_health()
|
| if self._signal_state in ("NO SAMPLER", "NO SAMPLES"):
|
| continue
|
|
|
| if self._paused.is_set() or self.observe_only or (now - self._startup_ts < self.STARTUP_OBS_S):
|
| continue
|
|
|
| if not self.sampler:
|
| continue
|
|
|
| base = self._sampler_stats(self.BASELINE_WIN_S)
|
| cur = self._sampler_stats(self.SHORT_WIN_S)
|
| self._last_p85 = cur.p85
|
| self._last_p95 = cur.p95
|
|
|
| if cur.n < 1:
|
| continue
|
|
|
| hour = time.localtime().tm_hour
|
| th = self.learner.threshold(hour)
|
| if th is None:
|
| th = max(base.p70, -45.0) + 6.0
|
| self._last_th = th
|
|
|
| over85 = cur.p85 - th
|
| if (now - self._last_set_ts) >= self.SET_COOLDOWN_S and over85 > self.OVER_MARGIN_DB:
|
| step_db = clamp(over85 * 0.35, 0.25, self.ATTACK_DB_MAX)
|
| self.vol_set(self.current * db_to_lin(-step_db), why="steady_over85")
|
| continue
|
|
|
| over95 = cur.p95 - th
|
| if (now - self._last_set_ts) >= self.SET_COOLDOWN_S and over95 > (self.OVER_MARGIN_DB + 1.8):
|
| step_db = clamp(over95 * 0.55, 0.6, 2.8)
|
| self.vol_set(self.current * db_to_lin(-step_db), why="spike_over95")
|
| continue
|
|
|
| block = None
|
| try:
|
| block = self.sampler.get_last_block()
|
| except Exception:
|
| block = None
|
|
|
| if block is not None and getattr(block, "size", 0) > 0:
|
| sp_prob = self.vad.prob(block)
|
| self._speech = 0.6 * sp_prob + 0.4 * self._speech
|
|
|
| if (now - self._last_set_ts) >= self.SET_COOLDOWN_S:
|
| target = self.resting
|
| if self._speech >= 0.55:
|
| target = min(1.0, self.resting * db_to_lin(self.SPEECH_UP_DB))
|
| else:
|
| target = max(self.MIN_VOL, self.resting * db_to_lin(self.NOSPEECH_DOWN_DB))
|
|
|
| if abs(target - self.current) > 0.015:
|
| step_up = db_to_lin(self.RELEASE_DB_MAX)
|
| step_dn = db_to_lin(-self.RELEASE_DB_MAX)
|
| if target > self.current:
|
| new = min(target, self.current * step_up)
|
| else:
|
| new = max(target, self.current * step_dn)
|
| self.vol_set(new, why="speech_gate")
|
| else:
|
| self.vad.prob(None)
|
| self._speech = 0.0
|
|
|
| if now - last_save >= 25.0:
|
| last_save = now
|
| self.learner.save()
|
|
|
|
|
|
|
|
|
| def make_icon(color_fg=(255, 255, 255, 255), color_bg=(0, 0, 0, 0)) -> Image.Image:
|
| W, H = 64, 64
|
| img = Image.new("RGBA", (W, H), color_bg)
|
| d = ImageDraw.Draw(img)
|
| d.rectangle([12, 24, 24, 40], fill=color_fg)
|
| d.polygon([(24, 24), (36, 16), (36, 48), (24, 40)], fill=color_fg)
|
| d.arc([38, 18, 58, 46], start=315, end=45, width=3, fill=color_fg)
|
| d.arc([42, 14, 62, 50], start=315, end=45, width=2, fill=color_fg)
|
| return img
|
|
|
|
|
| def resolve_paths(model_filename: str, events_filename: str) -> Tuple[str, str, str]:
|
| data_dir = _default_data_dir()
|
| os.makedirs(data_dir, exist_ok=True)
|
| model_path = model_filename if os.path.isabs(model_filename) else os.path.join(data_dir, model_filename)
|
| events_path = events_filename if os.path.isabs(events_filename) else os.path.join(data_dir, events_filename)
|
| return data_dir, model_path, events_path
|
|
|
|
|
| def run_tray():
|
| ap = argparse.ArgumentParser(add_help=True)
|
| ap.add_argument("--model", default="autovol_learn.json")
|
| ap.add_argument("--events", default="autovol_events.jsonl")
|
| ap.add_argument("--force-dryvol", action="store_true", help="don't touch system volume (debug)")
|
| ap.add_argument("--observe", action="store_true", help="start in observe-only mode (no volume changes)")
|
| ap.add_argument("--reset", action="store_true", help="reset learned downs before starting")
|
| ap.add_argument("--no-autoinstall", action="store_true", help="disable auto-install of missing deps")
|
| args = ap.parse_args()
|
|
|
| data_dir, model_path, events_path = resolve_paths(args.model, args.events)
|
| log_path = setup_logging(data_dir)
|
| logging.info("Log file: %s", log_path)
|
|
|
| ctl = AutoVolController(model_path=model_path, events_path=events_path, force_dryvol=args.force_dryvol)
|
| if args.reset:
|
| ctl.reset_learning()
|
| logging.info("Learning reset.")
|
| ctl.observe_only = bool(args.observe)
|
| ctl.start()
|
|
|
| icon_img = make_icon()
|
| icon = pystray.Icon("AutoVol", icon=icon_img, title="AutoVol")
|
|
|
| def update_title():
|
| icon.title = safe_tooltip("AutoVol — " + ctl.stats_text_short())
|
|
|
| def on_pause(_icon, _item):
|
| ctl.pause(not ctl._paused.is_set())
|
| update_title()
|
|
|
| def on_toggle_observe(_icon, _item):
|
| ctl.observe_only = not ctl.observe_only
|
| update_title()
|
|
|
| def on_reset(_icon, _item):
|
| ctl.reset_learning()
|
| update_title()
|
|
|
| def on_open(_icon, _item):
|
| ctl.open_data_folder(data_dir)
|
|
|
| def on_quit(icon_obj, _item):
|
| try:
|
| ctl.stop()
|
| finally:
|
| icon_obj.stop()
|
|
|
| menu = Menu(
|
| Item(lambda _item: safe_tooltip("Status: " + ctl.stats_text_long(), max_len=120), None, enabled=False),
|
| Item(lambda _item: "Observe only (no changes)", on_toggle_observe, checked=lambda _item: ctl.observe_only),
|
| Item(lambda _item: "Resume" if ctl._paused.is_set() else "Pause", on_pause),
|
| Item("Reset learning", on_reset),
|
| Item("Open data folder", on_open),
|
| Item("Quit", on_quit),
|
| )
|
| icon.menu = menu
|
|
|
| def refresher():
|
| while not ctl._stop.is_set():
|
| update_title()
|
| time.sleep(1.8)
|
|
|
| threading.Thread(target=refresher, name="TrayRefresh", daemon=True).start()
|
|
|
| logging.info("[AutoVol] tray up — check system tray.")
|
| update_title()
|
| icon.run()
|
|
|
|
|
| if __name__ == "__main__":
|
| try:
|
| run_tray()
|
| except KeyboardInterrupt:
|
| pass
|
| except Exception as e:
|
| try:
|
| dd = _default_data_dir()
|
| os.makedirs(dd, exist_ok=True)
|
| with open(os.path.join(dd, "autovol_crash.txt"), "w", encoding="utf-8") as f:
|
| f.write(repr(e) + "\n\n")
|
| f.write(traceback.format_exc())
|
| except Exception:
|
| pass
|
| raise |