PolySound.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582
  1. /*
  2. Copyright (C) 2011 by Ivan Safrin
  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. */
  19. #include "polycode/core/PolySound.h"
  20. #ifndef NO_OGG
  21. #define OV_EXCLUDE_STATIC_CALLBACKS
  22. #include <vorbis/vorbisfile.h>
  23. #endif
  24. #undef OV_EXCLUDE_STATIC_CALLBACKS
  25. #include "polycode/core/PolyString.h"
  26. #include "polycode/core/PolyLogger.h"
  27. #include "polycode/core/PolySoundManager.h"
  28. #include "polycode/core/PolyCore.h"
  29. #include "polycode/core/PolyCoreServices.h"
  30. #include <stdlib.h>
  31. #include <string>
  32. #include <vector>
  33. #include <stdint.h>
  34. #include <limits>
  35. #ifndef MAX_FLOAT
  36. #define MAX_FLOAT (std::numeric_limits<double>::infinity())
  37. #endif
  38. #ifndef INT32_MAX
  39. #define INT32_MAX (std::numeric_limits<int32_t>::max())
  40. #endif
  41. #ifndef INT16_MAX
  42. #define INT16_MAX (std::numeric_limits<int16_t>::max())
  43. #endif
  44. using namespace std;
  45. using namespace Polycode;
  46. AudioStreamingSource::AudioStreamingSource(unsigned int channels, unsigned int freq) : channels(channels), freq(freq) {
  47. }
  48. unsigned int AudioStreamingSource::getNumChannels() {
  49. return channels;
  50. }
  51. unsigned int AudioStreamingSource::getFrequency() {
  52. return freq;
  53. }
  54. unsigned int AudioStreamingSource::streamData(int16_t *buffer, unsigned int size) {
  55. return 0;
  56. }
  57. #ifndef NO_OGG
  58. size_t custom_readfunc(void *ptr, size_t size, size_t nmemb, void *datasource) {
  59. Polycode::CoreFile *file = (Polycode::CoreFile*) datasource;
  60. return file->read(ptr, size, nmemb);
  61. }
  62. int custom_seekfunc(void *datasource, ogg_int64_t offset, int whence){
  63. Polycode::CoreFile *file = (Polycode::CoreFile*) datasource;
  64. return file->seek(offset, whence);
  65. }
  66. int custom_closefunc(void *datasource) {
  67. Polycode::CoreFile *file = (Polycode::CoreFile*) datasource;
  68. Services()->getCore()->closeFile(file);
  69. return 0;
  70. }
  71. long custom_tellfunc(void *datasource) {
  72. CoreFile *file = (CoreFile*) datasource;
  73. return file->tell();
  74. }
  75. #endif
  76. Sound::Sound(const String& fileName) : referenceDistance(1), maxDistance(MAX_FLOAT), pitch(1), volume(1), numSamples(-1), streamingSound(false), playing(false), playbackOffset(0), streamingSource(NULL), frequencyAdjust(1.0) {
  77. soundLoaded = false;
  78. setIsPositional(false);
  79. loadFile(fileName);
  80. if(soundLoaded) {
  81. Services()->getSoundManager()->registerSound(this);
  82. }
  83. }
  84. Sound::Sound(int size, const char *data, int channels, unsigned int freq, SoundFormat format) : referenceDistance(1), maxDistance(MAX_FLOAT), pitch(1), volume(1), numSamples(-1), streamingSound(false), playing(false) , playbackOffset(0), streamingSource(NULL), frequencyAdjust(1.0) {
  85. setIsPositional(false);
  86. soundLoaded = loadBytes(data, size, channels, freq, format);
  87. if(soundLoaded) {
  88. Services()->getSoundManager()->registerSound(this);
  89. }
  90. }
  91. Sound::Sound(AudioStreamingSource *streamingSource) : referenceDistance(1), maxDistance(MAX_FLOAT), pitch(1), volume(1), numSamples(-1), streamingSound(true), streamingSource(streamingSource), playing(false), playbackOffset(0), frequencyAdjust(1.0) {
  92. soundBuffer = (int16_t*) malloc(sizeof(int16_t) * streamingSource->getNumChannels() * POLY_MIX_BUFFER_SIZE);
  93. Services()->getSoundManager()->registerSound(this);
  94. numChannels = streamingSource->getNumChannels();
  95. }
  96. void Sound::updateStream(unsigned int streamCount) {
  97. if(streamingSource) {
  98. playbackOffset = 0;
  99. numSamples = streamCount;
  100. streamingSource->streamData(soundBuffer, streamCount);
  101. }
  102. }
  103. void Sound::loadFile(String fileName) {
  104. if(soundLoaded) {
  105. free(soundBuffer);
  106. }
  107. String actualFilename = fileName;
  108. CoreFile *test = Services()->getCore()->openFile(fileName, "rb");
  109. if(!test) {
  110. actualFilename = "default/default.wav";
  111. } else {
  112. Services()->getCore()->closeFile(test);
  113. }
  114. String extension;
  115. size_t found;
  116. found=actualFilename.rfind(".");
  117. if (found!=string::npos) {
  118. extension = actualFilename.substr(found+1);
  119. } else {
  120. extension = "";
  121. }
  122. if(extension == "wav" || extension == "WAV") {
  123. soundLoaded = loadWAV(actualFilename);
  124. } else if(extension == "ogg" || extension == "OGG") {
  125. soundLoaded = loadOGG(actualFilename);
  126. }
  127. this->fileName = actualFilename;
  128. }
  129. String Sound::getFileName() {
  130. return fileName;
  131. }
  132. Number Sound::getVolume() {
  133. return volume;
  134. }
  135. Number Sound::getPitch() {
  136. return pitch;
  137. }
  138. Sound::~Sound() {
  139. free(soundBuffer);
  140. Services()->getSoundManager()->unregisterSound(this);
  141. }
  142. void Sound::soundCheck(bool result, const String& err) {
  143. if(!result)
  144. Logger::log(err);
  145. }
  146. unsigned long Sound::readByte32(const unsigned char data[4]) {
  147. #if TAU_BIG_ENDIAN
  148. return (data[0] << 24) + (data[1] << 16) + (data[2] << 8) + data[3];
  149. #else
  150. return (data[3] << 24) + (data[2] << 16) + (data[1] << 8) + data[0];
  151. #endif
  152. }
  153. unsigned short Sound::readByte16(const unsigned char data[2]) {
  154. #if TAU_BIG_ENDIAN
  155. return (data[0] << 8) + data[1];
  156. #else
  157. return (data[1] << 8) + data[0];
  158. #endif
  159. }
  160. void Sound::Play(bool loop, bool restartSound) {
  161. if(restartSound) {
  162. playbackOffset = 0;
  163. }
  164. playing = true;
  165. looped = loop;
  166. }
  167. bool Sound::isPlaying() {
  168. return playing;
  169. }
  170. bool Sound::isLooped() {
  171. return looped;
  172. }
  173. void Sound::setVolume(Number newVolume) {
  174. this->volume = newVolume;
  175. }
  176. void Sound::setPitch(Number newPitch) {
  177. this->pitch = newPitch;
  178. }
  179. void Sound::setSoundPosition(const Vector3 &position) {
  180. this->position = position;
  181. }
  182. void Sound::setSoundVelocity(const Vector3 &velocity) {
  183. this->velocity = velocity;
  184. }
  185. void Sound::setSoundDirection(const Vector3 &direction) {
  186. this->direction = direction;
  187. }
  188. Number Sound::getPlaybackTime() {
  189. /*
  190. float result = 0.0;
  191. alGetSourcef(soundSource, AL_SEC_OFFSET, &result);
  192. return result;
  193. */
  194. //NOAL_TODO
  195. return 0.0;
  196. }
  197. Number Sound::getPlaybackDuration() {
  198. /*
  199. ALint sizeInBytes;
  200. ALint channels;
  201. ALint bits;
  202. ALint bufferID;
  203. alGetSourcei(soundSource, AL_BUFFER, &bufferID);
  204. alGetBufferi(bufferID, AL_SIZE, &sizeInBytes);
  205. alGetBufferi(bufferID, AL_CHANNELS, &channels);
  206. alGetBufferi(bufferID, AL_BITS, &bits);
  207. int lengthInSamples = sizeInBytes * 8 / (channels * bits);
  208. ALint frequency;
  209. alGetBufferi(bufferID, AL_FREQUENCY, &frequency);
  210. Number durationInSeconds = (float)lengthInSamples / (float)frequency;
  211. return durationInSeconds;
  212. */
  213. //NOAL_TODO
  214. return 0.0;
  215. }
  216. int Sound::getOffset() {
  217. return playbackOffset;
  218. }
  219. void Sound::setOffset(unsigned int offset) {
  220. playbackOffset = (offset);
  221. Number adjustedOffset = ((Number)playbackOffset) * pitch * frequencyAdjust;
  222. if((unsigned int)adjustedOffset >= numSamples) {
  223. playbackOffset = 0;
  224. if(!looped && !streamingSource) {
  225. playing = false;
  226. }
  227. }
  228. }
  229. void Sound::seekTo(Number time) {
  230. /*
  231. if(time > getPlaybackDuration())
  232. return;
  233. alSourcef(soundSource, AL_SEC_OFFSET, time);
  234. checkALError("Seek");
  235. */
  236. //NOAL_TODO
  237. }
  238. int Sound::getSampleLength() {
  239. return numSamples;
  240. }
  241. void Sound::setPositionalProperties(Number referenceDistance, Number maxDistance) {
  242. setReferenceDistance(referenceDistance);
  243. setMaxDistance(maxDistance);
  244. }
  245. void Sound::setReferenceDistance(Number referenceDistance) {
  246. this->referenceDistance = referenceDistance;
  247. }
  248. void Sound::setMaxDistance(Number maxDistance) {
  249. this->maxDistance = maxDistance;
  250. }
  251. Number Sound::getReferenceDistance() {
  252. return referenceDistance;
  253. }
  254. Number Sound::getMaxDistance() {
  255. return maxDistance;
  256. }
  257. void Sound::setIsPositional(bool isPositional) {
  258. this->isPositional = isPositional;
  259. }
  260. void Sound::Stop() {
  261. playing = false;
  262. }
  263. Number Sound::getSampleAsNumber(unsigned int offset, unsigned int channel, const Vector3 &position, const Quaternion &orientation) {
  264. Number adjustedOffset = ((Number)offset) * pitch * frequencyAdjust;
  265. Number ret;
  266. if(isPositional) {
  267. ret = (((Number)(soundBuffer[((((unsigned int )adjustedOffset)%numSamples)*numChannels)])/((Number)INT16_MAX))) * volume;
  268. ret = modulateSampleForListener(ret, channel, position, orientation);
  269. } else {
  270. ret = (((Number)(soundBuffer[((((unsigned int )adjustedOffset)%numSamples)*numChannels)+(channel % numChannels)])/((Number)INT16_MAX))) * volume;
  271. }
  272. return ret;
  273. }
  274. Number Sound::modulateSampleForListener(Number sample, unsigned int channel, const Vector3 &position, const Quaternion &orientation) {
  275. // setup different channel configurations here
  276. // if(STEREO) {
  277. Vector3 earDirection;
  278. if(channel) {
  279. earDirection = Vector3(-1.0, 0.0, 0.0);
  280. } else {
  281. earDirection = Vector3(1.0, 0.0, 0.0);
  282. }
  283. earDirection = orientation.applyTo(earDirection);
  284. Vector3 dir = position - this->position;
  285. dir.Normalize();
  286. Number muliplier = earDirection.dot(dir);
  287. if(muliplier < 0.0) {
  288. muliplier = 0.0;
  289. }
  290. Number ret = sample * (0.1 + (muliplier * 0.9)); // bleed 0.1 into the other ear
  291. Number distance = position.distance(this->position);
  292. Number attenuate = 0.5 * pow(referenceDistance/distance, 2.0);
  293. attenuate = MIN(attenuate, 1.0);
  294. attenuate = MAX(attenuate, 0.0);
  295. ret *= attenuate;
  296. return ret;
  297. }
  298. bool Sound::loadBytes(const char *data, int size, int channels, unsigned int freq, SoundFormat format) {
  299. if(format == SoundFormatUnsupported) {
  300. Logger::log("[%s] Error: sound format unsupported!\n", fileName.c_str());
  301. return false;
  302. }
  303. soundBuffer = (int16_t*) malloc(sizeof(int16_t) * channels * size);
  304. int16_t *soundBufferPtr = soundBuffer;
  305. unsigned int dataOffset = 0;
  306. switch(format) {
  307. case SoundFormat8:
  308. numSamples = size / channels;
  309. break;
  310. case SoundFormat16:
  311. numSamples = size / channels / 2;
  312. break;
  313. case SoundFormat32:
  314. numSamples = size / channels / 4;
  315. break;
  316. default:
  317. break;
  318. }
  319. for(int i=0; i < numSamples; i++){
  320. for(int c=0; c < channels; c++) {
  321. switch(format) {
  322. case SoundFormat8:
  323. *soundBufferPtr = ((int8_t*)data)[dataOffset];
  324. break;
  325. case SoundFormat16:
  326. *soundBufferPtr = ((int16_t*)data)[dataOffset];
  327. break;
  328. case SoundFormat32:
  329. *soundBufferPtr = ((int32_t*)data)[dataOffset];
  330. break;
  331. default:
  332. break;
  333. }
  334. soundBufferPtr++;
  335. dataOffset++;
  336. }
  337. }
  338. numChannels = channels;
  339. frequency = freq;
  340. // adjust for different frequency
  341. frequencyAdjust = (Number)freq/(Number)POLY_AUDIO_FREQ;
  342. return true;
  343. }
  344. unsigned int Sound::getFrequency() {
  345. return frequency;
  346. }
  347. bool Sound::loadOGG(const String& fileName) {
  348. #ifndef NO_OGG
  349. vector<char> data;
  350. int bitStream;
  351. long bytes;
  352. char array[BUFFER_SIZE];
  353. CoreFile *f = Services()->getCore()->openFile(fileName.c_str(), "rb");
  354. if(!f) {
  355. Logger::log("Error loading OGG file!\n");
  356. return false;
  357. }
  358. vorbis_info *pInfo;
  359. OggVorbis_File oggFile;
  360. ov_callbacks callbacks;
  361. callbacks.read_func = custom_readfunc;
  362. callbacks.seek_func = custom_seekfunc;
  363. callbacks.close_func = custom_closefunc;
  364. callbacks.tell_func = custom_tellfunc;
  365. ov_open_callbacks( (void*)f, &oggFile, NULL, 0, callbacks);
  366. pInfo = ov_info(&oggFile, -1);
  367. do {
  368. bytes = ov_read(&oggFile, array, BUFFER_SIZE, 0, 2, 1, &bitStream);
  369. data.insert(data.end(), array, array + bytes);
  370. } while (bytes > 0);
  371. bool retVal = loadBytes(data.data(), data.size(), pInfo->channels, pInfo->rate, SoundFormat16);
  372. ov_clear(&oggFile);
  373. return retVal;
  374. #else
  375. return false;
  376. #endif
  377. }
  378. bool Sound::loadWAV(const String& fileName) {
  379. long bytes;
  380. vector <char> data;
  381. // Local resources
  382. CoreFile *f = NULL;
  383. char *array = NULL;
  384. // Open for binary reading
  385. f = Services()->getCore()->openFile(fileName.c_str(), "rb");
  386. if (!f) {
  387. Logger::log("LoadWav: Could not load wav from " + fileName);
  388. return false;
  389. }
  390. // buffers
  391. char magic[5];
  392. magic[4] = '\0';
  393. unsigned char data32[4];
  394. unsigned char data16[2];
  395. // check magic
  396. soundCheck(f->read(magic,4,1) == 1, "LoadWav: Cannot read wav file "+ fileName );
  397. soundCheck(String(magic) == "RIFF", "LoadWav: Wrong wav file format. This file is not a .wav file (no RIFF magic): "+ fileName );
  398. // skip 4 bytes (file size)
  399. f->seek(4,SEEK_CUR);
  400. // check file format
  401. soundCheck(f->read(magic,4,1) == 1, "LoadWav: Cannot read wav file "+ fileName );
  402. soundCheck(String(magic) == "WAVE", "LoadWav: Wrong wav file format. This file is not a .wav file (no WAVE format): "+ fileName );
  403. // check 'fmt ' sub chunk (1)
  404. soundCheck(f->read(magic,4,1) == 1, "LoadWav: Cannot read wav file "+ fileName );
  405. soundCheck(String(magic) == "fmt ", "LoadWav: Wrong wav file format. This file is not a .wav file (no 'fmt ' subchunk): "+ fileName );
  406. // read (1)'s size
  407. soundCheck(f->read(data32,4,1) == 1, "LoadWav: Cannot read wav file "+ fileName );
  408. unsigned long subChunk1Size = readByte32(data32);
  409. soundCheck(subChunk1Size >= 16, "Wrong wav file format. This file is not a .wav file ('fmt ' chunk too small, truncated file?): "+ fileName );
  410. // check PCM audio format
  411. soundCheck(f->read(data16,2,1) == 1, "LoadWav: Cannot read wav file "+ fileName );
  412. unsigned short audioFormat = readByte16(data16);
  413. soundCheck(audioFormat == 1, "LoadWav: Wrong wav file format. This file is not a .wav file (audio format is not PCM): "+ fileName );
  414. // read number of channels
  415. soundCheck(f->read(data16,2,1) == 1, "LoadWav: Cannot read wav file "+ fileName );
  416. unsigned short channels = readByte16(data16);
  417. // read frequency (sample rate)
  418. soundCheck(f->read(data32,4,1) == 1, "LoadWav: Cannot read wav file "+ fileName );
  419. unsigned long frequency = readByte32(data32);
  420. // skip 6 bytes (Byte rate (4), Block align (2))
  421. f->seek(6,SEEK_CUR);
  422. // read bits per sample
  423. soundCheck(f->read(data16,2,1) == 1, "LoadWav: Cannot read wav file "+ fileName );
  424. unsigned short bps = readByte16(data16);
  425. SoundFormat format = SoundFormatUnsupported;
  426. switch(bps) {
  427. case 8:
  428. format = SoundFormat8;
  429. break;
  430. case 16:
  431. format = SoundFormat16;
  432. break;
  433. case 32:
  434. format = SoundFormat32;
  435. break;
  436. }
  437. // check 'data' sub chunk (2)
  438. soundCheck(f->read(magic,4,1) == 1, "LoadWav: Cannot read wav file "+ fileName );
  439. soundCheck(String(magic) == "data", "LoadWav: Wrong wav file format. This file is not a .wav file (no data subchunk): "+ fileName );
  440. soundCheck(f->read(data32,4,1) == 1, "LoadWav: Cannot read wav file "+ fileName );
  441. unsigned long subChunk2Size = readByte32(data32);
  442. array = new char[BUFFER_SIZE];
  443. while (data.size() != subChunk2Size) {
  444. // Read up to a buffer's worth of decoded sound data
  445. bytes = f->read(array, 1, BUFFER_SIZE);
  446. if (bytes <= 0)
  447. break;
  448. if (data.size() + bytes > subChunk2Size)
  449. bytes = subChunk2Size - data.size();
  450. // Append to end of buffer
  451. data.insert(data.end(), array, array + bytes);
  452. };
  453. delete []array;
  454. array = NULL;
  455. Services()->getCore()->closeFile(f);
  456. f = NULL;
  457. return loadBytes(&data[0], data.size(), channels, frequency, format);
  458. }
  459. //NOAL_TODO