Repository navigation
Expand file tree
/
Copy pathAudioMixer.cs
More file actions
1396 lines (1272 loc) · 51 KB
/
Copy pathAudioMixer.cs
File metadata and controls
1396 lines (1272 loc) · 51 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
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
using AmpUp.Core.Engine;
using NAudio.CoreAudioApi;
using NAudio.CoreAudioApi.Interfaces;
namespace AmpUp;
public class AudioMixer : IDisposable
{
// P/Invoke declarations consolidated in NativeMethods.cs
private readonly MMDeviceEnumerator _enumerator = new();
private readonly DeviceNotificationClient _deviceNotificationClient;
private readonly Dictionary<int, int> _lastValues = new();
private readonly object _lock = new(); // guards _sessions / _sessionsByPid dict access
private readonly object _enumLock = new(); // guards _enumerator — accessed from multiple threads
private readonly object _lastValuesLock = new();
private System.Threading.Timer? _pollTimer;
private int _refreshInProgress;
private long _lastRefreshErrorLogTicks;
private string _lastRefreshError = "";
private volatile bool _disposed;
private const float NonZeroVolumeThreshold = 0.0001f;
/// <summary>Fires when Windows adds, removes, activates, or changes the default audio endpoint.</summary>
public event Action? AudioDevicesChanged;
public AudioMixer()
{
_deviceNotificationClient = new DeviceNotificationClient(this);
try { _enumerator.RegisterEndpointNotificationCallback(_deviceNotificationClient); }
catch (Exception ex) { Logger.Log($"Audio device watcher registration failed: {ex.Message}"); }
}
private sealed class DeviceNotificationClient : IMMNotificationClient
{
private readonly AudioMixer _owner;
public DeviceNotificationClient(AudioMixer owner) => _owner = owner;
private void Notify()
{
if (!_owner._disposed)
_owner.AudioDevicesChanged?.Invoke();
}
// Never dispose Core Audio objects synchronously inside an IMMNotificationClient
// callback. Windows can be holding its endpoint-notification lock here; disposing
// an endpoint may then wait on that same lock and deadlock every AudioMixer caller.
// The app event is debounced and performs invalidation after this callback returns.
public void OnDeviceStateChanged(string deviceId, DeviceState newState) => Notify();
public void OnDeviceAdded(string pwstrDeviceId) => Notify();
public void OnDeviceRemoved(string deviceId) => Notify();
public void OnDefaultDeviceChanged(DataFlow flow, Role role, string defaultDeviceId) => Notify();
public void OnPropertyValueChanged(string pwstrDeviceId, PropertyKey key) { }
}
// Map of processName (lowercase) -> AudioSessionControl
private Dictionary<string, AudioSessionControl> _sessions = new();
/// <summary>
/// Fuzzy process name match: strips spaces so "Apple Music" matches "AppleMusic".
/// Allocation-free char walk — equivalent to
/// processName.Replace(" ", "").Contains(search.Replace(" ", "")), case-insensitive.
/// Called per session per VU tick, so no string allocs allowed here.
/// </summary>
internal static bool FuzzyContains(string processName, string search)
{
// First non-space needle char — an empty/all-space needle matches anything
int nStart = 0;
while (nStart < search.Length && search[nStart] == ' ') nStart++;
if (nStart >= search.Length) return true;
for (int start = 0; start < processName.Length; start++)
{
if (processName[start] == ' ') continue;
int h = start, n = nStart;
while (true)
{
while (n < search.Length && search[n] == ' ') n++;
if (n >= search.Length) return true; // consumed the whole needle
while (h < processName.Length && processName[h] == ' ') h++;
if (h >= processName.Length) break;
if (char.ToLowerInvariant(processName[h]) != char.ToLowerInvariant(search[n])) break;
h++; n++;
}
}
return false;
}
/// <summary>
/// Lowercases without allocating when the string is already lowercase —
/// the common case for config target strings, checked per VU tick.
/// </summary>
private static string ToLowerNoAlloc(string s)
{
for (int i = 0; i < s.Length; i++)
if (s[i] != char.ToLowerInvariant(s[i])) return s.ToLowerInvariant();
return s;
}
// Map of processId -> AudioSessionControl (for active_window lookups)
private Dictionary<uint, AudioSessionControl> _sessionsByPid = new();
// Every session from the last refresh, one entry each. The name-keyed
// _sessions dict is first-wins, so a process with two sessions (Apple
// Music, Discord) or two processes sharing a WASAPI display name would
// lose all but one — volume/peak matching walks this list instead.
private sealed record SessionEntry(string ProcessName, string DisplayName, AudioSessionControl Session);
private List<SessionEntry> _sessionEntries = new();
/// <summary>
/// True when a configured app name targets this session by process name
/// or WASAPI display name. Legacy picks stored as "name:pid" (from older
/// pickers that listed internal keys) match on the name alone.
/// </summary>
private static bool SessionMatches(SessionEntry entry, string app)
{
int colon = app.IndexOf(':');
if (colon > 0 && colon < app.Length - 1 && app.AsSpan(colon + 1).IndexOfAnyExceptInRange('0', '9') < 0)
app = app[..colon];
return FuzzyContains(entry.ProcessName, app)
|| (entry.DisplayName.Length > 0 && FuzzyContains(entry.DisplayName, app));
}
// Loop instead of LINQ Any — runs per session per VU tick.
private static bool MatchesAnyApp(SessionEntry entry, List<string> apps)
{
for (int i = 0; i < apps.Count; i++)
if (SessionMatches(entry, apps[i])) return true;
return false;
}
public void Start()
{
RefreshSessions();
_pollTimer = new System.Threading.Timer(_ => RefreshSessions(), null, 2000, 2000);
}
public void RefreshNow() => RefreshSessions();
private MMDevice? _renderDevice; // kept alive so session COM objects remain valid
private MMDevice? _masterPeakDevice; // dedicated persistent device for master peak metering
private MMDevice? _micPeakDevice; // dedicated persistent device for mic peak metering
private MMDevice? _masterControlDevice; // persistent default render endpoint (Role.Console) for SetVolume("master")
private MMDevice? _micControlDevice; // persistent default capture endpoint for SetVolume("mic")
private AudioSessionControl? _systemPeakSession; // PID-0 System Sounds session for peak metering
private readonly Dictionary<string, MMDevice> _devicePeakCache = new(); // deviceId -> metering device (guarded by _enumLock)
private string? _defaultRenderId; // last-seen default render endpoint ID (guarded by _enumLock)
private string? _defaultCaptureId; // last-seen default capture endpoint ID (guarded by _enumLock)
// PID -> process name cache. Process.GetProcessById snapshots the entire
// system process table per call, so resolve each PID once and reuse across
// the 2s refresh ticks. Entries for PIDs no longer in the session list are
// evicted each refresh so the cache can't grow unbounded.
private readonly Dictionary<int, string> _pidNameCache = new();
private readonly object _pidNameLock = new();
// Distinct AudioSessionControl wrappers from the last refresh — disposed on swap
private List<AudioSessionControl> _sessionWrappers = new();
private void RefreshSessions()
{
if (_disposed) return;
if (Interlocked.Exchange(ref _refreshInProgress, 1) != 0) return;
MMDevice? pendingDevice = null;
List<AudioSessionControl>? pendingWrappers = null;
try
{
MMDevice? device;
lock (_enumLock)
{
if (_disposed) return;
device = _enumerator.GetDefaultAudioEndpoint(DataFlow.Render, Role.Multimedia);
}
pendingDevice = device;
// Drop cached endpoint objects if the default device changed — otherwise
// the master/mic knob + VU caches keep pointing at the old endpoint.
InvalidateStaleEndpointCaches(device!);
var newSessions = new Dictionary<string, AudioSessionControl>();
var newPidSessions = new Dictionary<uint, AudioSessionControl>();
var newWrappers = new List<AudioSessionControl>();
var newEntries = new List<SessionEntry>();
pendingWrappers = newWrappers;
var seenPids = new HashSet<int>();
var sessionMgr = device!.AudioSessionManager;
var sessions = sessionMgr.Sessions;
for (int i = 0; i < sessions.Count; i++)
{
var s = sessions[i];
bool stored = false;
try
{
var pid = (int)s.GetProcessID;
if (pid == 0) continue;
seenPids.Add(pid);
var rawName = ResolvePidName(pid);
if (rawName == null) continue; // process gone
var name = rawName.ToLowerInvariant();
string sessionDisplayName = "";
try { sessionDisplayName = s.DisplayName?.ToLowerInvariant() ?? ""; } catch { }
// Resource-path display names ("@%SystemRoot%\...") aren't app names
if (sessionDisplayName.StartsWith('@')) sessionDisplayName = "";
newEntries.Add(new SessionEntry(name, sessionDisplayName, s));
stored = true;
// Use compound key (name:pid) to store ALL sessions per process
// (apps like Discord create multiple: voice, screenshare, notifications)
var sessionKey = $"{name}:{pid}";
if (!newSessions.ContainsKey(sessionKey))
{
newSessions[sessionKey] = s;
stored = true;
}
// Also store by plain name for backward compat (first wins)
if (!newSessions.ContainsKey(name))
{
newSessions[name] = s;
stored = true;
}
// Also index by WASAPI display name — catches UWP/packaged apps
// where audio runs in a helper process (e.g. AMPLibraryAgent for Apple Music)
try
{
var displayName = s.DisplayName;
if (!string.IsNullOrEmpty(displayName))
{
var dnKey = displayName.ToLowerInvariant();
if (!newSessions.ContainsKey(dnKey))
{
newSessions[dnKey] = s;
stored = true;
}
}
}
catch { }
var upid = (uint)pid;
if (!newPidSessions.ContainsKey(upid))
{
newPidSessions[upid] = s;
stored = true;
}
}
catch { }
finally
{
if (stored)
newWrappers.Add(s);
else
try { s.Dispose(); } catch { }
}
}
// Evict cached names for PIDs that no longer have sessions
lock (_pidNameLock)
{
if (_pidNameCache.Count > 0)
{
List<int>? stale = null;
foreach (var p in _pidNameCache.Keys)
if (!seenPids.Contains(p)) (stale ??= new List<int>()).Add(p);
if (stale != null)
foreach (var p in stale) _pidNameCache.Remove(p);
}
}
// Swap atomically — old device + old session wrappers disposed after new sessions are live
lock (_lock)
{
var oldWrappers = _sessionWrappers;
_sessions = newSessions;
_sessionsByPid = newPidSessions;
_sessionEntries = newEntries;
_sessionWrappers = newWrappers;
var oldDevice = _renderDevice;
_renderDevice = device;
pendingDevice = null;
pendingWrappers = null;
try { oldDevice?.Dispose(); } catch { }
// Sessions are re-enumerated fresh each refresh (the SessionCollection
// indexer creates a new wrapper per access), so nothing from the previous
// refresh is carried forward — every old wrapper is safe to dispose.
// AudioSessionControl.Dispose only unregisters event callbacks (we register
// none) and suppresses the finalizer; the underlying COM object stays alive
// for any view still briefly holding a reference from GetSessionForProcess.
foreach (var w in oldWrappers)
try { w.Dispose(); } catch { }
}
}
catch (Exception ex)
{
// Don't clear _sessions on failure — keep stale data rather than empty
LogRefreshError(ex.Message);
}
finally
{
if (pendingWrappers != null)
{
foreach (var wrapper in pendingWrappers)
try { wrapper.Dispose(); } catch { }
}
try { pendingDevice?.Dispose(); } catch { }
Volatile.Write(ref _refreshInProgress, 0);
}
}
private void LogRefreshError(string message)
{
long nowTicks = DateTime.UtcNow.Ticks;
long lastTicks = Interlocked.Read(ref _lastRefreshErrorLogTicks);
if (!string.Equals(message, _lastRefreshError, StringComparison.Ordinal)
|| lastTicks == 0
|| nowTicks - lastTicks >= TimeSpan.FromMinutes(5).Ticks)
{
_lastRefreshError = message;
Interlocked.Exchange(ref _lastRefreshErrorLogTicks, nowTicks);
Logger.Log($"Session refresh error: {message} (identical errors suppressed for 5 minutes)");
}
}
/// <summary>
/// PID -> process name with a persistent cache (raw casing — callers lowercase
/// as needed). Returns null if the process is gone.
/// </summary>
private string? ResolvePidName(int pid)
{
lock (_pidNameLock)
{
if (_pidNameCache.TryGetValue(pid, out var cached)) return cached;
}
try
{
using var proc = System.Diagnostics.Process.GetProcessById(pid);
var name = proc.ProcessName;
lock (_pidNameLock) _pidNameCache[pid] = name;
return name;
}
catch { return null; }
}
/// <summary>
/// Compares the current default render/capture endpoint IDs against the last
/// refresh and drops the cached control/metering endpoints on change, so a
/// default-device switch (cycle_output, Windows settings) re-acquires the new
/// endpoint within one 2s refresh tick.
/// </summary>
private void InvalidateStaleEndpointCaches(MMDevice currentRenderDefault)
{
string? renderId = null;
try { renderId = currentRenderDefault.ID; } catch { }
string? captureId = null;
try
{
MMDevice? mic;
lock (_enumLock) mic = _enumerator.GetDefaultAudioEndpoint(DataFlow.Capture, Role.Communications);
using (mic) { captureId = mic?.ID; }
}
catch { } // no default capture device — leave capture caches as-is
lock (_enumLock)
{
if (renderId != null && _defaultRenderId != null && renderId != _defaultRenderId)
{
try { _masterPeakDevice?.Dispose(); } catch { }
_masterPeakDevice = null;
try { _masterControlDevice?.Dispose(); } catch { }
_masterControlDevice = null;
try { _systemPeakSession?.Dispose(); } catch { }
_systemPeakSession = null;
}
if (renderId != null) _defaultRenderId = renderId;
if (captureId != null && _defaultCaptureId != null && captureId != _defaultCaptureId)
{
try { _micPeakDevice?.Dispose(); } catch { }
_micPeakDevice = null;
try { _micControlDevice?.Dispose(); } catch { }
_micControlDevice = null;
}
if (captureId != null) _defaultCaptureId = captureId;
}
}
/// <summary>
/// Full pipeline: raw 0-1023 -> 0-1 -> curve -> range clamp -> final 0-1 volume.
/// Delegates to <see cref="VolumePipeline.ComputeVolume(int, KnobConfig)"/>.
/// </summary>
private static float ComputeVolume(int rawValue, KnobConfig knob)
=> VolumePipeline.ComputeVolume(rawValue, knob);
internal static void SetRenderEndpointVolume(AudioEndpointVolume endpointVolume, float volume)
{
endpointVolume.MasterVolumeLevelScalar = volume;
// Some Bluetooth endpoints flip endpoint mute when volume reaches 0 and
// do not automatically clear it when the scalar is raised again.
if (volume > NonZeroVolumeThreshold && endpointVolume.Mute)
{
endpointVolume.Mute = false;
}
}
public void SetVolume(KnobConfig knob, int rawValue, int? debounceKeyOverride = null)
{
// Debounce — skip if change < 5
int debounceKey = debounceKeyOverride ?? knob.Idx;
lock (_lastValuesLock)
{
if (_lastValues.TryGetValue(debounceKey, out int last) && Math.Abs(rawValue - last) < 5)
{
return;
}
_lastValues[debounceKey] = rawValue;
}
float vol = ComputeVolume(rawValue, knob);
try
{
var target = ToLowerNoAlloc(knob.Target);
if (target == "master")
{
// Persistent control endpoint — activating a fresh MMDevice per knob
// event is expensive. Invalidated on failure, device change (see
// InvalidateStaleEndpointCaches) and session lock (InvalidatePeakDevice).
lock (_enumLock)
{
try
{
_masterControlDevice ??= _enumerator.GetDefaultAudioEndpoint(DataFlow.Render, Role.Console);
SetRenderEndpointVolume(_masterControlDevice.AudioEndpointVolume, vol);
}
catch
{
// Endpoint went stale — drop it so the next knob event re-acquires
try { _masterControlDevice?.Dispose(); } catch { }
_masterControlDevice = null;
throw;
}
}
return;
}
if (target == "mic")
{
lock (_enumLock)
{
try
{
_micControlDevice ??= _enumerator.GetDefaultAudioEndpoint(DataFlow.Capture, Role.Communications);
_micControlDevice.AudioEndpointVolume.MasterVolumeLevelScalar = vol;
}
catch
{
try { _micControlDevice?.Dispose(); } catch { }
_micControlDevice = null;
throw;
}
}
return;
}
if (target == "output_device")
{
SetDeviceVolume(knob.DeviceId, DataFlow.Render, vol);
return;
}
if (target == "input_device")
{
SetDeviceVolume(knob.DeviceId, DataFlow.Capture, vol);
return;
}
if (target == "active_window")
{
SetActiveWindowVolume(vol);
return;
}
// Multi-app group target
if (target == "apps")
{
lock (_lock)
{
foreach (var entry in _sessionEntries)
{
if (MatchesAnyApp(entry, knob.Apps))
try { entry.Session.SimpleAudioVolume.Volume = vol; } catch { }
}
}
return;
}
lock (_lock)
{
if (target == "system")
{
// System Sounds has PID 0 — scan sessions on the default device directly
try
{
MMDevice? device;
lock (_enumLock) device = _enumerator.GetDefaultAudioEndpoint(DataFlow.Render, Role.Multimedia);
using (device)
{
var sessions = device!.AudioSessionManager.Sessions;
for (int i = 0; i < sessions.Count; i++)
{
var s = sessions[i];
if (s.GetProcessID == 0)
{
s.SimpleAudioVolume.Volume = vol;
break;
}
}
}
}
catch { }
return;
}
if (target == "any")
{
var first = _sessions.Values.FirstOrDefault();
if (first != null) first.SimpleAudioVolume.Volume = vol;
return;
}
// Match ALL sessions by process name substring (apps like Discord
// create multiple sessions — voice, screenshare, notifications)
foreach (var entry in _sessionEntries)
{
if (SessionMatches(entry, target))
try { entry.Session.SimpleAudioVolume.Volume = vol; } catch { }
}
}
}
catch (Exception ex)
{
Logger.Log($"SetVolume error for {knob.Label}: {ex.Message}");
}
}
/// <summary>
/// Forget the last raw value for one hardware control. Contextual N3
/// encoder bindings call this when a knob starts controlling a different
/// target so an equal raw value is still applied to the new target.
/// </summary>
public void ResetVolumeDebounce(int debounceKey)
{
lock (_lastValuesLock)
_lastValues.Remove(debounceKey);
}
private void SetDeviceVolume(string deviceId, DataFlow dataFlow, float vol)
{
if (string.IsNullOrEmpty(deviceId))
{
return;
}
lock (_enumLock)
{
try
{
var device = GetOrCacheDeviceEndpoint(deviceId, dataFlow);
if (device == null) return;
if (dataFlow == DataFlow.Render)
{
SetRenderEndpointVolume(device.AudioEndpointVolume, vol);
}
else
{
device.AudioEndpointVolume.MasterVolumeLevelScalar = vol;
}
}
catch (Exception ex)
{
if (_devicePeakCache.Remove(deviceId, out var stale))
{
try { stale.Dispose(); } catch { }
}
Logger.Log($"SetDeviceVolume error: {ex.Message}");
}
}
}
/// <summary>
/// Sets volume on a specific audio output device by its device ID.
/// Used by Device Groups to control audio device volume alongside lights.
/// </summary>
public void SetOutputDeviceVolume(string deviceId, float volume)
{
SetDeviceVolume(deviceId, DataFlow.Render, Math.Clamp(volume, 0f, 1f));
}
/// <summary>
/// Toggles mute on a specific audio output device by its device ID.
/// Used by Device Groups to toggle audio device mute alongside lights.
/// </summary>
public void ToggleOutputDeviceMute(string deviceId)
{
if (string.IsNullOrEmpty(deviceId))
{
return;
}
lock (_enumLock)
{
try
{
var device = GetOrCacheDeviceEndpoint(deviceId, DataFlow.Render);
if (device != null)
device.AudioEndpointVolume.Mute = !device.AudioEndpointVolume.Mute;
}
catch (Exception ex)
{
if (_devicePeakCache.Remove(deviceId, out var stale))
{
try { stale.Dispose(); } catch { }
}
Logger.Log($"ToggleOutputDeviceMute error: {ex.Message}");
}
}
}
private void SetActiveWindowVolume(float vol)
{
try
{
IntPtr hwnd = NativeMethods.GetForegroundWindow();
if (hwnd == IntPtr.Zero) return;
NativeMethods.GetWindowThreadProcessId(hwnd, out uint pid);
if (pid == 0) return;
lock (_lock)
{
if (_sessionsByPid.TryGetValue(pid, out var session))
{
session.SimpleAudioVolume.Volume = vol;
return;
}
}
// If not found by exact PID, try to find by process name
// (some apps like Chrome have child processes)
try
{
var name = ResolvePidName((int)pid)?.ToLowerInvariant();
if (name != null)
lock (_lock)
{
if (_sessions.TryGetValue(name, out var sessionByName))
{
sessionByName.SimpleAudioVolume.Volume = vol;
}
}
}
catch { }
}
catch (Exception ex)
{
Logger.Log($"SetActiveWindowVolume error: {ex.Message}");
}
}
public float GetVolume(KnobConfig knob)
{
try
{
var target = ToLowerNoAlloc(knob.Target);
if (target == "master")
{
// MixerView reads volume every 75ms. Reuse the same endpoint as
// peak metering instead of activating a fresh MMDevice each tick;
// repeated activation leaks native MMDevices property-store handles
// until a GC finalizer pass and eventually stalls long-running apps.
lock (_enumLock)
{
try
{
_masterPeakDevice ??= _enumerator.GetDefaultAudioEndpoint(DataFlow.Render, Role.Multimedia);
return _masterPeakDevice.AudioEndpointVolume.MasterVolumeLevelScalar;
}
catch
{
try { _masterPeakDevice?.Dispose(); } catch { }
_masterPeakDevice = null;
return 0f;
}
}
}
if (target == "mic")
{
lock (_enumLock)
{
try
{
_micPeakDevice ??= _enumerator.GetDefaultAudioEndpoint(DataFlow.Capture, Role.Communications);
return _micPeakDevice.AudioEndpointVolume.MasterVolumeLevelScalar;
}
catch
{
try { _micPeakDevice?.Dispose(); } catch { }
_micPeakDevice = null;
return 0f;
}
}
}
if (target == "output_device")
{
return GetDeviceVolume(knob.DeviceId, DataFlow.Render);
}
if (target == "input_device")
{
return GetDeviceVolume(knob.DeviceId, DataFlow.Capture);
}
if (target == "active_window")
{
return GetActiveWindowVolume();
}
if (target == "system")
{
try
{
MMDevice? device;
lock (_enumLock) device = _enumerator.GetDefaultAudioEndpoint(DataFlow.Render, Role.Multimedia);
using (device)
{
var sessions = device!.AudioSessionManager.Sessions;
for (int i = 0; i < sessions.Count; i++)
{
var s = sessions[i];
if (s.GetProcessID == 0)
return s.SimpleAudioVolume.Volume;
}
}
}
catch { }
return 0f;
}
if (target == "apps")
{
lock (_lock)
{
float maxVol = 0f;
foreach (var entry in _sessionEntries)
{
if (MatchesAnyApp(entry, knob.Apps))
try { maxVol = Math.Max(maxVol, entry.Session.SimpleAudioVolume.Volume); } catch { }
}
return maxVol;
}
}
if (target == "any")
{
lock (_lock)
{
var first = _sessions.Values.FirstOrDefault();
if (first != null) return first.SimpleAudioVolume.Volume;
}
return 0f;
}
// Process name substring match — return max volume across all matching sessions
// (apps like Discord have multiple sessions: voice, screenshare, notifications)
lock (_lock)
{
float maxVol = -1f;
foreach (var entry in _sessionEntries)
{
if (SessionMatches(entry, target))
try { maxVol = Math.Max(maxVol, entry.Session.SimpleAudioVolume.Volume); } catch { }
}
if (maxVol >= 0) return maxVol;
}
}
catch { }
return 0f;
}
private float GetDeviceVolume(string deviceId, DataFlow dataFlow)
{
if (string.IsNullOrEmpty(deviceId)) return 0f;
lock (_enumLock)
{
try
{
var device = GetOrCacheDeviceEndpoint(deviceId, dataFlow);
if (device == null) return 0f;
return device.AudioEndpointVolume.MasterVolumeLevelScalar;
}
catch
{
if (_devicePeakCache.Remove(deviceId, out var stale))
{
try { stale.Dispose(); } catch { }
}
return 0f;
}
}
}
/// <summary>
/// Returns a persistent endpoint for a specific device. Both volume and peak
/// reads share this cache because MixerView requests them back-to-back every
/// 75ms. Caller must hold <see cref="_enumLock"/>.
/// </summary>
private MMDevice? GetOrCacheDeviceEndpoint(string deviceId, DataFlow dataFlow)
{
if (_devicePeakCache.TryGetValue(deviceId, out var cached))
return cached;
var devices = _enumerator.EnumerateAudioEndPoints(dataFlow, DeviceState.Active);
MMDevice? match = null;
if (devices != null)
{
for (int i = 0; i < devices.Count; i++)
{
var device = devices[i];
bool isMatch = false;
try { isMatch = match == null && device.ID == deviceId; } catch { }
if (isMatch)
match = device;
else
try { device.Dispose(); } catch { }
}
}
if (match != null)
_devicePeakCache[deviceId] = match;
return match;
}
private float GetActiveWindowVolume()
{
try
{
IntPtr hwnd = NativeMethods.GetForegroundWindow();
if (hwnd == IntPtr.Zero) return 0f;
NativeMethods.GetWindowThreadProcessId(hwnd, out uint pid);
if (pid == 0) return 0f;
// Skip AmpUp's own window — user is just looking at the mixer
int myPid = Environment.ProcessId;
if (pid == myPid) return -1f; // -1 signals "no valid active window"
lock (_lock)
{
if (_sessionsByPid.TryGetValue(pid, out var session))
return session.SimpleAudioVolume.Volume;
}
// Fallback: match by process name
try
{
var name = ResolvePidName((int)pid)?.ToLowerInvariant();
if (name != null)
lock (_lock)
{
if (_sessions.TryGetValue(name, out var sessionByName))
return sessionByName.SimpleAudioVolume.Volume;
}
}
catch { }
}
catch { }
return 0f;
}
public float GetPeakLevel(KnobConfig knob)
{
try
{
var target = ToLowerNoAlloc(knob.Target);
if (target == "master")
{
// Use a dedicated persistent device for peak metering
// (separate from _renderDevice which gets swapped during RefreshSessions).
// All reads and writes to _masterPeakDevice go through _enumLock to avoid a
// TOCTOU race between GetPeakLevel (UI timer) and InvalidatePeakDevice
// (session-lock handler on a different thread).
lock (_enumLock)
{
if (_masterPeakDevice == null)
_masterPeakDevice = _enumerator.GetDefaultAudioEndpoint(DataFlow.Render, Role.Multimedia);
try
{
return _masterPeakDevice.AudioMeterInformation.MasterPeakValue;
}
catch
{
// Device may have changed — recreate on next call
try { _masterPeakDevice?.Dispose(); } catch { }
_masterPeakDevice = null;
return 0f;
}
}
}
if (target == "mic")
{
// Same persistent-device pattern as the master path — re-activating
// the capture endpoint per VU tick is expensive.
lock (_enumLock)
{
try
{
_micPeakDevice ??= _enumerator.GetDefaultAudioEndpoint(DataFlow.Capture, Role.Communications);
return _micPeakDevice.AudioMeterInformation.MasterPeakValue;
}
catch
{
// Device may have changed — recreate on next call
try { _micPeakDevice?.Dispose(); } catch { }
_micPeakDevice = null;
return 0f;
}
}
}
if (target == "output_device")
{
return GetPeakLevelForDevice(knob.DeviceId, DataFlow.Render);
}
if (target == "input_device")
{
return GetPeakLevelForDevice(knob.DeviceId, DataFlow.Capture);
}
if (target == "active_window")
{
return GetActiveWindowPeakLevel();
}
if (target == "system")
{
// System Sounds session (PID 0) cached off the persistent master peak
// device — re-activating the endpoint + enumerating sessions per VU
// tick is expensive. Invalidated on read failure, device change and
// session lock alongside _masterPeakDevice.
lock (_enumLock)
{
try
{
if (_systemPeakSession == null)
{
_masterPeakDevice ??= _enumerator.GetDefaultAudioEndpoint(DataFlow.Render, Role.Multimedia);
var sessionMgr = _masterPeakDevice.AudioSessionManager;
sessionMgr.RefreshSessions();
var sessions = sessionMgr.Sessions;
for (int i = 0; i < sessions.Count; i++)
{
var s = sessions[i];
bool keep = false;
try { keep = _systemPeakSession == null && s.GetProcessID == 0; } catch { }
if (keep)
_systemPeakSession = s;
else
try { s.Dispose(); } catch { }
}
}
if (_systemPeakSession != null)
return _systemPeakSession.AudioMeterInformation.MasterPeakValue;
}
catch
{
try { _systemPeakSession?.Dispose(); } catch { }
_systemPeakSession = null;
}
return 0f;
}
}
if (target == "apps")
{
lock (_lock)
{
float maxPeak = 0f;
foreach (var entry in _sessionEntries)
{