cjc0013 commited on
Commit
3744204
·
verified ·
1 Parent(s): bae198a

Delete autovol_tray.py

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