-
Notifications
You must be signed in to change notification settings - Fork 348
Expand file tree
/
Copy pathBassAudioManager.cs
More file actions
789 lines (656 loc) · 27.4 KB
/
Copy pathBassAudioManager.cs
File metadata and controls
789 lines (656 loc) · 27.4 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
using System;
using System.Collections.Generic;
using System.IO;
using ManagedBass;
using ManagedBass.Fx;
using ManagedBass.Mix;
using UnityEngine;
using YARG.Core.Audio;
using YARG.Core.Logging;
using YARG.Menu.Persistent;
using YARG.Settings;
#if UNITY_EDITOR
using UnityEditor;
#endif
namespace YARG.Audio.BASS
{
internal class StreamHandle : IDisposable
{
#nullable enable
public static StreamHandle? Create(int sourceStream, int[] indices)
{
const BassFlags splitFlags = BassFlags.Decode | BassFlags.SplitPosition;
int[]? channelMap = null;
#nullable disable
if (indices.Length > 0)
{
channelMap = new int[indices.Length + 1];
for (int i = 0; i < indices.Length; ++i)
{
channelMap[i] = indices[i];
}
channelMap[indices.Length] = -1;
}
int streamSplit = BassMix.CreateSplitStream(sourceStream, splitFlags, channelMap);
if (streamSplit == 0)
{
YargLogger.LogFormatError("Failed to create split stream: {0}!", Bass.LastError);
return null;
}
return new StreamHandle(streamSplit);
}
private bool _disposed;
public readonly int Stream;
#pragma warning disable CS0649
public int CompressorFX;
public int PitchFX;
public int ReverbFX;
public int LowEQ;
public int MidEQ;
public int HighEQ;
#pragma warning restore CS0649
private StreamHandle(int stream)
{
Stream = stream;
}
private void Dispose(bool disposing)
{
if (!_disposed)
{
// FX handles are freed automatically, we only need to free the stream
if (!Bass.StreamFree(Stream))
{
YargLogger.LogFormatError("Failed to free channel stream (THIS WILL LEAK MEMORY): {0}!", Bass.LastError);
}
_disposed = true;
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
~StreamHandle()
{
Dispose(false);
}
}
public class BassAudioManager : AudioManager
{
private static readonly string[] FORMATS =
{
".ogg", ".mogg", ".wav", ".mp3", ".aiff", ".opus",
};
protected override ReadOnlySpan<string> SupportedFormats => FORMATS;
private readonly int _opusHandle = 0;
private BassOutputDevice _currentDevice;
public BassAudioManager()
{
YargLogger.LogInfo("Initializing BASS...");
string bassPath = GetBassDirectory();
string opusLibDirectory = Path.Combine(bassPath, "bassopus");
_opusHandle = Bass.PluginLoad(opusLibDirectory);
if (_opusHandle == 0) YargLogger.LogFormatError("Failed to load .opus plugin: {0}!", Bass.LastError);
Bass.Configure(Configuration.IncludeDefaultDevice, true);
Bass.UpdatePeriod = 5;
//Bass.PlaybackBufferLength = BassHelpers.PLAYBACK_BUFFER_LENGTH;
Bass.DeviceNonStop = true;
Bass.AsyncFileBufferLength = 65536;
// This not the same as Bass.UpdatePeriod
// If not explicitly set by the audio driver or OS, the default will be 10
// https://www.un4seen.com/doc/#bass/BASS_CONFIG_DEV_PERIOD.html
int devPeriod = Bass.GetConfig(Configuration.DevicePeriod);
// Documentation recommends setting the device buffer to at least 2x the device period
// https://www.un4seen.com/doc/#bass/BASS_CONFIG_DEV_BUFFER.html
Bass.DeviceBufferLength = 2 * devPeriod;
// Affects Windows only. Forces device names to be in UTF-8 on Windows rather than ANSI.
Bass.UnicodeDeviceInformation = true;
Bass.FloatingPointDSP = true;
Bass.VistaTruePlayPosition = false;
Bass.UpdateThreads = GlobalAudioHandler.MAX_THREADS;
// Undocumented BASS_CONFIG_MP3_OLDGAPS config.
Bass.Configure((Configuration) 68, 1);
// Disable undocumented BASS_CONFIG_DEV_TIMEOUT config. Prevents pausing audio output if a device times out.
Bass.Configure((Configuration) 70, false);
int deviceCount = Bass.DeviceCount;
YargLogger.LogFormatInfo("Devices found: {0}", deviceCount);
#if UNITY_EDITOR
// Free BASS if it's already initialized (happens when stopping play mode in editor)
if (Bass.CurrentDevice != -1)
{
YargLogger.LogInfo("BASS already initialized, cleaning up first");
Bass.PluginFree(0);
Bass.Free();
}
#endif
var result = SetOutputDevice("Default");
if (!result)
{
var error = Bass.LastError;
YargLogger.LogFormatError("BASS Initialization Failure: Failed to set default output device: {0}", error);
#if UNITY_STANDALONE_LINUX
// Driver seems to be what we get when ALSA isn't available
if (error == Errors.Driver)
{
YargLogger.LogError("Failed to set default output device. This is likely due to a missing ALSA plugin. Install pipewire-alsa or equivalent.");
ToastManager.ToastError("Failed to initialize audio device. Make sure you have pipewire-alsa or equivalent installed.");
}
#endif
return;
}
var info = Bass.Info;
UpdatePlaybackLatency();
MinimumBufferLength = info.MinBufferLength + Bass.UpdatePeriod;
MaximumBufferLength = 5000;
YargLogger.LogInfo("BASS Successfully Initialized");
YargLogger.LogFormatInfo("BASS: {0} - BASS.FX: {1} - BASS.Mix: {2}", Bass.Version, BassFx.Version, BassMix.Version);
YargLogger.LogFormatInfo("Update Period: {0}ms. Device Buffer Length: {1}ms. Playback Buffer Length: {2}ms. Device Playback Latency: {3}ms",
Bass.UpdatePeriod, Bass.DeviceBufferLength, Bass.PlaybackBufferLength, PlaybackLatency);
YargLogger.LogFormatInfo("Current Device: {0}", Bass.GetDeviceInfo(Bass.CurrentDevice).Name);
}
private void UpdatePlaybackLatency()
{
double playbackLatency = BassLatencyProvider.GetPlaybackStreamLatency();
PlaybackLatency = (int) Math.Round(playbackLatency * 1000.0);
}
protected override bool SetOutputDevice(string name)
{
int currentDevice = Bass.CurrentDevice;
var device = GetOutputDevice(name);
if (device is not BassOutputDevice bassDevice || bassDevice.DeviceId == currentDevice)
{
return false;
}
YargLogger.LogFormatInfo("Changing BASS Device to: {0}", bassDevice.DisplayName);
base.SetOutputDevice(bassDevice.DisplayName);
_currentDevice?.Dispose();
_currentDevice = bassDevice.Use();
UpdatePlaybackLatency();
YargLogger.LogFormatInfo("Current BASS Device: {0}", Bass.GetDeviceInfo(Bass.CurrentDevice).Name);
// Load/reload samples
LoadSfx();
LoadDrumSfx(); // TODO: move drum sfx loading/disposal to song start/end respectively IF there are any drum players
LoadVox();
LoadMetronome();
return true;
}
#nullable enable
protected override StemMixer? CreateMixer(string name, float speed, double mixerVolume, bool clampStemVolume, bool normalize)
{
if (GlobalAudioHandler.LogMixerStatus)
{
YargLogger.LogDebug("Loading song");
}
if (!CreateMixerHandle(out int handle))
{
return null;
}
return new BassStemMixer(name, this, speed, mixerVolume, handle, clampStemVolume: clampStemVolume,
normalize: normalize, outputChannel: CreateOutputChannel(SettingsManager.Settings?.OutputChannelDefault.Value ?? 0));
}
protected override MicDevice? GetInputDevice(string name)
{
for (int deviceIndex = 0; Bass.RecordGetDeviceInfo(deviceIndex, out var info); deviceIndex++)
{
// Ignore disabled/claimed devices
if (!info.IsEnabled || info.IsInitialized)
{
continue;
}
// Ignore loopback devices, they're potentially confusing and can cause feedback loops
if (info.IsLoopback)
{
continue;
}
// Check if type is in whitelist
// The "Default" device is also excluded here since we want the user to explicitly pick which microphone to use
// if (!typeWhitelist.Contains(info.Type) || info.Name == "Default") continue;
if (info.Name == "Default" || info.Name != name)
{
continue;
}
return CreateInputDevice(deviceIndex, name);
}
return null;
}
#nullable disable
protected override List<(int id, string name)> GetAllInputDevices()
{
var mics = new List<(int id, string name)>();
// Ignored for now since it causes issues on Linux, BASS must not report device info correctly there
// TODO: allow configuring this at runtime?
// Also put into a static variable instead of instantiating every time
// var typeWhitelist = new List<DeviceType>()
// {
// DeviceType.Headset,
// DeviceType.Digital,
// DeviceType.Line,
// DeviceType.Headphones,
// DeviceType.Microphone,
// };
for (int deviceIndex = 0; Bass.RecordGetDeviceInfo(deviceIndex, out var info); deviceIndex++)
{
// Ignore disabled/claimed devices
if (!info.IsEnabled || info.IsInitialized)
{
continue;
}
// Ignore loopback devices, they're potentially confusing and can cause feedback loops
if (info.IsLoopback)
{
continue;
}
// Check if type is in whitelist
// The "Default" device is also excluded here since we want the user to explicitly pick which microphone to use
// if (!typeWhitelist.Contains(info.Type) || info.Name == "Default") continue;
if (info.Name == "Default")
{
continue;
}
mics.Add((deviceIndex, info.Name));
}
return mics;
}
#nullable enable
protected override MicDevice? CreateInputDevice(int deviceId, string name)
#nullable disable
{
var device = BassMicDevice.Create(deviceId, name);
device?.SetMonitoringLevel(SettingsManager.Settings.VocalMonitoring.Value);
return device;
}
#nullable enable
protected override OutputChannel? CreateOutputChannel(int channelId)
#nullable disable
{
return BassOutputChannel.Create(channelId);
}
#nullable enable
protected override OutputDevice? CreateOutputDevice(int deviceId, string name)
#nullable disable
{
return BassOutputDevice.Create(deviceId, name);
}
protected override List<(int id, string name)> GetAllOutputDevices()
{
var devices = new List<(int id, string name)>();
for (int deviceIndex = 1; Bass.GetDeviceInfo(deviceIndex, out var info); deviceIndex++)
{
// Ignore disabled devices
if (!info.IsEnabled)
{
continue;
}
// Ignore loopback devices, they're potentially confusing and can cause feedback loops
if (info.IsLoopback)
{
continue;
}
devices.Add((deviceIndex, info.Name));
}
return devices;
}
protected override int GetOutputChannelCount()
{
return BassHelpers.GetOutputChannelCount();
}
#nullable enable
protected override OutputDevice? GetOutputDevice(string name)
#nullable disable
{
for (int deviceIndex = 0; Bass.GetDeviceInfo(deviceIndex, out var info); deviceIndex++)
{
// Ignore disabled devices
if (!info.IsEnabled)
{
continue;
}
// Ignore loopback devices, they're potentially confusing and can cause feedback loops
if (info.IsLoopback)
{
continue;
}
// Ensure device names match
if (info.Name != name)
{
continue;
}
return CreateOutputDevice(deviceIndex, name);
}
return null;
}
private void LoadSfx()
{
YargLogger.LogInfo("Loading SFX");
#nullable enable
foreach (BassSampleChannel? sample in SfxSamples)
#nullable disable
{
sample?.Dispose();
}
SfxSamples = new SampleChannel[AudioHelpers.SfxSamples.Count];
string sfxFolder = Path.Combine(Application.streamingAssetsPath, "sfx");
foreach (var sample in AudioHelpers.SfxSamples)
{
var sfxFile = sample.File;
string sfxBase = Path.Combine(sfxFolder, sfxFile);
foreach (string format in SupportedFormats)
{
string sfxPath = sfxBase + format;
if (File.Exists(sfxPath))
{
var sfxSample = sample.Kind;
var sfx = BassSampleChannel.Create(sfxSample, sfxPath, 8,
CreateOutputChannel(SettingsManager.Settings?.OutputChannelSfx.Value ?? 0), sample.CanLoop);
if (sfx != null)
{
SfxSamples[(int) sfxSample] = sfx;
YargLogger.LogFormatInfo("Loaded {0}", sfxFile);
}
break;
}
}
}
YargLogger.LogInfo("Finished loading SFX");
}
private void LoadDrumSfx()
{
YargLogger.LogInfo("Loading Drum SFX");
#nullable enable
foreach (BassDrumSampleChannel? sample in DrumSfxSamples)
#nullable disable
{
sample?.Dispose();
}
DrumSfxSamples = new DrumSampleChannel[AudioHelpers.DrumSamples.Count];
string sfxFolder = Path.Combine(Application.streamingAssetsPath, "drumSfx");
foreach (var sample in AudioHelpers.DrumSamples)
{
string sfxBase = Path.Combine(sfxFolder, sample.File);
foreach (string format in SupportedFormats)
{
string sfxPath = sfxBase + format;
if (File.Exists(sfxPath))
{
var sfxSample = sample.Kind;
var sfx = BassDrumSampleChannel.Create(sfxSample, sfxPath, 8,
CreateOutputChannel(SettingsManager.Settings?.OutputChannelDrumSfx.Value ?? 0));
if (sfx != null)
{
DrumSfxSamples[(int) sfxSample] = sfx;
}
break;
}
}
}
YargLogger.LogInfo("Finished loading Drum SFX");
}
private void LoadVox()
{
YargLogger.LogInfo("Loading VOX");
#nullable enable
foreach (BassVoxSampleChannel? sample in VoxSamples)
#nullable disable
{
sample?.Dispose();
}
VoxSamples = new VoxSampleChannel[AudioHelpers.VoxSamples.Count];
string voxFolder = Path.Combine(Application.streamingAssetsPath, "vox");
foreach (var sample in AudioHelpers.VoxSamples)
{
string voxBase = Path.Combine(voxFolder, sample.File);
foreach (string format in SupportedFormats)
{
string voxPath = voxBase + format;
if (File.Exists(voxPath))
{
var voxSample = sample.Kind;
var vox = BassVoxSampleChannel.Create(voxSample, voxPath,
CreateOutputChannel(SettingsManager.Settings?.OutputChannelVox.Value ?? 0));
if (vox != null)
{
VoxSamples[(int) voxSample] = vox;
}
break;
}
}
}
YargLogger.LogInfo("Finished loading VOX");
}
private void LoadMetronome()
{
YargLogger.LogInfo("Loading Metronome");
#nullable enable
foreach (BassMetronomeSampleChannel? sample in MetronomeSamples)
#nullable disable
{
sample?.Dispose();
}
MetronomeSamples = new MetronomeSampleChannel[AudioHelpers.MetronomeSamples.Count];
string metronomeFolder = Path.Combine(Application.streamingAssetsPath, "metronome");
foreach (var sample in AudioHelpers.MetronomeSamples)
{
string metronomeHi = Path.Combine(metronomeFolder, sample.File);
string metronomeLo = Path.Combine(metronomeFolder, sample.AlternateFile);
string metronomeHiPath = "";
string metronomeLoPath = "";
foreach (string format in SupportedFormats)
{
if (File.Exists(metronomeHi + format))
{
metronomeHiPath = metronomeHi + format;
}
if (File.Exists(metronomeLo + format))
{
metronomeLoPath = metronomeLo + format;
}
}
if (!String.IsNullOrEmpty(metronomeHiPath) && !String.IsNullOrEmpty(metronomeLoPath))
{
var metronomeSample = sample.Kind;
var metronome = BassMetronomeSampleChannel.Create(metronomeSample, metronomeHiPath, metronomeLoPath,
CreateOutputChannel(SettingsManager.Settings?.OutputChannelDefault.Value ?? 0));
if (metronome != null)
{
MetronomeSamples[(int) metronomeSample] = metronome;
}
}
}
YargLogger.LogInfo("Finished loading Metronome");
}
public override void LoadVenueSample(string name, byte[] sampleData, OutputChannel? outputChannel = null)
{
VenueSamples[name] = BassVenueSampleChannel.Create(name, sampleData, outputChannel);
}
public override void ClearVenueSamples()
{
foreach(var sample in VenueSamples.Values)
{
sample.Stop();
sample.Dispose();
}
VenueSamples.Clear();
}
protected override void SetMasterVolume(double volume)
{
#if UNITY_EDITOR
if (EditorUtility.audioMasterMute)
volume = 0;
#endif
Bass.GlobalStreamVolume = (int) (10_000 * volume);
Bass.GlobalSampleVolume = (int) (10_000 * volume);
}
protected override void SetBufferLength_Internal(int length)
{
Bass.PlaybackBufferLength = length;
}
protected override void DisposeUnmanagedResources()
{
YargLogger.LogInfo("Unloading BASS plugins");
Bass.PluginFree(0);
Bass.Free();
}
private static string GetBassDirectory()
{
string pluginDirectory = Path.Combine(Application.dataPath, "Plugins");
// Locate windows directory
// Checks if running on 64 bit and sets the path accordingly
#if !UNITY_EDITOR && UNITY_STANDALONE_WIN
#if UNITY_64
pluginDirectory = Path.Combine(pluginDirectory, "x86_64");
#else
pluginDirectory = Path.Combine(pluginDirectory, "x86");
#endif
#endif
// Unity Editor directory, Assets/Plugins/Bass/
#if UNITY_EDITOR
pluginDirectory = Path.Combine(pluginDirectory, "BassNative");
#endif
// Editor paths differ to standalone paths, as the project contains platform specific folders
#if UNITY_EDITOR_WIN
pluginDirectory = Path.Combine(pluginDirectory, "Windows/x86_64");
#elif UNITY_EDITOR_OSX
pluginDirectory = Path.Combine(pluginDirectory, "Mac");
#elif UNITY_EDITOR_LINUX
pluginDirectory = Path.Combine(pluginDirectory, "Linux/x86_64");
#endif
return pluginDirectory;
}
private static bool CreateMixerHandle(out int mixerHandle)
{
// The float flag allows >0dB signals.
// Note that the compressor attempts to normalize signals >-2dB, but some mixes will pierce through.
mixerHandle = BassMix.CreateMixerStream(44100, 2, BassFlags.Float | BassFlags.Decode);
if (mixerHandle == 0)
{
YargLogger.LogFormatError("Failed to create mixer: {0}!", Bass.LastError);
return false;
}
int compressorFX = BassHelpers.AddCompressorToChannel(mixerHandle);
if (compressorFX == 0)
{
YargLogger.LogError("Failed to set up compressor for mixer stream!");
}
return true;
}
internal static bool CreateSourceStream(Stream stream, out int streamHandle)
{
// Last flag is new BASS_SAMPLE_NOREORDER flag, which is not in the BassFlags enum,
// as it was made as part of an update to fix <= 8 channel oggs.
// https://www.un4seen.com/forum/?topic=20148.msg140872#msg140872
const BassFlags streamFlags = BassFlags.Prescan | BassFlags.Decode | BassFlags.AsyncFile | (BassFlags) 64;
streamHandle = Bass.CreateStream(StreamSystem.NoBuffer, streamFlags, new BassStreamProcedures(stream));
if (streamHandle == 0)
{
YargLogger.LogFormatError("Failed to create source stream: {0}!", Bass.LastError);
return false;
}
return true;
}
internal static bool GetSpeed(int streamHandle, out float speed)
{
if (!Bass.ChannelGetAttribute(streamHandle, ChannelAttribute.Tempo, out float relativeSpeed))
{
speed = 0;
YargLogger.LogFormatError("Failed to get channel speed: {0}", Bass.LastError);
return false;
}
// Turn relative speed into percentage speed
float percentageSpeed = relativeSpeed + 100;
speed = percentageSpeed / 100;
return true;
}
internal static void SetSpeed(float speed, int streamHandle, bool shiftPitch)
{
// Gets relative speed from 100% (so 1.05f = 5% increase)
float percentageSpeed = speed * 100;
float relativeSpeed = percentageSpeed - 100;
if (!Bass.ChannelSetAttribute(streamHandle, ChannelAttribute.Tempo, relativeSpeed))
{
YargLogger.LogFormatError("Failed to set channel speed: {0}!", Bass.LastError);
}
if (GlobalAudioHandler.IsChipmunkSpeedup && shiftPitch)
{
SetChipmunking(speed, streamHandle);
}
}
#nullable enable
internal static (StreamHandle Stream, StreamHandle Reverb)? CreateSplitStreams(int sourceStream, int[] channelMap)
#nullable disable
{
var streamHandles = StreamHandle.Create(sourceStream, channelMap);
if (streamHandles == null)
{
return null;
}
var reverbHandles = StreamHandle.Create(sourceStream, channelMap);
if (reverbHandles == null)
{
streamHandles.Dispose();
return null;
}
return (streamHandles, reverbHandles);
}
internal static PitchShiftParametersStruct SetPitchParams(SongStem stem, float speed, StreamHandle streamHandles, StreamHandle reverbHandles)
{
PitchShiftParametersStruct pitchParams = new(1, 0, GlobalAudioHandler.WHAMMY_FFT_DEFAULT, GlobalAudioHandler.WHAMMY_OVERSAMPLE_DEFAULT);
// Set whammy pitch bending if enabled
if (GlobalAudioHandler.UseWhammyFx && AudioHelpers.PitchBendAllowedStems.Contains(stem))
{
// Setting the FFT size causes a crash in BASS_FX :/
// _pitchParams.FFTSize = _manager.Options.WhammyFFTSize;
pitchParams.OversampleFactor = GlobalAudioHandler.WhammyOversampleFactor;
if (SetupPitchBend(pitchParams, streamHandles))
{
SetupPitchBend(pitchParams, reverbHandles);
}
}
return pitchParams;
}
internal static void SetChipmunking(float speed, int streamHandle)
{
double accurateSemitoneShift = 12 * Math.Log(speed, 2);
float finalSemitoneShift = (float) Math.Clamp(accurateSemitoneShift, -60, 60);
if (!Bass.ChannelSetAttribute(streamHandle, ChannelAttribute.Pitch, finalSemitoneShift))
{
YargLogger.LogFormatError("Failed to set channel pitch: {0}!", Bass.LastError);
}
}
internal static bool SetupPitchBend(in PitchShiftParametersStruct pitchParams, StreamHandle handles)
{
handles.PitchFX = BassHelpers.FXAddParameters(handles.Stream, EffectType.PitchShift, pitchParams);
if (handles.PitchFX == 0)
{
YargLogger.LogError("Failed to set up pitch bend for main stream!");
return false;
}
return true;
}
internal static double GetLengthInSeconds(int handle)
{
long length = Bass.ChannelGetLength(handle);
if (length < 0)
{
YargLogger.LogFormatError("Failed to get channel length in bytes: {0}!", Bass.LastError);
return -1;
}
double seconds = Bass.ChannelBytes2Seconds(handle, length);
if (seconds < 0)
{
YargLogger.LogFormatError("Failed to get channel length in seconds: {0}!", Bass.LastError);
return -1;
}
return seconds;
}
private const double BASE = 2;
private const double FACTOR = BASE - 1;
internal static double ExponentialVolume(double volume)
{
return (Math.Pow(BASE, volume) - 1) / FACTOR;
}
internal static double LogarithmicVolume(double volume)
{
return Math.Log(FACTOR * volume + 1, BASE);
}
}
}