forked from id-Software/DOOM-iOS
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBackgroundMusic.cpp
More file actions
538 lines (437 loc) · 17.1 KB
/
BackgroundMusic.cpp
File metadata and controls
538 lines (437 loc) · 17.1 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
/*
Copyright (C) 2009-2011 id Software LLC, a ZeniMax Media company.
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
//==================================================================================================
// 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>
extern "C" {
#include "doomiphone.h"
}
enum {
kSoundEngineErrUnitialized = 1,
kSoundEngineErrInvalidID = 2,
kSoundEngineErrFileNotFound = 3,
kSoundEngineErrInvalidFileFormat = 4,
kSoundEngineErrDeviceNotFound = 5
};
#define AssertNoError(inMessage, inHandler) \
if(result != noErr) \
{ \
printf("%s: %d\n", inMessage, (int)result); \
goto inHandler; \
}
#define kNumberBuffers 3
static Float32 gMasterVolumeGain = 0.5f;
//==================================================================================================
// Helper functions
//==================================================================================================
OSStatus LoadFileDataInfo(const char *inFilePath, AudioFileID &outAFID, AudioStreamBasicDescription &outFormat, UInt64 &outDataSize)
{
UInt32 thePropSize;
CFURLRef theURL = CFURLCreateFromFileSystemRepresentation(kCFAllocatorDefault, (UInt8*)inFilePath, strlen(inFilePath), false);
if (theURL == NULL)
return kSoundEngineErrFileNotFound;
OSStatus result = AudioFileOpenURL(theURL, kAudioFileReadPermission, 0, &outAFID);
CFRelease(theURL);
AssertNoError("Error opening file", end);
thePropSize = sizeof(outFormat);
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
//==================================================================================================
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;
class BackgroundTrackMgr
{
public:
BackgroundTrackMgr();
~BackgroundTrackMgr();
void Teardown();
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 SetVolume(Float32 inVolume);
Float32 GetVolume() const;
OSStatus Start();
OSStatus Stop(Boolean inStopAtEnd);
AudioQueueRef mQueue;
AudioQueueBufferRef mBuffers[kNumberBuffers];
UInt32 mBufferByteSize;
SInt64 mCurrentPacket;
UInt32 mNumPacketsToRead;
Float32 mVolume;
AudioStreamPacketDescription * mPacketDescs;
static BG_FileInfo * CurFileInfo;
Boolean mStopAtEnd;
};
BG_FileInfo *BackgroundTrackMgr::CurFileInfo;
BackgroundTrackMgr::BackgroundTrackMgr()
: mQueue(0),
mBufferByteSize(0),
mCurrentPacket(0),
mNumPacketsToRead(0),
mVolume(1.0f),
mPacketDescs(NULL),
mStopAtEnd(false)
{ }
BackgroundTrackMgr::~BackgroundTrackMgr() {
Teardown();
}
void BackgroundTrackMgr::Teardown() {
if (mQueue) {
AudioQueueDispose(mQueue, true);
mQueue = NULL;
}
if ( CurFileInfo ) {
AudioFileClose( CurFileInfo->mAFID);
delete CurFileInfo;
CurFileInfo = NULL;
}
if (mPacketDescs) {
delete[] mPacketDescs;
mPacketDescs = NULL;
}
}
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;
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->mStopAtEnd)) {
nPackets = THIS->mNumPacketsToRead;
} else {
UInt32 numBytes;
while (nPackets == 0) {
// if loadAtOnce, get all packets in the file, otherwise ~.5 seconds of data
nPackets = THIS->mNumPacketsToRead;
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;
// we have gone through the playlist. if mStopAtEnd, stop the queue here
if ( THIS->mStopAtEnd ) {
result = AudioQueueStop(inAQ, false);
AssertNoError("Error stopping queue", end);
return;
}
}
}
}
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 err;
OSStatus result = AudioQueueNewOutput(&inFileInfo->mFileFormat, QueueCallback, this,
CFRunLoopGetMain() /* CFRunLoopGetCurrent() */, kCFRunLoopCommonModes, 0, &mQueue);
AssertNoError("Error creating queue", end);
#if 0
// (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);
}
#endif
// channel layout
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);
}
// volume
result = SetVolume(mVolume);
end:
return result;
}
OSStatus BackgroundTrackMgr::SetupBuffers(BG_FileInfo *inFileInfo) {
int numBuffersToQueue = kNumberBuffers;
UInt32 maxPacketSize;
UInt32 size = sizeof(maxPacketSize);
bool isFormatVBR;
// 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);
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) {
// OSStatus result = LoadFileDataInfo(CurFileInfo->mFilePath.c_str(), CurFileInfo->mAFID, CurFileInfo->mFileFormat, CurFileInfo->mFileDataSize);
// AssertNoError("Error getting file data info", fail);
OSStatus result;
UInt32 thePropSize;
CFURLRef theURL = CFURLCreateFromFileSystemRepresentation(kCFAllocatorDefault, (UInt8*)inFilePath, strlen(inFilePath), false);
if (theURL == NULL)
result = kSoundEngineErrFileNotFound;
else
result = 0;
AssertNoError("Error opening URL", fail);
CurFileInfo = new BG_FileInfo;
CurFileInfo->mFilePath = inFilePath;
result = AudioFileOpenURL(theURL, kAudioFileReadPermission, 0, &CurFileInfo->mAFID);
CFRelease(theURL);
AssertNoError("Error opening file", fail);
thePropSize = sizeof(CurFileInfo->mFileFormat);
result = AudioFileGetProperty(CurFileInfo->mAFID, kAudioFilePropertyDataFormat, &thePropSize, &CurFileInfo->mFileFormat);
AssertNoError("Error getting file format", fail);
thePropSize = sizeof(UInt64);
result = AudioFileGetProperty(CurFileInfo->mAFID, kAudioFilePropertyAudioDataByteCount, &thePropSize, &CurFileInfo->mFileDataSize);
AssertNoError("Error getting file data size", fail);
CurFileInfo->mLoadAtOnce = inLoadAtOnce;
CurFileInfo->mFileDataInQueue = false;
result = SetupQueue(CurFileInfo);
AssertNoError("Error setting up queue", fail);
result = SetupBuffers(CurFileInfo);
AssertNoError("Error setting up queue buffers", fail);
return result;
fail:
if (CurFileInfo) {
delete CurFileInfo;
CurFileInfo = NULL;
}
return result;
}
OSStatus BackgroundTrackMgr::SetVolume(Float32 inVolume) {
mVolume = inVolume;
return AudioQueueSetParameter(mQueue, kAudioQueueParam_Volume, mVolume * gMasterVolumeGain);
}
Float32 BackgroundTrackMgr::GetVolume() const {
return mVolume;
}
OSStatus BackgroundTrackMgr::Start() {
OSStatus result = AudioQueuePrime(mQueue, 1, NULL);
if (result) {
printf("BackgroundTrackMgr: 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);
}
}
static BackgroundTrackMgr sBackgroundTrackMgr;
static char currentMusicName[1024];
void iphonePauseMusic() {
if( music ) {
if ( music->value == 0 ) {
// music is disabled
return;
}
AudioQueuePause(sBackgroundTrackMgr.mQueue);
}
}
void iphoneResumeMusic() {
if ( music->value == 0 ) {
// music is disabled
return;
}
AudioQueueStart(sBackgroundTrackMgr.mQueue,NULL);
}
void iphoneStopMusic() {
sBackgroundTrackMgr.Teardown();
}
void iphoneStartMusic() {
if ( music->value == 0 ) {
// music is disabled
return;
}
char fullName[1024];
sprintf( fullName, "%s/base/music/d_%s.mp3", SysIphoneGetAppDir(), currentMusicName );
printf( "Starting music '%s'\n", fullName );
iphoneStopMusic();
sBackgroundTrackMgr.LoadTrack( fullName, false, true);
sBackgroundTrackMgr.Start();
if ( !strcmp( currentMusicName, "intro" ) ) {
// stop the intro music at end, don't loop
sBackgroundTrackMgr.mStopAtEnd = true;
} else {
sBackgroundTrackMgr.mStopAtEnd = false;
}
}
void iphonePlayMusic( const char *name ) {
strcpy( currentMusicName, name );
iphoneStartMusic();
}