forked from id-Software/DOOM-iOS
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSoundEngine.cpp
More file actions
1812 lines (1538 loc) · 54.7 KB
/
SoundEngine.cpp
File metadata and controls
1812 lines (1538 loc) · 54.7 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
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
/*
File: SoundEngine.cpp
Abstract: These functions play background music tracks, multiple sound effects,
and support stereo panning with a low-latency response.
Version: 1.7
Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple Inc.
("Apple") in consideration of your agreement to the following terms, and your
use, installation, modification or redistribution of this Apple software
constitutes acceptance of these terms. If you do not agree with these terms,
please do not use, install, modify or redistribute this Apple software.
In consideration of your agreement to abide by the following terms, and subject
to these terms, Apple grants you a personal, non-exclusive license, under
Apple's copyrights in this original Apple software (the "Apple Software"), to
use, reproduce, modify and redistribute the Apple Software, with or without
modifications, in source and/or binary forms; provided that if you redistribute
the Apple Software in its entirety and without modifications, you must retain
this notice and the following text and disclaimers in all such redistributions
of the Apple Software.
Neither the name, trademarks, service marks or logos of Apple Inc. may be used
to endorse or promote products derived from the Apple Software without specific
prior written permission from Apple. Except as expressly stated in this notice,
no other rights or licenses, express or implied, are granted by Apple herein,
including but not limited to any patent rights that may be infringed by your
derivative works or by other works in which the Apple Software may be
incorporated.
The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO
WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED
WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN
COMBINATION WITH YOUR PRODUCTS.
IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR
DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF
CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF
APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Copyright (C) 2008 Apple Inc. All Rights Reserved.
*/
// Local Includes
#include "SoundEngine.h"
#ifndef WIN32
/*==================================================================================================
SoundEngine.cpp
==================================================================================================*/
//==================================================================================================
// Includes
//==================================================================================================
// System Includes
#include <AudioToolbox/AudioToolbox.h>
#include <CoreFoundation/CFURL.h>
#include <OpenAL/al.h>
#include <OpenAL/alc.h>
#include <map>
#include <vector>
#include <pthread.h>
#include <mach/mach.h>
#include <string>
#define AssertNoError(inMessage, inHandler) \
if(result != noErr) \
{ \
printf("%s: %d\n", inMessage, (int)result); \
goto inHandler; \
}
#define AssertNoOALError(inMessage, inHandler) \
if((result = alGetError()) != AL_NO_ERROR) \
{ \
printf("%s: %x\n", inMessage, (int)result); \
goto inHandler; \
}
#define kNumberBuffers 3
class OpenALObject;
class BackgroundTrackMgr;
static OpenALObject *sOpenALObject = NULL;
static BackgroundTrackMgr *sBackgroundTrackMgr = NULL;
static Float32 gMasterVolumeGain = 1.0f;
static bool isInitialized = false;
static bool gInterrupted = false;
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
typedef ALvoid AL_APIENTRY (*alBufferDataStaticProcPtr) (const ALint bid, ALenum format, ALvoid* data, ALsizei size, ALsizei freq);
ALvoid alBufferDataStaticProc(const ALint bid, ALenum format, ALvoid* data, ALsizei size, ALsizei freq)
{
static alBufferDataStaticProcPtr proc = NULL;
if (proc == NULL) {
proc = (alBufferDataStaticProcPtr) alcGetProcAddress(NULL, (const ALCchar*) "alBufferDataStatic");
}
if (proc)
proc(bid, format, data, size, freq);
return;
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
typedef ALvoid AL_APIENTRY (*alcMacOSXMixerOutputRateProcPtr) (const ALdouble value);
ALvoid alcMacOSXMixerOutputRateProc(const ALdouble value)
{
static alcMacOSXMixerOutputRateProcPtr proc = NULL;
if (proc == NULL) {
proc = (alcMacOSXMixerOutputRateProcPtr) alcGetProcAddress(NULL, (const ALCchar*) "alcMacOSXMixerOutputRate");
}
if (proc)
proc(value);
return;
}
#pragma mark ***** OpenALThread *****
//==================================================================================================
// Threading functions
//==================================================================================================
class OpenALThread
{
// returns the thread's priority as it was last set by the API
#define OpenALThread_SET_PRIORITY 0
// returns the thread's priority as it was last scheduled by the Kernel
#define OpenALThread_SCHEDULED_PRIORITY 1
// Types
public:
typedef void* (*ThreadRoutine)(void* inParameter);
// Constants
public:
enum
{
kMinThreadPriority = 1,
kMaxThreadPriority = 63,
kDefaultThreadPriority = 31
};
// Construction/Destruction
public:
OpenALThread(ThreadRoutine inThreadRoutine, void* inParameter)
: mPThread(0),
mSpawningThreadPriority(getScheduledPriority(pthread_self(), OpenALThread_SET_PRIORITY)),
mThreadRoutine(inThreadRoutine),
mThreadParameter(inParameter),
mPriority(kDefaultThreadPriority),
mFixedPriority(false),
mAutoDelete(true) { }
~OpenALThread() { }
// Properties
bool IsRunning() const { return 0 != mPThread; }
void SetAutoDelete(bool b) { mAutoDelete = b; }
void SetPriority(UInt32 inPriority, bool inFixedPriority)
{
OSStatus result = noErr;
mPriority = inPriority;
mFixedPriority = inFixedPriority;
if(mPThread != 0)
{
if (mFixedPriority)
{
thread_extended_policy_data_t theFixedPolicy;
theFixedPolicy.timeshare = false; // set to true for a non-fixed thread
result = thread_policy_set(pthread_mach_thread_np(mPThread), THREAD_EXTENDED_POLICY, (thread_policy_t)&theFixedPolicy, THREAD_EXTENDED_POLICY_COUNT);
if (result) {
printf("OpenALThread::SetPriority: failed to set the fixed-priority policy");
return;
}
}
// We keep a reference to the spawning thread's priority around (initialized in the constructor),
// and set the importance of the child thread relative to the spawning thread's priority.
thread_precedence_policy_data_t thePrecedencePolicy;
thePrecedencePolicy.importance = mPriority - mSpawningThreadPriority;
result =thread_policy_set(pthread_mach_thread_np(mPThread), THREAD_PRECEDENCE_POLICY, (thread_policy_t)&thePrecedencePolicy, THREAD_PRECEDENCE_POLICY_COUNT);
if (result) {
printf("OpenALThread::SetPriority: failed to set the precedence policy");
return;
}
}
}
// Actions
void Start()
{
if(mPThread != 0)
{
printf("OpenALThread::Start: can't start because the thread is already running\n");
return;
}
OSStatus result;
pthread_attr_t theThreadAttributes;
result = pthread_attr_init(&theThreadAttributes);
AssertNoError("Error initializing thread", end);
result = pthread_attr_setdetachstate(&theThreadAttributes, PTHREAD_CREATE_DETACHED);
AssertNoError("Error setting thread detach state", end);
result = pthread_create(&mPThread, &theThreadAttributes, (ThreadRoutine)OpenALThread::Entry, this);
AssertNoError("Error creating thread", end);
pthread_attr_destroy(&theThreadAttributes);
AssertNoError("Error destroying thread attributes", end);
end:
return;
}
// Implementation
protected:
static void* Entry(OpenALThread* inOpenALThread)
{
void* theAnswer = NULL;
inOpenALThread->SetPriority(inOpenALThread->mPriority, inOpenALThread->mFixedPriority);
if(inOpenALThread->mThreadRoutine != NULL)
{
theAnswer = inOpenALThread->mThreadRoutine(inOpenALThread->mThreadParameter);
}
inOpenALThread->mPThread = 0;
if (inOpenALThread->mAutoDelete)
delete inOpenALThread;
return theAnswer;
}
static UInt32 getScheduledPriority(pthread_t inThread, int inPriorityKind)
{
thread_basic_info_data_t threadInfo;
policy_info_data_t thePolicyInfo;
unsigned int count;
if (inThread == NULL)
return 0;
// get basic info
count = THREAD_BASIC_INFO_COUNT;
thread_info (pthread_mach_thread_np (inThread), THREAD_BASIC_INFO, (thread_info_t)&threadInfo, &count);
switch (threadInfo.policy) {
case POLICY_TIMESHARE:
count = POLICY_TIMESHARE_INFO_COUNT;
thread_info(pthread_mach_thread_np (inThread), THREAD_SCHED_TIMESHARE_INFO, (thread_info_t)&(thePolicyInfo.ts), &count);
if (inPriorityKind == OpenALThread_SCHEDULED_PRIORITY) {
return thePolicyInfo.ts.cur_priority;
}
return thePolicyInfo.ts.base_priority;
break;
case POLICY_FIFO:
count = POLICY_FIFO_INFO_COUNT;
thread_info(pthread_mach_thread_np (inThread), THREAD_SCHED_FIFO_INFO, (thread_info_t)&(thePolicyInfo.fifo), &count);
if ( (thePolicyInfo.fifo.depressed) && (inPriorityKind == OpenALThread_SCHEDULED_PRIORITY) ) {
return thePolicyInfo.fifo.depress_priority;
}
return thePolicyInfo.fifo.base_priority;
break;
case POLICY_RR:
count = POLICY_RR_INFO_COUNT;
thread_info(pthread_mach_thread_np (inThread), THREAD_SCHED_RR_INFO, (thread_info_t)&(thePolicyInfo.rr), &count);
if ( (thePolicyInfo.rr.depressed) && (inPriorityKind == OpenALThread_SCHEDULED_PRIORITY) ) {
return thePolicyInfo.rr.depress_priority;
}
return thePolicyInfo.rr.base_priority;
break;
}
return 0;
}
pthread_t mPThread;
UInt32 mSpawningThreadPriority;
ThreadRoutine mThreadRoutine;
void* mThreadParameter;
SInt32 mPriority;
bool mFixedPriority;
bool mAutoDelete; // delete self when thread terminates
};
//==================================================================================================
// Helper functions
//==================================================================================================
OSStatus OpenFile(const char *inFilePath, AudioFileID &outAFID)
{
CFURLRef theURL = CFURLCreateFromFileSystemRepresentation(kCFAllocatorDefault, (UInt8*)inFilePath, strlen(inFilePath), false);
if (theURL == NULL)
return kSoundEngineErrFileNotFound;
#if TARGET_OS_IPHONE
OSStatus result = AudioFileOpenURL(theURL, kAudioFileReadPermission, 0, &outAFID);
#else
OSStatus result = AudioFileOpenURL(theURL, fsRdPerm, 0, &outAFID);
#endif
CFRelease(theURL);
AssertNoError("Error opening file", end);
end:
return result;
}
OSStatus LoadFileDataInfo(const char *inFilePath, AudioFileID &outAFID, AudioStreamBasicDescription &outFormat, UInt64 &outDataSize)
{
UInt32 thePropSize = sizeof(outFormat);
OSStatus result = OpenFile(inFilePath, outAFID);
AssertNoError("Error opening file", end);
result = AudioFileGetProperty(outAFID, kAudioFilePropertyDataFormat, &thePropSize, &outFormat);
AssertNoError("Error getting file format", end);
thePropSize = sizeof(UInt64);
result = AudioFileGetProperty(outAFID, kAudioFilePropertyAudioDataByteCount, &thePropSize, &outDataSize);
AssertNoError("Error getting file data size", end);
end:
return result;
}
void CalculateBytesForTime (AudioStreamBasicDescription & inDesc, UInt32 inMaxPacketSize, Float64 inSeconds, UInt32 *outBufferSize, UInt32 *outNumPackets)
{
static const UInt32 maxBufferSize = 0x10000; // limit size to 64K
static const UInt32 minBufferSize = 0x4000; // limit size to 16K
if (inDesc.mFramesPerPacket) {
Float64 numPacketsForTime = inDesc.mSampleRate / inDesc.mFramesPerPacket * inSeconds;
*outBufferSize = (long unsigned int)numPacketsForTime * inMaxPacketSize;
} else {
// if frames per packet is zero, then the codec has no predictable packet == time
// so we can't tailor this (we don't know how many Packets represent a time period
// we'll just return a default buffer size
*outBufferSize = maxBufferSize > inMaxPacketSize ? maxBufferSize : inMaxPacketSize;
}
// we're going to limit our size to our default
if (*outBufferSize > maxBufferSize && *outBufferSize > inMaxPacketSize)
*outBufferSize = maxBufferSize;
else {
// also make sure we're not too small - we don't want to go the disk for too small chunks
if (*outBufferSize < minBufferSize)
*outBufferSize = minBufferSize;
}
*outNumPackets = *outBufferSize / inMaxPacketSize;
}
static Boolean MatchFormatFlags(const AudioStreamBasicDescription& x, const AudioStreamBasicDescription& y)
{
UInt32 xFlags = x.mFormatFlags;
UInt32 yFlags = y.mFormatFlags;
// match wildcards
if (x.mFormatID == 0 || y.mFormatID == 0 || xFlags == 0 || yFlags == 0)
return true;
if (x.mFormatID == kAudioFormatLinearPCM)
{
// knock off the all clear flag
xFlags = xFlags & ~kAudioFormatFlagsAreAllClear;
yFlags = yFlags & ~kAudioFormatFlagsAreAllClear;
// if both kAudioFormatFlagIsPacked bits are set, then we don't care about the kAudioFormatFlagIsAlignedHigh bit.
if (xFlags & yFlags & kAudioFormatFlagIsPacked) {
xFlags = xFlags & ~kAudioFormatFlagIsAlignedHigh;
yFlags = yFlags & ~kAudioFormatFlagIsAlignedHigh;
}
// if both kAudioFormatFlagIsFloat bits are set, then we don't care about the kAudioFormatFlagIsSignedInteger bit.
if (xFlags & yFlags & kAudioFormatFlagIsFloat) {
xFlags = xFlags & ~kAudioFormatFlagIsSignedInteger;
yFlags = yFlags & ~kAudioFormatFlagIsSignedInteger;
}
// if the bit depth is 8 bits or less and the format is packed, we don't care about endianness
if((x.mBitsPerChannel <= 8) && ((xFlags & kAudioFormatFlagIsPacked) == kAudioFormatFlagIsPacked))
{
xFlags = xFlags & ~kAudioFormatFlagIsBigEndian;
}
if((y.mBitsPerChannel <= 8) && ((yFlags & kAudioFormatFlagIsPacked) == kAudioFormatFlagIsPacked))
{
yFlags = yFlags & ~kAudioFormatFlagIsBigEndian;
}
// if the number of channels is 0 or 1, we don't care about non-interleavedness
if (x.mChannelsPerFrame <= 1 && y.mChannelsPerFrame <= 1) {
xFlags &= ~kLinearPCMFormatFlagIsNonInterleaved;
yFlags &= ~kLinearPCMFormatFlagIsNonInterleaved;
}
}
return xFlags == yFlags;
}
Boolean FormatIsEqual(AudioStreamBasicDescription x, AudioStreamBasicDescription y)
{
// the semantics for equality are:
// 1) Values must match exactly
// 2) wildcard's are ignored in the comparison
#define MATCH(name) ((x.name) == 0 || (y.name) == 0 || (x.name) == (y.name))
return
((x.mSampleRate==0.) || (y.mSampleRate==0.) || (x.mSampleRate==y.mSampleRate))
&& MATCH(mFormatID)
&& MatchFormatFlags(x, y)
&& MATCH(mBytesPerPacket)
&& MATCH(mFramesPerPacket)
&& MATCH(mBytesPerFrame)
&& MATCH(mChannelsPerFrame)
&& MATCH(mBitsPerChannel) ;
}
#pragma mark ***** BackgroundTrackMgr *****
//==================================================================================================
// BackgroundTrackMgr class
//==================================================================================================
class BackgroundTrackMgr
{
#define CurFileInfo THIS->mBGFileInfo[THIS->mCurrentFileIndex]
public:
typedef struct BG_FileInfo {
std::string mFilePath;
AudioFileID mAFID;
AudioStreamBasicDescription mFileFormat;
UInt64 mFileDataSize;
//UInt64 mFileNumPackets; // this is only used if loading file to memory
Boolean mLoadAtOnce;
Boolean mFileDataInQueue;
} BackgroundMusicFileInfo;
BackgroundTrackMgr();
~BackgroundTrackMgr();
void Teardown();
void ClearFileInfo();
AudioStreamPacketDescription *GetPacketDescsPtr();
UInt32 GetNumPacketsToRead(BackgroundTrackMgr::BG_FileInfo *inFileInfo);
static OSStatus AttachNewCookie(AudioQueueRef inQueue, BackgroundTrackMgr::BG_FileInfo *inFileInfo);
static void QueueStoppedProc( void * inUserData, AudioQueueRef inAQ, AudioQueuePropertyID inID );
static Boolean DisposeBuffer(AudioQueueRef inAQ, std::vector<AudioQueueBufferRef> inDisposeBufferList, AudioQueueBufferRef inBufferToDispose);
enum {
kQueueState_DoNothing = 0,
kQueueState_ResizeBuffer = 1,
kQueueState_NeedNewCookie = 2,
kQueueState_NeedNewBuffers = 3,
kQueueState_NeedNewQueue = 4,
};
static SInt8 GetQueueStateForNextBuffer(BackgroundTrackMgr::BG_FileInfo *inFileInfo, BackgroundTrackMgr::BG_FileInfo *inNextFileInfo);
static void QueueCallback( void * inUserData, AudioQueueRef inAQ, AudioQueueBufferRef inCompleteAQBuffer);
OSStatus SetupQueue(BG_FileInfo *inFileInfo);
OSStatus SetupBuffers(BG_FileInfo *inFileInfo);
OSStatus LoadTrack(const char* inFilePath, Boolean inAddToQueue, Boolean inLoadAtOnce);
OSStatus UpdateGain();
OSStatus SetVolume(Float32 inVolume);
Float32 GetVolume() const;
OSStatus Start();
OSStatus Stop(Boolean inStopAtEnd);
private:
AudioQueueRef mQueue;
AudioQueueBufferRef mBuffers[kNumberBuffers];
UInt32 mBufferByteSize;
SInt64 mCurrentPacket;
UInt32 mNumPacketsToRead;
Float32 mVolume;
AudioStreamPacketDescription * mPacketDescs;
std::vector<BG_FileInfo*> mBGFileInfo;
UInt32 mCurrentFileIndex;
Boolean mMakeNewQueueWhenStopped;
Boolean mStopAtEnd;
std::vector<AudioQueueBufferRef> mBuffersToDispose;
};
BackgroundTrackMgr::BackgroundTrackMgr()
: mQueue(0),
mBufferByteSize(0),
mCurrentPacket(0),
mNumPacketsToRead(0),
mVolume(1.0f),
mPacketDescs(NULL),
mCurrentFileIndex(0),
mMakeNewQueueWhenStopped(false),
mStopAtEnd(false)
{ }
BackgroundTrackMgr::~BackgroundTrackMgr() {
Teardown();
}
void BackgroundTrackMgr::Teardown() {
if (mQueue) {
AudioQueueDispose(mQueue, true);
}
for (UInt32 i=0; i < mBGFileInfo.size(); i++) {
if (mBGFileInfo[i]->mAFID) {
AudioFileClose(mBGFileInfo[i]->mAFID);
}
}
if (mPacketDescs) {
delete mPacketDescs;
}
ClearFileInfo();
}
void BackgroundTrackMgr::ClearFileInfo() {
std::vector< BG_FileInfo* >::iterator itr = mBGFileInfo.begin();
std::vector< BG_FileInfo* >::iterator endItr = mBGFileInfo.end();
for( ; itr != endItr; ++itr ) {
delete *itr;
*itr = NULL;
}
mBGFileInfo.clear();
}
AudioStreamPacketDescription *BackgroundTrackMgr::GetPacketDescsPtr() {
return mPacketDescs;
}
UInt32 BackgroundTrackMgr::GetNumPacketsToRead(BackgroundTrackMgr::BG_FileInfo *inFileInfo) {
(void)inFileInfo;
return mNumPacketsToRead;
}
OSStatus BackgroundTrackMgr::AttachNewCookie(AudioQueueRef inQueue, BackgroundTrackMgr::BG_FileInfo *inFileInfo) {
OSStatus result = noErr;
UInt32 size = sizeof(UInt32);
result = AudioFileGetPropertyInfo (inFileInfo->mAFID, kAudioFilePropertyMagicCookieData, &size, NULL);
if (!result && size) {
char* cookie = new char [size];
result = AudioFileGetProperty (inFileInfo->mAFID, kAudioFilePropertyMagicCookieData, &size, cookie);
AssertNoError("Error getting cookie data", end);
result = AudioQueueSetProperty(inQueue, kAudioQueueProperty_MagicCookie, cookie, size);
delete [] cookie;
AssertNoError("Error setting cookie data for queue", end);
}
return noErr;
end:
return noErr;
}
void BackgroundTrackMgr::QueueStoppedProc( void * inUserData, AudioQueueRef inAQ, AudioQueuePropertyID inID ) {
(void)inID;
UInt32 isRunning;
UInt32 propSize = sizeof(isRunning);
BackgroundTrackMgr *THIS = (BackgroundTrackMgr*)inUserData;
OSStatus result = AudioQueueGetProperty(inAQ, kAudioQueueProperty_IsRunning, &isRunning, &propSize);
if ((!isRunning) && (THIS->mMakeNewQueueWhenStopped)) {
result = AudioQueueDispose(inAQ, true);
AssertNoError("Error disposing queue", end);
result = THIS->SetupQueue(CurFileInfo);
AssertNoError("Error setting up new queue", end);
result = THIS->SetupBuffers(CurFileInfo);
AssertNoError("Error setting up new queue buffers", end);
result = THIS->Start();
AssertNoError("Error starting queue", end);
}
end:
return;
}
Boolean BackgroundTrackMgr::DisposeBuffer(AudioQueueRef inAQ, std::vector<AudioQueueBufferRef> inDisposeBufferList, AudioQueueBufferRef inBufferToDispose) {
for (unsigned int i=0; i < inDisposeBufferList.size(); i++) {
if (inBufferToDispose == inDisposeBufferList[i]) {
OSStatus result = AudioQueueFreeBuffer(inAQ, inBufferToDispose);
if (result == noErr) {
inDisposeBufferList.pop_back();
}
return true;
}
}
return false;
}
SInt8 BackgroundTrackMgr::GetQueueStateForNextBuffer(BackgroundTrackMgr::BG_FileInfo *inFileInfo, BackgroundTrackMgr::BG_FileInfo *inNextFileInfo) {
inFileInfo->mFileDataInQueue = false;
// unless the data formats are the same, we need a new queue
if (!FormatIsEqual(inFileInfo->mFileFormat, inNextFileInfo->mFileFormat)) {
return kQueueState_NeedNewQueue;
}
// if going from a load-at-once file to streaming or vice versa, we need new buffers
if (inFileInfo->mLoadAtOnce != inNextFileInfo->mLoadAtOnce) {
return kQueueState_NeedNewBuffers;
}
// if the next file is smaller than the current, we just need to resize
if (inNextFileInfo->mLoadAtOnce) {
return (inFileInfo->mFileDataSize >= inNextFileInfo->mFileDataSize) ? kQueueState_ResizeBuffer : kQueueState_NeedNewBuffers;
}
return kQueueState_NeedNewCookie;
}
void BackgroundTrackMgr::QueueCallback( void * inUserData, AudioQueueRef inAQ, AudioQueueBufferRef inCompleteAQBuffer ) {
// dispose of the buffer if no longer in use
OSStatus result = noErr;
BackgroundTrackMgr *THIS = (BackgroundTrackMgr*)inUserData;
if (DisposeBuffer(inAQ, THIS->mBuffersToDispose, inCompleteAQBuffer)) {
return;
}
UInt32 nPackets = 0;
// loop the current buffer if the following:
// 1. file was loaded into the buffer previously
// 2. only one file in the queue
// 3. we have not been told to stop at playlist completion
if ((CurFileInfo->mFileDataInQueue) && (THIS->mBGFileInfo.size() == 1) && (!THIS->mStopAtEnd)) {
nPackets = THIS->GetNumPacketsToRead(CurFileInfo);
} else {
UInt32 numBytes;
while (nPackets == 0) {
// if loadAtOnce, get all packets in the file, otherwise ~.5 seconds of data
nPackets = THIS->GetNumPacketsToRead(CurFileInfo);
result = AudioFileReadPackets(CurFileInfo->mAFID, false, &numBytes, THIS->mPacketDescs, THIS->mCurrentPacket, &nPackets,
inCompleteAQBuffer->mAudioData);
AssertNoError("Error reading file data", end);
inCompleteAQBuffer->mAudioDataByteSize = numBytes;
if (nPackets == 0) { // no packets were read, this file has ended.
if (CurFileInfo->mLoadAtOnce) {
CurFileInfo->mFileDataInQueue = true;
}
THIS->mCurrentPacket = 0;
UInt32 theNextFileIndex = (THIS->mCurrentFileIndex < THIS->mBGFileInfo.size()-1) ? THIS->mCurrentFileIndex+1 : 0;
// we have gone through the playlist. if mStopAtEnd, stop the queue here
if (theNextFileIndex == 0 && THIS->mStopAtEnd) {
result = AudioQueueStop(inAQ, false);
AssertNoError("Error stopping queue", end);
return;
}
SInt8 theQueueState = GetQueueStateForNextBuffer(CurFileInfo, THIS->mBGFileInfo[theNextFileIndex]);
if (theNextFileIndex != THIS->mCurrentFileIndex) {
// if were are not looping the same file. Close the old one and open the new
result = AudioFileClose(CurFileInfo->mAFID);
AssertNoError("Error closing file", end);
THIS->mCurrentFileIndex = theNextFileIndex;
result = LoadFileDataInfo(CurFileInfo->mFilePath.c_str(), CurFileInfo->mAFID, CurFileInfo->mFileFormat, CurFileInfo->mFileDataSize);
AssertNoError("Error opening file", end);
}
switch (theQueueState) {
// if we need to resize the buffer, set the buffer's audio data size to the new file's size
// we will also need to get the new file cookie
case kQueueState_ResizeBuffer:
inCompleteAQBuffer->mAudioDataByteSize = (UInt32)CurFileInfo->mFileDataSize;
// if the data format is the same but we just need a new cookie, attach a new cookie
case kQueueState_NeedNewCookie:
result = AttachNewCookie(inAQ, CurFileInfo);
AssertNoError("Error attaching new file cookie data to queue", end);
break;
// we can keep the same queue, but not the same buffer(s)
case kQueueState_NeedNewBuffers:
THIS->mBuffersToDispose.push_back(inCompleteAQBuffer);
THIS->SetupBuffers(CurFileInfo);
break;
// if the data formats are not the same, we need to dispose the current queue and create a new one
case kQueueState_NeedNewQueue:
THIS->mMakeNewQueueWhenStopped = true;
result = AudioQueueStop(inAQ, false);
AssertNoError("Error stopping queue", end);
return;
default:
break;
}
}
}
}
result = AudioQueueEnqueueBuffer(inAQ, inCompleteAQBuffer, (THIS->mPacketDescs ? nPackets : 0), THIS->mPacketDescs);
if(result != noErr) {
result = AudioQueueFreeBuffer(inAQ, inCompleteAQBuffer);
AssertNoError("Error freeing buffers that didn't enqueue", end);
}
AssertNoError("Error enqueuing new buffer", end);
if (CurFileInfo->mLoadAtOnce) {
CurFileInfo->mFileDataInQueue = true;
}
THIS->mCurrentPacket += nPackets;
end:
return;
}
OSStatus BackgroundTrackMgr::SetupQueue(BG_FileInfo *inFileInfo) {
UInt32 size = 0;
OSStatus result = AudioQueueNewOutput(&inFileInfo->mFileFormat, QueueCallback, this, CFRunLoopGetCurrent(), kCFRunLoopCommonModes, 0, &mQueue);
AssertNoError("Error creating queue", end);
// (2) If the file has a cookie, we should get it and set it on the AQ
size = sizeof(UInt32);
result = AudioFileGetPropertyInfo (inFileInfo->mAFID, kAudioFilePropertyMagicCookieData, &size, NULL);
if (!result && size) {
char* cookie = new char [size];
result = AudioFileGetProperty (inFileInfo->mAFID, kAudioFilePropertyMagicCookieData, &size, cookie);
AssertNoError("Error getting magic cookie", end);
result = AudioQueueSetProperty(mQueue, kAudioQueueProperty_MagicCookie, cookie, size);
delete [] cookie;
AssertNoError("Error setting magic cookie", end);
}
// channel layout
OSStatus err = AudioFileGetPropertyInfo(inFileInfo->mAFID, kAudioFilePropertyChannelLayout, &size, NULL);
if (err == noErr && size > 0) {
AudioChannelLayout *acl = (AudioChannelLayout *)malloc(size);
result = AudioFileGetProperty(inFileInfo->mAFID, kAudioFilePropertyChannelLayout, &size, acl);
AssertNoError("Error getting channel layout from file", end);
result = AudioQueueSetProperty(mQueue, kAudioQueueProperty_ChannelLayout, acl, size);
free(acl);
AssertNoError("Error setting channel layout on queue", end);
}
// add a notification proc for when the queue stops
result = AudioQueueAddPropertyListener(mQueue, kAudioQueueProperty_IsRunning, QueueStoppedProc, this);
AssertNoError("Error adding isRunning property listener to queue", end);
// we need to reset this variable so that if the queue is stopped mid buffer we don't dispose it
mMakeNewQueueWhenStopped = false;
// volume
result = SetVolume(mVolume);
end:
return result;
}
OSStatus BackgroundTrackMgr::SetupBuffers(BG_FileInfo *inFileInfo) {
int numBuffersToQueue = kNumberBuffers;
UInt32 maxPacketSize;
UInt32 size = sizeof(maxPacketSize);
// we need to calculate how many packets we read at a time, and how big a buffer we need
// we base this on the size of the packets in the file and an approximate duration for each buffer
// first check to see what the max size of a packet is - if it is bigger
// than our allocation default size, that needs to become larger
OSStatus result = AudioFileGetProperty(inFileInfo->mAFID, kAudioFilePropertyPacketSizeUpperBound, &size, &maxPacketSize);
AssertNoError("Error getting packet upper bound size", end);
bool isFormatVBR = (inFileInfo->mFileFormat.mBytesPerPacket == 0 || inFileInfo->mFileFormat.mFramesPerPacket == 0);
CalculateBytesForTime(inFileInfo->mFileFormat, maxPacketSize, 0.5/*seconds*/, &mBufferByteSize, &mNumPacketsToRead);
// if the file is smaller than the capacity of all the buffer queues, always load it at once
if ((mBufferByteSize * numBuffersToQueue) > inFileInfo->mFileDataSize) {
inFileInfo->mLoadAtOnce = true;
}
if (inFileInfo->mLoadAtOnce) {
UInt64 theFileNumPackets;
size = sizeof(UInt64);
result = AudioFileGetProperty(inFileInfo->mAFID, kAudioFilePropertyAudioDataPacketCount, &size, &theFileNumPackets);
AssertNoError("Error getting packet count for file", end);
mNumPacketsToRead = (UInt32)theFileNumPackets;
mBufferByteSize = (UInt32)inFileInfo->mFileDataSize;
numBuffersToQueue = 1;
} else {
mNumPacketsToRead = mBufferByteSize / maxPacketSize;
}
if (isFormatVBR) {
mPacketDescs = new AudioStreamPacketDescription [mNumPacketsToRead];
} else {
mPacketDescs = NULL; // we don't provide packet descriptions for constant bit rate formats (like linear PCM)
}
// allocate the queue's buffers
for (int i = 0; i < numBuffersToQueue; ++i) {
result = AudioQueueAllocateBuffer(mQueue, mBufferByteSize, &mBuffers[i]);
AssertNoError("Error allocating buffer for queue", end);
QueueCallback (this, mQueue, mBuffers[i]);
if (inFileInfo->mLoadAtOnce) {
inFileInfo->mFileDataInQueue = true;
}
}
end:
return result;
}
OSStatus BackgroundTrackMgr::LoadTrack(const char* inFilePath, Boolean inAddToQueue, Boolean inLoadAtOnce) {
BG_FileInfo *fileInfo = new BG_FileInfo;
fileInfo->mFilePath = inFilePath;
OSStatus result = LoadFileDataInfo(fileInfo->mFilePath.c_str(), fileInfo->mAFID, fileInfo->mFileFormat, fileInfo->mFileDataSize);
AssertNoError("Error getting file data info", fail);
fileInfo->mLoadAtOnce = inLoadAtOnce;
fileInfo->mFileDataInQueue = false;
// if not adding to the queue, clear the current file vector
if (!inAddToQueue) {
ClearFileInfo();
}
mBGFileInfo.push_back(fileInfo);
// setup the queue if this is the first (or only) file
if (mBGFileInfo.size() == 1) {
result = SetupQueue(fileInfo);
AssertNoError("Error setting up queue", fail);
result = SetupBuffers(fileInfo);
AssertNoError("Error setting up queue buffers", fail);
} else { // if this is just part of the playlist, close the file for now
result = AudioFileClose(fileInfo->mAFID);
AssertNoError("Error closing file", fail);
}
return result;
fail:
if (fileInfo) {
delete fileInfo;
}
return result;
}
OSStatus BackgroundTrackMgr::UpdateGain() {
return SetVolume(mVolume);
}
OSStatus BackgroundTrackMgr::SetVolume(Float32 inVolume) {
mVolume = inVolume;
return AudioQueueSetParameter(mQueue, kAudioQueueParam_Volume, mVolume * gMasterVolumeGain);
}
Float32 BackgroundTrackMgr::GetVolume() const {
return mVolume;
}
OSStatus BackgroundTrackMgr::Start() {
if(gInterrupted) {
printf("Start called, but interrupted so ignoring.\n");
return noErr;
}
OSStatus result = AudioQueuePrime(mQueue, 1, NULL);
if (result) {
printf("Error priming queue: %d\n", (int)result);
return result;
}
return AudioQueueStart(mQueue, NULL);
}
OSStatus BackgroundTrackMgr::Stop(Boolean inStopAtEnd) {
if (inStopAtEnd) {
mStopAtEnd = true;
return noErr;
} else {
return AudioQueueStop(mQueue, true);
}
}
#pragma mark ***** SoundEngineEffect *****
//==================================================================================================
// SoundEngineEffect class
//==================================================================================================
class SoundEngineEffect
{
public:
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
SoundEngineEffect(const char* inLoopPath, const char* inAttackPath, const char* inDecayPath, Boolean inDoLoop)
: mSourceID(0),
mAttackBufferID(0),
mLoopBufferID(0),
mDecayBufferID(0),
mLoopPath(inLoopPath),
mAttackPath(inAttackPath),
mDecayPath(inDecayPath),
mLoopData(NULL),
mAttackData(NULL),
mDecayData(NULL),
mLoopDataSize(0),
mAttackDataSize(0),
mDecayDataSize(0),
mIsLoopingEffect(inDoLoop),
mPlayThread(NULL),
mPlayThreadState(kPlayThreadState_Loop) { alGenSources(1, &mSourceID); }
~SoundEngineEffect()
{
alDeleteSources(1, &mSourceID);
if (mLoopData)
free(mLoopData);
if (mAttackData)
free(mAttackData);
if (mDecayData)
free(mDecayData);
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Accessors
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
UInt32 GetEffectID() { return mSourceID; }
UInt32 GetPlayThreadState() { return mPlayThreadState; }
Boolean HasAttackBuffer() { return mAttackBufferID != 0; }
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Helper Functions
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
ALenum GetALFormat(AudioStreamBasicDescription inFileFormat)
{
if (inFileFormat.mFormatID != kAudioFormatLinearPCM)
return kSoundEngineErrInvalidFileFormat;
if ((inFileFormat.mChannelsPerFrame > 2) || (inFileFormat.mChannelsPerFrame < 1))
return kSoundEngineErrInvalidFileFormat;
if(inFileFormat.mBitsPerChannel == 8)
return (inFileFormat.mChannelsPerFrame == 1) ? AL_FORMAT_MONO8 : AL_FORMAT_STEREO8;
else if(inFileFormat.mBitsPerChannel == 16)
return (inFileFormat.mChannelsPerFrame == 1) ? AL_FORMAT_MONO16 : AL_FORMAT_STEREO16;
return kSoundEngineErrInvalidFileFormat;
}
OSStatus LoadFileData(const char *inFilePath, void* &outData, UInt32 &outDataSize, ALuint &outBufferID)
{
AudioFileID theAFID = 0;
OSStatus result = noErr;
UInt64 theFileSize = 0;
AudioStreamBasicDescription theFileFormat;
result = LoadFileDataInfo(inFilePath, theAFID, theFileFormat, theFileSize);
outDataSize = (UInt32)theFileSize;
AssertNoError("Error loading file info", fail)
outData = malloc(outDataSize);
result = AudioFileReadBytes(theAFID, false, 0, &outDataSize, outData);
AssertNoError("Error reading file data", fail)
if (!TestAudioFormatNativeEndian(theFileFormat) && (theFileFormat.mBitsPerChannel > 8))
return kSoundEngineErrInvalidFileFormat;
alGenBuffers(1, &outBufferID);
AssertNoOALError("Error generating buffer\n", fail);
alBufferDataStaticProc(outBufferID, GetALFormat(theFileFormat), outData, outDataSize, (ALsizei)theFileFormat.mSampleRate);
AssertNoOALError("Error attaching data to buffer\n", fail);
AudioFileClose(theAFID);
return result;
fail:
if (theAFID)
AudioFileClose(theAFID);
if (outData)
{
free(outData);
outData = NULL;
}
return result;
}
OSStatus AttachFilesToSource()
{
OSStatus result = AL_NO_ERROR;
// first check for the attack file. That will be first in the queue if present
if (mAttackPath)
{
result = LoadFileData(mAttackPath, mAttackData, mAttackDataSize, mAttackBufferID);
AssertNoError("Error loading attack file info", end)