PolySound.cpp 15 KB

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