forked from smooth80/defold
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathsound.cpp
1502 lines (1266 loc) · 53 KB
/
sound.cpp
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 2020 The Defold Foundation
// Licensed under the Defold License version 1.0 (the "License"); you may not use
// this file except in compliance with the License.
//
// You may obtain a copy of the License, together with FAQs at
// https://www.defold.com/license
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
#include <stdint.h>
#include <dlib/hashtable.h>
#include <dlib/index_pool.h>
#include <dlib/log.h>
#include <dlib/math.h>
#include <dlib/mutex.h>
#include <dlib/profile.h>
#include <dlib/thread.h>
#include <dlib/time.h>
#include "sound.h"
#include "sound_codec.h"
#include "sound_private.h"
#include <math.h>
#include <cfloat>
/**
* Defold simple sound system
* NOTE: Must units is in frames, i.e a sample in time with N channels
*
*/
namespace dmSound
{
using namespace Vectormath::Aos;
#define SOUND_MAX_MIX_CHANNELS (2)
#define SOUND_OUTBUFFER_COUNT (6)
#define SOUND_MAX_SPEED (5)
// TODO: How many bits?
const uint32_t RESAMPLE_FRACTION_BITS = 31;
const dmhash_t MASTER_GROUP_HASH = dmHashString64("master");
const uint32_t GROUP_MEMORY_BUFFER_COUNT = 64;
static void SoundThread(void* ctx);
/**
* Value with memory for "ramping" of values. See also struct Ramp below.
*/
struct Value
{
inline void Reset(float value)
{
// NOTE: We always ramp from zero to x. Otherwise we can
// get initial clicks when playing sounds
m_Prev = 0.0f;
m_Current = value;
m_Next = value;
}
inline void Set(float value, bool reset)
{
if (reset) {
Reset(value);
} else {
m_Next = value;
}
}
inline bool IsZero()
{
// Let's do the check in integer space instead (16 instructions -> 6)
const uint32_t* pa = (const uint32_t*)&m_Prev;
const uint32_t* pb = (const uint32_t*)&m_Current;
const uint32_t* pc = (const uint32_t*)&m_Next;
return (*pa | *pb | *pc ) == 0;
}
/**
* Set previous value to current and current to next, i.e. "sample"
*/
inline void Step()
{
m_Prev = m_Current;
m_Current = m_Next;
}
Value()
{
Reset(1.0f);
}
float m_Prev;
float m_Current;
float m_Next;
};
/**
* Helper for calculating ramps
*/
struct Ramp
{
float m_From, m_To, m_TotalSamplesRecip;
Ramp(const Value* value, uint32_t buffer, uint32_t total_buffers, uint32_t total_samples)
{
float ramp_length = (value->m_Current - value->m_Prev) / total_buffers;
m_From = value->m_Prev + ramp_length * buffer;
m_To = m_From + ramp_length;
m_TotalSamplesRecip = 1.0f / total_samples;
}
inline float GetValue(int i) const
{
float mix = i * m_TotalSamplesRecip;
return m_From + mix * (m_To - m_From);
}
};
/**
* Context with data for mixing N buffers, i.e. during update
*/
struct MixContext
{
MixContext(uint32_t current_buffer, uint32_t total_buffers)
{
m_CurrentBuffer = current_buffer;
m_TotalBuffers = total_buffers;
}
// Current buffer index
uint32_t m_CurrentBuffer;
// How many buffers to mix
uint32_t m_TotalBuffers;
};
Ramp GetRamp(const MixContext* mix_context, const Value* value, uint32_t total_samples)
{
Ramp ramp(value, mix_context->m_CurrentBuffer, mix_context->m_TotalBuffers, total_samples);
return ramp;
}
struct SoundData
{
dmhash_t m_NameHash;
void* m_Data;
int m_Size;
// Index in m_SoundData
uint16_t m_Index;
SoundDataType m_Type;
};
struct SoundInstance
{
dmSoundCodec::HDecoder m_Decoder;
void* m_Frames;
dmhash_t m_Group;
Value m_Gain; // default: 1.0f
Value m_Pan; // 0 = -45deg left, 1 = 45 deg right
float m_Speed; // 1.0 = normal speed, 0.5 = half speed, 2.0 = double speed
uint32_t m_FrameCount;
uint64_t m_FrameFraction;
uint16_t m_Index;
uint16_t m_SoundDataIndex;
uint8_t m_Looping : 1;
uint8_t m_EndOfStream : 1;
uint8_t m_Playing : 1;
uint8_t : 5;
int8_t m_Loopcounter; // if set to 3, there will be 3 loops effectively playing the sound 4 times.
};
struct SoundGroup
{
dmhash_t m_NameHash;
Value m_Gain;
float* m_MixBuffer;
float m_SumSquaredMemory[SOUND_MAX_MIX_CHANNELS * GROUP_MEMORY_BUFFER_COUNT];
float m_PeakMemorySq[SOUND_MAX_MIX_CHANNELS * GROUP_MEMORY_BUFFER_COUNT];
int m_NextMemorySlot;
};
struct SoundSystem
{
dmSoundCodec::HCodecContext m_CodecContext;
DeviceType* m_DeviceType;
HDevice m_Device;
dmThread::Thread m_Thread;
dmMutex::HMutex m_Mutex;
dmArray<SoundInstance> m_Instances;
dmIndexPool16 m_InstancesPool;
dmArray<SoundData> m_SoundData;
dmIndexPool16 m_SoundDataPool;
dmHashTable<dmhash_t, int> m_GroupMap;
SoundGroup m_Groups[MAX_GROUPS];
Result m_Status;
uint32_t m_MixRate;
uint32_t m_FrameCount;
uint32_t m_PlayCounter;
int16_t* m_OutBuffers[SOUND_OUTBUFFER_COUNT];
uint16_t m_NextOutBuffer;
bool m_IsDeviceStarted;
bool m_IsPhoneCallActive;
bool m_HasWindowFocus;
bool m_IsRunning;
bool m_IsPaused;
};
struct OptionalScopedMutexLock
{
OptionalScopedMutexLock(dmMutex::HMutex mutex) : m_Mutex(mutex) {
if (m_Mutex)
dmMutex::Lock(m_Mutex);
}
~OptionalScopedMutexLock() {
if (m_Mutex)
dmMutex::Unlock(m_Mutex);
}
dmMutex::HMutex m_Mutex;
};
#define DM_MUTEX_OPTIONAL_SCOPED_LOCK(mutex) OptionalScopedMutexLock SCOPED_LOCK_PASTE2(lock, __LINE__)(mutex);
SoundSystem* g_SoundSystem = 0;
DeviceType* g_FirstDevice = 0;
void SetDefaultInitializeParams(InitializeParams* params)
{
memset(params, 0, sizeof(InitializeParams));
params->m_OutputDevice = "default";
params->m_MasterGain = 1.0f;
params->m_MaxSoundData = 128;
params->m_MaxSources = 16;
params->m_MaxBuffers = 32;
params->m_BufferSize = 12 * 4096;
params->m_FrameCount = 768;
params->m_MaxInstances = 256;
params->m_UseThread = true;
}
Result RegisterDevice(struct DeviceType* device)
{
device->m_Next = g_FirstDevice;
g_FirstDevice = device;
return RESULT_OK;
}
static Result OpenDevice(const char* name, const OpenDeviceParams* params, DeviceType** device_type, HDevice* device)
{
DeviceType* d = g_FirstDevice;
while (d) {
if (strcmp(d->m_Name, name) == 0) {
*device_type = d;
return d->m_Open(params, device);
}
d = d->m_Next;
}
return RESULT_DEVICE_NOT_FOUND;
}
static int GetOrCreateGroup(const char* group_name)
{
dmhash_t group_hash = dmHashString64(group_name);
SoundSystem* sound = g_SoundSystem;
if (sound->m_GroupMap.Full()) {
return -1;
}
if (sound->m_GroupMap.Get(group_hash)) {
return *sound->m_GroupMap.Get(group_hash);
}
uint32_t index = sound->m_GroupMap.Size();
SoundGroup* group = &sound->m_Groups[index];
group->m_NameHash = group_hash;
group->m_Gain.Reset(1.0f);
size_t mix_buffer_size = sound->m_FrameCount * sizeof(float) * SOUND_MAX_MIX_CHANNELS;
group->m_MixBuffer = (float*) malloc(mix_buffer_size);
memset(group->m_MixBuffer, 0, mix_buffer_size);
sound->m_GroupMap.Put(group_hash, index);
return index;
}
Result Initialize(dmConfigFile::HConfig config, const InitializeParams* params)
{
Result r = PlatformInitialize(config, params);
if (r != RESULT_OK) {
return r;
}
HDevice device;
OpenDeviceParams device_params;
// TODO: m_BufferCount configurable?
device_params.m_BufferCount = SOUND_OUTBUFFER_COUNT;
device_params.m_FrameCount = params->m_FrameCount;
DeviceType* device_type;
r = OpenDevice(params->m_OutputDevice, &device_params, &device_type, &device);
if (r != RESULT_OK) {
dmLogError("Failed to Open device '%s'", params->m_OutputDevice);
return r;
}
DeviceInfo device_info;
device_type->m_DeviceInfo(device, &device_info);
float master_gain = params->m_MasterGain;
g_SoundSystem = new SoundSystem();
SoundSystem* sound = g_SoundSystem;
sound->m_IsDeviceStarted = false;
sound->m_IsPhoneCallActive = false;
sound->m_HasWindowFocus = true; // Assume we startup with the window focused
sound->m_DeviceType = device_type;
sound->m_Device = device;
dmSoundCodec::NewCodecContextParams codec_params;
codec_params.m_MaxDecoders = params->m_MaxInstances;
sound->m_CodecContext = dmSoundCodec::New(&codec_params);
uint32_t max_sound_data = params->m_MaxSoundData;
uint32_t max_buffers = params->m_MaxBuffers;
uint32_t max_sources = params->m_MaxSources;
uint32_t max_instances = params->m_MaxInstances;
if (config)
{
master_gain = dmConfigFile::GetFloat(config, "sound.gain", 1.0f);
max_sound_data = (uint32_t) dmConfigFile::GetInt(config, "sound.max_sound_data", (int32_t) max_sound_data);
max_buffers = (uint32_t) dmConfigFile::GetInt(config, "sound.max_sound_buffers", (int32_t) max_buffers);
max_sources = (uint32_t) dmConfigFile::GetInt(config, "sound.max_sound_sources", (int32_t) max_sources);
max_instances = (uint32_t) dmConfigFile::GetInt(config, "sound.max_sound_instances", (int32_t) max_instances);
}
sound->m_Instances.SetCapacity(max_instances);
sound->m_Instances.SetSize(max_instances);
sound->m_InstancesPool.SetCapacity(max_instances);
for (uint32_t i = 0; i < max_instances; ++i)
{
SoundInstance* instance = &sound->m_Instances[i];
memset(instance, 0, sizeof(*instance));
instance->m_Index = 0xffff;
instance->m_SoundDataIndex = 0xffff;
// NOTE: +1 for "over-fetch" when up-sampling
// NOTE: and x SOUND_MAX_SPEED for potential pitch range
instance->m_Frames = malloc((params->m_FrameCount * SOUND_MAX_SPEED + 1) * sizeof(int16_t) * SOUND_MAX_MIX_CHANNELS);
instance->m_FrameCount = 0;
instance->m_Speed = 1.0f;
}
sound->m_SoundData.SetCapacity(max_sound_data);
sound->m_SoundData.SetSize(max_sound_data);
sound->m_SoundDataPool.SetCapacity(max_sound_data);
for (uint32_t i = 0; i < max_sound_data; ++i)
{
sound->m_SoundData[i].m_Index = 0xffff;
}
sound->m_MixRate = device_info.m_MixRate;
sound->m_FrameCount = params->m_FrameCount;
for (int i = 0; i < SOUND_OUTBUFFER_COUNT; ++i) {
sound->m_OutBuffers[i] = (int16_t*) malloc(params->m_FrameCount * sizeof(int16_t) * SOUND_MAX_MIX_CHANNELS);
}
sound->m_NextOutBuffer = 0;
sound->m_GroupMap.SetCapacity(MAX_GROUPS * 2 + 1, MAX_GROUPS);
for (uint32_t i = 0; i < MAX_GROUPS; ++i) {
memset(&sound->m_Groups[i], 0, sizeof(SoundGroup));
}
int master_index = GetOrCreateGroup("master");
SoundGroup* master = &sound->m_Groups[master_index];
master->m_Gain.Reset(master_gain);
sound->m_IsRunning = true;
sound->m_IsPaused = false;
sound->m_Status = RESULT_NOTHING_TO_PLAY;
sound->m_Thread = 0;
sound->m_Mutex = 0;
if (params->m_UseThread)
{
sound->m_Mutex = dmMutex::New();
sound->m_Thread = dmThread::New((dmThread::ThreadStart)SoundThread, 0x80000, sound, "sound");
}
return RESULT_OK;
}
Result Finalize()
{
SoundSystem* sound = g_SoundSystem;
if (!sound)
return RESULT_OK;
sound->m_IsRunning = false;
if (sound->m_Thread)
{
dmThread::Join(sound->m_Thread);
dmMutex::Delete(sound->m_Mutex);
}
PlatformFinalize();
Result result = RESULT_OK;
if (sound)
{
dmSoundCodec::Delete(sound->m_CodecContext);
for (uint32_t i = 0; i < sound->m_Instances.Size(); ++i)
{
SoundInstance* instance = &sound->m_Instances[i];
instance->m_Index = 0xffff;
instance->m_SoundDataIndex = 0xffff;
free(instance->m_Frames);
memset(instance, 0, sizeof(*instance));
}
for (int i = 0; i < SOUND_OUTBUFFER_COUNT; ++i) {
free((void*) sound->m_OutBuffers[i]);
}
for (uint32_t i = 0; i < MAX_GROUPS; i++) {
SoundGroup* g = &sound->m_Groups[i];
if (g->m_MixBuffer) {
free((void*) g->m_MixBuffer);
}
}
sound->m_DeviceType->m_Close(sound->m_Device);
delete sound;
g_SoundSystem = 0;
}
return result;
}
static inline const char* GetSoundName(SoundSystem* sound, SoundInstance* instance)
{
dmhash_t hash = sound->m_SoundData[instance->m_SoundDataIndex].m_NameHash;
return dmHashReverseSafe64(hash);
}
static Result SetSoundDataNoLock(HSoundData sound_data, const void* sound_buffer, uint32_t sound_buffer_size)
{
free(sound_data->m_Data);
sound_data->m_Data = malloc(sound_buffer_size);
sound_data->m_Size = sound_buffer_size;
memcpy(sound_data->m_Data, sound_buffer, sound_buffer_size);
return RESULT_OK;
}
Result NewSoundData(const void* sound_buffer, uint32_t sound_buffer_size, SoundDataType type, HSoundData* sound_data, dmhash_t name)
{
SoundSystem* sound = g_SoundSystem;
if (sound->m_SoundDataPool.Remaining() == 0)
{
*sound_data = 0;
dmLogError("Out of sound data slots (%u). Increase the project setting 'sound.max_sound_data'", sound->m_SoundDataPool.Capacity());
return RESULT_OUT_OF_INSTANCES;
}
DM_MUTEX_OPTIONAL_SCOPED_LOCK(g_SoundSystem->m_Mutex);
uint16_t index = sound->m_SoundDataPool.Pop();
SoundData* sd = &sound->m_SoundData[index];
sd->m_NameHash = name;
sd->m_Type = type;
sd->m_Index = index;
sd->m_Data = 0;
sd->m_Size = 0;
Result result = SetSoundDataNoLock(sd, sound_buffer, sound_buffer_size);
if (result == RESULT_OK)
*sound_data = sd;
else
DeleteSoundData(sd);
return result;
}
Result SetSoundData(HSoundData sound_data, const void* sound_buffer, uint32_t sound_buffer_size)
{
DM_MUTEX_OPTIONAL_SCOPED_LOCK(g_SoundSystem->m_Mutex);
return SetSoundDataNoLock(sound_data, sound_buffer, sound_buffer_size);
}
uint32_t GetSoundResourceSize(HSoundData sound_data)
{
return sound_data->m_Size + sizeof(SoundData);
}
Result DeleteSoundData(HSoundData sound_data)
{
DM_MUTEX_OPTIONAL_SCOPED_LOCK(g_SoundSystem->m_Mutex);
if (sound_data->m_Data != 0x0)
free((void*) sound_data->m_Data);
SoundSystem* sound = g_SoundSystem;
sound->m_SoundDataPool.Push(sound_data->m_Index);
sound_data->m_Index = 0xffff;
return RESULT_OK;
}
Result NewSoundInstance(HSoundData sound_data, HSoundInstance* sound_instance)
{
SoundSystem* ss = g_SoundSystem;
if (ss->m_InstancesPool.Remaining() == 0)
{
*sound_instance = 0;
dmLogError("Out of sound data instance slots (%u). Increase the project setting 'sound.max_sound_instances'", ss->m_InstancesPool.Capacity());
return RESULT_OUT_OF_INSTANCES;
}
dmSoundCodec::HDecoder decoder;
dmSoundCodec::Format codec_format = dmSoundCodec::FORMAT_WAV;
if (sound_data->m_Type == SOUND_DATA_TYPE_WAV) {
codec_format = dmSoundCodec::FORMAT_WAV;
} else if (sound_data->m_Type == SOUND_DATA_TYPE_OGG_VORBIS) {
codec_format = dmSoundCodec::FORMAT_VORBIS;
} else {
assert(0);
}
uint16_t index;
{
DM_MUTEX_OPTIONAL_SCOPED_LOCK(ss->m_Mutex);
dmSoundCodec::Result r = dmSoundCodec::NewDecoder(ss->m_CodecContext, codec_format, sound_data->m_Data, sound_data->m_Size, &decoder);
if (r != dmSoundCodec::RESULT_OK) {
dmLogError("Failed to decode sound (%d)", r);
return RESULT_INVALID_STREAM_DATA;
}
index = ss->m_InstancesPool.Pop();
}
SoundInstance* si = &ss->m_Instances[index];
assert(si->m_Index == 0xffff);
si->m_SoundDataIndex = sound_data->m_Index;
si->m_Index = index;
si->m_Gain.Reset(1.0f);
si->m_Pan.Reset(0.5f);
si->m_Looping = 0;
si->m_EndOfStream = 0;
si->m_Playing = 0;
si->m_Decoder = decoder;
si->m_Group = MASTER_GROUP_HASH;
*sound_instance = si;
return RESULT_OK;
}
static void StopNoLock(SoundSystem* sound, HSoundInstance sound_instance);
Result DeleteSoundInstance(HSoundInstance sound_instance)
{
SoundSystem* sound = g_SoundSystem;
DM_MUTEX_OPTIONAL_SCOPED_LOCK(sound->m_Mutex);
if (IsPlaying(sound_instance))
{
dmLogError("Deleting playing sound instance (%s)", GetSoundName(sound, sound_instance));
StopNoLock(sound, sound_instance);
}
uint16_t index = sound_instance->m_Index;
sound->m_InstancesPool.Push(index);
sound_instance->m_Index = 0xffff;
sound_instance->m_SoundDataIndex = 0xffff;
dmSoundCodec::DeleteDecoder(sound->m_CodecContext, sound_instance->m_Decoder);
sound_instance->m_Decoder = 0;
sound_instance->m_FrameCount = 0;
sound_instance->m_Speed = 1.0f;
return RESULT_OK;
}
Result SetInstanceGroup(HSoundInstance instance, const char* group_name)
{
dmhash_t group_hash = dmHashString64(group_name);
return SetInstanceGroup(instance, group_hash);
}
Result SetInstanceGroup(HSoundInstance instance, dmhash_t group_hash)
{
DM_MUTEX_OPTIONAL_SCOPED_LOCK(g_SoundSystem->m_Mutex);
SoundSystem* sound = g_SoundSystem;
int* index = sound->m_GroupMap.Get(group_hash);
if (!index) {
return RESULT_NO_SUCH_GROUP;
}
instance->m_Group = group_hash;
return RESULT_OK;
}
Result AddGroup(const char* group)
{
DM_MUTEX_OPTIONAL_SCOPED_LOCK(g_SoundSystem->m_Mutex);
int index = GetOrCreateGroup(group);
if (index == -1) {
return RESULT_OUT_OF_GROUPS;
}
return RESULT_OK;
}
Result SetGroupGain(dmhash_t group_hash, float gain)
{
DM_MUTEX_OPTIONAL_SCOPED_LOCK(g_SoundSystem->m_Mutex);
SoundSystem* sound = g_SoundSystem;
int* index = sound->m_GroupMap.Get(group_hash);
if (!index) {
return RESULT_NO_SUCH_GROUP;
}
// If all playing sounds is currently at gain zero
// we can safely do a hard reset of the group gain
bool reset = true;
uint32_t instances = sound->m_Instances.Size();
for (uint32_t i = 0; i < instances; ++i)
{
SoundInstance* instance = &sound->m_Instances[i];
if (instance->m_Group != group_hash)
{
continue;
}
if (instance->m_Playing || instance->m_FrameCount > 0)
{
if (instance->m_Gain.m_Prev == 0.0)
{
continue;
}
reset = false;
break;
}
}
SoundGroup* group = &sound->m_Groups[*index];
group->m_Gain.Set(gain, reset);
return RESULT_OK;
}
Result GetGroupGain(dmhash_t group_hash, float* gain)
{
DM_MUTEX_OPTIONAL_SCOPED_LOCK(g_SoundSystem->m_Mutex);
SoundSystem* sound = g_SoundSystem;
int* index = sound->m_GroupMap.Get(group_hash);
if (!index) {
return RESULT_NO_SUCH_GROUP;
}
SoundGroup* group = &sound->m_Groups[*index];
*gain = group->m_Gain.m_Next;
return RESULT_OK;
}
Result GetGroupHashes(uint32_t* count, dmhash_t* buffer)
{
DM_MUTEX_OPTIONAL_SCOPED_LOCK(g_SoundSystem->m_Mutex);
SoundSystem* sound = g_SoundSystem;
uint32_t size = sound->m_GroupMap.Size();
assert(*count >= size);
for (uint32_t i = 0; i < size; ++i)
{
buffer[i] = sound->m_Groups[i].m_NameHash;
}
*count = size;
return RESULT_OK;
}
Result GetGroupRMS(dmhash_t group_hash, float window, float* rms_left, float* rms_right)
{
DM_MUTEX_OPTIONAL_SCOPED_LOCK(g_SoundSystem->m_Mutex);
SoundSystem* sound = g_SoundSystem;
int* index = sound->m_GroupMap.Get(group_hash);
if (!index) {
return RESULT_NO_SUCH_GROUP;
}
SoundGroup* g = &sound->m_Groups[*index];
uint32_t rms_frames = (uint32_t) (sound->m_MixRate * window);
int left = rms_frames;
int ss_index = (g->m_NextMemorySlot - 1) % GROUP_MEMORY_BUFFER_COUNT;
float sum_sq_left = 0;
float sum_sq_right = 0;
int count = 0;
while (left > 0) {
sum_sq_left += g->m_SumSquaredMemory[2 * ss_index + 0];
sum_sq_right += g->m_SumSquaredMemory[2 * ss_index + 1];
left -= sound->m_FrameCount;
ss_index = (ss_index - 1) % GROUP_MEMORY_BUFFER_COUNT;
count++;
}
*rms_left = sqrtf(sum_sq_left / (float) (count * sound->m_FrameCount)) / 32767.0f;
*rms_right = sqrtf(sum_sq_right / (float) (count * sound->m_FrameCount)) / 32767.0f;
return RESULT_OK;
}
Result GetGroupPeak(dmhash_t group_hash, float window, float* peak_left, float* peak_right)
{
DM_MUTEX_OPTIONAL_SCOPED_LOCK(g_SoundSystem->m_Mutex);
SoundSystem* sound = g_SoundSystem;
int* index = sound->m_GroupMap.Get(group_hash);
if (!index) {
return RESULT_NO_SUCH_GROUP;
}
SoundGroup* g = &sound->m_Groups[*index];
uint32_t rms_frames = (uint32_t) (sound->m_MixRate * window);
int left = rms_frames;
int ss_index = (g->m_NextMemorySlot - 1) % GROUP_MEMORY_BUFFER_COUNT;
float max_peak_left_sq = 0;
float max_peak_right_sq = 0;
int count = 0;
while (left > 0) {
max_peak_left_sq = dmMath::Max(max_peak_left_sq, g->m_PeakMemorySq[2 * ss_index + 0]);
max_peak_right_sq = dmMath::Max(max_peak_right_sq, g->m_PeakMemorySq[2 * ss_index + 1]);
left -= sound->m_FrameCount;
ss_index = (ss_index - 1) % GROUP_MEMORY_BUFFER_COUNT;
count++;
}
*peak_left = sqrtf(max_peak_left_sq) / 32767.0f;
*peak_right = sqrtf(max_peak_right_sq) / 32767.0f;
return RESULT_OK;
}
Result Play(HSoundInstance sound_instance)
{
DM_MUTEX_OPTIONAL_SCOPED_LOCK(g_SoundSystem->m_Mutex);
sound_instance->m_Playing = 1;
return RESULT_OK;
}
static void StopNoLock(SoundSystem* sound, HSoundInstance sound_instance)
{
DM_MUTEX_OPTIONAL_SCOPED_LOCK(g_SoundSystem->m_Mutex);
sound_instance->m_Playing = 0;
dmSoundCodec::Reset(sound->m_CodecContext, sound_instance->m_Decoder);
}
Result Stop(HSoundInstance sound_instance)
{
DM_MUTEX_OPTIONAL_SCOPED_LOCK(g_SoundSystem->m_Mutex);
StopNoLock(g_SoundSystem, sound_instance);
return RESULT_OK;
}
Result Pause(HSoundInstance sound_instance, bool pause)
{
if (!g_SoundSystem)
return RESULT_OK;
DM_MUTEX_OPTIONAL_SCOPED_LOCK(g_SoundSystem->m_Mutex);
sound_instance->m_Playing = (uint8_t)!pause;
return RESULT_OK;
}
uint32_t GetAndIncreasePlayCounter()
{
if (g_SoundSystem->m_PlayCounter == dmSound::INVALID_PLAY_ID)
{
g_SoundSystem->m_PlayCounter = 0;
}
return g_SoundSystem->m_PlayCounter++;
}
bool IsPlaying(HSoundInstance sound_instance)
{
return sound_instance->m_Playing; // && !sound_instance->m_EndOfStream;
}
Result SetLooping(HSoundInstance sound_instance, bool looping, int8_t loopcounter)
{
DM_MUTEX_OPTIONAL_SCOPED_LOCK(g_SoundSystem->m_Mutex);
sound_instance->m_Looping = (uint32_t) looping;
sound_instance->m_Loopcounter = loopcounter;
return RESULT_OK;
}
Result SetParameter(HSoundInstance sound_instance, Parameter parameter, const Vector4& value)
{
bool reset = !sound_instance->m_Playing;
switch(parameter)
{
case PARAMETER_GAIN:
sound_instance->m_Gain.Set(dmMath::Max(0.0f, value.getX()), reset);
break;
case PARAMETER_PAN:
{
float pan = dmMath::Max(-1.0f, dmMath::Min(1.0f, value.getX()));
pan = (pan + 1.0f) * 0.5f; // map [-1,1] to [0,1] for easier calculations later
sound_instance->m_Pan.Set(pan, reset);
}
break;
case PARAMETER_SPEED:
sound_instance->m_Speed = dmMath::Max(0.0f, dmMath::Min((float)SOUND_MAX_SPEED, value.getX()));
break;
default:
dmLogError("Invalid parameter: %d (%s)\n", parameter, GetSoundName(g_SoundSystem, sound_instance));
return RESULT_INVALID_PROPERTY;
}
return RESULT_OK;
}
static inline void GetPanScale(float pan, float* left_scale, float* right_scale)
{
// Constant power panning: https://www.cs.cmu.edu/~music/icm-online/readings/panlaws/index.html
const float theta = pan * M_PI_2;
*left_scale = cosf(theta);
*right_scale = sinf(theta);
}
/*
*
* Template parameters
*
* offset: determines the value around which the audio samples are oscillating in the source audio data. if 0, samples are
* both positive and negative.
* scale: changes the scale of the samples when mixed by multiplying their values with the 'scale' template param.
*/
template <typename T, int offset, int scale>
static void MixResampleUpMono(const MixContext* mix_context, SoundInstance* instance, uint32_t rate, uint32_t mix_rate, float* mix_buffer, uint32_t mix_buffer_count)
{
const uint32_t mask = (1U << RESAMPLE_FRACTION_BITS) - 1U;
const float range_recip = 1.0f / mask; // TODO: Divide by (1 << RESAMPLE_FRACTION_BITS) OR (1 << RESAMPLE_FRACTION_BITS) - 1?
uint64_t frac = instance->m_FrameFraction;
uint32_t prev_index = 0;
uint32_t index = 0;
uint64_t delta = (((uint64_t) rate) << RESAMPLE_FRACTION_BITS) / mix_rate;
delta *= instance->m_Speed;
T* frames = (T*) instance->m_Frames;
// Typically when the buffer is less than a mix-buffer we might overfetch
// We never overfetch for identity mixing as identity mixing is a special case
frames[instance->m_FrameCount] = frames[instance->m_FrameCount-1];
Ramp gain_ramp = GetRamp(mix_context, &instance->m_Gain, mix_buffer_count);
Ramp pan_ramp = GetRamp(mix_context, &instance->m_Pan, mix_buffer_count);
for (uint32_t i = 0; i < mix_buffer_count; i++)
{
float gain = gain_ramp.GetValue(i);
float pan = pan_ramp.GetValue(i);
float mix = frac * range_recip; // determines the bias between two consecutive samples in the sound instance. It ranges from 0-1. A mix of 0, makes only the first sample count while a mix of 0.5 will count equally both samples.
T s1 = frames[index];
T s2 = frames[index + 1];
s1 = (s1 - offset) * scale;
s2 = (s2 - offset) * scale;
float left_scale, right_scale;
GetPanScale(pan, &left_scale, &right_scale);
float s = (1.0f - mix) * s1 + mix * s2; // resulting destination sample value is a mix of two source samples since a kind of fractional indexing is used
mix_buffer[2 * i] += s * gain * left_scale;
mix_buffer[2 * i + 1] += s * gain * right_scale;
prev_index = index; // keep old index for assertion
frac += delta;
index += (uint32_t)(frac >> RESAMPLE_FRACTION_BITS);
frac &= ((1U << RESAMPLE_FRACTION_BITS) - 1U); // Keep lower RESAMPLE_FRACTION_BITS bits. Clear higher.
}
instance->m_FrameFraction = frac;
assert(prev_index <= instance->m_FrameCount);
// copy any remaining frames not mixed to the start of m_Frames
assert( instance->m_FrameCount >= index);
memmove(instance->m_Frames, (char*) instance->m_Frames + index * sizeof(T), (instance->m_FrameCount - index) * sizeof(T));
instance->m_FrameCount -= index;
}
template <typename T, int offset, int scale>
static void MixResampleUpStereo(const MixContext* mix_context, SoundInstance* instance, uint32_t rate, uint32_t mix_rate, float* mix_buffer, uint32_t mix_buffer_count)
{
const uint32_t mask = (1U << RESAMPLE_FRACTION_BITS) - 1U;
const float range_recip = 1.0f / mask; // TODO: Divide by (1 << RESAMPLE_FRACTION_BITS) OR (1 << RESAMPLE_FRACTION_BITS) - 1?
uint64_t frac = instance->m_FrameFraction;
uint32_t prev_index = 0;
uint32_t index = 0;
uint64_t delta = (((uint64_t) rate) << RESAMPLE_FRACTION_BITS) / mix_rate;
delta *= instance->m_Speed;
T* frames = (T*) instance->m_Frames;
// Typically when the buffer is less than a mix-buffer we might overfetch
// We never overfetch for identity mixing as identity mixing is a special case
frames[2 * instance->m_FrameCount] = frames[2 * instance->m_FrameCount - 2];
frames[2 * instance->m_FrameCount + 1] = frames[2 * instance->m_FrameCount - 1];
Ramp gain_ramp = GetRamp(mix_context, &instance->m_Gain, mix_buffer_count);
Ramp pan_ramp = GetRamp(mix_context, &instance->m_Pan, mix_buffer_count);
for (uint32_t i = 0; i < mix_buffer_count; i++)
{
float gain = gain_ramp.GetValue(i);
float pan = pan_ramp.GetValue(i);
float mix = frac * range_recip;
T sl1 = frames[2 * index];
T sl2 = frames[2 * index + 2];
sl1 = (sl1 - offset) * scale;
sl2 = (sl2 - offset) * scale;
T sr1 = frames[2 * index + 1];
T sr2 = frames[2 * index + 3];
sr1 = (sr1 - offset) * scale;
sr2 = (sr2 - offset) * scale;
float left_scale, right_scale;
GetPanScale(pan, &left_scale, &right_scale);
float sl = (1.0f - mix) * sl1 + mix * sl2;
float sr = (1.0f - mix) * sr1 + mix * sr2;
mix_buffer[2 * i] += sl * gain * left_scale;
mix_buffer[2 * i + 1] += sr * gain * right_scale;
prev_index = index;
frac += delta;
index += (uint32_t)(frac >> RESAMPLE_FRACTION_BITS);
frac &= ((1U << RESAMPLE_FRACTION_BITS) - 1U);
}
instance->m_FrameFraction = frac;
assert(prev_index <= instance->m_FrameCount);
memmove(instance->m_Frames, (char*) instance->m_Frames + index * sizeof(T) * 2, (instance->m_FrameCount - index) * sizeof(T) * 2);
instance->m_FrameCount -= index;
}
template <typename T, int offset, int scale>
static void MixResampleIdentityMono(const MixContext* mix_context, SoundInstance* instance, uint32_t rate, uint32_t mix_rate, float* mix_buffer, uint32_t mix_buffer_count)
{
(void)rate;
(void)mix_rate;
assert(instance->m_FrameCount == mix_buffer_count);
T* frames = (T*) instance->m_Frames;
Ramp gain_ramp = GetRamp(mix_context, &instance->m_Gain, mix_buffer_count);
Ramp pan_ramp = GetRamp(mix_context, &instance->m_Pan, mix_buffer_count);
for (uint32_t i = 0; i < mix_buffer_count; i++)
{
float gain = gain_ramp.GetValue(i);
float pan = pan_ramp.GetValue(i);
float s = frames[i];
s = (s - offset) * scale * gain;
float left_scale, right_scale;
GetPanScale(pan, &left_scale, &right_scale);
mix_buffer[2 * i] += s * left_scale;
mix_buffer[2 * i + 1] += s * right_scale;
}
instance->m_FrameCount -= mix_buffer_count;
}
template <typename T, int offset, int scale>
static void MixResampleIdentityStereo(const MixContext* mix_context, SoundInstance* instance, uint32_t rate, uint32_t mix_rate, float* mix_buffer, uint32_t mix_buffer_count)
{
(void)rate;
(void)mix_rate;
assert(instance->m_FrameCount == mix_buffer_count);
T* frames = (T*) instance->m_Frames;
Ramp gain_ramp = GetRamp(mix_context, &instance->m_Gain, mix_buffer_count);
Ramp pan_ramp = GetRamp(mix_context, &instance->m_Pan, mix_buffer_count);
for (uint32_t i = 0; i < mix_buffer_count; i++)
{
float gain = gain_ramp.GetValue(i);
float pan = pan_ramp.GetValue(i);
float s1 = frames[2 * i];
float s2 = frames[2 * i + 1];