-
Notifications
You must be signed in to change notification settings - Fork 13
/
BgMusicManager.cs
1511 lines (1363 loc) · 71.1 KB
/
BgMusicManager.cs
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 System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Linq;
using System.Diagnostics;
#if WINDOWS
using WinCoreAudioApiSoundServer;
#endif
namespace MuteFm
{
public enum Operation
{
Unknown = 0,
Play,
Pause,
Mute,
Unmute,
Stop,
Show,
Hide,
Shuffle,
NextTrack,
PrevTrack,
Exit,
Restore,
SmartMute,
SetVolumeTo,
SetVolumeToNoFade,
AutoMutingEnabled,
NoAutoMutingEnabled,
ChangeMusic,
ClearHistory, // internal command
IgnoreForAutoMute, // fgmusics only
NoIgnoreForAutoMute, // fgmusics only
Like,
Dislike,
AutoMutedPlay, // Used if user decides to play while automuted
Minimize,
}
}
// This file includes code that maintains and updates state
// It should not be updating the UI directly but rather should call assigned callbacks. Have OnStateChange that passes in the new state and maintains the old state
namespace MuteFm.SmartVolManagerPackage
{
public enum BgMusicState
{
Unknown = 0,
Play = 1,
Pause = 2,
Stop = 3, // in this state if process isn't running
Mute = 4
}
public class BgMusicManager
{
#region Transitional state
public static int FadingThreadCount = 0;
public static bool IsMuting = false;
public static bool IsPausing = false;
public static bool IsUnmuting = false;
public static bool IsRestoring = false;
public static bool DisableAutomuteTemporarily = false;
public static List<string> MutedFgSessionIds = new List<string>();
#endregion
#region Dicts
public static Dictionary<string, bool> IgnoreProcNameForAutomuteDict = new Dictionary<string, bool>();
public static Dictionary<long, long> IdToPidDict = null; // We only store one pid here (okay since we just use it to show)
public static Dictionary<long, List<string>> IdToSessionInstanceIdsDict = null;
#endregion
#region Player state
public static BgMusicState MusicState = BgMusicState.Stop;
public static bool BgMusicWindowShown = false;
private static bool _userWantsBgMusic;
public static bool UserWantsBgMusic
{
get
{
return _userWantsBgMusic;
}
set
{
if (_userWantsBgMusic != value)
{
_userWantsBgMusic = value;
UiPackage.UiCommands.UpdateUiForState();
}
}
}
private static bool _autoMuted = false;
public static bool AutoMuted
{
get
{
return _autoMuted;
}
set
{
if (_autoMuted != value)
{
_autoMuted = value;
UiPackage.UiCommands.UpdateUiForState();
}
}
}
public static bool MasterMuted = false;
public static float MasterVol = 0.5f;
public static bool BgMusicVolInit = false;
private static float _bgMusicVolume = 1.0f;
public static float BgMusicVolume
{
get
{
return _bgMusicVolume;
}
set
{
if ((_bgMusicVolume != value) && (FadingThreadCount == 0))
{
_bgMusicVolume = value;
UiPackage.UiCommands.UpdateUiForState();
}
}
}
private static bool _bgMusicMuted = false;
public static bool BgMusicMuted
{
get
{
return _bgMusicMuted;
}
set
{
if (_bgMusicMuted != value)
{
_bgMusicMuted = value;
UiPackage.UiCommands.UpdateUiForState();
}
}
}
public static string TrackName = "";
public static string AlbumArtFileName = "";
public static bool UserMustClickPlay = false;
#endregion
#region Background music state
public static MuteFm.SoundPlayerInfo ActiveBgMusic = null;
public static int[] BgMusicPids = new int[0];
public static bool OwnBgMusicPid = true;
private static Process BgMusicProcess = null;
public static MuteFm.MuteFmConfig MuteFmConfig = null;
#endregion
#region Foreground sounds state
private static FgInfo[] _oldFgInfos = null;
public static bool ForegroundSoundPlaying = false; // anything is actually heard over last half second or so
public static bool BgMusicHeard = false;
public static Dictionary<string, KeyValuePair<MuteFm.SoundPlayerInfo, DateTime>> RecentMusics = new Dictionary<string, KeyValuePair<MuteFm.SoundPlayerInfo, DateTime>>();
public static MuteFm.SoundPlayerInfo[] FgMusics = new SoundPlayerInfo[0];
public static Dictionary<long, float> FgMusicVol = null;
public static Dictionary<long, bool> FgMusicMuted = null;
public static Dictionary<long, bool> FgMusicIsActive = null;
public static Dictionary<long, bool> FgMusicIgnore = null;
public static Dictionary<string, SoundPlayerInfo> SessionInstanceToSoundPlayerInfoDict = null;
public static MuteFm.SoundPlayerInfo[] soundInfos;
public static DateTime EffectiveSilenceDateTime = DateTime.MaxValue;
public class FgInfo
{
public long Id;
public float Vol;
public bool Muted;
public bool IsActive;
public bool Ignore;
public FgInfo(long id)
{
Id = id;
Vol = 0.5f;
Muted = false;
IsActive = false;
Ignore = false;
}
}
#endregion
#region Delegates/threads
public static System.ComponentModel.BackgroundWorker AutoKillAfterMutedWorker = null;
public delegate void PostVolumeOp();
public delegate void OnUpdate();
#endregion
#region Init
static BgMusicManager()
{
Init(false);
}
public static void Init(bool ignoreInstalled)
{
#if WINDOWS
try
{
MuteFmConfig = null;
MuteFmConfig = MuteFm.MuteFmConfigUtil.Load();
}
catch (Exception ex)
{
MuteFm.SmartVolManagerPackage.SoundEventLogger.LogException(ex);
}
#endif // WINDOWS
if (MuteFmConfig == null)
{
if (!ignoreInstalled)
{
Program.Installed = false;
//UiPackage.UiCommands.TrackEvent("install"); // not actually install, but creating original config
}
MuteFmConfig = MuteFmConfigUtil.CreateDefaultConfig();
try
{
MuteFmConfig configOnDisk = MuteFmConfigUtil.Load();
MuteFmConfig = configOnDisk;
}
catch
{
MuteFm.SmartVolManagerPackage.SoundEventLogger.LogMsg("Could not read config off of disk (after just writing it.)");
MuteFm.SmartVolManagerPackage.SoundEventLogger.LogMsg(MuteFmConfig);
}
}
ActiveBgMusic = MuteFmConfig.GetInitialBgMusic();
InitConstants();
}
public static void InitConstants()
{
// How it works:
// Background music is muted if sound is heard for at least ACTIVE_OVER_DURATION_INTERVAL_IN_MS by fading out over interval fadetimeins.
// Background music disappears if it is silent for at least SILENT_DURATION_IN_S by fading out over interval fadetimeins
MuteFm.SmartVolManagerPackage.SoundSourceInfo.SILENT_DURATION_IN_S = MuteFmConfig.GeneralSettings.SilentDuration;
MuteFm.SmartVolManagerPackage.SoundSourceInfo.ACTIVE_OVER_DURATION_INTERVAL_IN_MS = MuteFmConfig.GeneralSettings.ActiveOverDurationInterval * 1000;
MuteFm.SmartVolManagerPackage.SoundServer.FadeInTimeInS = MuteFmConfig.GeneralSettings.FadeInTime;
MuteFm.SmartVolManagerPackage.SoundServer.FadeOutTimeInS = MuteFmConfig.GeneralSettings.FadeOutTime;
MuteFm.SmartVolManagerPackage.SoundServer.SoundPollIntervalInS = MuteFmConfig.GeneralSettings.SoundPollIntervalInS;
MuteFm.SmartVolManagerPackage.SoundSourceInfo.SILENT_THRESHOLD = MuteFmConfig.GeneralSettings.SilentThreshold; // what volume means silence?
MuteFm.SmartVolManagerPackage.SoundSourceInfo.SILENT_SHORT_DURATION_IN_MS = MuteFmConfig.GeneralSettings.SilentShortDuration * 1000; // Used to detect if playing or not
}
#endregion
#region Sound Events
public static void OnMasterVolumeChange(float newVol, bool newMuted)
{
MasterVol = newVol;
MasterMuted = newMuted;
UpdateFgMusicState();
}
public static void OnManualVolumeChange(SoundSourceInfo info)
{
if (Program.LicenseExpired)
return;
if (SoundSourceInfoIsBgMusic(info, ActiveBgMusic.ShortProcessName) && (FadingThreadCount == 0) && (IsMuting == false) && (IsUnmuting == false))
{
BgMusicVolume = info.MixerVolume;
BgMusicMuted = info.Muted;
BgMusicVolInit = true;
if ((BgMusicMuted == true) && (IsMuting == false) && (IsUnmuting == false))
UserWantsBgMusic = false;
UiPackage.UiCommands.UpdateUiForState();
//TODO: doesn't update state correctly
/*
if (BgMusicMuted == true)
UpdateBgMusicState(BgMusicState.Mute);
UpdateBgMusicState(MusicState);*/
}
// TODO: doesn't update fgvol/muted correctly
}
// This gets called when an active sound has been added or removed (and every five seconds)
public static void OnUpdateSoundSourceInfos(SoundSourceInfo[] soundSourceInfos)
{
if (Program.LicenseExpired)
return;
Dictionary<string, SoundPlayerInfo> prevSessionInstanceToPlayerInfoDict = SessionInstanceToSoundPlayerInfoDict;
SessionInstanceToSoundPlayerInfoDict = new Dictionary<string, SoundPlayerInfo>();
Dictionary<long, List<string>> idToSessionInstanceIdsDict = new Dictionary<long, List<string>>();
Dictionary<long, long> idToPidDict = new Dictionary<long, long>();
Dictionary<long, float> fgMusicVol = new Dictionary<long, float>();
Dictionary<long, bool> fgMusicMuted = new Dictionary<long, bool>();
Dictionary<long, bool> fgMusicIsActive = new Dictionary<long, bool>();
Dictionary<long, bool> fgMusicIgnore = new Dictionary<long, bool>();
//List<SoundPlayerInfo> fgMusics = new List<SoundPlayerInfo>();
bool bgMusicHeard = false;
bool nonBgMusicHeard = false;
DateTime now = DateTime.Now;
bool isEffectiveSound = false;
bool bgIsEmmittingSound = false;
SoundServer.SoundSourceInfos = soundSourceInfos;
// Determine if background music and any non-background music sound is active
DateTime newestActive = DateTime.MinValue;
for (int i = 0; i < SoundServer.SoundSourceInfos.Length; i++)
{
try
{
SoundSourceInfo info = SoundServer.SoundSourceInfos[i];
if (info.IsEmittingSound() && !info.Muted)
{
bool ignore = false;
IgnoreProcNameForAutomuteDict.TryGetValue(info.ProcessName, out ignore);
if (!ignore)
{
isEffectiveSound = true;
}
}
if (SoundSourceInfoIsBgMusic(info, ActiveBgMusic.ShortProcessName)) // background sound
{
List<string> temp;
if (!idToSessionInstanceIdsDict.TryGetValue(SmartVolManagerPackage.BgMusicManager.ActiveBgMusic.Id, out temp))
idToSessionInstanceIdsDict[SmartVolManagerPackage.BgMusicManager.ActiveBgMusic.Id] = new List<string>();
idToSessionInstanceIdsDict[SmartVolManagerPackage.BgMusicManager.ActiveBgMusic.Id].Add(info.SessionInstanceIdentifier);
if (bgIsEmmittingSound == true) // For media player and Zune, there are multiple session instances for the bgmusic; if one is emitting then bgmusic is emitting and we'll use that session instance properties
continue;
BgMusicVolume = info.MixerVolume;
BgMusicMuted = info.Muted;
BgMusicVolInit = true;
bgMusicHeard = !info.EffectiveVolumeIsZero();
bgIsEmmittingSound = info.IsEmittingSound();
if (IsPausing || !bgIsEmmittingSound)
{
if (MusicState != BgMusicState.Pause)
UpdateBgMusicState(BgMusicState.Pause); // Assume it is paused if we haven't heard background music in awhile
}
else
{
if (MusicState != BgMusicState.Stop)
{
if (info.MixerVolumeIsZeroOrMuted() || ((FadingThreadCount > 0) && (IsMuting)))
{
if (MusicState != BgMusicState.Mute)
UpdateBgMusicState(BgMusicState.Mute);
}
else
{
if (MusicState != BgMusicState.Play)
UpdateBgMusicState(BgMusicState.Play);
UserWantsBgMusic = true;
}
}
}
}
else // Foreground sounds
{
//string effectiveProcessPath = (info.ProcessFullPath != "") ? info.ProcessFullPath : info.ProcessName;
if ((info.IsEmittingSound() == true) && ((info.ProcessFullPath != "") || (info.IsSystemIsSystemSoundsSession)))
{
SoundPlayerInfo fgMusic;
if (!prevSessionInstanceToPlayerInfoDict.TryGetValue(info.SessionInstanceIdentifier, out fgMusic)) // TODO: just changed to use sessioninstance
{
fgMusic = new SoundPlayerInfo();
fgMusic.Id = MuteFmConfig.NextId;
MuteFmConfig.NextId++;
}
List<string> temp;
if (!idToSessionInstanceIdsDict.TryGetValue(fgMusic.Id, out temp))
idToSessionInstanceIdsDict[fgMusic.Id] = new List<string>();
idToSessionInstanceIdsDict[fgMusic.Id].Add(info.SessionInstanceIdentifier);
fgMusic.Name = (info.IsSystemIsSystemSoundsSession) ? "System Sounds" : info.WindowTitle;
fgMusic.UrlOrCommandLine = info.ProcessFullPath;
fgMusic.ShortProcessName = info.ProcessName;
fgMusic.IsWeb = false;
MuteFmConfigUtil.InitDefaultsProcess(fgMusic, info.ProcessName);
MuteFmConfigUtil.GenerateIconImage(fgMusic, false);
fgMusicVol[fgMusic.Id] = info.MixerVolume;
fgMusicMuted[fgMusic.Id] = info.Muted;
fgMusicIsActive[fgMusic.Id] = info.IsEmittingSound();
bool ignore = false;
IgnoreProcNameForAutomuteDict.TryGetValue(info.ProcessName, out ignore);
fgMusicIgnore[fgMusic.Id] = ignore;
SessionInstanceToSoundPlayerInfoDict[info.SessionInstanceIdentifier] = fgMusic;
}
if ((!DisableAutomuteTemporarily) && (info.IsContinuouslyActiveForAwhile() == true))
{
bool shouldIgnore = false;
IgnoreProcNameForAutomuteDict.TryGetValue(info.ProcessName.ToLower(), out shouldIgnore);
if (!shouldIgnore)
nonBgMusicHeard = true;
}
}
}
catch (Exception ex)
{
MuteFm.SmartVolManagerPackage.SoundEventLogger.LogException(ex);
}
}
if (isEffectiveSound)
EffectiveSilenceDateTime = DateTime.MaxValue;
else
EffectiveSilenceDateTime = (EffectiveSilenceDateTime < now) ? EffectiveSilenceDateTime : now;
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Update Automute
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
try
{
if ((UserWantsBgMusic) && (SmartVolManagerPackage.BgMusicManager.MuteFmConfig.GeneralSettings.AutoMuteEnabled == true) && (MasterMuted == false))
{
if ((nonBgMusicHeard == true) && (bgMusicHeard == true))
{
AutoMuted = true;
UiPackage.UiCommands.SetNotification("Music fading out...", true);
UiPackage.UiCommands.TrackEvent("automute");
PerformOperation(Operation.SmartMute);
}
else if ((MusicState != BgMusicState.Play) && (nonBgMusicHeard == false))
{
if (AutoMuted == true)
{
AutoMuted = false;
PerformOperation(Operation.Restore);
UiPackage.UiCommands.SetNotification("Music fading in...", true);
}
}
}
if (AutoMuted && UserWantsBgMusic && (SmartVolManagerPackage.BgMusicManager.MuteFmConfig.GeneralSettings.AutoMuteEnabled == false))
{
AutoMuted = false;
PerformOperation(Operation.Restore);
UiPackage.UiCommands.SetNotification("Music fading in...", true);
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Update background-related state
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
BgMusicHeard = bgMusicHeard;
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Update foreground-related state
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
if (ForegroundSoundPlaying != nonBgMusicHeard)
{
ForegroundSoundPlaying = nonBgMusicHeard;
UiPackage.UiCommands.UpdateUiForState();
}
SoundPlayerInfo[] fgMusics = new SoundPlayerInfo[SessionInstanceToSoundPlayerInfoDict.Count];
SessionInstanceToSoundPlayerInfoDict.Values.CopyTo(fgMusics, 0);
List<SoundPlayerInfo> fgMusicList = new List<SoundPlayerInfo>(fgMusics);
fgMusicList.Sort(delegate(SoundPlayerInfo c1, SoundPlayerInfo c2)
{
if ((c1.ShortProcessName == "") && (c2.ShortProcessName == ""))// System always goes first
return 0;
if (c1.ShortProcessName == "") // System always goes first
return -1;
if (c2.ShortProcessName == "")
return 1;
bool c1Active = false;
bool c2Active = false;
fgMusicIsActive.TryGetValue(c1.Id, out c1Active);
fgMusicIsActive.TryGetValue(c2.Id, out c2Active);
if (c1Active && !c2Active)
return -1;
if (!c1Active && c2Active)
return 1;
return -1 * c1.GetName().CompareTo(c2.GetName());
});
FgMusics = fgMusicList.ToArray();
IdToPidDict = idToPidDict;
FgMusicVol = fgMusicVol;
FgMusicMuted = fgMusicMuted;
FgMusicIsActive = fgMusicIsActive;
FgMusicIgnore = fgMusicIgnore;
FgInfo[] fgInfos = CollectFgInfo();
// Only update UI with fginfo if it is different
if (FgInfosAreDifferent(_oldFgInfos, fgInfos))
{
UpdateFgMusicState();
_oldFgInfos = fgInfos;
}
// Remove anything older than an hour
List<string> keys = RecentMusics.Keys.Take(RecentMusics.Keys.Count).ToList();
for (int i = 0; i < keys.Count(); i++)
{
if (RecentMusics[keys[i]].Value.AddSeconds(60 * 60) < DateTime.Now)
RecentMusics.Remove(keys[i]);
}
for (int i = 0; i < fgMusics.Length; i++)
{
KeyValuePair<SoundPlayerInfo, DateTime> kvp;
if (!RecentMusics.TryGetValue(fgMusics[i].UrlOrCommandLine, out kvp))
{
kvp = new KeyValuePair<SoundPlayerInfo, DateTime>(fgMusics[i], DateTime.Now);
RecentMusics[fgMusics[i].ShortProcessName] = kvp;
}
else
{
kvp = new KeyValuePair<SoundPlayerInfo, DateTime>(kvp.Key, DateTime.Now);
}
}
IdToSessionInstanceIdsDict = idToSessionInstanceIdsDict;
}
catch (Exception ex)
{
MuteFm.SmartVolManagerPackage.SoundEventLogger.LogException(ex);
}
}
private static bool SoundSourceInfoIsBgMusic(SoundSourceInfo info, string bgMusicProcessName)
{
bool isBgMusic = (BgMusicPids.Contains(info.Pid) || ((ActiveBgMusic.IsWeb == true) && Constants.ProcessIsMuteFm(info.ProcessName)));
if ((bgMusicProcessName.ToLower() == "") && (info.Pid == 0))
isBgMusic = false;
else if (!isBgMusic)
{
if (info.Pid == 0)
return false;
try
{
//System.Diagnostics.Process p = System.Diagnostics.Process.GetProcessById(info.Pid);
//if ((p != null) && (p.Modules != null) && (p.Modules.Count > 0) && (p.Modules[0].FileName == bgMusicProcessName))
if (info.ProcessName.ToLower() == bgMusicProcessName.ToLower())
isBgMusic = true;
}
catch (Exception ex)
{
string msg = ex.Message;
MuteFm.SmartVolManagerPackage.SoundEventLogger.LogMsg("Error getting process info for pid " + info.Pid);
}
}
if (isBgMusic)
{
if (!BgMusicPids.Contains(info.Pid))
{
List<int> bgMusicPidList = new List<int>();
bgMusicPidList.Add(info.Pid);
BgMusicPids = bgMusicPidList.ToArray();
}
}
return isBgMusic;
}
#endregion
#region Foreground sounds
private static FgInfo[] CollectFgInfo()
{
List<FgInfo> fgInfos = new List<FgInfo>();
for (int i = 0; i < FgMusics.Length; i++)
{
FgInfo fgInfo = new FgInfo(FgMusics[i].Id);
FgMusicVol.TryGetValue(FgMusics[i].Id, out fgInfo.Vol);
FgMusicMuted.TryGetValue(FgMusics[i].Id, out fgInfo.Muted);
FgMusicIsActive.TryGetValue(FgMusics[i].Id, out fgInfo.IsActive);
FgMusicIgnore.TryGetValue(FgMusics[i].Id, out fgInfo.Ignore);
fgInfos.Add(fgInfo);
}
return fgInfos.ToArray();
}
private static bool FgInfosAreDifferent(FgInfo[] oldInfos, FgInfo[] newInfos)
{
if (((oldInfos == null) && (newInfos != null)) || ((oldInfos != null) && (newInfos == null))) return true;
if (oldInfos.Length != newInfos.Length) return true;
for (int i = 0; i < oldInfos.Length; i++)
{
if (oldInfos[i].Id != newInfos[i].Id) return true;
if (oldInfos[i].Ignore != newInfos[i].Ignore) return true;
if (oldInfos[i].IsActive != newInfos[i].IsActive) return true;
if (oldInfos[i].Muted != newInfos[i].Muted) return true;
if (oldInfos[i].Vol != newInfos[i].Vol) return true;
}
return false;
}
public static MuteFm.SoundPlayerInfo[] GetRecentMusics()
{
List<MuteFm.SoundPlayerInfo> soundInfoList = new List<SoundPlayerInfo>();
// Remove anything older than 5 minutes
List<string> keys = RecentMusics.Keys.Take(RecentMusics.Keys.Count).ToList();
for (int i = 0; i < keys.Count(); i++)
{
soundInfoList.Add(RecentMusics[keys[i]].Key);
}
return soundInfoList.ToArray();
}
#endregion
#region State
public static Operation GetValidOperation()
{
Operation validOp = Operation.Unknown;
switch (MusicState)
{
case BgMusicState.Mute:
validOp = Operation.Unmute;
break;
case BgMusicState.Pause:
validOp = Operation.Play;
break;
case BgMusicState.Play:
// Pause if possible, otherwise mute. Should perhaps allow stop in addition to mute to save cpu and maybe network activity
if ((ActiveBgMusic.PauseCommand != null) && (ActiveBgMusic.PauseCommand != ""))
validOp = Operation.Pause;
else
validOp = Operation.Mute;
break;
case BgMusicState.Stop:
validOp = Operation.Play;
break;
}
return validOp;
}
public static bool IsRunning()
{
bool notRunning = (BgMusicPids.Length == 0) || ((ActiveBgMusic.IsWeb == true) && (MusicState == BgMusicState.Stop));
return !notRunning;
}
public static void UpdateBgMusicState(BgMusicState state)
{
if (MusicState != state)
{
MusicState = state;
UiPackage.UiCommands.UpdateUiForState(MuteFm.SmartVolManagerPackage.BgMusicManager.GetValidOperation(), BgMusicWindowShown, IsRunning());
}
}
public static void UpdateFgMusicState()
{
// TODO: have this only update fgmusic info. And maybe only for a specific id
UiPackage.UiCommands.UpdateUiForState(MuteFm.SmartVolManagerPackage.BgMusicManager.GetValidOperation(), BgMusicWindowShown, IsRunning());
}
private static void UpdateWindowShownState(bool visible)
{
BgMusicWindowShown = visible;
bool notRunning = (BgMusicPids.Length == 0);
#if !NOAWE
notRunning = notRunning || ((ActiveBgMusic.IsWeb == true) && !UiPackage.UiCommands.IsWebBgMusicSiteCurrent(ActiveBgMusic.UrlOrCommandLine)); // (MusicState == BgMusicState.Stop));
#endif
UiPackage.UiCommands.UpdateUiForState(MuteFm.SmartVolManagerPackage.BgMusicManager.GetValidOperation(), BgMusicWindowShown, !notRunning);
}
#endregion
public static string[] getSessionInstanceIdentifiers(long musicId)
{
List<string> sessionInstanceIdentifierList;
if (musicId == MuteFmConfig.MasterVolId)
{
sessionInstanceIdentifierList = new List<string>();
sessionInstanceIdentifierList.Add(WinCoreAudioApiSoundServer.WinCoreAudioApiSoundServer.MasterVolSessionInstanceIdentifier);
} else
IdToSessionInstanceIdsDict.TryGetValue((int)musicId, out sessionInstanceIdentifierList);
if (sessionInstanceIdentifierList == null)
sessionInstanceIdentifierList = new List<string>();
return sessionInstanceIdentifierList.ToArray();
}
#region Operations
public static void PerformOperation(Operation op)
{
PerformOperation(op, "");
}
public static void PerformOperation(Operation op, string param)
{
PerformOperation(ActiveBgMusic.Id, op, param, false);
}
private static int getPidForPlayerInfoId(long playerInfoId) // only used for fgmusic
{
if (playerInfoId == SmartVolManagerPackage.BgMusicManager.ActiveBgMusic.Id)
{
if (BgMusicPids.Length > 0)
return BgMusicPids[0]; // TODO: should handle multiple pids (and the dict should, too)
else
return 0;
}
long longPid = 0;
IdToPidDict.TryGetValue((int)playerInfoId, out longPid);
if (longPid < 0)
longPid *= -1; // probably not necessary; used to store some as negative values
if (playerInfoId == MuteFmConfig.MasterVolId)
longPid = -1;
return (int)longPid;
}
public static void PerformOperation(long playerInfoId, Operation op, string param, bool ignoreCommand)
{
if (Program.LicenseExpired == true)
return;
try
{
if (playerInfoId != ActiveBgMusic.Id)
{
// Foreground sound infos
SoundPlayerInfo playerInfo;
switch (op)
{
case Operation.Show:
OperationHelper.Show(getPidForPlayerInfoId(playerInfoId));
break;
case Operation.Minimize:
OperationHelper.Minimize(getPidForPlayerInfoId(playerInfoId));
break;
case Operation.IgnoreForAutoMute:
playerInfo = FindPlayerInfo(playerInfoId);
if (playerInfo != null)
{
SmartVolManagerPackage.BgMusicManager.FgMusicIgnore[playerInfo.Id] = true;
SmartVolManagerPackage.BgMusicManager.IgnoreProcNameForAutomuteDict[playerInfo.ShortProcessName] = true;
MuteFmConfigUtil.InitIgnoreForAutoMute(SmartVolManagerPackage.BgMusicManager.IgnoreProcNameForAutomuteDict, SmartVolManagerPackage.BgMusicManager.MuteFmConfig);
MuteFmConfigUtil.Save(SmartVolManagerPackage.BgMusicManager.MuteFmConfig);
UpdateFgMusicState();
}
break;
case Operation.NoIgnoreForAutoMute:
playerInfo = FindPlayerInfo(playerInfoId);
if (playerInfo != null)
{
SmartVolManagerPackage.BgMusicManager.FgMusicIgnore[playerInfo.Id] = false;
SmartVolManagerPackage.BgMusicManager.IgnoreProcNameForAutomuteDict[playerInfo.ShortProcessName] = false;
MuteFmConfigUtil.InitIgnoreForAutoMute(SmartVolManagerPackage.BgMusicManager.IgnoreProcNameForAutomuteDict, SmartVolManagerPackage.BgMusicManager.MuteFmConfig);
MuteFmConfigUtil.Save(SmartVolManagerPackage.BgMusicManager.MuteFmConfig);
UpdateFgMusicState();
}
break;
default:
string[] sessionInstanceIdentifiers = getSessionInstanceIdentifiers(playerInfoId);
foreach (string sessionInstanceIdentifier in sessionInstanceIdentifiers)
{
switch (op)
{
case Operation.Mute:
FgMusicMuted[playerInfoId] = true;
MuteFm.SmartVolManagerPackage.SoundServer.PerformOperation(sessionInstanceIdentifier, OperationEnum.Mute.ToString(), null, null, new PostVolumeOp(delegate() { UpdateFgMusicState(); }));
break;
case Operation.Unmute:
FgMusicMuted[playerInfoId] = false;
MuteFm.SmartVolManagerPackage.SoundServer.PerformOperation(sessionInstanceIdentifier, OperationEnum.Unmute.ToString(), null, null, new PostVolumeOp(delegate() { UpdateFgMusicState(); }));
break;
case Operation.SetVolumeTo:
FgMusicVol[playerInfoId] = float.Parse(param);
MuteFm.SmartVolManagerPackage.SoundServer.PerformOperation(sessionInstanceIdentifier, OperationEnum.SetVolumeTo.ToString(), param, null, new PostVolumeOp(delegate() { UpdateFgMusicState(); }));
break;
case Operation.SetVolumeToNoFade:
FgMusicVol[playerInfoId] = float.Parse(param);
MuteFm.SmartVolManagerPackage.SoundServer.PerformOperation(sessionInstanceIdentifier, OperationEnum.SetVolumeToNoFade.ToString(), param, null, new PostVolumeOp(delegate() { UpdateFgMusicState(); }));
break;
}
}
break;
}
// TODO: update state via postoperation in all of the above
}
else
{
MuteFm.SmartVolManagerPackage.SoundEventLogger.LogBg(op.ToString());
switch (op)
{
case Operation.Play:
case Operation.ChangeMusic:
PerformOperation(playerInfoId, Operation.Unmute, null, ignoreCommand); //todo is this trying to unmute before loaded???
//if (_runCommand(ActiveBgMusic.PlayCommand))
//{
// Update MusicState(BgMusicState.Play);
//}
break;
case Operation.Pause:
if (_runCommand(ActiveBgMusic.PauseCommand))
UpdateBgMusicState(BgMusicState.Pause);
break;
case Operation.Mute:
Mute(new PostVolumeOp(delegate() { FadingThreadCount--; }), 0);
break;
case Operation.Stop:
if (ActiveBgMusic.IsWeb == false)
{
if (!_runCommand(ActiveBgMusic.StopCommand))
Close();
}
else
{
#if !NOAWE
MuteFm.UiPackage.UiCommands.StopWebBgMusic();
PerformOperation(playerInfoId, Operation.Hide, null, ignoreCommand);
#endif
}
UpdateBgMusicState(BgMusicState.Stop);
break;
case Operation.Show:
if (BgMusicPids.Length == 0)
{
_run();
if (BgMusicPids.Length == 0)
return;
}
if (ActiveBgMusic.IsWeb)
{
#if !NOAWE
MuteFm.UiPackage.UiCommands.ShowWebBgMusic();
#endif
}
else
{
for (int i = 0; i < BgMusicPids.Length; i++)
OperationHelper.Show(BgMusicPids[i]);
}
UpdateWindowShownState(true);
break;
case Operation.Hide: // not used
if (ActiveBgMusic.IsWeb)
{
#if !NOAWE
UiPackage.UiCommands.HideWebBgMusic();
#endif
}
else
{
for (int i = 0; i < BgMusicPids.Length; i++)
MuteFm.OperationHelper.Hide(BgMusicPids[i]);
}
UpdateWindowShownState(false);
break;
case Operation.Restore:
if (AutoKillAfterMutedWorker != null)
{
AutoKillAfterMutedWorker.CancelAsync();
AutoKillAfterMutedWorker = null;
}
bool shouldPlay = false;
if (ActiveBgMusic.IsWeb)
shouldPlay = true; // TODO: maybe be smarter here. don't want to show window
else
{
// We don't want a restore to launch the music player if it isn't running (annoying to user)
Process[] processes = (Process.GetProcessesByName(ActiveBgMusic.ShortProcessName));
shouldPlay = (processes.Length != 0);
}
if (shouldPlay)
{
//if (MusicState == BgMusicState.Mute)
PerformOperation(playerInfoId, Operation.Unmute, null, true);
IsRestoring = true;
if ((MusicState == BgMusicState.Stop) || (MusicState == BgMusicState.Pause))
PerformOperation(playerInfoId, Operation.Play, null, false);
IsRestoring = false;
}
break;
case Operation.AutoMutedPlay: // This will take music that is not running and launch it, mute it, play it, and then pause.
Mute(new PostVolumeOp(delegate() {
_runCommand(ActiveBgMusic.PlayCommand);
_runCommand(ActiveBgMusic.PauseCommand);
FadingThreadCount--;
SmartVolManagerPackage.BgMusicManager.AutoMuted = true;
}), MuteFmConfig.GeneralSettings.FadeDownToLevel);
break;
case Operation.SmartMute:
// Pause if possible, otherwise mute. Should perhaps allow stop in addition to mute to save cpu and maybe network activity
if ((ActiveBgMusic.PauseCommand != null) && (ActiveBgMusic.PauseCommand != "") && (MuteFmConfig.GeneralSettings.FadeDownToLevel == 0))
Mute(new PostVolumeOp(delegate() { FadingThreadCount--; PerformOperation(Operation.Pause, null); }), MuteFmConfig.GeneralSettings.FadeDownToLevel);
else
Mute(new PostVolumeOp(delegate() { FadingThreadCount--; }), MuteFmConfig.GeneralSettings.FadeDownToLevel);
if (AutoKillAfterMutedWorker != null)
{
AutoKillAfterMutedWorker.CancelAsync();
AutoKillAfterMutedWorker = null;
}
// Autokillaftermute should only happen when automuting
if ((MuteFmConfig.GeneralSettings.FadeDownToLevel == 0) && ActiveBgMusic.KillAfterAutoMute)
{
AutoKillAfterMutedWorker = new System.ComponentModel.BackgroundWorker();
AutoKillAfterMutedWorker.WorkerSupportsCancellation = true;
AutoKillAfterMutedWorker.DoWork += new System.ComponentModel.DoWorkEventHandler(AutoKillAfterMutedWorker_DoWork);
AutoKillAfterMutedWorker.RunWorkerAsync();
}
break;
case Operation.NextTrack:
if (!ignoreCommand)
_runCommand(ActiveBgMusic.NextSongCommand);
break;
case Operation.PrevTrack:
if (!ignoreCommand)
_runCommand(ActiveBgMusic.PrevSongCommand);
break;
case Operation.Shuffle: // not used
if (!ignoreCommand)
_runCommand(ActiveBgMusic.ShuffleCommand);
break;
case Operation.Like:
if (!ignoreCommand)
_runCommand(ActiveBgMusic.LikeCommand);
break;
case Operation.Dislike:
if (!ignoreCommand)
_runCommand(ActiveBgMusic.DislikeCommand);
break;
case Operation.AutoMutingEnabled:
MuteFmConfig.GeneralSettings.AutoMuteEnabled = true;
MuteFmConfigUtil.Save(SmartVolManagerPackage.BgMusicManager.MuteFmConfig);
UiPackage.UiCommands.UpdateUiForState();
//PerformOperation(Operation.Restore);
break;
case Operation.NoAutoMutingEnabled:
SmartVolManagerPackage.BgMusicManager.MuteFmConfig.GeneralSettings.AutoMuteEnabled = false;
MuteFmConfigUtil.Save(SmartVolManagerPackage.BgMusicManager.MuteFmConfig);
UiPackage.UiCommands.UpdateUiForState();
//PerformOperation(Operation.SmartMute);
break;
default:
string[] sessionInstanceIdentifiers = getSessionInstanceIdentifiers(playerInfoId);
switch (op)
{
case Operation.Unmute:
if (AutoKillAfterMutedWorker != null)
{
AutoKillAfterMutedWorker.CancelAsync();
AutoKillAfterMutedWorker = null;
}
bool ranSomething = _run();
bool autoPlayOnStartup = false;
SoundPlayerInfo playerInfo = FindPlayerInfo(playerInfoId);
if (playerInfo != null)
autoPlayOnStartup = playerInfo.AutoPlaysOnStartup;
if ((!ignoreCommand) && (!ranSomething || (!autoPlayOnStartup) || (IsRestoring && ActiveBgMusic.IsWeb)) && (MusicState == BgMusicState.Pause))
//if ((!ignoreCommand) && (!bgmusic.autoplayonstartup) && (MusicState == BgMusicState.Pause))
{
string cmd = ActiveBgMusic.PlayCommand;
if ((ranSomething || IsRestoring) && (ActiveBgMusic.IsWeb)) // Add a delay before running to allow page to load
{