audioBuffer.cc 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  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( malBuffer != 0 )
  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. }
  105. }
  106. //--------------------------------------
  107. Resource<AudioBuffer> AudioBuffer::find(const char *filename)
  108. {
  109. U32 mark = FrameAllocator::getWaterMark();
  110. char * f2 = NULL;
  111. Resource<AudioBuffer> buffer = ResourceManager->load(filename);
  112. if (bool(buffer) == false)
  113. {
  114. // wav file doesn't exist, try ogg file instead
  115. S32 len = dStrlen(filename);
  116. if (len>3 && !dStricmp(filename+len-4,".wav"))
  117. {
  118. f2 = (char*)FrameAllocator::alloc(len+1);
  119. dStrcpy(f2,filename);
  120. f2[len-3] = 'o';
  121. f2[len-2] = 'g';
  122. f2[len-1] = 'g';
  123. buffer = ResourceManager->load(filename);
  124. }
  125. }
  126. // if resource still not there, try to create it if file exists
  127. if (bool(buffer) == false)
  128. {
  129. // see if the file exists -- first try default
  130. if (ResourceManager->getPathOf(filename))
  131. {
  132. AudioBuffer *temp = new AudioBuffer(StringTable->insert(filename));
  133. ResourceManager->add(filename, temp);
  134. buffer = ResourceManager->load(filename);
  135. }
  136. else if (f2 && ResourceManager->getPathOf(f2))
  137. {
  138. AudioBuffer *temp = new AudioBuffer(StringTable->insert(f2));
  139. ResourceManager->add(f2, temp);
  140. buffer = ResourceManager->load(f2);
  141. }
  142. }
  143. FrameAllocator::setWaterMark(mark);
  144. return buffer;
  145. }
  146. ResourceInstance* AudioBuffer::construct(Stream &)
  147. {
  148. return NULL;
  149. }
  150. //-----------------------------------------------------------------
  151. ALuint AudioBuffer::getALBuffer()
  152. {
  153. if (!alcGetCurrentContext())
  154. return 0;
  155. // clear the error state
  156. alGetError();
  157. // Intangir> fix for newest openAL from creative (it returns true, yea right 0 is not a valid buffer)
  158. // it MIGHT not work at all for all i know.
  159. if (malBuffer && alIsBuffer(malBuffer))
  160. return malBuffer;
  161. alGenBuffers(1, &malBuffer);
  162. if(alGetError() != AL_NO_ERROR)
  163. return 0;
  164. ResourceObject * obj = ResourceManager->find(mFilename);
  165. if(obj)
  166. {
  167. bool readSuccess = false;
  168. S32 len = dStrlen(mFilename);
  169. if(len > 3 && !dStricmp(mFilename + len - 4, ".wav"))
  170. {
  171. #ifdef LOG_SOUND_LOADS
  172. Con::printf("Reading WAV: %s\n", mFilename);
  173. #endif
  174. readSuccess = readWAV(obj);
  175. }
  176. #ifdef TORQUE_OS_IOS
  177. //-Mat lod a caf file on iPhone only
  178. if(len > 3 && !dStricmp(mFilename + len - 4, ".caf"))
  179. {
  180. #ifdef LOG_SOUND_LOADS
  181. Con::printf("Reading Caf: %s\n", mFilename);
  182. #endif
  183. SoundEngine::UInt32 bufferID;
  184. readSuccess = SoundEngine::LoadSoundFile(mFilename, &bufferID);
  185. //-Mat need to save the buffer
  186. malBuffer = bufferID;
  187. }
  188. #endif
  189. if(readSuccess)
  190. return(malBuffer);
  191. }
  192. alDeleteBuffers(1, &malBuffer);
  193. return 0;
  194. }
  195. /*! The Read a WAV file from the given ResourceObject and initialize
  196. an alBuffer with it.
  197. */
  198. bool AudioBuffer::readWAV(ResourceObject *obj)
  199. {
  200. WAVChunkHdr chunkHdr;
  201. WAVFmtExHdr fmtExHdr;
  202. WAVFileHdr fileHdr;
  203. WAVSmplHdr smplHdr;
  204. WAVFmtHdr fmtHdr;
  205. ALenum format = AL_FORMAT_MONO16;
  206. char *data = NULL;
  207. ALsizei size = 0;
  208. ALsizei freq = 22050;
  209. ALboolean loop = AL_FALSE;
  210. Stream *stream = ResourceManager->openStream(obj);
  211. if (!stream)
  212. return false;
  213. stream->read(4, &fileHdr.id[0]);
  214. stream->read(&fileHdr.size);
  215. stream->read(4, &fileHdr.type[0]);
  216. fileHdr.size=((fileHdr.size+1)&~1)-4;
  217. stream->read(4, &chunkHdr.id[0]);
  218. stream->read(&chunkHdr.size);
  219. // unread chunk data rounded up to nearest WORD
  220. S32 chunkRemaining = chunkHdr.size + (chunkHdr.size&1);
  221. while ((fileHdr.size!=0) && (stream->getStatus() != Stream::EOS))
  222. {
  223. // WAV Format header
  224. if (!dStrncmp((const char*)chunkHdr.id,"fmt ",4))
  225. {
  226. stream->read(&fmtHdr.format);
  227. stream->read(&fmtHdr.channels);
  228. stream->read(&fmtHdr.samplesPerSec);
  229. stream->read(&fmtHdr.bytesPerSec);
  230. stream->read(&fmtHdr.blockAlign);
  231. stream->read(&fmtHdr.bitsPerSample);
  232. if (fmtHdr.format==0x0001)
  233. {
  234. format=(fmtHdr.channels==1?
  235. (fmtHdr.bitsPerSample==8?AL_FORMAT_MONO8:AL_FORMAT_MONO16):
  236. (fmtHdr.bitsPerSample==8?AL_FORMAT_STEREO8:AL_FORMAT_STEREO16));
  237. freq=fmtHdr.samplesPerSec;
  238. chunkRemaining -= sizeof(WAVFmtHdr);
  239. }
  240. else
  241. {
  242. stream->read(sizeof(WAVFmtExHdr), &fmtExHdr);
  243. chunkRemaining -= sizeof(WAVFmtExHdr);
  244. }
  245. }
  246. // WAV Format header
  247. else if (!dStrncmp((const char*)chunkHdr.id,"data",4))
  248. {
  249. if (fmtHdr.format==0x0001)
  250. {
  251. size=chunkHdr.size;
  252. data=new char[chunkHdr.size];
  253. if (data)
  254. {
  255. stream->read(chunkHdr.size, data);
  256. #if defined(TORQUE_BIG_ENDIAN)
  257. // need to endian-flip the 16-bit data.
  258. if (fmtHdr.bitsPerSample==16) // !!!TBD we don't handle stereo, so may be RL flipped.
  259. {
  260. U16 *ds = (U16*)data;
  261. U16 *de = (U16*)(data+size);
  262. while (ds<de)
  263. {
  264. #if defined(TORQUE_BIG_ENDIAN)
  265. *ds = convertLEndianToHost(*ds);
  266. #else
  267. *ds = convertBEndianToHost(*ds);
  268. #endif
  269. ds++;
  270. }
  271. }
  272. #endif
  273. chunkRemaining -= chunkHdr.size;
  274. }
  275. else
  276. break;
  277. }
  278. else if (fmtHdr.format==0x0011)
  279. {
  280. //IMA ADPCM
  281. }
  282. else if (fmtHdr.format==0x0055)
  283. {
  284. //MP3 WAVE
  285. }
  286. }
  287. // WAV Loop header
  288. else if (!dStrncmp((const char*)chunkHdr.id,"smpl",4))
  289. {
  290. // this struct read is NOT endian safe but it is ok because
  291. // we are only testing the loops field against ZERO
  292. stream->read(sizeof(WAVSmplHdr), &smplHdr);
  293. loop = (smplHdr.loops ? AL_TRUE : AL_FALSE);
  294. chunkRemaining -= sizeof(WAVSmplHdr);
  295. }
  296. // either we have unread chunk data or we found an unknown chunk type
  297. // loop and read up to 1K bytes at a time until we have
  298. // read to the end of this chunk
  299. char buffer[1024];
  300. AssertFatal(chunkRemaining >= 0, "AudioBuffer::readWAV: remaining chunk data should never be less than zero.");
  301. while (chunkRemaining > 0)
  302. {
  303. S32 readSize = getMin(1024, chunkRemaining);
  304. stream->read(readSize, buffer);
  305. chunkRemaining -= readSize;
  306. }
  307. fileHdr.size-=(((chunkHdr.size+1)&~1)+8);
  308. // read next chunk header...
  309. stream->read(4, &chunkHdr.id[0]);
  310. stream->read(&chunkHdr.size);
  311. // unread chunk data rounded up to nearest WORD
  312. chunkRemaining = chunkHdr.size + (chunkHdr.size&1);
  313. }
  314. ResourceManager->closeStream(stream);
  315. if (data)
  316. {
  317. alBufferData(malBuffer, format, data, size, freq);
  318. delete [] data;
  319. return (alGetError() == AL_NO_ERROR);
  320. }
  321. return false;
  322. }