-
Notifications
You must be signed in to change notification settings - Fork 69
Expand file tree
/
Copy pathAudio.cpp
More file actions
752 lines (593 loc) · 24 KB
/
Audio.cpp
File metadata and controls
752 lines (593 loc) · 24 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
/*
===========================================================================
Daemon BSD Source Code
Copyright (c) 2013-2016, Daemon Developers
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Daemon developers nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL DAEMON DEVELOPERS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
===========================================================================
*/
#include <common/FileSystem.h>
#include "framework/CvarSystem.h"
#include "AudioPrivate.h"
#include "AudioData.h"
namespace Audio {
/* When adding an entry point to the audio subsystem,
make sure the non-null implementation returns early
when audio subsystem is not initialized.
See https://github.com/DaemonEngine/Daemon/pull/524 */
Log::Logger audioLogs("audio");
static Cvar::Range<Cvar::Cvar<float>> masterVolume("audio.volume.master", "the global audio volume", Cvar::ARCHIVE, 0.8f, 0.0f, 1.0f);
static Cvar::Range<Cvar::Cvar<float>> musicVolume("audio.volume.music", "the volume of the music", Cvar::NONE, 0.8f, 0.0f, 1.0f);
static Cvar::Cvar<bool> muteWhenMinimized("audio.muteWhenMinimized", "should the game be muted when minimized", Cvar::NONE, false);
static Cvar::Cvar<bool> muteWhenUnfocused("audio.muteWhenUnfocused", "should the game be muted when not focused", Cvar::NONE, false);
static Cvar::Cvar<std::string> deviceString("audio.al.device", "the OpenAL device to use", Cvar::ARCHIVE, "");
static Cvar::Cvar<std::string> availableDevices("audio.al.availableDevices", "the available OpenAL devices", Cvar::ROM, "");
static Cvar::Cvar<std::string> availableCaptureDevices("audio.al.availableCaptureDevices", "the available capture OpenAL devices", Cvar::ROM, "");
// We mimic the behavior of the previous sound system by allowing only one looping sound per entity.
// (and only one entities) CGame will add at each frame all the loops: if a loop hasn't been given
// in a frame, it means it sould be destroyed.
struct entityLoop_t {
bool addedThisFrame;
bool persistent;
std::shared_ptr<LoopingSound> sound;
sfxHandle_t newSfx;
sfxHandle_t oldSfx;
};
struct EntityMultiLoop {
entityLoop_t loops[MAX_ENTITY_SOUNDS];
entityLoop_t& FindSlot( const sfxHandle_t sfx ) {
uint32_t bestSlot = 0;
float minGain = FLT_MAX;
for ( entityLoop_t& loop : loops ) {
if ( sfx == loop.oldSfx ) {
return loop;
}
if ( !loop.sound ) {
return loop;
}
if ( loop.sound->currentGain < minGain ) {
bestSlot = &loop - loops;
minGain = loop.sound->currentGain;
}
}
return loops[bestSlot];
}
void StopAll() {
for ( entityLoop_t& loop : loops ) {
if ( loop.sound ) {
loop.sound->Stop();
}
loop = { false, false, nullptr, -1, -1 };
}
}
void ResetAll() {
for ( entityLoop_t& loop : loops ) {
loop = { false, false, nullptr, -1, -1 };
}
}
void ClearLoopingSounds() {
for ( entityLoop_t& loop : loops ) {
if ( loop.sound ) {
loop.addedThisFrame = false;
}
}
}
};
static EntityMultiLoop entityLoops[MAX_GENTITIES];
static std::shared_ptr<StreamingSound> streams[N_STREAMS];
static bool initialized = false;
int playerClientNum;
static AL::Device* device;
static AL::Context* context;
void CaptureTestStop();
void CaptureTestUpdate();
// Like in the previous sound system, we only have a single music
std::shared_ptr<LoopingSound> music;
bool IsValidEntity(int entityNum) {
return entityNum >= 0 and entityNum < MAX_GENTITIES;
}
bool IsValidVector(Vec3 v) {
return Math::IsFinite(v[0]) && Math::IsFinite(v[1]) && Math::IsFinite(v[2]);
}
bool Init() {
if (initialized) {
return true;
}
// Initializes a device
Cvar::Latch(deviceString);
std::string deviceToTry = deviceString.Get();
if (not deviceToTry.empty()) {
device = AL::Device::FromName(deviceToTry);
if (not device) {
Log::Warn("Could not open OpenAL device '%s', trying the default device.", deviceToTry);
device = AL::Device::GetDefaultDevice();
}
} else {
device = AL::Device::GetDefaultDevice();
}
if (not device) {
Log::Warn("Could not open an OpenAL device.");
return false;
}
// Initializes a context
context = AL::Context::GetDefaultContext(*device);
if (not context) {
delete device;
device = nullptr;
Log::Warn("Could not create an OpenAL context.");
return false;
}
std::stringstream deviceList;
for (const auto& deviceName : AL::Device::ListByName()) {
deviceList << deviceName << "\n";
}
Cvar::SetValueForce(availableDevices.Name(), deviceList.str());
context->MakeCurrent();
// Initializes the list of input devices
std::stringstream captureDeviceList;
for (const auto& captureDeviceName : AL::CaptureDevice::ListByName()) {
captureDeviceList << captureDeviceName << "\n";
}
Cvar::SetValueForce(availableCaptureDevices.Name(), captureDeviceList.str());
audioLogs.Notice(AL::GetSystemInfo(device, nullptr));
initialized = true;
// Initializes the rest of the audio system
AL::InitEffectPresets();
InitSamples();
InitSounds();
InitEmitters();
UpdateListenerGain();
for ( EntityMultiLoop& loop : entityLoops ) {
loop.ResetAll();
}
return true;
}
void Shutdown() {
if (not initialized) {
return;
}
// Shuts down the wrapper
for ( EntityMultiLoop& loop : entityLoops ) {
loop.StopAll();
}
StopMusic();
CaptureTestStop();
StopCapture();
// Shuts down the rest of the system
// Shutdown sounds before emitters because they are using a effects defined in emitters
// and that OpenAL checks the refcount before deleting the object.
ShutdownSounds();
ShutdownEmitters();
ShutdownSamples();
// Free OpenAL resources
delete context;
delete device;
context = nullptr;
device = nullptr;
initialized = false;
}
void Update() {
if (not initialized) {
return;
}
for ( uint32_t i = 0; i < MAX_GENTITIES; i++ ) {
EntityMultiLoop& multiLoop = entityLoops[i];
for ( entityLoop_t& loop : multiLoop.loops ) {
if ( loop.sound and not loop.addedThisFrame ) {
if ( loop.persistent ) {
loop.sound->soundGain = 0;
} else {
// The loop wasn't added this frame, that means it has to be removed.
loop.sound->FadeOutAndDie();
loop = { false, false, nullptr, -1, -1 };
}
} else if ( loop.oldSfx != loop.newSfx ) {
// The last sfx added in the frame is not the current one being played
// To mimic the previous sound system's behavior we sart playing the new one.
loop.sound->FadeOutAndDie();
int newSfx = loop.newSfx;
bool persistent = loop.persistent;
loop = { false, false, nullptr, -1, -1 };
AddEntityLoopingSound( i, newSfx, persistent );
}
}
}
UpdateListenerGain();
// Update the rest of the system
CaptureTestUpdate();
UpdateEmitters();
UpdateSounds();
for ( EntityMultiLoop& multiLoop : entityLoops ) {
for ( entityLoop_t& loop : multiLoop.loops ) {
loop.addedThisFrame = false;
// if we are the unique owner of a loop pointer, then it means it was stopped, free it.
if ( loop.sound.use_count() == 1 ) {
loop = { false, false, nullptr, -1, -1 };
}
}
}
for ( std::shared_ptr<StreamingSound> &stream : streams ) {
if (stream and stream.use_count() == 1) {
stream = nullptr;
}
}
}
void BeginRegistration( const int playerNum ) {
if (not initialized) {
return;
}
playerClientNum = playerNum;
BeginSampleRegistration();
}
sfxHandle_t RegisterSFX(Str::StringRef filename) {
if (not initialized) {
return 0;
}
// TODO: what should we do if we aren't initialized?
return RegisterSample(filename)->GetHandle();
}
void EndRegistration() {
if (not initialized) {
return;
}
EndSampleRegistration();
}
static int GetSoundPriorityForEntity( const int entityNum ) {
return entityNum < MAX_CLIENTS ? CLIENT : ANY;
}
void StartSound(int entityNum, Vec3 origin, sfxHandle_t sfx) {
if (not initialized or not Sample::IsValidHandle(sfx)) {
return;
}
std::shared_ptr<Emitter> emitter;
// A valid number means it is an entity sound
if (IsValidEntity(entityNum)) {
emitter = GetEmitterForEntity(entityNum);
} else if(IsValidVector(origin)){
emitter = GetEmitterForPosition(origin);
} else {
return;
}
AddSound( emitter, std::make_shared<OneShotSound>( Sample::FromHandle( sfx ) ), GetSoundPriorityForEntity( entityNum ) );
}
void StartLocalSound(sfxHandle_t sfx) {
if (not initialized or not Sample::IsValidHandle(sfx)) {
return;
}
AddSound( GetLocalEmitter(), std::make_shared<OneShotSound>( Sample::FromHandle( sfx ) ), ANY );
}
void AddEntityLoopingSound(int entityNum, sfxHandle_t sfx, bool persistent) {
if (not initialized or not Sample::IsValidHandle(sfx) or not IsValidEntity(entityNum)) {
return;
}
entityLoop_t& loop = entityLoops[entityNum].FindSlot( sfx );
// If we have no sound we can play the loop directly
if (not loop.sound) {
loop.sound = std::make_shared<LoopingSound>(Sample::FromHandle(sfx));
loop.oldSfx = sfx;
AddSound( GetEmitterForEntity( entityNum ), loop.sound, GetSoundPriorityForEntity( entityNum ) );
}
loop.addedThisFrame = true;
loop.persistent = persistent;
// We remember what is the last sfx asked because cgame expects the sfx added last in the frame to be played
loop.newSfx = sfx;
}
void ClearAllLoopingSounds() {
if (not initialized) {
return;
}
for (int i = 0; i < MAX_GENTITIES; i++) {
ClearLoopingSoundsForEntity(i);
}
}
void ClearLoopingSoundsForEntity(int entityNum) {
if (not initialized or not IsValidEntity(entityNum)) {
return;
}
entityLoops[entityNum].ClearLoopingSounds();
}
void StartMusic(Str::StringRef leadingSound, Str::StringRef loopSound) {
if (not initialized) {
return;
}
std::shared_ptr<Sample> leadingSample = nullptr;
std::shared_ptr<Sample> loopingSample = nullptr;
if (not leadingSound.empty()) {
leadingSample = RegisterSample(leadingSound);
}
if (not loopSound.empty()) {
loopingSample = RegisterSample(loopSound);
}
StopMusic();
music = std::make_shared<LoopingSound>(loopingSample, leadingSample);
music->volumeModifier = &musicVolume;
AddSound( GetLocalEmitter(), music, ANY );
}
void StopMusic() {
if (not initialized) {
return;
}
if (music) {
music->Stop();
}
music = nullptr;
}
void StopAllSounds() {
if (not initialized) {
return;
}
StopMusic();
StopSounds();
}
void StreamData(int streamNum, const void* data, int numSamples, int rate, int width, int channels, float volume, int entityNum) {
if (not initialized or (streamNum < 0 or streamNum >= N_STREAMS)) {
return;
}
if (not streams[streamNum]) {
streams[streamNum] = std::make_shared<StreamingSound>();
if (IsValidEntity(entityNum)) {
AddSound( GetEmitterForEntity( entityNum ), streams[streamNum], GetSoundPriorityForEntity( entityNum ) );
} else {
AddSound( GetLocalEmitter(), streams[streamNum], ANY );
}
}
streams[streamNum]->soundGain = volume;
AudioData audioData { rate, width, channels };
audioData.rawSamples.resize( width * numSamples * channels );
memcpy( audioData.rawSamples.data(), data, width * numSamples * channels * sizeof( char ) );
AL::Buffer buffer;
int feedError = buffer.Feed(audioData);
if (not feedError) {
streams[streamNum]->AppendBuffer(std::move(buffer));
}
}
void UpdateListener(int entityNum, const Vec3 orientation[3]) {
if (not initialized or
not IsValidEntity(entityNum) or
not orientation or
not IsValidVector(orientation[0]) or
not IsValidVector(orientation[1]) or
not IsValidVector(orientation[2])) {
return;
}
UpdateListenerEntity(entityNum, orientation);
}
void UpdateListenerGain() {
if ((muteWhenMinimized.Get() and com_minimized->integer) or (muteWhenUnfocused.Get() and com_unfocused->integer)) {
AL::SetListenerGain(0.0f);
} else {
AL::SetListenerGain(SliderToAmplitude(masterVolume.Get()));
}
}
void UpdateEntityPosition(int entityNum, Vec3 position) {
if (not initialized or not IsValidEntity(entityNum) or not IsValidVector(position)) {
return;
}
UpdateRegisteredEntityPosition(entityNum, position);
}
void UpdateEntityVelocity(int entityNum, Vec3 velocity) {
if (not initialized or not IsValidEntity(entityNum) or not IsValidVector(velocity)) {
return;
}
UpdateRegisteredEntityVelocity(entityNum, velocity);
}
void SetReverb(int slotNum, std::string name, float ratio) {
if (not initialized) {
return;
}
if (slotNum < 0 or slotNum >= N_REVERB_SLOTS or !Math::IsFinite(ratio)) {
return;
}
UpdateReverbSlot(slotNum, std::move(name), ratio);
}
// Capture functions
static AL::CaptureDevice* capture = nullptr;
void StartCapture(int rate) {
if (capture or not initialized) {
return;
}
audioLogs.Notice("Started the OpenAL capture with rate %i", rate);
capture = AL::CaptureDevice::GetDefaultDevice(rate);
capture->Start();
}
int AvailableCaptureSamples() {
if (not capture) {
return 0;
}
return capture->GetNumCapturedSamples();
}
void GetCapturedData(int numSamples, void* buffer) {
if (not capture) {
return;
}
capture->Capture(numSamples, buffer);
}
void StopCapture() {
if (not initialized) {
return;
}
if (capture) {
audioLogs.Notice("Stopped the OpenAL capture");
capture->Stop();
}
delete capture;
capture = nullptr;
}
bool doingCaptureTest = false;
void CaptureTestStart() {
if (not initialized or capture or doingCaptureTest) {
return;
}
audioLogs.Notice("Starting the sound capture test");
StartCapture(16000);
doingCaptureTest = true;
}
void CaptureTestUpdate() {
if (not doingCaptureTest) {
return;
}
int numSamples = AvailableCaptureSamples();
if (numSamples > 0) {
uint16_t* buffer = ( uint16_t* ) Hunk_AllocateTempMemory( numSamples * sizeof( uint16_t ) );
GetCapturedData(numSamples, buffer);
StreamData(N_STREAMS - 1, buffer, numSamples, 16000, 2, 1, 1.0, -1);
Hunk_FreeTempMemory( buffer );
}
}
void CaptureTestStop() {
if (not doingCaptureTest) {
return;
}
audioLogs.Notice("Stopping the sound capture test");
StopCapture();
doingCaptureTest = false;
}
// Console commands
class ALInfoCmd : public Cmd::StaticCmd {
public:
ALInfoCmd(): StaticCmd("printALInfo", Cmd::AUDIO, "Prints information about OpenAL") {
}
virtual void Run(const Cmd::Args&) const override {
Print(AL::GetSystemInfo(device, capture));
}
};
static ALInfoCmd alInfoRegistration;
class ListSamplesCmd : public Cmd::StaticCmd {
public:
ListSamplesCmd(): StaticCmd("listAudioSamples", Cmd::AUDIO, "Lists all the loaded sound samples") {
}
virtual void Run(const Cmd::Args&) const override {
std::vector<std::string> samples = ListSamples();
std::sort(samples.begin(), samples.end());
for (const auto& sample: samples) {
Print(sample);
}
Print("%i samples", samples.size());
}
};
static ListSamplesCmd listSamplesRegistration;
class StopSoundsCmd : public Cmd::StaticCmd {
public:
StopSoundsCmd(): StaticCmd("stopSounds", Cmd::AUDIO, "Stops the music and the looping sounds") {
}
virtual void Run(const Cmd::Args&) const override {
ClearAllLoopingSounds();
StopMusic();
}
};
static StopSoundsCmd stopSoundsRegistration;
class StartCaptureTestCmd : public Cmd::StaticCmd {
public:
StartCaptureTestCmd(): StaticCmd("startSoundCaptureTest", Cmd::AUDIO, "Starts testing the sound capture") {
}
virtual void Run(const Cmd::Args&) const override {
CaptureTestStart();
}
};
static StartCaptureTestCmd startCaptureTestRegistration;
class StopCaptureTestCmd : public Cmd::StaticCmd {
public:
StopCaptureTestCmd(): StaticCmd("stopSoundCaptureTest", Cmd::AUDIO, "Stops the testing of the sound capture") {
}
virtual void Run(const Cmd::Args&) const override {
CaptureTestStop();
}
};
static StopCaptureTestCmd stopCaptureTestRegistration;
// Play the sounds from the filenames specified as arguments of the command
class PlaySoundCmd : public Cmd::StaticCmd {
public:
PlaySoundCmd(): StaticCmd("playSound", Cmd::AUDIO, "Plays the given sound effects") {
}
virtual void Run(const Cmd::Args& args) const override {
if (args.Argc() == 1) {
PrintUsage(args, "/playSound <file> [<file>…]", "play sound files");
return;
}
for (int i = 1; i < args.Argc(); i++) {
sfxHandle_t soundHandle = RegisterSFX(args.Argv(i));
StartLocalSound(soundHandle);
}
}
virtual Cmd::CompletionResult Complete(int argNum, const Cmd::Args&, Str::StringRef prefix) const override {
if (argNum >= 1) {
//TODO have a list of supported extensions somewhere and use that?
return FS::PakPath::CompleteFilename(prefix, "", "", true, false);
}
return {};
}
};
static PlaySoundCmd playSoundRegistration;
// Play the music from the filename specified as argument of the command
class PlayMusicCmd : public Cmd::StaticCmd {
public:
PlayMusicCmd(): StaticCmd("playMusic", Cmd::AUDIO, "Plays a music") {
}
virtual void Run(const Cmd::Args& args) const override {
if (args.Argc() == 2) {
StartMusic( args.Argv(1) , "");
} else {
PrintUsage(args, "/playMusic <file>", "play a music file");
}
}
virtual Cmd::CompletionResult Complete(int argNum, const Cmd::Args&, Str::StringRef prefix) const override {
if (argNum == 1) {
//TODO have a list of supported extensions somewhere and use that?
return FS::PakPath::CompleteFilename(prefix, "", "", true, false);
}
return {};
}
};
static PlayMusicCmd playMusicRegistration;
// Stop the current music
class StopMusicCmd : public Cmd::StaticCmd {
public:
StopMusicCmd(): StaticCmd("stopMusic", Cmd::AUDIO, "Stops the currently playing music") {
}
virtual void Run(const Cmd::Args&) const override {
StopMusic();
}
};
static StopMusicCmd stopMusicRegistration;
// Additional utility functions
// Some volume slider-tweaking functions, full of heuristics and probably very slow for what they do.
static float PerceptualToAmplitude(float perceptual) {
// Conversion from a perceptual audio scale on [0, 1] to an amplitude scale on [0, 1]
// Assuming the decibel scale is perceptual, naming A the amplitude and B the perceived volume:
// B = 3log_10(A + c) + d and A = 10^((B - d)/3) - c
// With c and d two constants such that the equation holds for A = B = 0 and A = B = 1.
// Solving gives us:
// c = 10^(-d/3) and 10^((1-d)/3) - 10^(-d/3) = 1
// With Wolfram Alpha we get:
// d = 3log_10(10^(1/3) - 1) and c = 1 / (10^(1/3) - 1)
const float PERCEPTUAL_C = 0.866224835960518f;
const float PERCEPTUAL_D = 0.187108105667604f;
return std::pow(10.0f, (perceptual - PERCEPTUAL_D) / 3.0f) - PERCEPTUAL_C;
}
float SliderToAmplitude(float slider) {
// We want the users to control the perceptual volume but at the same time have more
// control over the small value than over bigger ones so we tweak the slider value
// first.
float perceptual = slider * slider;
return PerceptualToAmplitude(perceptual);
}
}