audioBuffer.cc 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  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. #include "platform/platformAL.h"
  23. #include "audio/audioBuffer.h"
  24. #include "io/stream.h"
  25. #include "console/console.h"
  26. #include "memory/frameAllocator.h"
  27. #ifndef _MMATH_H_
  28. #include "math/mMath.h"
  29. #endif
  30. #ifdef TORQUE_OS_IOS
  31. //Luma: include proper path for this file
  32. #include "platformiOS/SoundEngine.h"
  33. #endif
  34. //#define LOG_SOUND_LOADS
  35. /// WAV File-header
  36. struct WAVFileHdr
  37. {
  38. ALubyte id[4];
  39. ALsizei size;
  40. ALubyte type[4];
  41. };
  42. //// WAV Fmt-header
  43. struct WAVFmtHdr
  44. {
  45. ALushort format;
  46. ALushort channels;
  47. ALuint samplesPerSec;
  48. ALuint bytesPerSec;
  49. ALushort blockAlign;
  50. ALushort bitsPerSample;
  51. };
  52. /// WAV FmtEx-header
  53. struct WAVFmtExHdr
  54. {
  55. ALushort size;
  56. ALushort samplesPerBlock;
  57. };
  58. /// WAV Smpl-header
  59. struct WAVSmplHdr
  60. {
  61. ALuint manufacturer;
  62. ALuint product;
  63. ALuint samplePeriod;
  64. ALuint note;
  65. ALuint fineTune;
  66. ALuint SMPTEFormat;
  67. ALuint SMPTEOffest;
  68. ALuint loops;
  69. ALuint samplerData;
  70. struct
  71. {
  72. ALuint identifier;
  73. ALuint type;
  74. ALuint start;
  75. ALuint end;
  76. ALuint fraction;
  77. ALuint count;
  78. } loop[1];
  79. };
  80. /// WAV Chunk-header
  81. struct WAVChunkHdr
  82. {
  83. ALubyte id[4];
  84. ALuint size;
  85. };
  86. #define CHUNKSIZE 4096
  87. //--------------------------------------
  88. AudioBuffer::AudioBuffer(StringTableEntry filename)
  89. {
  90. AssertFatal(StringTable->lookup(filename), "AudioBuffer:: filename is not a string table entry");
  91. mFilename = filename;
  92. mLoading = false;
  93. malBuffer = 0;
  94. }
  95. AudioBuffer::~AudioBuffer()
  96. {
  97. if( alIsBuffer(malBuffer) )
  98. {
  99. alGetError();
  100. alDeleteBuffers( 1, &malBuffer );
  101. ALenum error;
  102. error = alGetError();
  103. AssertWarn( error == AL_NO_ERROR, "AudioBuffer::~AudioBuffer() - failed to release buffer" );
  104. switch (error)
  105. {
  106. case AL_NO_ERROR:
  107. break;
  108. case AL_INVALID_NAME:
  109. Con::errorf("AudioBuffer::~AudioBuffer() - alDeleteBuffers OpenAL AL_INVALID_NAME error code returned");
  110. break;
  111. case AL_INVALID_ENUM:
  112. Con::errorf("AudioBuffer::~AudioBuffer() - alDeleteBuffers OpenAL AL_INVALID_ENUM error code returned");
  113. break;
  114. case AL_INVALID_VALUE:
  115. Con::errorf("AudioBuffer::~AudioBuffer() - alDeleteBuffers OpenAL AL_INVALID_VALUE error code returned");
  116. break;
  117. case AL_INVALID_OPERATION:
  118. Con::errorf("AudioBuffer::~AudioBuffer() - alDeleteBuffers OpenAL AL_INVALID_OPERATION error code returned");
  119. break;
  120. case AL_OUT_OF_MEMORY:
  121. Con::errorf("AudioBuffer::~AudioBuffer() - alDeleteBuffers OpenAL AL_OUT_OF_MEMORY error code returned");
  122. break;
  123. default:
  124. Con::errorf("AudioBuffer::~AudioBuffer() - alDeleteBuffers OpenAL has encountered a problem and won't tell us what it is. %d", error);
  125. };
  126. }
  127. }
  128. //--------------------------------------
  129. Resource<AudioBuffer> AudioBuffer::find(const char *filename)
  130. {
  131. U32 mark = FrameAllocator::getWaterMark();
  132. char * f2 = NULL;
  133. Resource<AudioBuffer> buffer = ResourceManager->load(filename);
  134. if (bool(buffer) == false)
  135. {
  136. // wav file doesn't exist, try ogg file instead
  137. S32 len = dStrlen(filename);
  138. if (len>3 && !dStricmp(filename+len-4,".wav"))
  139. {
  140. f2 = (char*)FrameAllocator::alloc(len+1);
  141. dStrcpy(f2,filename);
  142. f2[len-3] = 'o';
  143. f2[len-2] = 'g';
  144. f2[len-1] = 'g';
  145. buffer = ResourceManager->load(filename);
  146. }
  147. }
  148. // if resource still not there, try to create it if file exists
  149. if (bool(buffer) == false)
  150. {
  151. // see if the file exists -- first try default
  152. if (ResourceManager->getPathOf(filename))
  153. {
  154. AudioBuffer *temp = new AudioBuffer(StringTable->insert(filename));
  155. ResourceManager->add(filename, temp);
  156. buffer = ResourceManager->load(filename);
  157. }
  158. else if (f2 && ResourceManager->getPathOf(f2))
  159. {
  160. AudioBuffer *temp = new AudioBuffer(StringTable->insert(f2));
  161. ResourceManager->add(f2, temp);
  162. buffer = ResourceManager->load(f2);
  163. }
  164. }
  165. FrameAllocator::setWaterMark(mark);
  166. return buffer;
  167. }
  168. ResourceInstance* AudioBuffer::construct(Stream &)
  169. {
  170. return NULL;
  171. }
  172. //-----------------------------------------------------------------
  173. ALuint AudioBuffer::getALBuffer()
  174. {
  175. if (!alcGetCurrentContext())
  176. return 0;
  177. // clear the error state
  178. alGetError();
  179. // Intangir> fix for newest openAL from creative (it returns true, yea right 0 is not a valid buffer)
  180. // it MIGHT not work at all for all i know.
  181. if (malBuffer && alIsBuffer(malBuffer))
  182. return malBuffer;
  183. alGenBuffers(1, &malBuffer);
  184. if(alGetError() != AL_NO_ERROR)
  185. return 0;
  186. ResourceObject * obj = ResourceManager->find(mFilename);
  187. if(obj)
  188. {
  189. bool readSuccess = false;
  190. S32 len = dStrlen(mFilename);
  191. if(len > 3 && !dStricmp(mFilename + len - 4, ".wav"))
  192. {
  193. #ifdef LOG_SOUND_LOADS
  194. Con::printf("Reading WAV: %s\n", mFilename);
  195. #endif
  196. readSuccess = readWAV(obj);
  197. }
  198. #ifdef TORQUE_OS_IOS
  199. //-Mat lod a caf file on iPhone only
  200. if(len > 3 && !dStricmp(mFilename + len - 4, ".caf"))
  201. {
  202. #ifdef LOG_SOUND_LOADS
  203. Con::printf("Reading Caf: %s\n", mFilename);
  204. #endif
  205. SoundEngine::UInt32 bufferID;
  206. readSuccess = SoundEngine::LoadSoundFile(mFilename, &bufferID);
  207. //-Mat need to save the buffer
  208. malBuffer = bufferID;
  209. }
  210. #endif
  211. if(readSuccess)
  212. return(malBuffer);
  213. }
  214. alDeleteBuffers(1, &malBuffer);
  215. return 0;
  216. }
  217. /*! The Read a WAV file from the given ResourceObject and initialize
  218. an alBuffer with it.
  219. */
  220. bool AudioBuffer::readWAV(ResourceObject *obj)
  221. {
  222. WAVChunkHdr chunkHdr;
  223. WAVFmtExHdr fmtExHdr;
  224. WAVFileHdr fileHdr;
  225. WAVSmplHdr smplHdr;
  226. WAVFmtHdr fmtHdr;
  227. ALenum format = AL_FORMAT_MONO16;
  228. char *data = NULL;
  229. ALsizei size = 0;
  230. ALsizei freq = 22050;
  231. ALboolean loop = AL_FALSE;
  232. Stream *stream = ResourceManager->openStream(obj);
  233. if (!stream)
  234. return false;
  235. stream->read(4, &fileHdr.id[0]);
  236. stream->read(&fileHdr.size);
  237. stream->read(4, &fileHdr.type[0]);
  238. fileHdr.size=((fileHdr.size+1)&~1)-4;
  239. stream->read(4, &chunkHdr.id[0]);
  240. stream->read(&chunkHdr.size);
  241. // unread chunk data rounded up to nearest WORD
  242. S32 chunkRemaining = chunkHdr.size + (chunkHdr.size&1);
  243. while ((fileHdr.size!=0) && (stream->getStatus() != Stream::EOS))
  244. {
  245. // WAV Format header
  246. if (!dStrncmp((const char*)chunkHdr.id,"fmt ",4))
  247. {
  248. stream->read(&fmtHdr.format);
  249. stream->read(&fmtHdr.channels);
  250. stream->read(&fmtHdr.samplesPerSec);
  251. stream->read(&fmtHdr.bytesPerSec);
  252. stream->read(&fmtHdr.blockAlign);
  253. stream->read(&fmtHdr.bitsPerSample);
  254. if (fmtHdr.format==0x0001)
  255. {
  256. format=(fmtHdr.channels==1?
  257. (fmtHdr.bitsPerSample==8?AL_FORMAT_MONO8:AL_FORMAT_MONO16):
  258. (fmtHdr.bitsPerSample==8?AL_FORMAT_STEREO8:AL_FORMAT_STEREO16));
  259. freq=fmtHdr.samplesPerSec;
  260. chunkRemaining -= sizeof(WAVFmtHdr);
  261. }
  262. else
  263. {
  264. stream->read(sizeof(WAVFmtExHdr), &fmtExHdr);
  265. chunkRemaining -= sizeof(WAVFmtExHdr);
  266. }
  267. }
  268. // WAV Format header
  269. else if (!dStrncmp((const char*)chunkHdr.id,"data",4))
  270. {
  271. if (fmtHdr.format==0x0001)
  272. {
  273. size=chunkHdr.size;
  274. data=new char[chunkHdr.size];
  275. if (data)
  276. {
  277. stream->read(chunkHdr.size, data);
  278. #if defined(TORQUE_BIG_ENDIAN)
  279. // need to endian-flip the 16-bit data.
  280. if (fmtHdr.bitsPerSample==16) // !!!TBD we don't handle stereo, so may be RL flipped.
  281. {
  282. U16 *ds = (U16*)data;
  283. U16 *de = (U16*)(data+size);
  284. while (ds<de)
  285. {
  286. #if defined(TORQUE_BIG_ENDIAN)
  287. *ds = convertLEndianToHost(*ds);
  288. #else
  289. *ds = convertBEndianToHost(*ds);
  290. #endif
  291. ds++;
  292. }
  293. }
  294. #endif
  295. chunkRemaining -= chunkHdr.size;
  296. }
  297. else
  298. break;
  299. }
  300. else if (fmtHdr.format==0x0011)
  301. {
  302. //IMA ADPCM
  303. }
  304. else if (fmtHdr.format==0x0055)
  305. {
  306. //MP3 WAVE
  307. }
  308. }
  309. // WAV Loop header
  310. else if (!dStrncmp((const char*)chunkHdr.id,"smpl",4))
  311. {
  312. // this struct read is NOT endian safe but it is ok because
  313. // we are only testing the loops field against ZERO
  314. stream->read(sizeof(WAVSmplHdr), &smplHdr);
  315. loop = (smplHdr.loops ? AL_TRUE : AL_FALSE);
  316. chunkRemaining -= sizeof(WAVSmplHdr);
  317. }
  318. // either we have unread chunk data or we found an unknown chunk type
  319. // loop and read up to 1K bytes at a time until we have
  320. // read to the end of this chunk
  321. char buffer[1024];
  322. AssertFatal(chunkRemaining >= 0, "AudioBuffer::readWAV: remaining chunk data should never be less than zero.");
  323. while (chunkRemaining > 0)
  324. {
  325. S32 readSize = getMin(1024, chunkRemaining);
  326. stream->read(readSize, buffer);
  327. chunkRemaining -= readSize;
  328. }
  329. fileHdr.size-=(((chunkHdr.size+1)&~1)+8);
  330. // read next chunk header...
  331. stream->read(4, &chunkHdr.id[0]);
  332. stream->read(&chunkHdr.size);
  333. // unread chunk data rounded up to nearest WORD
  334. chunkRemaining = chunkHdr.size + (chunkHdr.size&1);
  335. }
  336. ResourceManager->closeStream(stream);
  337. if (data)
  338. {
  339. alBufferData(malBuffer, format, data, size, freq);
  340. delete [] data;
  341. return (alGetError() == AL_NO_ERROR);
  342. }
  343. return false;
  344. }