audioBuffer.cc 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545
  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 TORQUE_OS_IOS
  28. #include "vorbis/vorbisfile.h"
  29. #endif
  30. #ifndef _MMATH_H_
  31. #include "math/mMath.h"
  32. #endif
  33. #ifdef TORQUE_OS_IOS
  34. //Luma: include proper path for this file
  35. #include "platformiOS/SoundEngine.h"
  36. #endif
  37. //#define LOG_SOUND_LOADS
  38. /// WAV File-header
  39. struct WAVFileHdr
  40. {
  41. ALubyte id[4];
  42. ALsizei size;
  43. ALubyte type[4];
  44. };
  45. //// WAV Fmt-header
  46. struct WAVFmtHdr
  47. {
  48. ALushort format;
  49. ALushort channels;
  50. ALuint samplesPerSec;
  51. ALuint bytesPerSec;
  52. ALushort blockAlign;
  53. ALushort bitsPerSample;
  54. };
  55. /// WAV FmtEx-header
  56. struct WAVFmtExHdr
  57. {
  58. ALushort size;
  59. ALushort samplesPerBlock;
  60. };
  61. /// WAV Smpl-header
  62. struct WAVSmplHdr
  63. {
  64. ALuint manufacturer;
  65. ALuint product;
  66. ALuint samplePeriod;
  67. ALuint note;
  68. ALuint fineTune;
  69. ALuint SMPTEFormat;
  70. ALuint SMPTEOffest;
  71. ALuint loops;
  72. ALuint samplerData;
  73. struct
  74. {
  75. ALuint identifier;
  76. ALuint type;
  77. ALuint start;
  78. ALuint end;
  79. ALuint fraction;
  80. ALuint count;
  81. } loop[1];
  82. };
  83. /// WAV Chunk-header
  84. struct WAVChunkHdr
  85. {
  86. ALubyte id[4];
  87. ALuint size;
  88. };
  89. #define CHUNKSIZE 4096
  90. #ifndef TORQUE_OS_IOS
  91. // Ogg Vorbis
  92. static size_t _ov_read_func(void *ptr, size_t size, size_t nmemb, void *datasource)
  93. {
  94. Stream *stream = reinterpret_cast<Stream*>(datasource);
  95. // Stream::read() returns true if any data was
  96. // read, so we must track the read bytes ourselves.
  97. U32 startByte = stream->getPosition();
  98. stream->read(size * nmemb, ptr);
  99. U32 endByte = stream->getPosition();
  100. // How many did we actually read?
  101. U32 readBytes = (endByte - startByte);
  102. U32 readItems = readBytes / size;
  103. return readItems;
  104. }
  105. static int _ov_seek_func(void *datasource, ogg_int64_t offset, int whence)
  106. {
  107. Stream *stream = reinterpret_cast<Stream*>(datasource);
  108. U32 newPos = 0;
  109. if (whence == SEEK_CUR)
  110. newPos = stream->getPosition() + (U32)offset;
  111. else if (whence == SEEK_END)
  112. newPos = stream->getStreamSize() - (U32)offset;
  113. else
  114. newPos = (U32)offset;
  115. return stream->setPosition(newPos) ? 0 : -1;
  116. }
  117. static long _ov_tell_func(void *datasource)
  118. {
  119. Stream *stream = reinterpret_cast<Stream*>(datasource);
  120. return stream->getPosition();
  121. }
  122. #endif
  123. //--------------------------------------
  124. AudioBuffer::AudioBuffer(StringTableEntry filename)
  125. {
  126. AssertFatal(StringTable->lookup(filename), "AudioBuffer:: filename is not a string table entry");
  127. mFilename = filename;
  128. mLoading = false;
  129. malBuffer = 0;
  130. }
  131. AudioBuffer::~AudioBuffer()
  132. {
  133. if( alIsBuffer(malBuffer) )
  134. {
  135. alGetError();
  136. alDeleteBuffers( 1, &malBuffer );
  137. ALenum error;
  138. error = alGetError();
  139. AssertWarn( error == AL_NO_ERROR, "AudioBuffer::~AudioBuffer() - failed to release buffer" );
  140. switch (error)
  141. {
  142. case AL_NO_ERROR:
  143. break;
  144. case AL_INVALID_NAME:
  145. Con::errorf("AudioBuffer::~AudioBuffer() - alDeleteBuffers OpenAL AL_INVALID_NAME error code returned");
  146. break;
  147. case AL_INVALID_ENUM:
  148. Con::errorf("AudioBuffer::~AudioBuffer() - alDeleteBuffers OpenAL AL_INVALID_ENUM error code returned");
  149. break;
  150. case AL_INVALID_VALUE:
  151. Con::errorf("AudioBuffer::~AudioBuffer() - alDeleteBuffers OpenAL AL_INVALID_VALUE error code returned");
  152. break;
  153. case AL_INVALID_OPERATION:
  154. Con::errorf("AudioBuffer::~AudioBuffer() - alDeleteBuffers OpenAL AL_INVALID_OPERATION error code returned");
  155. break;
  156. case AL_OUT_OF_MEMORY:
  157. Con::errorf("AudioBuffer::~AudioBuffer() - alDeleteBuffers OpenAL AL_OUT_OF_MEMORY error code returned");
  158. break;
  159. default:
  160. Con::errorf("AudioBuffer::~AudioBuffer() - alDeleteBuffers OpenAL has encountered a problem and won't tell us what it is. %d", error);
  161. };
  162. }
  163. }
  164. //--------------------------------------
  165. Resource<AudioBuffer> AudioBuffer::find(const char *filename)
  166. {
  167. U32 mark = FrameAllocator::getWaterMark();
  168. char * f2 = NULL;
  169. Resource<AudioBuffer> buffer = ResourceManager->load(filename);
  170. if (bool(buffer) == false)
  171. {
  172. // wav file doesn't exist, try ogg file instead
  173. S32 len = dStrlen(filename);
  174. if (len>3 && !dStricmp(filename+len-4,".wav"))
  175. {
  176. f2 = (char*)FrameAllocator::alloc(len+1);
  177. dStrcpy(f2,filename);
  178. f2[len-3] = 'o';
  179. f2[len-2] = 'g';
  180. f2[len-1] = 'g';
  181. buffer = ResourceManager->load(filename);
  182. }
  183. }
  184. // if resource still not there, try to create it if file exists
  185. if (bool(buffer) == false)
  186. {
  187. // see if the file exists -- first try default
  188. if (ResourceManager->getPathOf(filename))
  189. {
  190. AudioBuffer *temp = new AudioBuffer(StringTable->insert(filename));
  191. ResourceManager->add(filename, temp);
  192. buffer = ResourceManager->load(filename);
  193. }
  194. else if (f2 && ResourceManager->getPathOf(f2))
  195. {
  196. AudioBuffer *temp = new AudioBuffer(StringTable->insert(f2));
  197. ResourceManager->add(f2, temp);
  198. buffer = ResourceManager->load(f2);
  199. }
  200. }
  201. FrameAllocator::setWaterMark(mark);
  202. return buffer;
  203. }
  204. ResourceInstance* AudioBuffer::construct(Stream &)
  205. {
  206. return NULL;
  207. }
  208. //-----------------------------------------------------------------
  209. ALuint AudioBuffer::getALBuffer()
  210. {
  211. if (!alcGetCurrentContext())
  212. return 0;
  213. // clear the error state
  214. alGetError();
  215. // Intangir> fix for newest openAL from creative (it returns true, yea right 0 is not a valid buffer)
  216. // it MIGHT not work at all for all i know.
  217. if (malBuffer && alIsBuffer(malBuffer))
  218. return malBuffer;
  219. alGenBuffers(1, &malBuffer);
  220. if(alGetError() != AL_NO_ERROR)
  221. return 0;
  222. ResourceObject * obj = ResourceManager->find(mFilename);
  223. if(obj)
  224. {
  225. bool readSuccess = false;
  226. S32 len = dStrlen(mFilename);
  227. if(len > 3 && !dStricmp(mFilename + len - 4, ".wav"))
  228. {
  229. #ifdef LOG_SOUND_LOADS
  230. Con::printf("Reading WAV: %s\n", mFilename);
  231. #endif
  232. readSuccess = readWAV(obj);
  233. }
  234. #ifdef TORQUE_OS_IOS
  235. //-Mat lod a caf file on iPhone only
  236. if(len > 3 && !dStricmp(mFilename + len - 4, ".caf"))
  237. {
  238. #ifdef LOG_SOUND_LOADS
  239. Con::printf("Reading Caf: %s\n", mFilename);
  240. #endif
  241. SoundEngine::UInt32 bufferID;
  242. readSuccess = SoundEngine::LoadSoundFile(mFilename, &bufferID);
  243. //-Mat need to save the buffer
  244. malBuffer = bufferID;
  245. }
  246. #endif
  247. #ifndef TORQUE_OS_IOS
  248. else if (len > 3 && !dStricmp(mFilename + len - 4, ".ogg"))
  249. {
  250. # ifdef LOG_SOUND_LOADS
  251. Con::printf("Reading Ogg: %s\n", mFilename);
  252. # endif
  253. readSuccess = readOgg(obj);
  254. }
  255. #endif
  256. if(readSuccess)
  257. return(malBuffer);
  258. }
  259. alDeleteBuffers(1, &malBuffer);
  260. return 0;
  261. }
  262. /*! The Read a WAV file from the given ResourceObject and initialize
  263. an alBuffer with it.
  264. */
  265. bool AudioBuffer::readWAV(ResourceObject *obj)
  266. {
  267. WAVChunkHdr chunkHdr;
  268. WAVFmtExHdr fmtExHdr;
  269. WAVFileHdr fileHdr;
  270. WAVSmplHdr smplHdr;
  271. WAVFmtHdr fmtHdr;
  272. ALenum format = AL_FORMAT_MONO16;
  273. char *data = NULL;
  274. ALsizei size = 0;
  275. ALsizei freq = 22050;
  276. ALboolean loop = AL_FALSE;
  277. Stream *stream = ResourceManager->openStream(obj);
  278. if (!stream)
  279. return false;
  280. stream->read(4, &fileHdr.id[0]);
  281. stream->read(&fileHdr.size);
  282. stream->read(4, &fileHdr.type[0]);
  283. fileHdr.size=((fileHdr.size+1)&~1)-4;
  284. stream->read(4, &chunkHdr.id[0]);
  285. stream->read(&chunkHdr.size);
  286. // unread chunk data rounded up to nearest WORD
  287. S32 chunkRemaining = chunkHdr.size + (chunkHdr.size&1);
  288. while ((fileHdr.size!=0) && (stream->getStatus() != Stream::EOS))
  289. {
  290. // WAV Format header
  291. if (!dStrncmp((const char*)chunkHdr.id,"fmt ",4))
  292. {
  293. stream->read(&fmtHdr.format);
  294. stream->read(&fmtHdr.channels);
  295. stream->read(&fmtHdr.samplesPerSec);
  296. stream->read(&fmtHdr.bytesPerSec);
  297. stream->read(&fmtHdr.blockAlign);
  298. stream->read(&fmtHdr.bitsPerSample);
  299. if (fmtHdr.format==0x0001)
  300. {
  301. format=(fmtHdr.channels==1?
  302. (fmtHdr.bitsPerSample==8?AL_FORMAT_MONO8:AL_FORMAT_MONO16):
  303. (fmtHdr.bitsPerSample==8?AL_FORMAT_STEREO8:AL_FORMAT_STEREO16));
  304. freq=fmtHdr.samplesPerSec;
  305. chunkRemaining -= sizeof(WAVFmtHdr);
  306. }
  307. else
  308. {
  309. stream->read(sizeof(WAVFmtExHdr), &fmtExHdr);
  310. chunkRemaining -= sizeof(WAVFmtExHdr);
  311. }
  312. }
  313. // WAV Format header
  314. else if (!dStrncmp((const char*)chunkHdr.id,"data",4))
  315. {
  316. if (fmtHdr.format==0x0001)
  317. {
  318. size=chunkHdr.size;
  319. data=new char[chunkHdr.size];
  320. if (data)
  321. {
  322. stream->read(chunkHdr.size, data);
  323. #if defined(TORQUE_BIG_ENDIAN)
  324. // need to endian-flip the 16-bit data.
  325. if (fmtHdr.bitsPerSample==16) // !!!TBD we don't handle stereo, so may be RL flipped.
  326. {
  327. U16 *ds = (U16*)data;
  328. U16 *de = (U16*)(data+size);
  329. while (ds<de)
  330. {
  331. #if defined(TORQUE_BIG_ENDIAN)
  332. *ds = convertLEndianToHost(*ds);
  333. #else
  334. *ds = convertBEndianToHost(*ds);
  335. #endif
  336. ds++;
  337. }
  338. }
  339. #endif
  340. chunkRemaining -= chunkHdr.size;
  341. }
  342. else
  343. break;
  344. }
  345. else if (fmtHdr.format==0x0011)
  346. {
  347. //IMA ADPCM
  348. }
  349. else if (fmtHdr.format==0x0055)
  350. {
  351. //MP3 WAVE
  352. }
  353. }
  354. // WAV Loop header
  355. else if (!dStrncmp((const char*)chunkHdr.id,"smpl",4))
  356. {
  357. // this struct read is NOT endian safe but it is ok because
  358. // we are only testing the loops field against ZERO
  359. stream->read(sizeof(WAVSmplHdr), &smplHdr);
  360. loop = (smplHdr.loops ? AL_TRUE : AL_FALSE);
  361. chunkRemaining -= sizeof(WAVSmplHdr);
  362. }
  363. // either we have unread chunk data or we found an unknown chunk type
  364. // loop and read up to 1K bytes at a time until we have
  365. // read to the end of this chunk
  366. char buffer[1024];
  367. AssertFatal(chunkRemaining >= 0, "AudioBuffer::readWAV: remaining chunk data should never be less than zero.");
  368. while (chunkRemaining > 0)
  369. {
  370. S32 readSize = getMin(1024, chunkRemaining);
  371. stream->read(readSize, buffer);
  372. chunkRemaining -= readSize;
  373. }
  374. fileHdr.size-=(((chunkHdr.size+1)&~1)+8);
  375. // read next chunk header...
  376. stream->read(4, &chunkHdr.id[0]);
  377. stream->read(&chunkHdr.size);
  378. // unread chunk data rounded up to nearest WORD
  379. chunkRemaining = chunkHdr.size + (chunkHdr.size&1);
  380. }
  381. ResourceManager->closeStream(stream);
  382. if (data)
  383. {
  384. alBufferData(malBuffer, format, data, size, freq);
  385. delete [] data;
  386. return (alGetError() == AL_NO_ERROR);
  387. }
  388. return false;
  389. }
  390. #ifndef TORQUE_OS_IOS
  391. // Read an Ogg Vorbis file from the given ResourceObject and initialize an alBuffer with it.
  392. // Pulled from: https://www.garagegames.com/community/forums/viewthread/136675
  393. bool AudioBuffer::readOgg(ResourceObject *obj)
  394. {
  395. ALenum format = AL_FORMAT_MONO16;
  396. char *data = NULL;
  397. ALsizei size = 0;
  398. ALsizei freq = 22050;
  399. ALboolean loop = AL_FALSE;
  400. int current_section = 0;
  401. #if defined(TORQUE_BIG_ENDIAN)
  402. int endian = 1;
  403. #else
  404. int endian = 0;
  405. #endif
  406. int eof = 0;
  407. Stream *stream = ResourceManager->openStream(obj);
  408. if (!stream)
  409. return false;
  410. OggVorbis_File vf;
  411. dMemset(&vf, 0, sizeof(OggVorbis_File));
  412. const bool canSeek = stream->hasCapability(Stream::StreamPosition);
  413. ov_callbacks cb;
  414. cb.read_func = _ov_read_func;
  415. cb.seek_func = canSeek ? _ov_seek_func : NULL;
  416. cb.close_func = NULL;
  417. cb.tell_func = canSeek ? _ov_tell_func : NULL;
  418. // Open it.
  419. int ovResult = ov_open_callbacks(stream, &vf, NULL, 0, cb);
  420. if (ovResult != 0)
  421. {
  422. ResourceManager->closeStream(stream);
  423. return false;
  424. }
  425. const vorbis_info *vi = ov_info(&vf, -1);
  426. freq = vi->rate;
  427. long samples = (long)ov_pcm_total(&vf, -1);
  428. if (vi->channels == 1) {
  429. format = AL_FORMAT_MONO16;
  430. size = 2 * samples;
  431. }
  432. else {
  433. format = AL_FORMAT_STEREO16;
  434. size = 4 * samples;
  435. }
  436. data = new char[size];
  437. if (data)
  438. {
  439. long ret = oggRead(&vf, data, size, endian, &current_section);
  440. }
  441. /* cleanup */
  442. ov_clear(&vf);
  443. ResourceManager->closeStream(stream);
  444. if (data)
  445. {
  446. alBufferData(malBuffer, format, data, size, freq);
  447. delete[] data;
  448. return (alGetError() == AL_NO_ERROR);
  449. }
  450. return false;
  451. }
  452. // ov_read() only returns a maximum of one page worth of data
  453. // this helper function will repeat the read until buffer is full
  454. // Pulled from: https://www.garagegames.com/community/forums/viewthread/136675
  455. long AudioBuffer::oggRead(OggVorbis_File* vf, char *buffer, int length, int bigendianp, int *bitstream)
  456. {
  457. long bytesRead = 0;
  458. long totalBytes = 0;
  459. long offset = 0;
  460. long bytesToRead = 0;
  461. while ((offset) < length)
  462. {
  463. if ((length - offset) < CHUNKSIZE)
  464. bytesToRead = length - offset;
  465. else
  466. bytesToRead = CHUNKSIZE;
  467. bytesRead = ov_read(vf, buffer, bytesToRead, bigendianp, 2, 1, bitstream);
  468. if (bytesRead <= 0)
  469. break;
  470. offset += bytesRead;
  471. buffer += bytesRead;
  472. }
  473. return offset;
  474. }
  475. #endif