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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""

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))

# ------------------ dependency bootstrap ------------------

_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  # noqa: F401
    except Exception:
        need.append("numpy")

    try:
        import PIL  # noqa: F401
    except Exception:
        need.append("Pillow")

    try:
        import pystray  # noqa: F401
    except Exception:
        need.append("pystray")

    if _WIN:
        try:
            import comtypes  # noqa: F401
        except Exception:
            need.append("comtypes")
        try:
            import pycaw  # noqa: F401
        except Exception:
            need.append("pycaw")
        try:
            import win32api  # type: ignore  # noqa: F401
        except Exception:
            need.append("pywin32")

    try:
        import sounddevice  # noqa: F401
    except Exception:
        need.append("sounddevice")

    # Optional fallback
    try:
        import soundcard  # noqa: F401
    except Exception:
        if auto_install:
            need.append("soundcard")

    # Optional VAD (do not force install)
    try:
        import webrtcvad  # noqa: F401
    except Exception:
        pass

    if need and auto_install:
        _pip_install(need)


# Install before importing heavy deps (best effort).
try:
    _ensure_deps(auto_install=(not _NO_AUTOINSTALL))
except Exception:
    pass

# Third-party deps
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  # type: ignore
    _HAVE_WEBRTCVAD = True
except Exception:
    webrtcvad = None
    _HAVE_WEBRTCVAD = False

import pystray
from pystray import MenuItem as Item, Menu
from PIL import Image, ImageDraw


# ------------------ logging ------------------

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


# ------------------ utils ------------------

_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
    # Very low score is suspicious as "default"
    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))


# ------------------ samplers ------------------

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

        # Prefer loopback device that matches the default output device name
        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

        # Otherwise choose best score (avoid HDMI loopback variants when multiple exist)
        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

        # Prefer default output unless it looks like HDMI/display; then pick best-scored output.
        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):  # noqa: ANN001
            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

        # Prefer higher score names (realtek tends to be correct)
        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):  # noqa: ANN001
            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 dev_name supplied, try it first.
        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:
                # Bad default endpoint: do NOT force it to the front.
                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()
            # v0.10.11: be less trigger-happy.
            # Only declare degraded if we haven't had a successful read in a long time AND fail streak is huge.
            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)

                            # keep trying to reacquire periodically, but don't force-switch early
                            if fs in (3, 10, 25, 50, 100, 200, 350) or (time.time() - self._last_ok_ts) > 10.0:
                                acquire()

                        # ALWAYS push a sample (even last known) so the controller sees "alive"
                        self.win.push(time.time(), db)
                        time.sleep(self.frame_s)
                finally:
                    # IMPORTANT: drop COM interface refs BEFORE CoUninitialize
                    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
            # slightly relaxed vs old: require longer time with no ok and a big fail streak
            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:
                    # IMPORTANT: drop COM interface refs BEFORE CoUninitialize
                    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)


# ------------------ volume backends ------------------

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  # type: ignore
            from ctypes import POINTER, cast
            from pycaw.pycaw import AudioUtilities, IAudioEndpointVolume  # type: ignore

            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:
                # IMPORTANT: drop COM interface refs BEFORE CoUninitialize
                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()


# ------------------ learner ------------------

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()


# ------------------ speech gate ------------------

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


# ------------------ volume poller ------------------

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)


# ------------------ controller ------------------

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

        # v0.10.11: selection preflight and backoff (reduces infinite sampler cycling)
        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()  # observe-only mode (no volume changes)
        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

        # v0.10.11: per-sampler backoff
        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()

            # v0.10.11: skip samplers in backoff
            if now < self._sampler_backoff_until(key):
                continue

            try:
                cand.start()
            except Exception:
                pass

            # v0.10.11: preflight must see actual sample flow (n>0)
            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

            # preflight failed -> stop and backoff this sampler
            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)  # type: ignore[attr-defined]
            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:
        # This method exists in some builds; keep it safe even if called.
        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()


# ------------------ tray ------------------

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