CocosDenshion.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  1. /*
  2. Copyright (c) 2010 Steve Oldmeadow
  3. Permission is hereby granted, free of charge, to any person obtaining a copy
  4. of this software and associated documentation files (the "Software"), to deal
  5. in the Software without restriction, including without limitation the rights
  6. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  7. copies of the Software, and to permit persons to whom the Software is
  8. furnished to do so, subject to the following conditions:
  9. The above copyright notice and this permission notice shall be included in
  10. all copies or substantial portions of the Software.
  11. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  12. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  13. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  14. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  15. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  16. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  17. THE SOFTWARE.
  18. $Id$
  19. */
  20. /**
  21. @file
  22. @b IMPORTANT
  23. There are 3 different ways of using CocosDenshion. Depending on which you choose you
  24. will need to include different files and frameworks.
  25. @par SimpleAudioEngine
  26. This is recommended for basic audio requirements. If you just want to play some sound fx
  27. and some background music and have no interest in learning the lower level workings then
  28. this is the interface to use.
  29. Requirements:
  30. - Firmware: OS 2.2 or greater
  31. - Files: SimpleAudioEngine.*, CocosDenshion.*
  32. - Frameworks: OpenAL, AudioToolbox, AVFoundation
  33. @par CDAudioManager
  34. CDAudioManager is basically a thin wrapper around an AVAudioPlayer object used for playing
  35. background music and a CDSoundEngine object used for playing sound effects. It manages the
  36. audio session for you deals with audio session interruption. It is fairly low level and it
  37. is expected you have some understanding of the underlying technologies. For example, for
  38. many use cases regarding background music it is expected you will work directly with the
  39. backgroundMusic AVAudioPlayer which is exposed as a property.
  40. Requirements:
  41. - Firmware: OS 2.2 or greater
  42. - Files: CDAudioManager.*, CocosDenshion.*
  43. - Frameworks: OpenAL, AudioToolbox, AVFoundation
  44. @par CDSoundEngine
  45. CDSoundEngine is a sound engine built upon OpenAL and derived from Apple's oalTouch
  46. example. It can playback up to 32 sounds simultaneously with control over pitch, pan
  47. and gain. It can be set up to handle audio session interruption automatically. You
  48. may decide to use CDSoundEngine directly instead of CDAudioManager or SimpleAudioEngine
  49. because you require OS 2.0 compatibility.
  50. Requirements:
  51. - Firmware: OS 2.0 or greater
  52. - Files: CocosDenshion.*
  53. - Frameworks: OpenAL, AudioToolbox
  54. */
  55. #import <OpenAL/al.h>
  56. #import <OpenAL/alc.h>
  57. #import <AudioToolbox/AudioToolbox.h>
  58. #import <Foundation/Foundation.h>
  59. #import "audio/ios/CDConfig.h"
  60. #if !defined(CD_DEBUG) || CD_DEBUG == 0
  61. #define CDLOG(...) do {} while (0)
  62. #define CDLOGINFO(...) do {} while (0)
  63. #elif CD_DEBUG == 1
  64. #define CDLOG(...) NSLog(__VA_ARGS__)
  65. #define CDLOGINFO(...) do {} while (0)
  66. #elif CD_DEBUG > 1
  67. #define CDLOG(...) NSLog(__VA_ARGS__)
  68. #define CDLOGINFO(...) NSLog(__VA_ARGS__)
  69. #endif // CD_DEBUG
  70. #import "audio/ios/CDOpenALSupport.h"
  71. //Tested source limit on 2.2.1 and 3.1.2 with up to 128 sources and appears to work. Older OS versions e.g 2.2 may support only 32
  72. #define CD_SOURCE_LIMIT 32 //Total number of sources we will ever want, may actually get less
  73. #define CD_NO_SOURCE 0xFEEDFAC //Return value indicating playback failed i.e. no source
  74. #define CD_IGNORE_AUDIO_SESSION 0xBEEFBEE //Used internally to indicate audio session will not be handled
  75. #define CD_MUTE 0xFEEDBAB //Return value indicating sound engine is muted or non functioning
  76. #define CD_NO_SOUND = -1;
  77. #define CD_SAMPLE_RATE_HIGH 44100
  78. #define CD_SAMPLE_RATE_MID 22050
  79. #define CD_SAMPLE_RATE_LOW 16000
  80. #define CD_SAMPLE_RATE_BASIC 8000
  81. #define CD_SAMPLE_RATE_DEFAULT 44100
  82. extern NSString * const kCDN_BadAlContext;
  83. extern NSString * const kCDN_AsynchLoadComplete;
  84. extern float const kCD_PitchDefault;
  85. extern float const kCD_PitchLowerOneOctave;
  86. extern float const kCD_PitchHigherOneOctave;
  87. extern float const kCD_PanDefault;
  88. extern float const kCD_PanFullLeft;
  89. extern float const kCD_PanFullRight;
  90. extern float const kCD_GainDefault;
  91. enum bufferState {
  92. CD_BS_EMPTY = 0,
  93. CD_BS_LOADED = 1,
  94. CD_BS_FAILED = 2
  95. };
  96. typedef struct _sourceGroup {
  97. int startIndex;
  98. int currentIndex;
  99. int totalSources;
  100. bool enabled;
  101. bool nonInterruptible;
  102. int *sourceStatuses;//pointer into array of source status information
  103. } sourceGroup;
  104. typedef struct _bufferInfo {
  105. ALuint bufferId;
  106. int bufferState;
  107. void* bufferData;
  108. ALenum format;
  109. ALsizei sizeInBytes;
  110. ALsizei frequencyInHertz;
  111. } bufferInfo;
  112. typedef struct _sourceInfo {
  113. bool usable;
  114. ALuint sourceId;
  115. ALuint attachedBufferId;
  116. } sourceInfo;
  117. #pragma mark CDAudioTransportProtocol
  118. @protocol CDAudioTransportProtocol <NSObject>
  119. /** Play the audio */
  120. -(BOOL) play;
  121. /** Pause the audio, retain resources */
  122. -(BOOL) pause;
  123. /** Stop the audio, release resources */
  124. -(BOOL) stop;
  125. /** Return playback to beginning */
  126. -(BOOL) rewind;
  127. @end
  128. #pragma mark CDAudioInterruptProtocol
  129. @protocol CDAudioInterruptProtocol <NSObject>
  130. /** Is audio mute */
  131. -(BOOL) mute;
  132. /** If YES then audio is silenced but not stopped, calls to start new audio will proceed but silently */
  133. -(void) setMute:(BOOL) muteValue;
  134. /** Is audio enabled */
  135. -(BOOL) enabled;
  136. /** If NO then all audio is stopped and any calls to start new audio will be ignored */
  137. -(void) setEnabled:(BOOL) enabledValue;
  138. @end
  139. #pragma mark CDUtilities
  140. /**
  141. Collection of utilities required by CocosDenshion
  142. */
  143. @interface CDUtilities : NSObject
  144. {
  145. }
  146. /** Fundamentally the same as the corresponding method is FileUtils but added to break binding to cocos2d */
  147. +(NSString*) fullPathFromRelativePath:(NSString*) relPath;
  148. @end
  149. #pragma mark CDSoundEngine
  150. /** CDSoundEngine is built upon OpenAL and works with SDK 2.0.
  151. CDSoundEngine is a sound engine built upon OpenAL and derived from Apple's oalTouch
  152. example. It can playback up to 32 sounds simultaneously with control over pitch, pan
  153. and gain. It can be set up to handle audio session interruption automatically. You
  154. may decide to use CDSoundEngine directly instead of CDAudioManager or SimpleAudioEngine
  155. because you require OS 2.0 compatibility.
  156. Requirements:
  157. - Firmware: OS 2.0 or greater
  158. - Files: CocosDenshion.*
  159. - Frameworks: OpenAL, AudioToolbox
  160. @since v0.8
  161. */
  162. @class CDSoundSource;
  163. @interface CDSoundEngine : NSObject <CDAudioInterruptProtocol> {
  164. bufferInfo *_buffers;
  165. sourceInfo *_sources;
  166. sourceGroup *_sourceGroups;
  167. ALCcontext *context;
  168. NSUInteger _sourceGroupTotal;
  169. UInt32 _audioSessionCategory;
  170. BOOL _handleAudioSession;
  171. ALfloat _preMuteGain;
  172. NSObject *_mutexBufferLoad;
  173. BOOL mute_;
  174. BOOL enabled_;
  175. ALenum lastErrorCode_;
  176. BOOL functioning_;
  177. float asynchLoadProgress_;
  178. BOOL getGainWorks_;
  179. //For managing dynamic allocation of sources and buffers
  180. int sourceTotal_;
  181. int bufferTotal;
  182. }
  183. @property (readwrite, nonatomic) ALfloat masterGain;
  184. @property (readonly) ALenum lastErrorCode;//Last OpenAL error code that was generated
  185. @property (readonly) BOOL functioning;//Is the sound engine functioning
  186. @property (readwrite) float asynchLoadProgress;
  187. @property (readonly) BOOL getGainWorks;//Does getting the gain for a source work
  188. /** Total number of sources available */
  189. @property (readonly) int sourceTotal;
  190. /** Total number of source groups that have been defined */
  191. @property (readonly) NSUInteger sourceGroupTotal;
  192. /** Sets the sample rate for the audio mixer. For best performance this should match the sample rate of your audio content */
  193. +(void) setMixerSampleRate:(Float32) sampleRate;
  194. /** Initializes the engine with a group definition and a total number of groups */
  195. -(id)init;
  196. /** Plays a sound in a channel group with a pitch, pan and gain. The sound could played looped or not */
  197. -(ALuint) playSound:(int) soundId sourceGroupId:(int)sourceGroupId pitch:(float) pitch pan:(float) pan gain:(float) gain loop:(BOOL) loop;
  198. /** Creates and returns a sound source object for the specified sound within the specified source group.
  199. */
  200. -(CDSoundSource *) soundSourceForSound:(int) soundId sourceGroupId:(int) sourceGroupId;
  201. /** Stops playing a sound */
  202. - (void) stopSound:(ALuint) sourceId;
  203. /** Stops playing a source group */
  204. - (void) stopSourceGroup:(int) sourceGroupId;
  205. /** Stops all playing sounds */
  206. -(void) stopAllSounds;
  207. /** Pause a sound */
  208. -(void) pauseSound:(ALuint) sourceId;
  209. /** Pause all sounds */
  210. -(void) pauseAllSounds;
  211. /** Resume a sound */
  212. -(void) resumeSound:(ALuint) sourceId;
  213. /** Resume all sounds */
  214. -(void) resumeAllSounds;
  215. -(void) defineSourceGroups:(NSArray*) sourceGroupDefinitions;
  216. -(void) defineSourceGroups:(int[]) sourceGroupDefinitions total:(NSUInteger) total;
  217. -(void) setSourceGroupNonInterruptible:(int) sourceGroupId isNonInterruptible:(BOOL) isNonInterruptible;
  218. -(void) setSourceGroupEnabled:(int) sourceGroupId enabled:(BOOL) enabled;
  219. -(BOOL) sourceGroupEnabled:(int) sourceGroupId;
  220. -(BOOL) loadBufferFromData:(int) soundId soundData:(ALvoid*) soundData format:(ALenum) format size:(ALsizei) size freq:(ALsizei) freq;
  221. -(BOOL) loadBuffer:(int) soundId filePath:(NSString*) filePath;
  222. -(void) loadBuffersAsynchronously:(NSArray *) loadRequests;
  223. -(BOOL) unloadBuffer:(int) soundId;
  224. -(ALCcontext *) openALContext;
  225. /** Returns the duration of the buffer in seconds or a negative value if the buffer id is invalid */
  226. -(float) bufferDurationInSeconds:(int) soundId;
  227. /** Returns the size of the buffer in bytes or a negative value if the buffer id is invalid */
  228. -(ALsizei) bufferSizeInBytes:(int) soundId;
  229. /** Returns the sampling frequency of the buffer in hertz or a negative value if the buffer id is invalid */
  230. -(ALsizei) bufferFrequencyInHertz:(int) soundId;
  231. /** Used internally, never call unless you know what you are doing */
  232. -(void) _soundSourcePreRelease:(CDSoundSource *) soundSource;
  233. @end
  234. #pragma mark CDSoundSource
  235. /** CDSoundSource is a wrapper around an OpenAL sound source.
  236. It allows you to manipulate properties such as pitch, gain, pan and looping while the
  237. sound is playing. CDSoundSource is based on the old CDSourceWrapper class but with much
  238. added functionality.
  239. @since v1.0
  240. */
  241. @interface CDSoundSource : NSObject <CDAudioTransportProtocol, CDAudioInterruptProtocol> {
  242. ALenum lastError;
  243. @public
  244. ALuint _sourceId;
  245. ALuint _sourceIndex;
  246. CDSoundEngine* _engine;
  247. int _soundId;
  248. float _preMuteGain;
  249. BOOL enabled_;
  250. BOOL mute_;
  251. }
  252. @property (readwrite, nonatomic) float pitch;
  253. @property (readwrite, nonatomic) float gain;
  254. @property (readwrite, nonatomic) float pan;
  255. @property (readwrite, nonatomic) BOOL looping;
  256. @property (readonly) BOOL isPlaying;
  257. @property (readwrite, nonatomic) int soundId;
  258. /** Returns the duration of the attached buffer in seconds or a negative value if the buffer is invalid */
  259. @property (readonly) float durationInSeconds;
  260. /** Stores the last error code that occurred. Check against AL_NO_ERROR */
  261. @property (readonly) ALenum lastError;
  262. /** Do not init yourself, get an instance from the sourceForSound factory method on CDSoundEngine */
  263. -(id)init:(ALuint) theSourceId sourceIndex:(int) index soundEngine:(CDSoundEngine*) engine;
  264. @end
  265. #pragma mark CDAudioInterruptTargetGroup
  266. /** Container for objects that implement audio interrupt protocol i.e. they can be muted and enabled.
  267. Setting mute and enabled for the group propagates to all children.
  268. Designed to be used with your CDSoundSource objects to get them to comply with global enabled and mute settings
  269. if that is what you want to do.*/
  270. @interface CDAudioInterruptTargetGroup : NSObject <CDAudioInterruptProtocol> {
  271. BOOL mute_;
  272. BOOL enabled_;
  273. NSMutableArray *children_;
  274. }
  275. -(void) addAudioInterruptTarget:(NSObject<CDAudioInterruptProtocol>*) interruptibleTarget;
  276. @end
  277. #pragma mark CDAsynchBufferLoader
  278. /** CDAsynchBufferLoader
  279. TODO
  280. */
  281. @interface CDAsynchBufferLoader : NSOperation {
  282. NSArray *_loadRequests;
  283. CDSoundEngine *_soundEngine;
  284. }
  285. -(id) init:(NSArray *)loadRequests soundEngine:(CDSoundEngine *) theSoundEngine;
  286. @end
  287. #pragma mark CDBufferLoadRequest
  288. /** CDBufferLoadRequest */
  289. @interface CDBufferLoadRequest: NSObject
  290. {
  291. NSString *filePath;
  292. int soundId;
  293. //id loader;
  294. }
  295. @property (readonly) NSString *filePath;
  296. @property (readonly) int soundId;
  297. - (id)init:(int) theSoundId filePath:(const NSString *) theFilePath;
  298. @end
  299. /** Interpolation type */
  300. typedef enum {
  301. kIT_Linear, //!Straight linear interpolation fade
  302. kIT_SCurve, //!S curved interpolation
  303. kIT_Exponential //!Exponential interpolation
  304. } tCDInterpolationType;
  305. #pragma mark CDFloatInterpolator
  306. @interface CDFloatInterpolator: NSObject
  307. {
  308. float start;
  309. float end;
  310. float lastValue;
  311. tCDInterpolationType interpolationType;
  312. }
  313. @property (readwrite, nonatomic) float start;
  314. @property (readwrite, nonatomic) float end;
  315. @property (readwrite, nonatomic) tCDInterpolationType interpolationType;
  316. /** Return a value between min and max based on t which represents fractional progress where 0 is the start
  317. and 1 is the end */
  318. -(float) interpolate:(float) t;
  319. -(id) init:(tCDInterpolationType) type startVal:(float) startVal endVal:(float) endVal;
  320. @end
  321. #pragma mark CDPropertyModifier
  322. /** Base class for classes that modify properties such as pitch, pan and gain */
  323. @interface CDPropertyModifier: NSObject
  324. {
  325. CDFloatInterpolator *interpolator;
  326. float startValue;
  327. float endValue;
  328. id target;
  329. BOOL stopTargetWhenComplete;
  330. }
  331. @property (readwrite, nonatomic) BOOL stopTargetWhenComplete;
  332. @property (readwrite, nonatomic) float startValue;
  333. @property (readwrite, nonatomic) float endValue;
  334. @property (readwrite, nonatomic) tCDInterpolationType interpolationType;
  335. -(id) init:(id) theTarget interpolationType:(tCDInterpolationType) type startVal:(float) startVal endVal:(float) endVal;
  336. /** Set to a fractional value between 0 and 1 where 0 equals the start and 1 equals the end*/
  337. -(void) modify:(float) t;
  338. -(void) _setTargetProperty:(float) newVal;
  339. -(float) _getTargetProperty;
  340. -(void) _stopTarget;
  341. -(Class) _allowableType;
  342. @end
  343. #pragma mark CDSoundSourceFader
  344. /** Fader for CDSoundSource objects */
  345. @interface CDSoundSourceFader : CDPropertyModifier{}
  346. @end
  347. #pragma mark CDSoundSourcePanner
  348. /** Panner for CDSoundSource objects */
  349. @interface CDSoundSourcePanner : CDPropertyModifier{}
  350. @end
  351. #pragma mark CDSoundSourcePitchBender
  352. /** Pitch bender for CDSoundSource objects */
  353. @interface CDSoundSourcePitchBender : CDPropertyModifier{}
  354. @end
  355. #pragma mark CDSoundEngineFader
  356. /** Fader for CDSoundEngine objects */
  357. @interface CDSoundEngineFader : CDPropertyModifier{}
  358. @end