SoundEngine.mm 64 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) 2013 GarageGames, LLC
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to
  6. // deal in the Software without restriction, including without limitation the
  7. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  8. // sell copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  20. // IN THE SOFTWARE.
  21. //-----------------------------------------------------------------------------
  22. /*
  23. ===== IMPORTANT =====
  24. This is sample code demonstrating API, technology or techniques in development.
  25. Although this sample code has been reviewed for technical accuracy, it is not
  26. final. Apple is supplying this information to help you plan for the adoption of
  27. the technologies and programming interfaces described herein. This information
  28. is subject to change, and software implemented based on this sample code should
  29. be tested with final operating system software and final documentation. Newer
  30. versions of this sample code may be provided with future seeds of the API or
  31. technology. For information about updates to this and other developer
  32. documentation, view the New & Updated sidebars in subsequent documentation
  33. seeds.
  34. =====================
  35. File: SoundEngine.cpp
  36. Abstract: These functions play background music tracks, multiple sound effects,
  37. and support stereo panning with a low-latency response.
  38. Version: 1.6
  39. Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple Inc.
  40. ("Apple") in consideration of your agreement to the following terms, and your
  41. use, installation, modification or redistribution of this Apple software
  42. constitutes acceptance of these terms. If you do not agree with these terms,
  43. please do not use, install, modify or redistribute this Apple software.
  44. In consideration of your agreement to abide by the following terms, and subject
  45. to these terms, Apple grants you a personal, non-exclusive license, under
  46. Apple's copyrights in this original Apple software (the "Apple Software"), to
  47. use, reproduce, modify and redistribute the Apple Software, with or without
  48. modifications, in source and/or binary forms; provided that if you redistribute
  49. the Apple Software in its entirety and without modifications, you must retain
  50. this notice and the following text and disclaimers in all such redistributions
  51. of the Apple Software.
  52. Neither the name, trademarks, service marks or logos of Apple Inc. may be used
  53. to endorse or promote products derived from the Apple Software without specific
  54. prior written permission from Apple. Except as expressly stated in this notice,
  55. no other rights or licenses, express or implied, are granted by Apple herein,
  56. including but not limited to any patent rights that may be infringed by your
  57. derivative works or by other works in which the Apple Software may be
  58. incorporated.
  59. The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO
  60. WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED
  61. WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  62. PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN
  63. COMBINATION WITH YOUR PRODUCTS.
  64. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR
  65. CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
  66. GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  67. ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR
  68. DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF
  69. CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF
  70. APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  71. Copyright (C) 2008 Apple Inc. All Rights Reserved.
  72. */
  73. //==================================================================================================
  74. // Includes
  75. //==================================================================================================
  76. // System Includes
  77. #include <AudioToolbox/AudioToolbox.h>
  78. #include <CoreFoundation/CFURL.h>
  79. #include <OpenAL/al.h>
  80. #include <OpenAL/alc.h>
  81. #include <map>
  82. #include <vector>
  83. #include <pthread.h>
  84. #include <mach/mach.h>
  85. // Local Includes
  86. #include "SoundEngine.h"
  87. namespace SoundEngine {
  88. #define AssertNoError(inMessage, inHandler) \
  89. if(result != noErr) \
  90. { \
  91. printf("%s: %d\n", inMessage, (int)result); \
  92. }
  93. #define AssertNoOALError(inMessage, inHandler) \
  94. if((result = alGetError()) != AL_NO_ERROR) \
  95. { \
  96. printf("%s: %x\n", inMessage, (int)result); \
  97. goto inHandler; \
  98. }
  99. #define kNumberBuffers 3
  100. class OpenALObject;
  101. class BackgroundTrackMgr;
  102. static OpenALObject *sOpenALObject = NULL;
  103. static BackgroundTrackMgr *sBackgroundTrackMgr = NULL;
  104. static Float32 gMasterVolumeGain = 1.0;
  105. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  106. typedef ALvoid AL_APIENTRY (*alBufferDataStaticProcPtr) (const ALint bid, ALenum format, ALvoid* data, ALsizei size, ALsizei freq);
  107. ALvoid alBufferDataStaticProc(const ALint bid, ALenum format, ALvoid* data, ALsizei size, ALsizei freq)
  108. {
  109. static alBufferDataStaticProcPtr proc = NULL;
  110. if (proc == NULL) {
  111. proc = (alBufferDataStaticProcPtr) alcGetProcAddress(NULL, (const ALCchar*) "alBufferDataStatic");
  112. }
  113. if (proc)
  114. proc(bid, format, data, size, freq);
  115. return;
  116. }
  117. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  118. typedef ALvoid AL_APIENTRY (*alcMacOSXMixerOutputRateProcPtr) (const ALdouble value);
  119. ALvoid alcMacOSXMixerOutputRateProc(const ALdouble value)
  120. {
  121. static alcMacOSXMixerOutputRateProcPtr proc = NULL;
  122. if (proc == NULL) {
  123. proc = (alcMacOSXMixerOutputRateProcPtr) alcGetProcAddress(NULL, (const ALCchar*) "alcMacOSXMixerOutputRate");
  124. }
  125. if (proc)
  126. proc(value);
  127. return;
  128. }
  129. #pragma mark ***** OpenALThread *****
  130. //==================================================================================================
  131. // Threading functions
  132. //==================================================================================================
  133. class OpenALThread
  134. {
  135. // returns the thread's priority as it was last set by the API
  136. #define OpenALThread_SET_PRIORITY 0
  137. // returns the thread's priority as it was last scheduled by the Kernel
  138. #define OpenALThread_SCHEDULED_PRIORITY 1
  139. // Types
  140. public:
  141. typedef void* (*ThreadRoutine)(void* inParameter);
  142. // Constants
  143. public:
  144. enum
  145. {
  146. kMinThreadPriority = 1,
  147. kMaxThreadPriority = 63,
  148. kDefaultThreadPriority = 31
  149. };
  150. // Construction/Destruction
  151. public:
  152. OpenALThread(ThreadRoutine inThreadRoutine, void* inParameter)
  153. : mPThread(0),
  154. mSpawningThreadPriority(getScheduledPriority(pthread_self(), OpenALThread_SET_PRIORITY)),
  155. mThreadRoutine(inThreadRoutine),
  156. mThreadParameter(inParameter),
  157. mPriority(kDefaultThreadPriority),
  158. mFixedPriority(false),
  159. mAutoDelete(true) { }
  160. ~OpenALThread() { }
  161. // Properties
  162. bool IsRunning() const { return 0 != mPThread; }
  163. void SetAutoDelete(bool b) { mAutoDelete = b; }
  164. void SetPriority(UInt32 inPriority, bool inFixedPriority)
  165. {
  166. OSStatus result = noErr;
  167. mPriority = inPriority;
  168. mFixedPriority = inFixedPriority;
  169. if(mPThread != 0)
  170. {
  171. if (mFixedPriority)
  172. {
  173. thread_extended_policy_data_t theFixedPolicy;
  174. theFixedPolicy.timeshare = false; // set to true for a non-fixed thread
  175. result = thread_policy_set(pthread_mach_thread_np(mPThread), THREAD_EXTENDED_POLICY, (thread_policy_t)&theFixedPolicy, THREAD_EXTENDED_POLICY_COUNT);
  176. if (result) {
  177. printf("OpenALThread::SetPriority: failed to set the fixed-priority policy");
  178. return;
  179. }
  180. }
  181. // We keep a reference to the spawning thread's priority around (initialized in the constructor),
  182. // and set the importance of the child thread relative to the spawning thread's priority.
  183. thread_precedence_policy_data_t thePrecedencePolicy;
  184. thePrecedencePolicy.importance = mPriority - mSpawningThreadPriority;
  185. result =thread_policy_set(pthread_mach_thread_np(mPThread), THREAD_PRECEDENCE_POLICY, (thread_policy_t)&thePrecedencePolicy, THREAD_PRECEDENCE_POLICY_COUNT);
  186. if (result) {
  187. printf("OpenALThread::SetPriority: failed to set the precedence policy");
  188. return;
  189. }
  190. }
  191. }
  192. // Actions
  193. void Start()
  194. {
  195. if(mPThread != 0)
  196. {
  197. printf("OpenALThread::Start: can't start because the thread is already running\n");
  198. return;
  199. }
  200. OSStatus result;
  201. pthread_attr_t theThreadAttributes;
  202. result = pthread_attr_init(&theThreadAttributes);
  203. AssertNoError("Error initializing thread", end);
  204. result = pthread_attr_setdetachstate(&theThreadAttributes, PTHREAD_CREATE_DETACHED);
  205. AssertNoError("Error setting thread detach state", end);
  206. result = pthread_create(&mPThread, &theThreadAttributes, (ThreadRoutine)OpenALThread::Entry, this);
  207. AssertNoError("Error creating thread", end);
  208. pthread_attr_destroy(&theThreadAttributes);
  209. AssertNoError("Error destroying thread attributes", end);
  210. end:
  211. return;
  212. }
  213. // Implementation
  214. protected:
  215. static void* Entry(OpenALThread* inOpenALThread)
  216. {
  217. void* theAnswer = NULL;
  218. inOpenALThread->SetPriority(inOpenALThread->mPriority, inOpenALThread->mFixedPriority);
  219. if(inOpenALThread->mThreadRoutine != NULL)
  220. {
  221. theAnswer = inOpenALThread->mThreadRoutine(inOpenALThread->mThreadParameter);
  222. }
  223. inOpenALThread->mPThread = 0;
  224. if (inOpenALThread->mAutoDelete)
  225. delete inOpenALThread;
  226. return theAnswer;
  227. }
  228. static UInt32 getScheduledPriority(pthread_t inThread, int inPriorityKind)
  229. {
  230. thread_basic_info_data_t threadInfo;
  231. policy_info_data_t thePolicyInfo;
  232. unsigned int count;
  233. if (inThread == NULL)
  234. return 0;
  235. // get basic info
  236. count = THREAD_BASIC_INFO_COUNT;
  237. thread_info (pthread_mach_thread_np (inThread), THREAD_BASIC_INFO, (thread_info_t)&threadInfo, &count);
  238. switch (threadInfo.policy) {
  239. case POLICY_TIMESHARE:
  240. count = POLICY_TIMESHARE_INFO_COUNT;
  241. thread_info(pthread_mach_thread_np (inThread), THREAD_SCHED_TIMESHARE_INFO, (thread_info_t)&(thePolicyInfo.ts), &count);
  242. if (inPriorityKind == OpenALThread_SCHEDULED_PRIORITY) {
  243. return thePolicyInfo.ts.cur_priority;
  244. }
  245. return thePolicyInfo.ts.base_priority;
  246. break;
  247. case POLICY_FIFO:
  248. count = POLICY_FIFO_INFO_COUNT;
  249. thread_info(pthread_mach_thread_np (inThread), THREAD_SCHED_FIFO_INFO, (thread_info_t)&(thePolicyInfo.fifo), &count);
  250. if ( (thePolicyInfo.fifo.depressed) && (inPriorityKind == OpenALThread_SCHEDULED_PRIORITY) ) {
  251. return thePolicyInfo.fifo.depress_priority;
  252. }
  253. return thePolicyInfo.fifo.base_priority;
  254. break;
  255. case POLICY_RR:
  256. count = POLICY_RR_INFO_COUNT;
  257. thread_info(pthread_mach_thread_np (inThread), THREAD_SCHED_RR_INFO, (thread_info_t)&(thePolicyInfo.rr), &count);
  258. if ( (thePolicyInfo.rr.depressed) && (inPriorityKind == OpenALThread_SCHEDULED_PRIORITY) ) {
  259. return thePolicyInfo.rr.depress_priority;
  260. }
  261. return thePolicyInfo.rr.base_priority;
  262. break;
  263. }
  264. return 0;
  265. }
  266. pthread_t mPThread;
  267. UInt32 mSpawningThreadPriority;
  268. ThreadRoutine mThreadRoutine;
  269. void* mThreadParameter;
  270. SInt32 mPriority;
  271. bool mFixedPriority;
  272. bool mAutoDelete; // delete self when thread terminates
  273. };
  274. //==================================================================================================
  275. // Helper functions
  276. //==================================================================================================
  277. OSStatus OpenFile(const char *inFilePath, AudioFileID &outAFID)
  278. {
  279. CFURLRef theURL = CFURLCreateFromFileSystemRepresentation(kCFAllocatorDefault, (UInt8*)inFilePath, strlen(inFilePath), false);
  280. if (theURL == NULL)
  281. return kSoundEngineErrFileNotFound;
  282. #if TARGET_OS_iOS
  283. OSStatus result = AudioFileOpenURL(theURL, fsRdPerm, 0, &outAFID);
  284. #else
  285. OSStatus result = AudioFileOpenURL(theURL, kAudioFileReadPermission, 0, &outAFID);
  286. #endif
  287. CFRelease(theURL);
  288. AssertNoError("Error opening file", end);
  289. end:
  290. return result;
  291. }
  292. OSStatus LoadFileDataInfo(const char *inFilePath, AudioFileID &outAFID, AudioStreamBasicDescription &outFormat, UInt64 &outDataSize)
  293. {
  294. UInt32 thePropSize = sizeof(outFormat);
  295. OSStatus result = OpenFile(inFilePath, outAFID);
  296. if( result != noErr ) {
  297. int a = 0;
  298. a++;
  299. } else {
  300. int a = 0;
  301. a++;
  302. }
  303. AssertNoError("Error opening file", end);
  304. result = AudioFileGetProperty(outAFID, kAudioFilePropertyDataFormat, &thePropSize, &outFormat);
  305. AssertNoError("Error getting file format", end);
  306. thePropSize = sizeof(UInt64);
  307. result = AudioFileGetProperty(outAFID, kAudioFilePropertyAudioDataByteCount, &thePropSize, &outDataSize);
  308. AssertNoError("Error getting file data size", end);
  309. end:
  310. return result;
  311. }
  312. void CalculateBytesForTime (AudioStreamBasicDescription & inDesc, UInt32 inMaxPacketSize, Float64 inSeconds, UInt32 *outBufferSize, UInt32 *outNumPackets)
  313. {
  314. static const UInt32 maxBufferSize = 0x10000; // limit size to 64K
  315. static const UInt32 minBufferSize = 0x4000; // limit size to 16K
  316. if (inDesc.mFramesPerPacket) {
  317. Float64 numPacketsForTime = inDesc.mSampleRate / inDesc.mFramesPerPacket * inSeconds;
  318. *outBufferSize = numPacketsForTime * inMaxPacketSize;
  319. } else {
  320. // if frames per packet is zero, then the codec has no predictable packet == time
  321. // so we can't tailor this (we don't know how many Packets represent a time period
  322. // we'll just return a default buffer size
  323. *outBufferSize = maxBufferSize > inMaxPacketSize ? maxBufferSize : inMaxPacketSize;
  324. }
  325. // we're going to limit our size to our default
  326. if (*outBufferSize > maxBufferSize && *outBufferSize > inMaxPacketSize)
  327. *outBufferSize = maxBufferSize;
  328. else {
  329. // also make sure we're not too small - we don't want to go the disk for too small chunks
  330. if (*outBufferSize < minBufferSize)
  331. *outBufferSize = minBufferSize;
  332. }
  333. *outNumPackets = *outBufferSize / inMaxPacketSize;
  334. }
  335. static Boolean MatchFormatFlags(const AudioStreamBasicDescription& x, const AudioStreamBasicDescription& y)
  336. {
  337. UInt32 xFlags = x.mFormatFlags;
  338. UInt32 yFlags = y.mFormatFlags;
  339. // match wildcards
  340. if (x.mFormatID == 0 || y.mFormatID == 0 || xFlags == 0 || yFlags == 0)
  341. return true;
  342. if (x.mFormatID == kAudioFormatLinearPCM)
  343. {
  344. // knock off the all clear flag
  345. xFlags = xFlags & ~kAudioFormatFlagsAreAllClear;
  346. yFlags = yFlags & ~kAudioFormatFlagsAreAllClear;
  347. // if both kAudioFormatFlagIsPacked bits are set, then we don't care about the kAudioFormatFlagIsAlignedHigh bit.
  348. if (xFlags & yFlags & kAudioFormatFlagIsPacked) {
  349. xFlags = xFlags & ~kAudioFormatFlagIsAlignedHigh;
  350. yFlags = yFlags & ~kAudioFormatFlagIsAlignedHigh;
  351. }
  352. // if both kAudioFormatFlagIsFloat bits are set, then we don't care about the kAudioFormatFlagIsSignedInteger bit.
  353. if (xFlags & yFlags & kAudioFormatFlagIsFloat) {
  354. xFlags = xFlags & ~kAudioFormatFlagIsSignedInteger;
  355. yFlags = yFlags & ~kAudioFormatFlagIsSignedInteger;
  356. }
  357. // if the bit depth is 8 bits or less and the format is packed, we don't care about endianness
  358. if((x.mBitsPerChannel <= 8) && ((xFlags & kAudioFormatFlagIsPacked) == kAudioFormatFlagIsPacked))
  359. {
  360. xFlags = xFlags & ~kAudioFormatFlagIsBigEndian;
  361. }
  362. if((y.mBitsPerChannel <= 8) && ((yFlags & kAudioFormatFlagIsPacked) == kAudioFormatFlagIsPacked))
  363. {
  364. yFlags = yFlags & ~kAudioFormatFlagIsBigEndian;
  365. }
  366. // if the number of channels is 0 or 1, we don't care about non-interleavedness
  367. if (x.mChannelsPerFrame <= 1 && y.mChannelsPerFrame <= 1) {
  368. xFlags &= ~kLinearPCMFormatFlagIsNonInterleaved;
  369. yFlags &= ~kLinearPCMFormatFlagIsNonInterleaved;
  370. }
  371. }
  372. return xFlags == yFlags;
  373. }
  374. Boolean FormatIsEqual(AudioStreamBasicDescription x, AudioStreamBasicDescription y)
  375. {
  376. // the semantics for equality are:
  377. // 1) Values must match exactly
  378. // 2) wildcard's are ignored in the comparison
  379. #define MATCH(name) ((x.name) == 0 || (y.name) == 0 || (x.name) == (y.name))
  380. return
  381. ((x.mSampleRate==0.) || (y.mSampleRate==0.) || (x.mSampleRate==y.mSampleRate))
  382. && MATCH(mFormatID)
  383. && MatchFormatFlags(x, y)
  384. && MATCH(mBytesPerPacket)
  385. && MATCH(mFramesPerPacket)
  386. && MATCH(mBytesPerFrame)
  387. && MATCH(mChannelsPerFrame)
  388. && MATCH(mBitsPerChannel) ;
  389. }
  390. #pragma mark ***** BackgroundTrackMgr *****
  391. //==================================================================================================
  392. // BackgroundTrackMgr class
  393. //==================================================================================================
  394. class BackgroundTrackMgr
  395. {
  396. #define CurFileInfo THIS->mBGFileInfo[THIS->mCurrentFileIndex]
  397. public:
  398. typedef struct BG_FileInfo {
  399. const char* mFilePath;
  400. AudioFileID mAFID;
  401. AudioStreamBasicDescription mFileFormat;
  402. UInt64 mFileDataSize;
  403. //UInt64 mFileNumPackets; // this is only used if loading file to memory
  404. Boolean mLoadAtOnce;
  405. Boolean mIsPlaying;//-Mat added this
  406. Boolean mFileDataInQueue;
  407. } BackgroundMusicFileInfo;
  408. BackgroundTrackMgr()
  409. : mQueue(0),
  410. mBufferByteSize(0),
  411. mCurrentPacket(0),
  412. mNumPacketsToRead(0),
  413. mVolume(1.0),
  414. mPacketDescs(NULL),
  415. mCurrentFileIndex(0),
  416. mMakeNewQueueWhenStopped(false),
  417. mStopAtEnd(false) { }
  418. ~BackgroundTrackMgr() { Teardown(); }
  419. void Teardown()
  420. {
  421. if (mQueue)
  422. AudioQueueDispose(mQueue, true);
  423. for (UInt32 i=0; i < mBGFileInfo.size(); i++)
  424. if (mBGFileInfo[i]->mAFID)
  425. AudioFileClose(mBGFileInfo[i]->mAFID);
  426. if (mPacketDescs)
  427. {
  428. delete mPacketDescs;
  429. mPacketDescs = NULL;
  430. }
  431. }
  432. AudioStreamPacketDescription *GetPacketDescsPtr() { return mPacketDescs; }
  433. UInt32 GetNumPacketsToRead(BackgroundTrackMgr::BG_FileInfo *inFileInfo)
  434. {
  435. return mNumPacketsToRead;
  436. }
  437. static OSStatus AttachNewCookie(AudioQueueRef inQueue, BackgroundTrackMgr::BG_FileInfo *inFileInfo)
  438. {
  439. OSStatus result = noErr;
  440. UInt32 size = sizeof(UInt32);
  441. result = AudioFileGetPropertyInfo (inFileInfo->mAFID, kAudioFilePropertyMagicCookieData, &size, NULL);
  442. if (!result && size)
  443. {
  444. char* cookie = new char [size];
  445. result = AudioFileGetProperty (inFileInfo->mAFID, kAudioFilePropertyMagicCookieData, &size, cookie);
  446. AssertNoError("Error getting cookie data", end);
  447. result = AudioQueueSetProperty(inQueue, kAudioQueueProperty_MagicCookie, cookie, size);
  448. delete [] cookie;
  449. AssertNoError("Error setting cookie data for queue", end);
  450. }
  451. return noErr;
  452. end:
  453. return noErr;
  454. }
  455. static void QueueStoppedProc( void * inUserData,
  456. AudioQueueRef inAQ,
  457. AudioQueuePropertyID inID)
  458. {
  459. UInt32 isRunning;
  460. UInt32 propSize = sizeof(isRunning);
  461. BackgroundTrackMgr *THIS = (BackgroundTrackMgr*)inUserData;
  462. OSStatus result = AudioQueueGetProperty(inAQ, kAudioQueueProperty_IsRunning, &isRunning, &propSize);
  463. if ((!isRunning) && (THIS->mMakeNewQueueWhenStopped))
  464. {
  465. result = AudioQueueDispose(inAQ, true);
  466. AssertNoError("Error disposing queue", end);
  467. result = THIS->SetupQueue(CurFileInfo);
  468. AssertNoError("Error setting up new queue", end);
  469. result = THIS->SetupBuffers(CurFileInfo);
  470. AssertNoError("Error setting up new queue buffers", end);
  471. result = THIS->Start();
  472. AssertNoError("Error starting queue", end);
  473. }
  474. end:
  475. return;
  476. }
  477. static Boolean DisposeBuffer(AudioQueueRef inAQ, std::vector<AudioQueueBufferRef> inDisposeBufferList, AudioQueueBufferRef inBufferToDispose)
  478. {
  479. for (unsigned int i=0; i < inDisposeBufferList.size(); i++)
  480. {
  481. if (inBufferToDispose == inDisposeBufferList[i])
  482. {
  483. OSStatus result = AudioQueueFreeBuffer(inAQ, inBufferToDispose);
  484. if (result == noErr)
  485. inDisposeBufferList.pop_back();
  486. return true;
  487. }
  488. }
  489. return false;
  490. }
  491. enum {
  492. kQueueState_DoNothing = 0,
  493. kQueueState_ResizeBuffer = 1,
  494. kQueueState_NeedNewCookie = 2,
  495. kQueueState_NeedNewBuffers = 3,
  496. kQueueState_NeedNewQueue = 4,
  497. };
  498. static SInt8 GetQueueStateForNextBuffer(BackgroundTrackMgr::BG_FileInfo *inFileInfo, BackgroundTrackMgr::BG_FileInfo *inNextFileInfo)
  499. {
  500. inFileInfo->mFileDataInQueue = false;
  501. // unless the data formats are the same, we need a new queue
  502. if (!FormatIsEqual(inFileInfo->mFileFormat, inNextFileInfo->mFileFormat))
  503. return kQueueState_NeedNewQueue;
  504. // if going from a load-at-once file to streaming or vice versa, we need new buffers
  505. if (inFileInfo->mLoadAtOnce != inNextFileInfo->mLoadAtOnce)
  506. return kQueueState_NeedNewBuffers;
  507. // if the next file is smaller than the current, we just need to resize
  508. if (inNextFileInfo->mLoadAtOnce)
  509. return (inFileInfo->mFileDataSize >= inNextFileInfo->mFileDataSize) ? kQueueState_ResizeBuffer : kQueueState_NeedNewBuffers;
  510. return kQueueState_NeedNewCookie;
  511. }
  512. static void QueueCallback( void * inUserData,
  513. AudioQueueRef inAQ,
  514. AudioQueueBufferRef inCompleteAQBuffer)
  515. {
  516. // dispose of the buffer if no longer in use
  517. OSStatus result = noErr;
  518. BackgroundTrackMgr *THIS = (BackgroundTrackMgr*)inUserData;
  519. if (DisposeBuffer(inAQ, THIS->mBuffersToDispose, inCompleteAQBuffer))
  520. return;
  521. UInt32 nPackets = 0;
  522. //-Mat
  523. if (CurFileInfo->mIsPlaying == false)
  524. {
  525. result = AudioQueueStop(inAQ, false);
  526. AssertNoError("Error stopping queue", end);
  527. return;
  528. }
  529. // loop the current buffer if the following:
  530. // 1. file was loaded into the buffer previously
  531. // 2. only one file in the queue
  532. // 3. we have not been told to stop at playlist completion
  533. if ((CurFileInfo->mFileDataInQueue) && (THIS->mBGFileInfo.size() == 1) && (!THIS->mStopAtEnd))
  534. nPackets = THIS->GetNumPacketsToRead(CurFileInfo);
  535. else
  536. {
  537. UInt32 numBytes;
  538. while (nPackets == 0)
  539. {
  540. // if loadAtOnce, get all packets in the file, otherwise ~.5 seconds of data
  541. nPackets = THIS->GetNumPacketsToRead(CurFileInfo);
  542. result = AudioFileReadPackets(CurFileInfo->mAFID, false, &numBytes, THIS->mPacketDescs, THIS->mCurrentPacket, &nPackets,
  543. inCompleteAQBuffer->mAudioData);
  544. AssertNoError("Error reading file data", end);
  545. inCompleteAQBuffer->mAudioDataByteSize = numBytes;
  546. if (nPackets == 0) // no packets were read, this file has ended.
  547. {
  548. if (CurFileInfo->mLoadAtOnce)
  549. CurFileInfo->mFileDataInQueue = true;
  550. THIS->mCurrentPacket = 0;
  551. UInt32 theNextFileIndex = (THIS->mCurrentFileIndex < THIS->mBGFileInfo.size()-1) ? THIS->mCurrentFileIndex+1 : 0;
  552. // we have gone through the playlist. if mStopAtEnd, stop the queue here
  553. if (theNextFileIndex == 0 && THIS->mStopAtEnd)
  554. {
  555. result = AudioQueueStop(inAQ, false);
  556. AssertNoError("Error stopping queue", end);
  557. return;
  558. }
  559. SInt8 theQueueState = GetQueueStateForNextBuffer(CurFileInfo, THIS->mBGFileInfo[theNextFileIndex]);
  560. if (theNextFileIndex != THIS->mCurrentFileIndex)
  561. {
  562. // if were are not looping the same file. Close the old one and open the new
  563. result = AudioFileClose(CurFileInfo->mAFID);
  564. AssertNoError("Error closing file", end);
  565. THIS->mCurrentFileIndex = theNextFileIndex;
  566. result = LoadFileDataInfo(CurFileInfo->mFilePath, CurFileInfo->mAFID, CurFileInfo->mFileFormat, CurFileInfo->mFileDataSize);
  567. AssertNoError("Error opening file", end);
  568. }
  569. switch (theQueueState)
  570. {
  571. // if we need to resize the buffer, set the buffer's audio data size to the new file's size
  572. // we will also need to get the new file cookie
  573. case kQueueState_ResizeBuffer:
  574. inCompleteAQBuffer->mAudioDataByteSize = CurFileInfo->mFileDataSize;
  575. // if the data format is the same but we just need a new cookie, attach a new cookie
  576. case kQueueState_NeedNewCookie:
  577. result = AttachNewCookie(inAQ, CurFileInfo);
  578. AssertNoError("Error attaching new file cookie data to queue", end);
  579. break;
  580. // we can keep the same queue, but not the same buffer(s)
  581. case kQueueState_NeedNewBuffers:
  582. THIS->mBuffersToDispose.push_back(inCompleteAQBuffer);
  583. THIS->SetupBuffers(CurFileInfo);
  584. break;
  585. // if the data formats are not the same, we need to dispose the current queue and create a new one
  586. case kQueueState_NeedNewQueue:
  587. THIS->mMakeNewQueueWhenStopped = true;
  588. result = AudioQueueStop(inAQ, false);
  589. AssertNoError("Error stopping queue", end);
  590. return;
  591. default:
  592. break;
  593. }
  594. }
  595. }
  596. }
  597. result = AudioQueueEnqueueBuffer(inAQ, inCompleteAQBuffer, (THIS->mPacketDescs ? nPackets : 0), THIS->mPacketDescs);
  598. if(result != noErr) {
  599. int a = 0;
  600. a++;
  601. }
  602. AssertNoError("Error enqueuing new buffer", end);
  603. if (CurFileInfo->mLoadAtOnce)
  604. CurFileInfo->mFileDataInQueue = true;
  605. THIS->mCurrentPacket += nPackets;
  606. end:
  607. return;
  608. }
  609. OSStatus SetupQueue(BG_FileInfo *inFileInfo)
  610. {
  611. UInt32 size = 0;
  612. OSStatus result = AudioQueueNewOutput(&inFileInfo->mFileFormat, QueueCallback, this, CFRunLoopGetCurrent(), kCFRunLoopCommonModes, 0, &mQueue);
  613. AssertNoError("Error creating queue", end);
  614. // (2) If the file has a cookie, we should get it and set it on the AQ
  615. size = sizeof(UInt32);
  616. result = AudioFileGetPropertyInfo (inFileInfo->mAFID, kAudioFilePropertyMagicCookieData, &size, NULL);
  617. if (!result && size) {
  618. char* cookie = new char [size];
  619. result = AudioFileGetProperty (inFileInfo->mAFID, kAudioFilePropertyMagicCookieData, &size, cookie);
  620. AssertNoError("Error getting magic cookie", end);
  621. result = AudioQueueSetProperty(mQueue, kAudioQueueProperty_MagicCookie, cookie, size);
  622. delete [] cookie;
  623. AssertNoError("Error setting magic cookie", end);
  624. }
  625. // channel layout
  626. OSStatus err = AudioFileGetPropertyInfo(inFileInfo->mAFID, kAudioFilePropertyChannelLayout, &size, NULL);
  627. if (err == noErr && size > 0) {
  628. AudioChannelLayout *acl = (AudioChannelLayout *)malloc(size);
  629. result = AudioFileGetProperty(inFileInfo->mAFID, kAudioFilePropertyChannelLayout, &size, acl);
  630. AssertNoError("Error getting channel layout from file", end);
  631. result = AudioQueueSetProperty(mQueue, kAudioQueueProperty_ChannelLayout, acl, size);
  632. free(acl);
  633. AssertNoError("Error setting channel layout on queue", end);
  634. }
  635. // add a notification proc for when the queue stops
  636. result = AudioQueueAddPropertyListener(mQueue, kAudioQueueProperty_IsRunning, QueueStoppedProc, this);
  637. AssertNoError("Error adding isRunning property listener to queue", end);
  638. // we need to reset this variable so that if the queue is stopped mid buffer we don't dispose it
  639. mMakeNewQueueWhenStopped = false;
  640. // volume
  641. result = SetVolume(mVolume);
  642. end:
  643. return result;
  644. }
  645. OSStatus SetupBuffers(BG_FileInfo *inFileInfo)
  646. {
  647. int numBuffersToQueue = kNumberBuffers;
  648. UInt32 maxPacketSize;
  649. UInt32 size = sizeof(maxPacketSize);
  650. // we need to calculate how many packets we read at a time, and how big a buffer we need
  651. // we base this on the size of the packets in the file and an approximate duration for each buffer
  652. // first check to see what the max size of a packet is - if it is bigger
  653. // than our allocation default size, that needs to become larger
  654. OSStatus result = AudioFileGetProperty(inFileInfo->mAFID, kAudioFilePropertyPacketSizeUpperBound, &size, &maxPacketSize);
  655. AssertNoError("Error getting packet upper bound size", end);
  656. bool isFormatVBR = (inFileInfo->mFileFormat.mBytesPerPacket == 0 || inFileInfo->mFileFormat.mFramesPerPacket == 0);
  657. CalculateBytesForTime(inFileInfo->mFileFormat, maxPacketSize, 0.5/*seconds*/, &mBufferByteSize, &mNumPacketsToRead);
  658. // if the file is smaller than the capacity of all the buffer queues, always load it at once
  659. if ((mBufferByteSize * numBuffersToQueue) > inFileInfo->mFileDataSize)
  660. inFileInfo->mLoadAtOnce = true;
  661. if (inFileInfo->mLoadAtOnce)
  662. {
  663. UInt64 theFileNumPackets;
  664. size = sizeof(UInt64);
  665. result = AudioFileGetProperty(inFileInfo->mAFID, kAudioFilePropertyAudioDataPacketCount, &size, &theFileNumPackets);
  666. AssertNoError("Error getting packet count for file", end);
  667. mNumPacketsToRead = (UInt32)theFileNumPackets;
  668. mBufferByteSize = inFileInfo->mFileDataSize;
  669. numBuffersToQueue = 1;
  670. }
  671. else
  672. {
  673. mNumPacketsToRead = mBufferByteSize / maxPacketSize;
  674. }
  675. if (isFormatVBR)
  676. mPacketDescs = new AudioStreamPacketDescription [mNumPacketsToRead];
  677. else
  678. mPacketDescs = NULL; // we don't provide packet descriptions for constant bit rate formats (like linear PCM)
  679. // allocate the queue's buffers
  680. for (int i = 0; i < numBuffersToQueue; ++i)
  681. {
  682. result = AudioQueueAllocateBuffer(mQueue, mBufferByteSize, &mBuffers[i]);
  683. AssertNoError("Error allocating buffer for queue", end);
  684. QueueCallback (this, mQueue, mBuffers[i]);
  685. if (inFileInfo->mLoadAtOnce)
  686. inFileInfo->mFileDataInQueue = true;
  687. }
  688. end:
  689. return result;
  690. }
  691. OSStatus LoadTrack(const char* inFilePath, Boolean inAddToQueue, Boolean inLoadAtOnce)
  692. {
  693. BG_FileInfo *fileInfo = new BG_FileInfo;
  694. fileInfo->mFilePath = inFilePath;
  695. OSStatus result = LoadFileDataInfo(fileInfo->mFilePath, fileInfo->mAFID, fileInfo->mFileFormat, fileInfo->mFileDataSize);
  696. AssertNoError("Error getting file data info", fail);
  697. fileInfo->mLoadAtOnce = inLoadAtOnce;
  698. fileInfo->mFileDataInQueue = false;
  699. // if not adding to the queue, clear the current file vector
  700. if (!inAddToQueue)
  701. mBGFileInfo.clear();
  702. fileInfo->mIsPlaying = true;
  703. mBGFileInfo.push_back(fileInfo);
  704. // setup the queue if this is the first (or only) file
  705. if (mBGFileInfo.size() == 1)
  706. {
  707. result = SetupQueue(fileInfo);
  708. AssertNoError("Error setting up queue", fail);
  709. result = SetupBuffers(fileInfo);
  710. AssertNoError("Error setting up queue buffers", fail);
  711. }
  712. // if this is just part of the playlist, close the file for now
  713. else
  714. {
  715. result = AudioFileClose(fileInfo->mAFID);
  716. AssertNoError("Error closing file", fail);
  717. }
  718. return result;
  719. fail:
  720. if (fileInfo)
  721. delete fileInfo;
  722. return result;
  723. }
  724. OSStatus UpdateGain()
  725. {
  726. return SetVolume(mVolume);
  727. }
  728. OSStatus SetVolume(Float32 inVolume)
  729. {
  730. mVolume = inVolume;
  731. return AudioQueueSetParameter(mQueue, kAudioQueueParam_Volume, mVolume * gMasterVolumeGain);
  732. }
  733. OSStatus Start()
  734. {
  735. OSStatus result = AudioQueuePrime(mQueue, 1, NULL);
  736. if (result)
  737. {
  738. printf("Error priming queue");
  739. return result;
  740. }
  741. //-Mat set mIsPlaying flag
  742. mBGFileInfo.back()->mIsPlaying = true;
  743. return AudioQueueStart(mQueue, NULL);
  744. }
  745. OSStatus Stop(Boolean inStopAtEnd)
  746. {
  747. if (inStopAtEnd)
  748. {
  749. mStopAtEnd = true;
  750. return noErr;
  751. }
  752. else {
  753. mBGFileInfo.back()->mIsPlaying = false;
  754. return AudioQueueStop(mQueue, true);
  755. }
  756. }
  757. private:
  758. AudioQueueRef mQueue;
  759. AudioQueueBufferRef mBuffers[kNumberBuffers];
  760. UInt32 mBufferByteSize;
  761. SInt64 mCurrentPacket;
  762. UInt32 mNumPacketsToRead;
  763. Float32 mVolume;
  764. AudioStreamPacketDescription * mPacketDescs;
  765. std::vector<BG_FileInfo*> mBGFileInfo;
  766. UInt32 mCurrentFileIndex;
  767. Boolean mMakeNewQueueWhenStopped;
  768. Boolean mStopAtEnd;
  769. std::vector<AudioQueueBufferRef> mBuffersToDispose;
  770. };
  771. #pragma mark ***** SoundEngineEffect *****
  772. //==================================================================================================
  773. // SoundEngineEffect class
  774. //==================================================================================================
  775. class SoundEngineEffect
  776. {
  777. public:
  778. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  779. SoundEngineEffect(const char* inLoopPath, const char* inAttackPath, const char* inDecayPath, Boolean inDoLoop)
  780. : mSourceID(0),
  781. mAttackBufferID(0),
  782. mLoopBufferID(0),
  783. mDecayBufferID(0),
  784. mLoopPath(inLoopPath),
  785. mAttackPath(inAttackPath),
  786. mDecayPath(inDecayPath),
  787. mLoopData(NULL),
  788. mAttackData(NULL),
  789. mDecayData(NULL),
  790. mLoopDataSize(0),
  791. mAttackDataSize(0),
  792. mDecayDataSize(0),
  793. mIsLoopingEffect(inDoLoop),
  794. mPlayThread(NULL),
  795. mPlayThreadState(kPlayThreadState_Loop)
  796. {
  797. alGenSources(1, &mSourceID);
  798. }
  799. ~SoundEngineEffect()
  800. {
  801. alDeleteSources(1, &mSourceID);
  802. if (mLoopData)
  803. free(mLoopData);
  804. if (mAttackData)
  805. free(mAttackData);
  806. if (mDecayData)
  807. free(mDecayData);
  808. }
  809. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  810. // Accessors
  811. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  812. UInt32 GetEffectID() { return mSourceID; }
  813. UInt32 GetPlayThreadState() { return mPlayThreadState; }
  814. Boolean HasAttackBuffer() { return mAttackBufferID != 0; }
  815. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  816. // Helper Functions
  817. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  818. ALenum GetALFormat(AudioStreamBasicDescription inFileFormat)
  819. {
  820. if (inFileFormat.mFormatID != kAudioFormatLinearPCM)
  821. return kSoundEngineErrInvalidFileFormat;
  822. if ((inFileFormat.mChannelsPerFrame > 2) || (inFileFormat.mChannelsPerFrame < 1))
  823. return kSoundEngineErrInvalidFileFormat;
  824. if(inFileFormat.mBitsPerChannel == 8)
  825. return (inFileFormat.mChannelsPerFrame == 1) ? AL_FORMAT_MONO8 : AL_FORMAT_STEREO8;
  826. else if(inFileFormat.mBitsPerChannel == 16)
  827. return (inFileFormat.mChannelsPerFrame == 1) ? AL_FORMAT_MONO16 : AL_FORMAT_STEREO16;
  828. return kSoundEngineErrInvalidFileFormat;
  829. }
  830. OSStatus LoadFileData(const char *inFilePath, void* &outData, UInt32 &outDataSize, ALuint &outBufferID)
  831. {
  832. AudioFileID theAFID = 0;
  833. OSStatus result = noErr;
  834. UInt64 theFileSize = 0;
  835. AudioStreamBasicDescription theFileFormat;
  836. result = LoadFileDataInfo(inFilePath, theAFID, theFileFormat, theFileSize);
  837. outDataSize = (UInt32)theFileSize;
  838. AssertNoError("Error loading file info", fail)
  839. outData = malloc(outDataSize);
  840. result = AudioFileReadBytes(theAFID, false, 0, &outDataSize, outData);
  841. AssertNoError("Error reading file data", fail)
  842. if (!TestAudioFormatNativeEndian(theFileFormat) && (theFileFormat.mBitsPerChannel > 8))
  843. return kSoundEngineErrInvalidFileFormat;
  844. alGenBuffers(1, &outBufferID);
  845. AssertNoOALError("Error generating buffer\n", fail);
  846. alBufferDataStaticProc(outBufferID, GetALFormat(theFileFormat), outData, outDataSize, theFileFormat.mSampleRate);
  847. AssertNoOALError("Error attaching data to buffer\n", fail);
  848. AudioFileClose(theAFID);
  849. return result;
  850. fail:
  851. if (theAFID)
  852. AudioFileClose(theAFID);
  853. if (outData)
  854. {
  855. free(outData);
  856. outData = NULL;
  857. }
  858. return result;
  859. }
  860. OSStatus AttachFilesToSource()
  861. {
  862. OSStatus result = AL_NO_ERROR;
  863. // first check for the attack file. That will be first in the queue if present
  864. if (mAttackPath)
  865. {
  866. result = LoadFileData(mAttackPath, mAttackData, mAttackDataSize, mAttackBufferID);
  867. AssertNoError("Error loading attack file info", end)
  868. }
  869. result = LoadFileData(mLoopPath, mLoopData, mLoopDataSize, mLoopBufferID);
  870. AssertNoError("Error loading looping file info", end)
  871. // if one-shot effect, attach the buffer to the source now
  872. if (!mIsLoopingEffect)
  873. {
  874. alSourcei(mSourceID, AL_BUFFER, mLoopBufferID);
  875. AssertNoOALError("Error attaching file data to effect", end)
  876. }
  877. if (mDecayPath)
  878. {
  879. result = LoadFileData(mDecayPath, mDecayData, mDecayDataSize, mDecayBufferID);
  880. AssertNoError("Error loading decay file info", end)
  881. }
  882. end:
  883. return result;
  884. }
  885. OSStatus ClearSourceBuffers()
  886. {
  887. OSStatus result = AL_NO_ERROR;
  888. ALint numQueuedBuffers = 0;
  889. ALuint *bufferIDs = (ALuint*)malloc(numQueuedBuffers * sizeof(ALint));
  890. alGetSourcei(mSourceID, AL_BUFFERS_QUEUED, &numQueuedBuffers);
  891. AssertNoOALError("Error getting OpenAL queued buffer size", end)
  892. alSourceUnqueueBuffers(mSourceID, numQueuedBuffers, bufferIDs);
  893. AssertNoOALError("Error unqueueing buffers from source", end)
  894. end:
  895. free(bufferIDs);
  896. return result;
  897. }
  898. static void* PlaybackProc(void *args)
  899. {
  900. OSStatus result = AL_NO_ERROR;
  901. SoundEngineEffect *THIS = (SoundEngineEffect*)args;
  902. alSourcePlay(THIS->GetEffectID());
  903. AssertNoOALError("Error starting effect playback", end)
  904. // if attack buffer is present, wait until it has completed, then turn looping on
  905. if (THIS->HasAttackBuffer())
  906. {
  907. ALint numBuffersProcessed = 0;
  908. while (numBuffersProcessed < 1)
  909. {
  910. alGetSourcei(THIS->GetEffectID(), AL_BUFFERS_PROCESSED, &numBuffersProcessed);
  911. AssertNoOALError("Error getting processed buffer number", end)
  912. }
  913. ALuint tmpBuffer = 0;
  914. alSourceUnqueueBuffers(THIS->GetEffectID(), 1, &tmpBuffer);
  915. AssertNoOALError("Error unqueueing buffers from source", end)
  916. }
  917. // now that we have processed the attack buffer, loop the main one
  918. THIS->SetLooping(true);
  919. end:
  920. return NULL;
  921. }
  922. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  923. // Effect management
  924. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  925. OSStatus Start()
  926. {
  927. OSStatus result = AL_NO_ERROR;
  928. alSourceStop(mSourceID);
  929. AssertNoOALError("Error stopping source", end)
  930. if (!mIsLoopingEffect)
  931. {
  932. // if we are just playing one-short effects, start playback here
  933. alSourcePlay(mSourceID);
  934. return alGetError();
  935. }
  936. // for loops we need to spawn a new thread
  937. mPlayThread = new OpenALThread(PlaybackProc, (void*)this);
  938. // we want this to delete upon thread completion
  939. mPlayThreadState = kPlayThreadState_Loop;
  940. // clean up remnants from any previous playback of the source
  941. result = ClearSourceBuffers();
  942. AssertNoError("Error clearing buffers", end)
  943. // if the effect has an attack sample, queue this first
  944. if (HasAttackBuffer())
  945. {
  946. alSourceQueueBuffers(mSourceID, 1, &mAttackBufferID);
  947. AssertNoOALError("Error queueing buffers for attack", end)
  948. // turn on looping after the attack buffer has been processed
  949. SetLooping(false);
  950. }
  951. alSourceQueueBuffers(mSourceID, 1, &mLoopBufferID);
  952. AssertNoOALError("Error queueing looping buffer", end)
  953. mPlayThread->Start();
  954. end:
  955. return result;
  956. }
  957. OSStatus StartDecay()
  958. {
  959. // turn off looping, and queue the decay buffer
  960. OSStatus result = AL_NO_ERROR;
  961. alSourcei(mSourceID, AL_LOOPING, 0);
  962. AssertNoOALError("Error turning off looping", end)
  963. alSourceQueueBuffers(mSourceID, 1, &mDecayBufferID);
  964. AssertNoOALError("Error queueing decay file", end)
  965. end:
  966. return result;
  967. }
  968. OSStatus Stop(Boolean inDoDecay)
  969. {
  970. OSStatus result = AL_NO_ERROR;
  971. // for non looped effects and loops with no decay sample
  972. if ((mDecayBufferID == 0) || !inDoDecay)
  973. {
  974. // if no decay to play, just stop the source
  975. alSourceStop(mSourceID);
  976. AssertNoOALError("Error stopping source", end)
  977. }
  978. else
  979. return StartDecay();
  980. end:
  981. return result;
  982. }
  983. OSStatus SetPitch(Float32 inValue)
  984. {
  985. alSourcef(mSourceID, AL_PITCH, inValue);
  986. return alGetError();
  987. }
  988. OSStatus SetLooping(Boolean inDoLoop)
  989. {
  990. ALint doLoop = inDoLoop ? 1 : 0;
  991. alSourcei(mSourceID, AL_LOOPING, doLoop);
  992. return alGetError();
  993. }
  994. OSStatus SetPosition(Float32 inX, Float32 inY, Float32 inZ)
  995. {
  996. alSource3f(mSourceID, AL_POSITION, inX, inY, inZ);
  997. return alGetError();
  998. }
  999. OSStatus SetMaxDistance(Float32 inValue)
  1000. {
  1001. alSourcef(mSourceID, AL_MAX_DISTANCE, inValue);
  1002. return alGetError();
  1003. }
  1004. OSStatus SetReferenceDistance(Float32 inValue)
  1005. {
  1006. alSourcef(mSourceID, AL_REFERENCE_DISTANCE, inValue);
  1007. return alGetError();
  1008. }
  1009. OSStatus SetLevel(Float32 inValue)
  1010. {
  1011. alSourcef(mSourceID, AL_GAIN, inValue * gMasterVolumeGain);
  1012. return alGetError();
  1013. }
  1014. enum {
  1015. kPlayThreadState_Loop = 0,
  1016. kPlayThreadState_Decay = 1,
  1017. kPlayThreadState_End = 2
  1018. };
  1019. private:
  1020. ALuint mSourceID;
  1021. ALuint mAttackBufferID;
  1022. ALuint mLoopBufferID;
  1023. ALuint mDecayBufferID;
  1024. UInt32 mNumberBuffers;
  1025. const char* mLoopPath;
  1026. const char* mAttackPath;
  1027. const char* mDecayPath;
  1028. void* mLoopData;
  1029. void* mAttackData;
  1030. void* mDecayData;
  1031. UInt32 mLoopDataSize;
  1032. UInt32 mAttackDataSize;
  1033. UInt32 mDecayDataSize;
  1034. Boolean mIsLoopingEffect;
  1035. OpenALThread* mPlayThread;
  1036. UInt32 mPlayThreadState;
  1037. };
  1038. #pragma mark ***** SoundEngineEffectMap *****
  1039. //==================================================================================================
  1040. // SoundEngineEffectMap class
  1041. //==================================================================================================
  1042. class SoundEngineEffectMap
  1043. : std::multimap<UInt32, SoundEngineEffect*, std::less<ALuint> >
  1044. {
  1045. public:
  1046. // add a new context to the map
  1047. void Add (const ALuint inEffectToken, SoundEngineEffect **inEffect)
  1048. {
  1049. iterator it = upper_bound(inEffectToken);
  1050. insert(it, value_type (inEffectToken, *inEffect));
  1051. }
  1052. SoundEngineEffect* Get(ALuint inEffectToken)
  1053. {
  1054. iterator it = find(inEffectToken);
  1055. if (it != end())
  1056. return ((*it).second);
  1057. return (NULL);
  1058. }
  1059. void Remove (const ALuint inSourceToken) {
  1060. iterator it = find(inSourceToken);
  1061. if (it != end())
  1062. erase(it);
  1063. }
  1064. SoundEngineEffect* GetEffectByIndex(UInt32 inIndex) {
  1065. iterator it = begin();
  1066. for (UInt32 i = 0; i < inIndex; i++) {
  1067. if (it != end())
  1068. ++it;
  1069. else
  1070. i = inIndex;
  1071. }
  1072. if (it != end())
  1073. return ((*it).second);
  1074. return (NULL);
  1075. }
  1076. iterator GetIterator() { return begin(); }
  1077. UInt32 Size () const { return size(); }
  1078. bool Empty () const { return empty(); }
  1079. };
  1080. #pragma mark ***** OpenALObject *****
  1081. //==================================================================================================
  1082. // OpenALObject class
  1083. //==================================================================================================
  1084. class OpenALObject
  1085. {
  1086. public:
  1087. OpenALObject(Float32 inMixerOutputRate)
  1088. : mOutputRate(inMixerOutputRate),
  1089. mGain(1.0),
  1090. mContext(NULL),
  1091. mDevice(NULL),
  1092. mEffectsMap(NULL)
  1093. {
  1094. mEffectsMap = new SoundEngineEffectMap();
  1095. }
  1096. ~OpenALObject() { Teardown(); }
  1097. OSStatus Initialize()
  1098. {
  1099. OSStatus result = noErr;
  1100. mDevice = alcOpenDevice(NULL);
  1101. ALenum err = alGetError();
  1102. int mRequestSources = 16;
  1103. static ALuint mSource[16];
  1104. AssertNoOALError("Error opening output device", end)
  1105. if(mDevice == NULL) { return kSoundEngineErrDeviceNotFound; }
  1106. // if a mixer output rate was specified, set it here
  1107. // must be done before the alcCreateContext() call
  1108. if (mOutputRate)
  1109. alcMacOSXMixerOutputRateProc(mOutputRate);
  1110. // Create an OpenAL Context
  1111. mContext = alcCreateContext(mDevice, NULL);
  1112. AssertNoOALError("Error creating OpenAL context", end)
  1113. alcMakeContextCurrent(mContext);
  1114. AssertNoOALError("Error setting current OpenAL context", end)
  1115. //we will get a a source as we play it
  1116. while(true)
  1117. {
  1118. alGenSources(1, &mSource[0]);
  1119. err = alGetError();
  1120. if (err == AL_NO_ERROR)
  1121. break;
  1122. mRequestSources--;
  1123. if (mRequestSources == 0)
  1124. {
  1125. return (false);
  1126. }
  1127. }
  1128. end:
  1129. return result;
  1130. }
  1131. void Teardown()
  1132. {
  1133. if (mEffectsMap)
  1134. {
  1135. for (UInt32 i = 0; i < mEffectsMap->Size(); i++)
  1136. {
  1137. SoundEngineEffect *theEffect = mEffectsMap->GetEffectByIndex(0);
  1138. if (theEffect)
  1139. {
  1140. mEffectsMap->Remove(theEffect->GetEffectID());
  1141. delete theEffect;
  1142. }
  1143. }
  1144. delete mEffectsMap;
  1145. }
  1146. if (mContext) alcDestroyContext(mContext);
  1147. if (mDevice) alcCloseDevice(mDevice);
  1148. }
  1149. OSStatus SetListenerPosition(Float32 inX, Float32 inY, Float32 inZ)
  1150. {
  1151. alListener3f(AL_POSITION, inX, inY, inZ);
  1152. return alGetError();
  1153. }
  1154. OSStatus SetListenerGain(Float32 inValue)
  1155. {
  1156. alListenerf(AL_GAIN, inValue);
  1157. return alGetError();
  1158. }
  1159. OSStatus SetMaxDistance(Float32 inValue)
  1160. {
  1161. OSStatus result = 0;
  1162. for (UInt32 i=0; i < mEffectsMap->Size(); i++)
  1163. {
  1164. SoundEngineEffect *theEffect = mEffectsMap->GetEffectByIndex(i);
  1165. if ((result = theEffect->SetMaxDistance(inValue)) != AL_NO_ERROR)
  1166. return result;
  1167. }
  1168. return result;
  1169. }
  1170. OSStatus SetReferenceDistance(Float32 inValue)
  1171. {
  1172. OSStatus result = 0;
  1173. for (UInt32 i=0; i < mEffectsMap->Size(); i++)
  1174. {
  1175. SoundEngineEffect *theEffect = mEffectsMap->GetEffectByIndex(i);
  1176. if ((result = theEffect->SetReferenceDistance(inValue)) != AL_NO_ERROR)
  1177. return result;
  1178. }
  1179. return result;
  1180. }
  1181. OSStatus SetEffectsVolume(Float32 inValue)
  1182. {
  1183. OSStatus result = 0;
  1184. for (UInt32 i=0; i < mEffectsMap->Size(); i++)
  1185. {
  1186. SoundEngineEffect *theEffect = mEffectsMap->GetEffectByIndex(i);
  1187. if ((result = theEffect->SetLevel(inValue)) != AL_NO_ERROR)
  1188. return result;
  1189. }
  1190. return result;
  1191. }
  1192. OSStatus UpdateGain()
  1193. {
  1194. return SetEffectsVolume(mGain);
  1195. }
  1196. OSStatus LoadEffect(const char *inFilePath, UInt32 *outEffectID)
  1197. {
  1198. SoundEngineEffect *theEffect = new SoundEngineEffect(inFilePath, NULL, NULL, false);
  1199. OSStatus result = theEffect->AttachFilesToSource();
  1200. if (result == noErr)
  1201. {
  1202. *outEffectID = theEffect->GetEffectID();
  1203. mEffectsMap->Add(*outEffectID, &theEffect);
  1204. }
  1205. return result;
  1206. }
  1207. OSStatus LoadLoopingEffect(const char *inLoopFilePath, const char *inAttackFilePath, const char *inDecayFilePath, UInt32 *outEffectID)
  1208. {
  1209. SoundEngineEffect *theEffect = new SoundEngineEffect(inLoopFilePath, inAttackFilePath, inDecayFilePath, true);
  1210. OSStatus result = theEffect->AttachFilesToSource();
  1211. if (result == noErr)
  1212. {
  1213. *outEffectID = theEffect->GetEffectID();
  1214. mEffectsMap->Add(*outEffectID, &theEffect);
  1215. }
  1216. return result;
  1217. }
  1218. OSStatus UnloadEffect(UInt32 inEffectID)
  1219. {
  1220. mEffectsMap->Remove(inEffectID);
  1221. return 0;
  1222. }
  1223. OSStatus StartEffect(UInt32 inEffectID)
  1224. {
  1225. SoundEngineEffect *theEffect = mEffectsMap->Get(inEffectID);
  1226. return (theEffect) ? theEffect->Start() : kSoundEngineErrInvalidID;
  1227. }
  1228. OSStatus StopEffect(UInt32 inEffectID, Boolean inDoDecay)
  1229. {
  1230. SoundEngineEffect *theEffect = mEffectsMap->Get(inEffectID);
  1231. return (theEffect) ? theEffect->Stop(inDoDecay) : kSoundEngineErrInvalidID;
  1232. }
  1233. OSStatus SetEffectPitch(UInt32 inEffectID, Float32 inValue)
  1234. {
  1235. SoundEngineEffect *theEffect = mEffectsMap->Get(inEffectID);
  1236. return (theEffect) ? theEffect->SetPitch(inValue) : kSoundEngineErrInvalidID;
  1237. }
  1238. OSStatus SetEffectVolume(UInt32 inEffectID, Float32 inValue)
  1239. {
  1240. SoundEngineEffect *theEffect = mEffectsMap->Get(inEffectID);
  1241. return (theEffect) ? theEffect->SetLevel(inValue) : kSoundEngineErrInvalidID;
  1242. }
  1243. OSStatus SetEffectPosition(UInt32 inEffectID, Float32 inX, Float32 inY, Float32 inZ)
  1244. {
  1245. SoundEngineEffect *theEffect = mEffectsMap->Get(inEffectID);
  1246. return (theEffect) ? theEffect->SetPosition(inX, inY, inZ) : kSoundEngineErrInvalidID;
  1247. }
  1248. private:
  1249. Float32 mOutputRate;
  1250. Float32 mGain;
  1251. ALCcontext* mContext;
  1252. ALCdevice* mDevice;
  1253. SoundEngineEffectMap* mEffectsMap;
  1254. };
  1255. #pragma mark ***** API *****
  1256. //==================================================================================================
  1257. // Sound Engine
  1258. //==================================================================================================
  1259. extern "C"
  1260. OSStatus SoundEngine_Initialize(Float32 inMixerOutputRate)
  1261. {
  1262. if (sOpenALObject)
  1263. delete sOpenALObject;
  1264. if (sBackgroundTrackMgr)
  1265. delete sBackgroundTrackMgr;
  1266. AudioSessionInitialize(nil, nil, nil, nil);
  1267. UInt32 sessionCategory = kAudioSessionCategory_AmbientSound;
  1268. AudioSessionSetProperty(kAudioSessionProperty_AudioCategory, sizeof(sessionCategory), &sessionCategory);
  1269. AudioSessionSetActive(true);
  1270. sOpenALObject = new OpenALObject(inMixerOutputRate);
  1271. sBackgroundTrackMgr = new BackgroundTrackMgr();
  1272. return sOpenALObject->Initialize();
  1273. }
  1274. extern "C"
  1275. OSStatus SoundEngine_Teardown()
  1276. {
  1277. if (sOpenALObject)
  1278. {
  1279. delete sOpenALObject;
  1280. sOpenALObject = NULL;
  1281. }
  1282. if (sBackgroundTrackMgr)
  1283. {
  1284. delete sBackgroundTrackMgr;
  1285. sBackgroundTrackMgr = NULL;
  1286. }
  1287. return 0;
  1288. }
  1289. extern "C"
  1290. OSStatus SoundEngine_SetMasterVolume(Float32 inValue)
  1291. {
  1292. OSStatus result = noErr;
  1293. gMasterVolumeGain = inValue;
  1294. if (sBackgroundTrackMgr)
  1295. result = sBackgroundTrackMgr->UpdateGain();
  1296. if (result) return result;
  1297. if (sOpenALObject)
  1298. return sOpenALObject->UpdateGain();
  1299. return result;
  1300. }
  1301. extern "C"
  1302. OSStatus SoundEngine_SetListenerPosition(Float32 inX, Float32 inY, Float32 inZ)
  1303. {
  1304. return (sOpenALObject) ? sOpenALObject->SetListenerPosition(inX, inY, inZ) : kSoundEngineErrUnitialized;
  1305. }
  1306. extern "C"
  1307. OSStatus SoundEngine_SetListenerGain(Float32 inValue)
  1308. {
  1309. return (sOpenALObject) ? sOpenALObject->SetListenerGain(inValue) : kSoundEngineErrUnitialized;
  1310. }
  1311. extern "C"
  1312. OSStatus SoundEngine_LoadBackgroundMusicTrack(const char* inPath, Boolean inAddToQueue, Boolean inLoadAtOnce)
  1313. {
  1314. if (sBackgroundTrackMgr == NULL)
  1315. sBackgroundTrackMgr = new BackgroundTrackMgr();
  1316. return sBackgroundTrackMgr->LoadTrack(inPath, inAddToQueue, inLoadAtOnce);
  1317. }
  1318. extern "C"
  1319. OSStatus SoundEngine_UnloadBackgroundMusicTrack()
  1320. {
  1321. if (sBackgroundTrackMgr)
  1322. {
  1323. delete sBackgroundTrackMgr;
  1324. sBackgroundTrackMgr = NULL;
  1325. }
  1326. return 0;
  1327. }
  1328. extern "C"
  1329. OSStatus SoundEngine_StartBackgroundMusic()
  1330. {
  1331. return (sBackgroundTrackMgr) ? sBackgroundTrackMgr->Start() : kSoundEngineErrUnitialized;
  1332. }
  1333. extern "C"
  1334. OSStatus SoundEngine_StopBackgroundMusic(Boolean stopAtEnd)
  1335. {
  1336. return (sBackgroundTrackMgr) ? sBackgroundTrackMgr->Stop(stopAtEnd) : kSoundEngineErrUnitialized;
  1337. }
  1338. extern "C"
  1339. OSStatus SoundEngine_SetBackgroundMusicVolume(Float32 inValue)
  1340. {
  1341. return (sBackgroundTrackMgr) ? sBackgroundTrackMgr->SetVolume(inValue) : kSoundEngineErrUnitialized;
  1342. }
  1343. extern "C"
  1344. bool LoadSoundFile(const char *inFilePath, UInt32 *outEffectID)
  1345. {
  1346. SoundEngineEffect *theEffect = new SoundEngineEffect(inFilePath, NULL, NULL, false);
  1347. OSStatus result = theEffect->AttachFilesToSource();
  1348. if (result == noErr)
  1349. {
  1350. //-Mat getEffectID() returns sourceID, but we want the genBuffer ID that was done last (mAttackBufferID), I have no idea
  1351. //what SourceID is used for, but it's not the sound buffer, anyhow, the buffer after mSourceID is the one we want so +1
  1352. *outEffectID = theEffect->GetEffectID()+1;
  1353. }
  1354. return (result == noErr);
  1355. }
  1356. }//namespace SoundEngine