-
Notifications
You must be signed in to change notification settings - Fork 3
/
Player.cs
2155 lines (1877 loc) · 81.9 KB
/
Player.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
// Copyright © 2011-2013 Yanick Castonguay
//
// This file is part of MPfm.
//
// MPfm is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// MPfm is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with MPfm. If not, see <http://www.gnu.org/licenses/>.
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using MPfm.Core;
using MPfm.Sound;
using MPfm.Sound.AudioFiles;
using MPfm.Sound.BassNetWrapper;
using MPfm.Sound.Playlists;
using Un4seen.Bass;
using Un4seen.Bass.AddOn.Fx;
using MPfm.Player.Events;
using MPfm.Player.Exceptions;
using MPfm.Player.Objects;
#if !IOS && !ANDROID
using Un4seen.BassAsio;
using Un4seen.BassWasapi;
using MPfm.Sound.BassNetWrapper.ASIO;
using MPfm.Sound.BassNetWrapper.WASAPI;
#endif
#if IOS
using MonoTouch;
#endif
namespace MPfm.Player
{
/// <summary>
/// The Player class manages audio playback through playlists and supports
/// multiple driver types and devices.
/// </summary>
public class Player : MPfm.Player.IPlayer
{
/// <summary>
/// This static instance of the player is used only on iOS, because MonoTouch requires all C callbacks
/// to be static.
/// http://docs.xamarin.com/ios/guides/advanced_topics/limitations
/// </summary>
public static Player CurrentPlayer = null;
/// <summary>
/// Defines the BASS plugin path. Useful for Android where this cannot be determined by Environment.SpecialFolder.
/// </summary>
/// </value>
public static string PluginDirectoryPath { get; set; }
/// <summary>
/// Returns true if the position is currently changing.
/// </summary>
public bool IsSettingPosition { get; private set; }
private System.Timers.Timer _timerPlayer = null;
private Channel _streamChannel = null;
private Channel _fxChannel = null;
private MixerChannel _mixerChannel = null;
// Plugin handles
private int _fxEQHandle;
private int _aacPluginHandle = 0;
private int _apePluginHandle = 0;
private int _flacPluginHandle = 0;
private int _mpcPluginHandle = 0;
private int _ofrPluginHandle = 0;
private int _ttaPluginHandle = 0;
private int _wvPluginHandle = 0;
private int _wmaPluginHandle = 0;
/// <summary>
/// Indicates the current playlist item index used by the mixer.
/// The playlist index is incremented when the mixer starts to play the next song.
/// Depending on the buffer size used, the index can be incremented a few seconds before actually hearing
/// the song change.
/// </summary>
private int _currentMixPlaylistIndex = 0;
/// <summary>
/// Position from which to resume after pausing the stream. This allows changing the player position
/// while the player is paused.
/// </summary>
private long _positionAfterUnpause;
/// <summary>
/// Offset position (necessary to calculate the offset in the output stream position
/// if the user has seeked the position in the decode stream). The output stream position
/// is reset to 0 in these cases to clear the audio buffer.
/// </summary>
private long _positionOffset = 0;
private List<PlayerSyncProc> _syncProcs = null;
private STREAMPROC _streamProc;
private BPMPROC _bpmProc;
//private BPMBEATPROC _bpmBeatProc;
#if IOS
private IOSNOTIFYPROC _iosNotifyProc;
#endif
#if !IOS && !ANDROID
private ASIOPROC asioProc;
private WASAPIPROC wasapiProc;
#endif
#region Events
/// <summary>
/// The OnPlaylistIndexChanged event is triggered when the playlist index changes (i.e. when an audio file
/// starts to play).
/// </summary>
public event PlaylistIndexChanged OnPlaylistIndexChanged;
/// <summary>
/// The OnAudioInterrupted event is triggered when the audio is interrupted by a system event.
/// Only useful on iOS for now. An example of use of this event would be to react when the user stops the
/// playback using the lock screen, remote control, etc.
/// </summary>
public event AudioInterrupted OnAudioInterrupted;
/// <summary>
/// The OnBPMDetected event is triggered when the current BPM has been deteted or has changed.
/// </summary>
public event BPMDetected OnBPMDetected;
#endregion
#region Properties
private bool _isPlaying = false;
/// <summary>
/// Indicates if the player is currently playing an audio file.
/// </summary>
public bool IsPlaying
{
get
{
return _isPlaying;
}
}
private bool _isPaused = false;
/// <summary>
/// Indicates if the player is currently paused.
/// </summary>
public bool IsPaused
{
get
{
return _isPaused;
}
}
private bool _useFloatingPoint;
/// <summary>
/// Determines if the device uses floating point.
/// </summary>
public bool UseFloatingPoint
{
get
{
return _useFloatingPoint;
}
}
private Device _device = null;
/// <summary>
/// Defines the currently used device for playback.
/// </summary>
public Device Device
{
get
{
return _device;
}
}
private bool _isDeviceInitialized = false;
/// <summary>
/// Indicates if the device (as in the Device property) is initialized.
/// </summary>
public bool IsDeviceInitialized
{
get
{
return _isDeviceInitialized;
}
}
private RepeatType _repeatType = RepeatType.Off;
/// <summary>
/// Repeat type (Off, Playlist, Song)
/// </summary>
public RepeatType RepeatType
{
get
{
return _repeatType;
}
set
{
_repeatType = value;
Console.WriteLine("Player - RepeatType: {0}", value.ToString());
// Check if the current song exists
if (_playlist != null && _playlist.CurrentItem != null)
{
// If the repeat type is Song, force song looping
if (_repeatType == RepeatType.Song)
_playlist.CurrentItem.Channel.SetFlags(BASSFlag.BASS_SAMPLE_LOOP, BASSFlag.BASS_SAMPLE_LOOP);
else
_playlist.CurrentItem.Channel.SetFlags(BASSFlag.BASS_DEFAULT, BASSFlag.BASS_SAMPLE_LOOP);
}
}
}
private float _volume = 1.0f;
/// <summary>
/// Defines the master volume (from 0 to 1).
/// </summary>
public float Volume
{
get
{
return _volume;
}
set
{
// Set value
_volume = value;
// Check if the player is playing
if (_mixerChannel != null)
{
// Set main volume
_mixerChannel.Volume = value;
}
#if !IOS && !ANDROID
// Check driver type
if (_device.DriverType == DriverType.ASIO)
{
// Set ASIO channel volume on left and right channel
bool success = BassAsio.BASS_ASIO_ChannelSetVolume(false, 0, value);
if (!success)
{
// Check for error
Base.CheckForError();
}
success = BassAsio.BASS_ASIO_ChannelSetVolume(false, 1, value);
if (!success)
{
// Check for error
Base.CheckForError();
}
}
else if (_device.DriverType == DriverType.WASAPI)
{
// Set WASAPI volume
bool success = BassWasapi.BASS_WASAPI_SetVolume(BASSWASAPIVolume.BASS_WASAPI_CURVE_LINEAR, value);
if (!success)
{
// Check for error
Base.CheckForError();
}
}
#endif
}
}
private float _timeShifting = 0.0f;
/// <summary>
/// Defines the time shifting applied to the currently playing stream.
/// Value range from -100.0f (-100%) to 100.0f (+100%). To reset, set to 0.0f.
/// </summary>
public float TimeShifting
{
get
{
return _timeShifting;
}
set
{
_timeShifting = value;
RemoveBPMCallbacks();
if (_fxChannel != null)
_fxChannel.SetAttribute(BASSAttribute.BASS_ATTRIB_TEMPO, _timeShifting);
AddBPMCallbacks();
}
}
private int _pitchShifting = 0;
/// <summary>
/// Defines the pitch shifting applied to the currently playing stream.
/// Value range from -12 to +12 semitones. To reset, set to 0.
/// </summary>
public int PitchShifting
{
get
{
return _pitchShifting;
}
set
{
_pitchShifting = value;
RemoveBPMCallbacks();
if (_fxChannel != null)
_fxChannel.SetAttribute(BASSAttribute.BASS_ATTRIB_TEMPO_PITCH, _pitchShifting);
AddBPMCallbacks();
}
}
private int _mixerSampleRate = 44100;
/// <summary>
/// Defines the sample rate of the mixer.
/// </summary>
public int MixerSampleRate
{
get
{
return _mixerSampleRate;
}
}
private int _bufferSize = 1000;
/// <summary>
/// Defines the buffer size (in milliseconds). Increase this value if older computers have trouble
/// filling up the buffer in time.
/// Default value: 1000ms. The default BASS value is 500ms.
/// </summary>
public int BufferSize
{
get
{
return _bufferSize;
}
set
{
_bufferSize = value;
Base.SetConfig(BASSConfig.BASS_CONFIG_BUFFER, _bufferSize);
}
}
private int _updatePeriod = 10;
/// <summary>
/// Defines how often BASS fills the buffer to make sure it is always full (in milliseconds).
/// This affects the accuracy of the ChannelGetPosition value.
/// Default value: 10ms. The default BASS value is 100ms.
/// </summary>
public int UpdatePeriod
{
get
{
return _updatePeriod;
}
set
{
_updatePeriod = value;
Base.SetConfig(BASSConfig.BASS_CONFIG_UPDATEPERIOD, _updatePeriod);
}
}
private int _updateThreads = 1;
/// <summary>
/// Defines how many threads BASS can use to update playback buffers in parrallel.
/// Note: The playback engine plays perfectly with just one update thread.
/// Default value: 1 thread. The default BASS value is 1 thread.
/// </summary>
public int UpdateThreads
{
get
{
return _updateThreads;
}
set
{
_updateThreads = value;
Base.SetConfig(BASSConfig.BASS_CONFIG_UPDATETHREADS, _updateThreads);
}
}
private Playlist _playlist = null;
/// <summary>
/// Playlist used for playback. Contains the audio file metadata and decode channels for
/// playback.
/// </summary>
public Playlist Playlist
{
get
{
return _playlist;
}
}
private EQPreset _currentEQPreset = null;
/// <summary>
/// Defines the current EQ preset.
/// </summary>
public EQPreset EQPreset
{
get
{
return _currentEQPreset;
}
set
{
_currentEQPreset = value;
}
}
private bool _isEQEnabled = false;
/// <summary>
/// Indicates if the EQ is enabled.
/// </summary>
public bool IsEQEnabled
{
get
{
return _isEQEnabled;
}
}
private bool _isEQBypassed = false;
/// <summary>
/// Indicates if the EQ is bypassed.
/// </summary>
public bool IsEQBypassed
{
get
{
return _isEQBypassed;
}
}
private Loop _currentLoop = null;
/// <summary>
/// Defines the currently playing loop.
/// </summary>
public Loop Loop
{
get
{
return _currentLoop;
}
}
#endregion
#region Constructors, Initialization/Dispose
/// <summary>
/// Default constructor for the Player class. Initializes the player using the default
/// values (see property comments).
/// </summary>
public Player()
{
Initialize(new Device(), 44100, 1000, 10, true);
}
/// <summary>
/// Constructor for the Player class which requires the mixer sample rate value to be passed
/// in parameter.
/// </summary>
/// <param name="device">Device output</param>
/// <param name="mixerSampleRate">Mixer sample rate (default: 44100 Hz)</param>
/// <param name="bufferSize">Buffer size (default: 500 ms)</param>
/// <param name="updatePeriod">Update period (default: 10 ms)</param>
/// <param name="initializeDevice">Indicates if the device should be initialized</param>
public Player(Device device, int mixerSampleRate, int bufferSize, int updatePeriod, bool initializeDevice)
{
Initialize(device, mixerSampleRate, bufferSize, updatePeriod, initializeDevice);
}
/// <summary>
/// Initializes the player.
/// </summary>
/// <param name="device">Device output</param>
/// <param name="mixerSampleRate">Mixer sample rate (default: 44100 Hz)</param>
/// <param name="bufferSize">Buffer size (default: 500 ms)</param>
/// <param name="updatePeriod">Update period (default: 10 ms)</param>
/// <param name="initializeDevice">Indicates if the device should be initialized</param>
private void Initialize(Device device, int mixerSampleRate, int bufferSize, int updatePeriod, bool initializeDevice)
{
Player.CurrentPlayer = this;
_device = device;
_mixerSampleRate = mixerSampleRate;
_bufferSize = bufferSize;
_updatePeriod = updatePeriod;
_playlist = new Playlist();
_syncProcs = new List<PlayerSyncProc>();
#if !ANDROID
_useFloatingPoint = true;
#endif
_timerPlayer = new System.Timers.Timer();
_timerPlayer.Elapsed += new System.Timers.ElapsedEventHandler(timerPlayer_Elapsed);
_timerPlayer.Interval = 1000;
_timerPlayer.Enabled = false;
// Register BASS.NET
Base.Register(BassNetKey.Email, BassNetKey.RegistrationKey);
// Initialize BASS library by OS type
if (OS.Type == OSType.Windows)
{
// Load decoding plugins
//plugins = Base.LoadPluginDirectory(Path.GetDirectoryName((new Uri(Assembly.GetExecutingAssembly().CodeBase)).AbsolutePath));
Tracing.Log("Player init -- Loading plugins...");
//aacPluginHandle = Base.LoadPlugin("bass_aac.dll");
_apePluginHandle = Base.LoadPlugin("bass_ape.dll");
_flacPluginHandle = Base.LoadPlugin("bassflac.dll");
_mpcPluginHandle = Base.LoadPlugin("bass_mpc.dll");
//ofrPluginHandle = Base.LoadPlugin("bass_ofr.dll"); // Requires OptimFrog.DLL
//ttaPluginHandle = Base.LoadPlugin("bass_tta.dll");
_wmaPluginHandle = Base.LoadPlugin("basswma.dll");
_wvPluginHandle = Base.LoadPlugin("basswv.dll");
int bassFxVersion = Base.GetFxPluginVersion();
//Base.LoadFxPlugin();
}
else // Linux or Mac OS X
{
// Load BASS library
Tracing.Log("Player init -- Checking BASS library and plugin versions...");
int bassVersion = Base.GetBASSVersion();
int bassFxVersion = Base.GetFxPluginVersion();
int bassMixVersion = Base.GetMixPluginVersion();
Tracing.Log("Player init -- BASS Version: " + bassVersion);
Tracing.Log("Player init -- BASS FX Version: " + bassFxVersion);
Tracing.Log("Player init -- BASS Mix Version: " + bassMixVersion);
// Check OS type
Console.WriteLine("Player init -- OS is " + OS.Type.ToString());
if (OS.Type == OSType.Linux)
{
string pluginPath = string.Empty;
#if ANDROID
pluginPath = PluginDirectoryPath;
_aacPluginHandle = Base.LoadPlugin(Path.Combine(pluginPath, "libbass_aac.so"));
//_alacPluginHandle = Base.LoadPlugin(Path.Combine(pluginPath, "libbass_alac.so"));
_apePluginHandle = Base.LoadPlugin(Path.Combine(pluginPath, "libbass_ape.so"));
_flacPluginHandle = Base.LoadPlugin(Path.Combine(pluginPath, "libbassflac.so"));
_wvPluginHandle = Base.LoadPlugin(Path.Combine(pluginPath, "libbasswv.so"));
#else
// Find plugins either in current directory (i.e. development) or in a system directory (ex: /usr/lib/mpfm or /opt/lib/mpfm)
string exePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
// Check in the current directory first
if(!File.Exists(exePath + "/libbassflac.so"))
{
// Check in /usr/lib/mpfm
if(!File.Exists("/usr/lib/mpfm/libbassflac.so"))
{
// Check in /opt/lib/mpfm
if(!File.Exists("/opt/lib/mpfm/libbassflac.so"))
{
// The plugins could not be found!
throw new Exception("The BASS plugins could not be found either in the current directory, in /usr/lib/mpfm or in /opt/lib/mpfm!");
}
else
{
pluginPath = "/opt/lib/mpfm";
}
}
else
{
pluginPath = "/usr/lib/mpfm";
}
}
else
{
pluginPath = exePath;
}
// Load decoding plugins
_flacPluginHandle = Base.LoadPlugin(Path.Combine(pluginPath, "libbassflac.so"));
_wvPluginHandle = Base.LoadPlugin(Path.Combine(pluginPath, "libbasswv.so"));
_mpcPluginHandle = Base.LoadPlugin(Path.Combine(pluginPath, "libbass_mpc.so"));
#endif
}
else if (OS.Type == OSType.MacOSX)
{
#if IOS
// Load decoding plugins (http://www.un4seen.com/forum/?topic=13851.msg96559#msg96559)
Console.WriteLine("Loading iOS plugins (FLAC)...");
_flacPluginHandle = Base.LoadPlugin("BASSFLAC");
Console.WriteLine("Loading iOS plugins (WV)...");
_wvPluginHandle = Base.LoadPlugin("BASSWV");
Console.WriteLine("Loading iOS plugins (APE)...");
_apePluginHandle = Base.LoadPlugin("BASS_APE");
Console.WriteLine("Loading iOS plugins (MPC)...");
_mpcPluginHandle = Base.LoadPlugin("BASS_MPC");
Console.WriteLine("Configuring IOSNOTIFY delegate...");
_iosNotifyProc = new IOSNOTIFYPROC(IOSNotifyProc);
IntPtr ptr = Marshal.GetFunctionPointerForDelegate(_iosNotifyProc);
Bass.BASS_SetConfigPtr((BASSConfig)46, ptr);
//Bass.BASS_SetConfigPtr(BASSIOSConfig.BASS_CONFIG_IOS_NOTIFY, ptr);
Console.WriteLine("Configuring AirPlay and remote control...");
Bass.BASS_SetConfig(BASSConfig.BASS_CONFIG_IOS_MIXAUDIO, 0); // 0 = AirPlay
#else
// Try to get the plugins in the current path
Console.WriteLine("Loading OS X plugins...");
string exePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
string pluginPath = exePath.Replace("MonoBundle", "Resources");
// Check in the current directory first
if(!File.Exists(pluginPath + "/libbassflac.dylib"))
{
// The plugins could not be found!
throw new Exception("The BASS plugins could not be found in the current directory!");
}
// Load decoding plugins
_flacPluginHandle = Base.LoadPlugin(pluginPath + "/libbassflac.dylib");
_wvPluginHandle = Base.LoadPlugin(pluginPath + "/libbasswv.dylib");
_mpcPluginHandle = Base.LoadPlugin(pluginPath + "/libbass_mpc.dylib");
#endif
}
}
#if IOS
_bpmProc = new BPMPROC(BPMDetectionProcIOS);
//bpmBeatProc = new BPMBEATPROC(BPMDetectionBeatProcIOS);
#else
_bpmProc = new BPMPROC(BPMDetectionProc);
//bpmBeatProc = new BPMBEATPROC(BPMDetectionBeatProc);
#endif
// Create default EQ
Tracing.Log("Player init -- Creating default EQ preset...");
_currentEQPreset = new EQPreset();
if (initializeDevice)
{
Tracing.Log("Player init -- Initializing device...");
InitializeDevice(device, mixerSampleRate);
}
}
/// <summary>
/// Initializes the default audio device for playback.
/// </summary>
public void InitializeDevice()
{
InitializeDevice(new Device(), _mixerSampleRate);
}
/// <summary>
/// Initializes a specific audio device for playback.
/// </summary>
/// <param name="device">Audio device</param>
/// <param name="mixerSampleRate">Mixer sample rate (in Hz)</param>
public void InitializeDevice(Device device, int mixerSampleRate)
{
_device = device;
_mixerSampleRate = mixerSampleRate;
Tracing.Log("Player -- Initializing device (SampleRate: " + mixerSampleRate.ToString() + " Hz, DriverType: " + device.DriverType.ToString() + ", Id: " + device.Id.ToString() + ", Name: " + device.Name + ", BufferSize: " + _bufferSize.ToString() + ", UpdatePeriod: " + _updatePeriod.ToString() + ")");
// Check driver type
if (device.DriverType == DriverType.DirectSound)
{
// Initialize sound system
Base.Init(device.Id, mixerSampleRate, BASSInit.BASS_DEVICE_DEFAULT);
}
#if !IOS && !ANDROID
else if (device.DriverType == DriverType.ASIO)
{
// Initialize sound system
BaseASIO.Init(device.Id, mixerSampleRate, BASSInit.BASS_DEVICE_DEFAULT, BASSASIOInit.BASS_ASIO_THREAD);
}
else if (device.DriverType == DriverType.WASAPI)
{
// Create callback
wasapiProc = new WASAPIPROC(WASAPICallback);
// Initialize sound system
//Base.InitWASAPI(device.Id, mixerSampleRate, 2, BASSInit.BASS_DEVICE_DEFAULT, BASSWASAPIInit.BASS_WASAPI_SHARED, 10.0f, 0, wasapiProc);
BaseWASAPI.Init(device.Id, mixerSampleRate, 2, BASSInit.BASS_DEVICE_DEFAULT, BASSWASAPIInit.BASS_WASAPI_SHARED, 0.5f, 0, wasapiProc);
//Base.InitWASAPI(device.Id, mixerSampleRate, 2, BASSInit.BASS_DEVICE_DEFAULT, BASSWASAPIInit.BASS_WASAPI_EXCLUSIVE, 1, 0, wasapiProc);
//BASS_WASAPI_INFO info = BassWasapi.BASS_WASAPI_GetInfo();
}
#endif
// Default BASS.NET configuration values for Windows *AND* Linux:
//
// BASS_CONFIG_BUFFER: 500
// BASS_CONFIG_UPDATEPERIOD: 100
// BASS_CONFIG_UPDATETHREADS: 1
if(OS.Type == OSType.Windows)
{
// Set configuration for buffer and update period
// This only works for the default BASS output (http://www.un4seen.com/forum/?topic=13429.msg93740#msg93740)
Base.SetConfig(BASSConfig.BASS_CONFIG_BUFFER, _bufferSize);
Base.SetConfig(BASSConfig.BASS_CONFIG_UPDATEPERIOD, _updatePeriod);
}
else if (OS.Type == OSType.Linux)
{
// Default
// 10ms update period does not work under Linux. Major stuttering
Base.SetConfig(BASSConfig.BASS_CONFIG_BUFFER, _bufferSize);
Base.SetConfig(BASSConfig.BASS_CONFIG_UPDATEPERIOD, 100);
#if ANDROID
Base.SetConfig(BASSConfig.BASS_CONFIG_DEV_BUFFER, 500); // Default on Android: 30ms
#endif
}
else if (OS.Type == OSType.MacOSX)
{
// Default
// 10ms update period does not work under Linux. Major stuttering
Base.SetConfig(BASSConfig.BASS_CONFIG_BUFFER, _bufferSize);
Base.SetConfig(BASSConfig.BASS_CONFIG_UPDATEPERIOD, 100);
}
_isDeviceInitialized = true;
}
/// <summary>
/// Frees the device currently used for playback.
/// </summary>
public void FreeDevice()
{
if (!_isDeviceInitialized)
return;
#if !IOS && !ANDROID
// Check driver type
if (_device.DriverType == DriverType.ASIO)
{
// Free ASIO device
if (!BassAsio.BASS_ASIO_Free())
{
// Get error
BASSError error = Bass.BASS_ErrorGetCode();
throw new Exception("Error freeing ASIO device: " + error.ToString());
}
}
else if (_device.DriverType == DriverType.WASAPI)
{
// Free WASAPI device
if (!BassWasapi.BASS_WASAPI_Free())
{
// Get error
BASSError error = Bass.BASS_ErrorGetCode();
throw new Exception("Error freeing WASAPI device: " + error.ToString());
}
}
#endif
Base.Free();
_mixerChannel = null;
_device = null;
_isDeviceInitialized = false;
}
/// <summary>
/// Frees the BASS plugins used by the player.
/// </summary>
public void FreePlugins()
{
// Dispose plugins
//Base.FreeFxPlugin();
// Free plugins if they have been loaded successfully
if(_aacPluginHandle > 0)
Base.FreePlugin(_aacPluginHandle);
if(_apePluginHandle > 0)
Base.FreePlugin(_apePluginHandle);
if(_flacPluginHandle > 0)
Base.FreePlugin(_flacPluginHandle);
if(_mpcPluginHandle > 0)
Base.FreePlugin(_mpcPluginHandle);
if(_ofrPluginHandle > 0)
Base.FreePlugin(_ofrPluginHandle);
if(_ttaPluginHandle > 0)
Base.FreePlugin(_ttaPluginHandle);
if(_wvPluginHandle > 0)
Base.FreePlugin(_wvPluginHandle);
if(_wmaPluginHandle > 0)
Base.FreePlugin(_wmaPluginHandle);
}
/// <summary>
/// Disposes the current device and the audio plugins.
/// </summary>
public void Dispose()
{
FreeDevice();
FreePlugins();
}
#endregion
#region Timers
/// <summary>
/// Occurs when the timer for loading the next song in advance expires.
/// </summary>
/// <param name="sender">Event sender</param>
/// <param name="e">Event arguments</param>
protected void timerPlayer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
if (_timerPlayer != null)
{
_timerPlayer.Enabled = false;
// Check if the next channel needs to be loaded
if (_playlist.CurrentItemIndex < _playlist.Items.Count - 1)
{
// Check if the channel has already been loaded
if (!_playlist.Items[_playlist.CurrentItemIndex + 1].IsLoaded)
_playlist.Items[_playlist.CurrentItemIndex + 1].Load(_useFloatingPoint);
}
}
// Set time shifting value
//m_currentSubChannel.Channel.SetAttribute(BASSAttribute.BASS_ATTRIB_TEMPO, TimeShifting);
}
#endregion
#region Playback Methods
/// <summary>
/// Plays the playlist from the current item index.
/// </summary>
public void Play()
{
try
{
if (_isPlaying)
{
if (_currentLoop != null)
{
Tracing.Log("Player.Play -- Stopping current loop...");
StopLoop();
}
Tracing.Log("Player.Play -- Stopping playback...");
Stop();
}
RemoveSyncCallbacks();
_currentLoop = null;
_positionOffset = 0;
_currentMixPlaylistIndex = Playlist.CurrentItemIndex;
// How many channels are left?
int channelsToLoad = Playlist.Items.Count - Playlist.CurrentItemIndex;
// If there are more than 2, just limit to 2 for now. The other channels are loaded dynamically.
if (channelsToLoad > 2)
channelsToLoad = 2;
// Check for channels to load
if (channelsToLoad == 0)
throw new Exception("Error in Player.Play: There aren't any channels to play!");
// Load the current channel and the next channel if it exists
for (int a = Playlist.CurrentItemIndex; a < Playlist.CurrentItemIndex + channelsToLoad; a++)
_playlist.Items[a].Load(_useFloatingPoint);
// Start decoding first playlist item
//playlist.Items[Playlist.CurrentItemIndex].Decode(0);
try
{
// Create the streaming channel (set the frequency to the first file in the list)
Tracing.Log("Player.Play -- Creating streaming channel (SampleRate: " + _playlist.CurrentItem.AudioFile.SampleRate + " Hz, FloatingPoint: true)...");
#if IOS
_streamProc = new STREAMPROC(StreamCallbackIOS);
#else
_streamProc = new STREAMPROC(StreamCallback);
#endif
_streamChannel = Channel.CreateStream(_playlist.CurrentItem.AudioFile.SampleRate, 2, _useFloatingPoint, _streamProc);
Tracing.Log("Player.Play -- Creating time shifting channel...");
_fxChannel = Channel.CreateStreamForTimeShifting(_streamChannel.Handle, true, _useFloatingPoint);
}
catch(Exception ex)
{
// Raise custom exception with information (so the client application can maybe deactivate floating point for example)
PlayerCreateStreamException newEx = new PlayerCreateStreamException("The player has failed to create the stream channel (" + ex.Message + ").", ex);
newEx.Decode = true;
newEx.UseFloatingPoint = true;
newEx.SampleRate = _playlist.CurrentItem.AudioFile.SampleRate;
throw newEx;
}
// Check driver type
if (_device.DriverType == DriverType.DirectSound)
{
try
{
// Create mixer stream
Tracing.Log("Player.Play -- Creating mixer channel (DirectSound)...");
_mixerChannel = MixerChannel.CreateMixerStream(_playlist.CurrentItem.AudioFile.SampleRate, 2, _useFloatingPoint, false);
_mixerChannel.AddChannel(_fxChannel.Handle);
AddBPMCallbacks();
}
catch (Exception ex)
{
// Raise custom exception with information (so the client application can maybe deactivate floating point for example)
PlayerCreateStreamException newEx = new PlayerCreateStreamException("The player has failed to create the time shifting channel.", ex);
newEx.UseFloatingPoint = true;
newEx.UseTimeShifting = true;
newEx.SampleRate = _playlist.CurrentItem.AudioFile.SampleRate;
throw newEx;
}
}
#if !IOS && !ANDROID
else if (_device.DriverType == DriverType.ASIO)
{
try
{
// Create mixer stream
Tracing.Log("Player.Play -- Creating mixer channel (ASIO)...");
_mixerChannel = MixerChannel.CreateMixerStream(_playlist.CurrentItem.AudioFile.SampleRate, 2, _useFloatingPoint, true);
_mixerChannel.AddChannel(_fxChannel.Handle);
}
catch (Exception ex)
{
// Raise custom exception with information (so the client application can maybe deactivate floating point for example)
PlayerCreateStreamException newEx = new PlayerCreateStreamException("The player has failed to create the time shifting channel.", ex);
newEx.DriverType = DriverType.ASIO;
newEx.UseFloatingPoint = true;
newEx.UseTimeShifting = true;
newEx.Decode = true;
newEx.SampleRate = _playlist.CurrentItem.AudioFile.SampleRate;
throw newEx;
}
// Set floating point
BassAsio.BASS_ASIO_ChannelSetFormat(false, 0, BASSASIOFormat.BASS_ASIO_FORMAT_FLOAT);
// Create callback
asioProc = new ASIOPROC(AsioCallback);
try
{
// Enable and join channels (for stereo output
Tracing.Log("Player.Play -- Enabling ASIO channels...");
BassAsio.BASS_ASIO_ChannelEnable(false, 0, asioProc, new IntPtr(_mixerChannel.Handle));
Tracing.Log("Player.Play -- Joining ASIO channels...");
BassAsio.BASS_ASIO_ChannelJoin(false, 1, 0);
// Set sample rate
Tracing.Log("Player.Play -- Set ASIO sample rates...");
BassAsio.BASS_ASIO_ChannelSetRate(false, 0, _playlist.CurrentItem.AudioFile.SampleRate);
BassAsio.BASS_ASIO_SetRate(_playlist.CurrentItem.AudioFile.SampleRate);
}
catch (Exception ex)
{
// Raise custom exception with information (so the client application can maybe deactivate floating point for example)
PlayerCreateStreamException newEx = new PlayerCreateStreamException("The player has failed to enable or join ASIO channels.", ex);
newEx.DriverType = DriverType.ASIO;
newEx.SampleRate = _playlist.CurrentItem.AudioFile.SampleRate;
throw newEx;
}
// Start playback
Tracing.Log("Player.Play -- Starting ASIO buffering...");
if (!BassAsio.BASS_ASIO_Start(0))
{
// Get BASS error
BASSError error = Bass.BASS_ErrorGetCode();