SoundEngine.cpp 55 KB

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