-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathVCVM.py
More file actions
927 lines (813 loc) · 39.1 KB
/
VCVM.py
File metadata and controls
927 lines (813 loc) · 39.1 KB
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
import time
import threading
import sys
import os
import subprocess
import io
import winreg
import configparser
import logging
from datetime import datetime
from pystray import Icon, MenuItem as item
from PIL import Image, ImageDraw
import ctypes
from pycaw.pycaw import AudioUtilities, IAudioEndpointVolume
from comtypes import CLSCTX_ALL, wintypes
class LoggerMaster:
def __init__(self):
self.logger = None
self.logging_enabled = False
self.log_file = "VCVM.log"
sys.excepthook = self.handle_exception
def setup_logging(self):
"""Setup logging configuration"""
if self.logger:
for handler in self.logger.handlers[:]:
self.logger.removeHandler(handler)
handler.close()
if self.logging_enabled:
self.logger = logging.getLogger('VolumeControl for Voicemeeter')
self.logger.setLevel(logging.DEBUG)
try:
file_handler = logging.FileHandler(self.log_file, encoding='utf-8')
file_handler.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
file_handler.setFormatter(formatter)
self.logger.addHandler(file_handler)
except IOError as e:
print(f"ERROR: Failed to open log file {self.log_file}: {e}")
console_handler = logging.StreamHandler()
console_handler.setLevel(logging.INFO)
formatter_console = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
console_handler.setFormatter(formatter_console)
self.logger.addHandler(console_handler)
self.logger.propagate = False
else:
self.logger = None
def log(self, message, level='info', exc_info=None):
"""Log a message"""
if self.logger:
if level.lower() == 'debug':
self.logger.debug(message, exc_info=exc_info)
elif level.lower() == 'warning':
self.logger.warning(message, exc_info=exc_info)
elif level.lower() == 'error':
self.logger.error(message, exc_info=exc_info)
else:
self.logger.info(message, exc_info=exc_info)
else:
print(f"{datetime.now().strftime('%Y-%m-%d %H:%M:%S')} - {level.upper()} - {message}")
if exc_info:
import traceback
traceback.print_exception(exc_info[0], exc_info[1], exc_info[2], file=sys.stderr)
def handle_exception(self, exc_type, exc_value, exc_traceback):
if issubclass(exc_type, KeyboardInterrupt):
sys.__excepthook__(exc_type, exc_value, exc_traceback)
return
self.log("Uncaught exception", level='error', exc_info=(exc_type, exc_value, exc_traceback))
class VoicemeeterVolumeSync:
def __init__(self):
self.vm_lock = threading.RLock()
self.vm_connected = False
self.running = False
self.connected = False
self.vol_interface = None
self.last_windows_vol = 0
self.last_vm_gain = 0
self.last_change_time = 0
self.sync_thread = None
self.monitor_thread = None
self.icon = None
self.voicemeeter = None
self.base_dir = os.path.dirname(sys.executable) if getattr(sys, 'frozen', False) else os.path.dirname(os.path.abspath(__file__))
self.config_file = self.get_data_path("config.ini")
self.log_file = "VCVM.log"
self.config = configparser.ConfigParser()
self.load_config()
self.autostart_enabled = self.is_autostart_enabled()
self.load_tray_icon()
self.last_change_source = None # Can be 'windows' or 'voicemeeter'
# Check if we're starting up with the system
self.is_startup_launch = self.detect_startup_launch()
logclass.log("Application initialized")
def detect_startup_launch(self):
"""Detect if we're being launched at system startup"""
# Check if we're within the first few minutes after boot
try:
import psutil
boot_time = psutil.boot_time()
current_time = time.time()
time_since_boot = current_time - boot_time
# If less than 5 minutes since boot, likely a startup launch
if time_since_boot < 300: # 5 minutes
logclass.log(f"Detected startup launch - {time_since_boot:.1f}s since boot")
return True
except ImportError:
# Fallback: check if certain processes are still starting
pass
# Alternative method: check system uptime via Windows API
try:
uptime_ms = ctypes.windll.kernel32.GetTickCount64()
uptime_seconds = uptime_ms / 1000
if uptime_seconds < 300: # 5 minutes
logclass.log(f"Detected startup launch - {uptime_seconds:.1f}s uptime")
return True
except:
pass
return False
def initialize_com(self):
"""Initialize COM for audio operations"""
try:
import comtypes
comtypes.CoInitialize()
logclass.log("COM initialized successfully")
return True
except Exception as e:
logclass.log(f"Failed to initialize COM: {e}", 'error')
return False
def wait_for_system_ready(self):
"""Wait for system to be ready before connecting"""
if not self.is_startup_launch:
return
startup_delay = self.config.getint('Startup', 'delay_seconds', fallback=5)
logclass.log(f"Startup launch detected - waiting {startup_delay}s for system to be ready...")
time.sleep(startup_delay)
# Initialize COM first
if not self.initialize_com():
logclass.log("Failed to initialize COM - audio operations may fail", 'warning')
# Additional checks to ensure audio system is ready
max_wait = 120 # Maximum 2 minutes additional wait
wait_interval = 5
waited = 0
while waited < max_wait:
try:
# Try to initialize audio interface as a readiness test
devices = AudioUtilities.GetSpeakers()
if devices:
self.update_tray_icon("icon_status_on.ico")
logclass.log("Audio system appears ready")
break
except Exception as e:
logclass.log(f"Audio system not ready yet: {e}")
logclass.log(f"Waiting for audio system... ({waited}s/{max_wait}s)")
time.sleep(wait_interval)
waited += wait_interval
if waited >= max_wait:
logclass.log("Maximum wait time reached - proceeding anyway", 'warning')
def get_resource_path(self, relative_path):
"""Get absolute path to resource, works for dev and for PyInstaller"""
try:
base_path = sys._MEIPASS
except Exception:
base_path = os.path.abspath(".")
return os.path.join(base_path, relative_path)
def get_data_path(self, filename):
"""Get path for data files that should be in the same directory as the exe"""
if getattr(sys, 'frozen', False):
exe_dir = os.path.dirname(sys.executable)
else:
exe_dir = os.path.dirname(os.path.abspath(__file__))
return os.path.join(exe_dir, filename)
def load_config(self):
"""Load configuration from config.ini"""
default_config = {
'Voicemeeter': {
'dll_path': r'c:\Program Files (x86)\VB\Voicemeeter\VoicemeeterRemote64.dll'
},
'Logging': {
'enabled': 'true',
'verbose': 'false',
'log_file': 'VCVM.log'
},
'Settings': {
'curve_power': '0.55',
'sync_interval': '0.3',
'change_timeout': '4',
'gain_threshold': '3.0',
'volume_threshold': '1',
'bus': '0'
},
'Startup': {
'delay_seconds': '10',
'max_retry_attempts': '5',
'retry_interval': '3',
'task_delay_seconds': '15'
}
}
if not os.path.exists(self.config_file):
self.config.read_dict(default_config)
try:
with open(self.config_file, 'w') as f:
self.config.write(f)
print(f"Created default config file: {self.config_file}")
logclass.log(f"Created config file at: {self.config_file}")
except Exception as e:
print(f"Error creating config file: {e}")
logclass.log(f"Error creating config file: {e}", 'error')
else:
try:
self.config.read(self.config_file)
logclass.log(f"Loaded config from: {self.config_file}")
except Exception as e:
logclass.log(f"Error reading config file: {e}", 'error')
self.config.read_dict(default_config)
config_changed = False
for section, options in default_config.items():
if not self.config.has_section(section):
self.config.add_section(section)
config_changed = True
for key, value in options.items():
if not self.config.has_option(section, key):
self.config.set(section, key, value)
config_changed = True
if config_changed:
try:
with open(self.config_file, 'w') as f:
self.config.write(f)
logclass.log("Updated config file with missing entries")
except Exception as e:
logclass.log(f"Error updating config file: {e}", 'error')
logclass.logging_enabled = self.config.getboolean('Logging', 'enabled', fallback=True)
log_filename = self.config.get('Logging', 'log_file', fallback="VCVM.log")
logclass.log_file = self.get_data_path(log_filename)
logclass.setup_logging()
self.logging_verbose = self.config.getboolean('Logging', 'verbose', fallback=False)
def save_config(self):
"""Save current configuration to file"""
try:
with open(self.config_file, 'w') as f:
self.config.write(f)
except Exception as e:
print(f"Error saving config: {e}")
def get_configured_buses(self):
"""Return the configured Voicemeeter bus indexes."""
bus_list_str = self.config.get('Settings', 'bus', fallback='0,1,2,3,4')
try:
return [int(x.strip()) for x in bus_list_str.split(',') if x.strip()]
except ValueError as e:
logclass.log(f"Invalid bus configuration: '{bus_list_str}' - {e}", 'error')
return [0]
def load_voicemeeter_dll(self):
"""Load the Voicemeeter DLL with retry"""
dll_path = self.config.get('Voicemeeter', 'dll_path')
max_attempts = 5
for attempt in range(max_attempts):
try:
if os.path.exists(dll_path):
self.voicemeeter = ctypes.WinDLL(dll_path)
self._setup_vm_prototypes()
logclass.log(f"Loaded Voicemeeter DLL from: {dll_path} (attempt {attempt+1})")
return
else:
logclass.log(f"Voicemeeter DLL not found at: {dll_path}", 'error')
break
except Exception as e:
logclass.log(f"Failed to load Voicemeeter DLL (attempt {attempt+1}): {e}", 'error')
time.sleep(2)
self.voicemeeter = None
logclass.log("Giving up on loading Voicemeeter DLL after retries", 'error')
def _setup_vm_prototypes(self):
# return types
self.voicemeeter.VBVMR_Login.restype = ctypes.c_long
self.voicemeeter.VBVMR_Logout.restype = ctypes.c_long
self.voicemeeter.VBVMR_GetParameterFloat.restype = ctypes.c_long
self.voicemeeter.VBVMR_SetParameterFloat.restype = ctypes.c_long
# arg types
self.voicemeeter.VBVMR_GetParameterFloat.argtypes = [ctypes.c_char_p, ctypes.POINTER(ctypes.c_float)]
self.voicemeeter.VBVMR_SetParameterFloat.argtypes = [ctypes.c_char_p, ctypes.c_float]
def load_tray_icon(self):
"""Load the tray icon image"""
try:
icon_path = self.get_resource_path("icon.ico")
if os.path.exists(icon_path):
self.tray_icon_image = Image.open(icon_path)
logclass.log(f"Loaded tray icon from bundled resource: {icon_path}")
else:
icon_path = self.get_data_path("icon.ico")
if os.path.exists(icon_path):
self.tray_icon_image = Image.open(icon_path)
logclass.log(f"Loaded tray icon from data path: {icon_path}")
else:
raise FileNotFoundError("Icon not found in either location")
except Exception as e:
logclass.log(f"Could not load icon file ({e}), generating fallback", 'warning')
self.tray_icon_image = Image.new('RGBA', (64, 64), color=(0, 0, 0, 0))
d = ImageDraw.Draw(self.tray_icon_image)
d.ellipse((0, 0, 63, 63), fill=(10, 50, 120, 255))
d.rectangle((18, 24, 28, 40), fill=(255, 255, 255, 255))
d.polygon([(28, 24), (38, 20), (38, 44), (28, 40)], fill=(255, 255, 255, 255))
d.arc((40, 22, 54, 42), start=300, end=60, fill=(255, 255, 255, 180), width=2)
d.arc((44, 18, 60, 46), start=300, end=60, fill=(255, 255, 255, 100), width=2)
logclass.log("Generated fallback tray icon (speaker symbol)")
def connect_voicemeeter(self):
"""Connect to Voicemeeter API with enhanced retry logic"""
self.load_voicemeeter_dll()
if not self.voicemeeter:
logclass.log("Voicemeeter DLL not loaded", 'error')
return False
max_attempts = self.config.getint('Startup', 'max_retry_attempts', fallback=5)
retry_interval = self.config.getint('Startup', 'retry_interval', fallback=2)
for attempt in range(max_attempts):
try:
with self.vm_lock:
res = self.voicemeeter.VBVMR_Login()
if res == 0:
self.vm_connected = True
logclass.log(f"Connected to Voicemeeter on attempt {attempt+1}")
return True
else:
error_msg = self.get_voicemeeter_error_message(res)
logclass.log(f"VBVMR_Login failed (code: {res} - {error_msg}), attempt {attempt+1}/{max_attempts}")
# For startup launches, wait longer between attempts
wait_time = retry_interval if self.is_startup_launch else 2
if attempt < max_attempts - 1: # Don't wait after the last attempt
logclass.log(f"Waiting {wait_time}s before retry...")
time.sleep(wait_time)
except Exception as e:
logclass.log(f"Exception in VBVMR_Login: {e}", 'error')
if attempt < max_attempts - 1:
wait_time = retry_interval if self.is_startup_launch else 2
time.sleep(wait_time)
logclass.log(f"Failed to connect to Voicemeeter after {max_attempts} attempts", 'error')
self.update_tray_icon("icon_status_off.ico")
self.vm_connected = False
return False
def get_voicemeeter_error_message(self, error_code):
"""Get human-readable error message for Voicemeeter error codes"""
error_messages = {
-1: "Voicemeeter not running or not installed",
-2: "Voicemeeter DLL not found or incompatible version",
-3: "Parameter error",
-4: "Structure mismatch",
-5: "Connection lost",
-6: "System error",
-7: "Unknown error",
1: "Voicemeeter not running"
}
return error_messages.get(error_code, f"Unknown error code: {error_code}")
def disconnect_voicemeeter(self):
"""Disconnect from Voicemeeter API"""
if not self.voicemeeter:
return
try:
with self.vm_lock:
self.voicemeeter.VBVMR_Logout()
logclass.log("Disconnected from Voicemeeter")
except Exception as e:
logclass.log(f"Error disconnecting from Voicemeeter: {e}", 'error')
finally:
self.vm_connected = False
def set_bus_gain(self, bus_index, gain_db):
"""Set gain for a specific bus"""
if not self.voicemeeter:
return
try:
param_name = f"Bus[{bus_index}].Gain".encode("utf-8")
with self.vm_lock:
self.voicemeeter.VBVMR_SetParameterFloat(ctypes.c_char_p(param_name), ctypes.c_float(gain_db))
except Exception as e:
logclass.log(f"Error setting bus {bus_index} gain: {e}", 'error')
self.vm_connected = False
def get_bus_gain(self, bus_index):
"""Get gain for a specific bus"""
if not self.voicemeeter:
return None
try:
param_name = f"Bus[{bus_index}].Gain".encode("utf-8")
gain = ctypes.c_float()
with self.vm_lock:
result = self.voicemeeter.VBVMR_GetParameterFloat(ctypes.c_char_p(param_name), ctypes.byref(gain))
"""return gain.value if result == 0 else None"""
if result == 0:
self.vm_connected = True
return gain.value
else:
self.vm_connected = False
return None
except Exception as e:
self.vm_connected = False
logclass.log(f"Error getting bus {bus_index} gain: {e}", 'error')
return None
def map_volume_to_gain(self, volume):
"""Convert Windows volume percentage to Voicemeeter gain in dB"""
if volume <= 0:
return -60
elif volume >= 100:
return 12
curve_power = self.config.getfloat('Settings', 'curve_power')
gain = (volume / 100) ** curve_power * 72 - 60
return round(gain, 2)
def map_gain_to_volume(self, gain):
"""Convert Voicemeeter gain to Windows volume percentage"""
if gain <= -60:
return 0
elif gain >= 12:
return 100
curve_power = self.config.getfloat('Settings', 'curve_power')
volume = ((gain + 60) / 72) ** (1 / curve_power) * 100
return int(volume)
def init_windows_volume_interface(self):
"""Initialize Windows volume control interface with retry"""
# Ensure COM is initialized
try:
import comtypes
comtypes.CoInitialize()
except:
pass # May already be initialized
max_attempts = 5
for attempt in range(max_attempts):
try:
devices = AudioUtilities.GetSpeakers()
interface = devices.Activate(IAudioEndpointVolume._iid_, CLSCTX_ALL, None)
logclass.log(f"Initialized Windows volume interface (attempt {attempt+1})")
return ctypes.cast(interface, ctypes.POINTER(IAudioEndpointVolume))
except Exception as e:
logclass.log(f"Failed to initialize Windows volume interface (attempt {attempt+1}): {e}", 'error')
if attempt < max_attempts - 1:
time.sleep(2)
logclass.log("Failed to initialize Windows volume interface after retries", 'error')
return None
def get_windows_volume(self):
try:
if self.vol_interface:
return int(self.vol_interface.GetMasterVolumeLevelScalar() * 100)
except Exception as e:
logclass.log(f"Error getting Windows volume: {e}", 'error')
# Recreate the endpoint interface
self.vol_interface = None
time.sleep(0.5)
self.vol_interface = self.init_windows_volume_interface()
return 0
def set_windows_volume(self, vol_percent):
try:
if self.vol_interface:
scalar = vol_percent / 100
self.vol_interface.SetMasterVolumeLevelScalar(scalar, None)
except Exception as e:
logclass.log(f"Error setting Windows volume: {e}", 'error')
self.vol_interface = None
time.sleep(0.5)
self.vol_interface = self.init_windows_volume_interface()
# def get_windows_volume(self):
# """Get current Windows volume"""
# try:
# if self.vol_interface:
# return int(self.vol_interface.GetMasterVolumeLevelScalar() * 100)
# except Exception as e:
# logclass.log(f"Error getting Windows volume: {e}", 'error')
# return 0
# def set_windows_volume(self, vol_percent):
# """Set Windows volume"""
# try:
# if self.vol_interface:
# scalar = vol_percent / 100
# self.vol_interface.SetMasterVolumeLevelScalar(scalar, None)
# except Exception as e:
# logclass.log(f"Error setting Windows volume: {e}", 'error')
def is_voicemeeter_ok(self):
"""Check if Voicemeeter is responding"""
try:
return self.get_bus_gain(self.get_configured_buses()[0]) is not None
except:
return False
def sync_volumes(self):
"""Main volume synchronization loop with startup handling"""
logclass.log("Starting volume sync...")
self.wait_for_system_ready()
sync_interval = self.config.getfloat('Settings', 'sync_interval')
change_timeout = self.config.getfloat('Settings', 'change_timeout')
gain_threshold = self.config.getfloat('Settings', 'gain_threshold')
volume_threshold = self.config.getint('Settings', 'volume_threshold')
retry_interval = self.config.getint('Startup', 'retry_interval', fallback=2)
sync_initialized = False
while self.running:
try:
if not self.vm_connected:
if self.connect_voicemeeter():
sync_initialized = False
else:
logclass.log(
f"Voicemeeter not ready yet; retrying in {retry_interval}s",
'warning'
)
time.sleep(retry_interval)
continue
if not self.vol_interface:
self.vol_interface = self.init_windows_volume_interface()
if not self.vol_interface:
logclass.log(
f"Windows audio interface not ready yet; retrying in {retry_interval}s",
'warning'
)
self.disconnect_voicemeeter()
time.sleep(retry_interval)
continue
if not sync_initialized:
primary_bus = self.get_configured_buses()[0]
self.last_windows_vol = self.get_windows_volume()
self.last_vm_gain = self.get_bus_gain(primary_bus) or 0
self.last_change_time = time.time()
self.last_change_source = None
sync_initialized = True
logclass.log("Volume sync active. Monitoring...")
current_windows_vol = self.get_windows_volume()
primary_bus = self.get_configured_buses()[0]
current_vm_gain = self.get_bus_gain(primary_bus) or 0
if current_vm_gain is None:
# likely disconnected; attempt lazy reconnect
self.vm_connected = False
time.sleep(retry_interval)
continue
time_now = time.time()
if abs(current_windows_vol - self.last_windows_vol) >= volume_threshold:
gain = self.map_volume_to_gain(current_windows_vol)
for bus in self.get_configured_buses():
try:
self.set_bus_gain(bus, gain)
self.last_vm_gain = gain
except Exception as e:
logclass.log(f"Failed to set gain for bus {bus}: {e}", 'error')
if self.logging_verbose:
logclass.log(f"Windows volume changed: {current_windows_vol}% → {gain}dB", 'debug')
self.last_windows_vol = current_windows_vol
self.last_vm_gain = gain
self.last_change_time = time_now
self.last_change_source = 'windows'
elif time_now - self.last_change_time > change_timeout:
if abs(current_vm_gain - self.last_vm_gain) >= gain_threshold:
if self.last_change_source == 'windows':
continue # Prevent bounce back
target_volume = self.map_gain_to_volume(current_vm_gain)
gain_diff = current_vm_gain - self.last_vm_gain
if self.logging_verbose:
logclass.log(f"Voicemeeter gain changed: {self.last_vm_gain}dB → {current_vm_gain}dB (Δ{gain_diff:+.1f}dB) | Target Windows vol: {target_volume}%", 'debug')
if abs(target_volume - current_windows_vol) > 10:
step = int((target_volume - current_windows_vol) * 0.3)
new_volume = current_windows_vol + step
self.set_windows_volume(new_volume)
self.last_windows_vol = new_volume
if self.logging_verbose:
logclass.log(f"Applied smooth Windows volume adjustment: {current_windows_vol}% → {new_volume}% (step: {step})", 'debug')
else:
self.set_windows_volume(target_volume)
self.last_windows_vol = target_volume
if self.logging_verbose:
logclass.log(f"Applied direct Windows volume adjustment: {current_windows_vol}% → {target_volume}%", 'debug')
self.last_vm_gain = current_vm_gain
self.last_change_time = time_now
self.last_change_source = 'voicemeeter'
# Don't sync if we were the one who just set the gain
if abs(current_vm_gain - self.last_vm_gain) < gain_threshold:
continue
time.sleep(sync_interval)
except Exception as e:
logclass.log(f"Error in sync loop: {e}", 'error')
self.vm_connected = False
self.vol_interface = None
sync_initialized = False
time.sleep(retry_interval)
logclass.log("Volume sync stopped")
self.disconnect_voicemeeter()
def monitor_voicemeeter_status(self):
"""Monitor Voicemeeter connection status"""
last_status = None
while self.running:
try:
"""self.connected = self.is_voicemeeter_ok()"""
status = self.vm_connected
"""if self.connected != last_status:"""
if status != last_status:
status_text = 'Connected' if self.connected else 'Disconnected'
if self.logging_verbose:
logclass.log(f"Voicemeeter status changed: {status_text}")
last_status = self.connected
"""if self.connected:"""
if status:
self.update_tray_icon("icon_status_on.ico")
else:
self.update_tray_icon("icon_status_off.ico")
last_status = status
except Exception as e:
logclass.log(f"Error monitoring Voicemeeter status: {e}", 'error')
self.connected = False
time.sleep(1)
def start_sync(self):
"""Start the volume synchronization"""
if self.running:
return
self.running = True
self.sync_thread = threading.Thread(target=self.sync_volumes, daemon=True)
self.monitor_thread = threading.Thread(target=self.monitor_voicemeeter_status, daemon=True)
self.sync_thread.start()
self.monitor_thread.start()
logclass.log("Volume sync started")
def stop_sync(self):
"""Stop the volume synchronization"""
if not self.running:
return
logclass.log("Stopping volume sync...")
self.running = False
if self.sync_thread and self.sync_thread.is_alive():
self.sync_thread.join(timeout=2)
if self.monitor_thread and self.monitor_thread.is_alive():
self.monitor_thread.join(timeout=2)
logclass.log("Volume sync stopped")
def delete_startup_task(task_name="VolumeControl for Voicemeeter"):
try:
result = subprocess.run(
["schtasks", "/Delete", "/TN", task_name, "/F"],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
universal_newlines=True
)
if result.returncode == 0:
print(f"Scheduled task '{task_name}' deleted.")
return True
else:
print(f"Error deleting task: {result.stderr.strip()}")
return False
except Exception as e:
print(f"Exception deleting task: {e}")
return False
def toggle_autostart(self, enable):
"""Toggle autostart using Windows Task Scheduler with delay"""
task_name = "VolumeControl for Voicemeeter"
if enable:
is_py = not getattr(sys, 'frozen', False)
python_exe = sys.executable
script_path = os.path.abspath(__file__)
cmd = f'"{python_exe}" "{script_path}"' if is_py else f'"{sys.executable}"' #keep as such to AVOID having quotes around python path, otherwise will fail
task_delay_seconds = self.config.getint('Startup', 'task_delay_seconds', fallback=15)
task_delay = f"0000:{task_delay_seconds:02d}"
schtasks_cmd = [
"schtasks",
"/Create",
"/TN", task_name,
"/TR", cmd,
"/SC", "ONLOGON",
"/RL", "LIMITED",
"/DELAY", task_delay,
"/F"
]
try:
result = subprocess.run(
schtasks_cmd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
universal_newlines=True
)
if result.returncode == 0:
logclass.log(
f"Autostart task created successfully with {task_delay_seconds}s delay and limited privileges"
)
else:
logclass.log(f"Failed to create autostart task: {result.stderr.strip()}", 'error')
except Exception as e:
logclass.log(f"Error creating autostart task: {e}", 'error')
else:
try:
result = subprocess.run(
["schtasks", "/Delete", "/TN", task_name, "/F"],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
universal_newlines=True
)
if result.returncode == 0:
logclass.log("Autostart task removed successfully")
else:
logclass.log(f"Failed to remove autostart task: {result.stderr.strip()}", 'error')
except Exception as e:
logclass.log(f"Error removing autostart task: {e}", 'error')
def is_autostart_enabled(self):
result = subprocess.run(
["schtasks", "/Query", "/TN", "VolumeControl for Voicemeeter"],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
universal_newlines=True
)
return result.returncode == 0
def on_quit(self, icon, _):
"""Handle quit from tray menu"""
logclass.log("Quit requested from tray")
self.stop_sync()
if self.icon:
self.icon.stop()
def on_reload(self, icon, _):
"""Handle reload from tray menu"""
logclass.log("Reload requested from tray")
self.stop_sync()
time.sleep(1)
self.load_config()
self.load_voicemeeter_dll()
if self.voicemeeter:
self.start_sync()
else:
logclass.log("Voicemeeter DLL not loaded — skipping sync", 'error')
def on_toggle_autostart(self, icon, _):
"""Handle autostart toggle from tray menu"""
self.autostart_enabled = not self.autostart_enabled
self.toggle_autostart(self.autostart_enabled)
def on_toggle_logging(self, icon, _):
"""Handle logging toggle from tray menu"""
logclass.logging_enabled = not logclass.logging_enabled
self.config.set('Logging', 'enabled', str(logclass.logging_enabled).lower())
self.save_config()
logclass.setup_logging()
logclass.log(f"Logging {'enabled' if logclass.logging_enabled else 'disabled'}")
def on_toggle_logging_verbose(self, icon, _):
self.logging_verbose = not self.logging_verbose
self.config.set('Logging', 'verbose', str(self.logging_verbose).lower())
self.save_config()
logclass.log(f"Verbose logging {'enabled' if self.logging_verbose else 'disabled'}")
def get_autostart_text(self, icon):
"""Get autostart menu text"""
state = self.is_autostart_enabled()
return f"Autostart: {'On' if state else 'Off'}"
def get_logging_text(self, icon):
"""Get logging menu text"""
return f"Logging: {'On' if logclass.logging_enabled else 'Off'}"
def get_verbose_text(self, icon):
"""Get verbose menu text"""
return f"Verbose: {'On' if self.logging_verbose else 'Off'}"
def creditsinfo(self, icon=None, item=None):
"""Show About dialog using native Windows MessageBox"""
try:
logclass.log("Attempting to show About dialog using Windows MessageBox.", level='debug')
MB_OK = 0x0
MB_ICONINFORMATION = 0x40
title = "About VolumeControl for Voicemeeter"
message = ("VolumeControl for Voicemeeter.\n"
"Version 1.0.2 of april 2026\n\n"
"https://github.com/dayeggpi \n\n"
"Synchronizes Windows volume with Voicemeeter.\n"
"Support them : https://vb-audio.com/\n\n"
"by dayeggpi")
result = ctypes.windll.user32.MessageBoxW(
0, # hWnd (0 = no parent window)
message,
title,
MB_OK | MB_ICONINFORMATION
)
logclass.log("About dialog shown successfully using Windows MessageBox.", level='debug')
except Exception as e:
error_msg = f"Error showing About dialog: {e}"
logclass.log(error_msg, level='error', exc_info=True)
print(f"Error: {error_msg}")
print("\n=== About VolumeControl for Voicemeeter ===")
print("Version 1.0.2")
print("https://github.com/dayeggpi")
print("Synchronizes Windows volume with Voicemeeter")
print("by dayeggpi")
print("=====================================\n")
def start_tray(self):
"""Start the system tray icon"""
self.icon = Icon(
"Voicemeeter",
self.tray_icon_image,
"VolumeControl for Voicemeeter",
menu=(
item("About", self.creditsinfo),
item(self.get_autostart_text, self.on_toggle_autostart),
item(self.get_logging_text, self.on_toggle_logging),
item(self.get_verbose_text, self.on_toggle_logging_verbose),
item("Reload", self.on_reload),
item("Quit", self.on_quit),
)
)
logclass.log("Starting tray icon...")
self.icon.run()
def resource_path(self, filename):
if getattr(sys, 'frozen', False): # running as .exe (PyInstaller)
return os.path.join(sys._MEIPASS, filename)
else: # running as .py
base_dir = os.path.dirname(os.path.abspath(__file__))
return os.path.join(base_dir, filename)
def update_tray_icon(self, icon_name):
"""Change the tray icon dynamically"""
try:
icon_path = self.resource_path(icon_name)
if os.path.exists(icon_path):
image = Image.open(icon_path)
self.icon.icon = image
logclass.log(f"Tray icon updated to: {icon_name}")
else:
logclass.log(f"Icon not found: {icon_path}", 'error')
except Exception as e:
logclass.log(f"Failed to update tray icon to {icon_name}: {e}", 'error')
def run(self):
"""Main application entry point"""
logclass.log("Starting VolumeControl for Voicemeeter application")
self.start_sync()
try:
self.start_tray()
except KeyboardInterrupt:
logclass.log("KeyboardInterrupt received")
except Exception as e:
logclass.log(f"Tray error: {e}", 'error')
finally:
self.stop_sync()
logclass.log("Application stopped")
if __name__ == "__main__":
logclass = LoggerMaster()
app = VoicemeeterVolumeSync()
app.run()