audioBuffer.cc 15 KB

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