2
0

PolySound.cpp 16 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 "PolySound.h"
  20. #define OV_EXCLUDE_STATIC_CALLBACKS
  21. #include <vorbis/vorbisfile.h>
  22. #undef OV_EXCLUDE_STATIC_CALLBACKS
  23. #include "PolyString.h"
  24. #include "PolyLogger.h"
  25. #include "OSBasics.h"
  26. #include <string>
  27. #include <vector>
  28. #include <stdint.h>
  29. #include <limits>
  30. #define MAX_FLOAT (std::numeric_limits<double>::infinity())
  31. #define INT32_MAX (std::numeric_limits<int32_t>::max())
  32. using namespace std;
  33. using namespace Polycode;
  34. size_t custom_readfunc(void *ptr, size_t size, size_t nmemb, void *datasource) {
  35. OSFILE *file = (OSFILE*) datasource;
  36. return OSBasics::read(ptr, size, nmemb, file);
  37. }
  38. int custom_seekfunc(void *datasource, ogg_int64_t offset, int whence){
  39. OSFILE *file = (OSFILE*) datasource;
  40. return OSBasics::seek(file, offset, whence);
  41. }
  42. int custom_closefunc(void *datasource) {
  43. OSFILE *file = (OSFILE*) datasource;
  44. return OSBasics::close(file);
  45. }
  46. long custom_tellfunc(void *datasource) {
  47. OSFILE *file = (OSFILE*) datasource;
  48. return OSBasics::tell(file);
  49. }
  50. Sound::Sound(const String& fileName, bool generateFloatBuffer) : referenceDistance(1), maxDistance(MAX_FLOAT), pitch(1), volume(1), sampleLength(-1) {
  51. checkALError("Construct: Loose error before construction");
  52. soundLoaded = false;
  53. loadFile(fileName, generateFloatBuffer);
  54. setIsPositional(false);
  55. checkALError("Construct from file: Finished");
  56. }
  57. Sound::Sound(int size, const char *data, int channels, int freq, int bps, bool generateFloatBuffer) : referenceDistance(1), maxDistance(MAX_FLOAT), pitch(1), volume(1), buffer(AL_NONE), soundSource(AL_NONE), sampleLength(-1) {
  58. checkALError("Construct: Loose error before construction");
  59. buffer = loadBytes(data, size, freq, channels, bps, generateFloatBuffer);
  60. soundSource = GenSource(buffer);
  61. setIsPositional(false);
  62. reloadProperties();
  63. soundLoaded = true;
  64. checkALError("Construct from data: Finished");
  65. }
  66. void Sound::loadFile(String fileName, bool generateFloatBuffer) {
  67. if(soundLoaded) {
  68. alDeleteSources(1,&soundSource);
  69. }
  70. String actualFilename = fileName;
  71. OSFILE *test = OSBasics::open(fileName, "rb");
  72. if(!test) {
  73. actualFilename = "default/default.wav";
  74. } else {
  75. OSBasics::close(test);
  76. }
  77. String extension;
  78. size_t found;
  79. found=actualFilename.rfind(".");
  80. if (found!=string::npos) {
  81. extension = actualFilename.substr(found+1);
  82. } else {
  83. extension = "";
  84. }
  85. if(extension == "wav" || extension == "WAV") {
  86. buffer = loadWAV(actualFilename, generateFloatBuffer);
  87. } else if(extension == "ogg" || extension == "OGG") {
  88. buffer = loadOGG(actualFilename, generateFloatBuffer);
  89. }
  90. this->fileName = actualFilename;
  91. soundSource = GenSource(buffer);
  92. reloadProperties();
  93. soundLoaded = true;
  94. checkALError("Sound load: complete");
  95. }
  96. void Sound::reloadProperties() { // Re-set stored properties into sound source.
  97. setVolume(volume);
  98. setPitch(pitch);
  99. setReferenceDistance(referenceDistance);
  100. setMaxDistance(maxDistance);
  101. }
  102. String Sound::getFileName() {
  103. return fileName;
  104. }
  105. Number Sound::getVolume() {
  106. return volume;
  107. }
  108. Number Sound::getPitch() {
  109. return pitch;
  110. }
  111. Sound::~Sound() {
  112. alDeleteSources(1,&soundSource);
  113. checkALError("Destroying sound");
  114. alDeleteBuffers(1, &buffer);
  115. checkALError("Deleting buffer");
  116. }
  117. void Sound::soundCheck(bool result, const String& err) {
  118. if(!result)
  119. soundError(err);
  120. }
  121. void Sound::soundError(const String& err) {
  122. Logger::log("SOUND ERROR: %s\n", err.c_str());
  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) {
  139. if(!loop) {
  140. alSourcei(soundSource, AL_LOOPING, AL_FALSE);
  141. } else {
  142. alSourcei(soundSource, AL_LOOPING, AL_TRUE);
  143. }
  144. checkALError("Play: loop");
  145. alSourcePlay(soundSource);
  146. checkALError("Play: play");
  147. }
  148. bool Sound::isPlaying() {
  149. ALenum state;
  150. alGetSourcei(soundSource, AL_SOURCE_STATE, &state);
  151. return (state == AL_PLAYING);
  152. }
  153. void Sound::setVolume(Number newVolume) {
  154. this->volume = newVolume;
  155. alSourcef(soundSource, AL_GAIN, newVolume);
  156. checkALError("Set volume");
  157. }
  158. void Sound::setPitch(Number newPitch) {
  159. this->pitch = newPitch;
  160. alSourcef(soundSource, AL_PITCH, newPitch);
  161. checkALError("Set pitch");
  162. }
  163. void Sound::setSoundPosition(Vector3 position) {
  164. if(isPositional)
  165. alSource3f(soundSource,AL_POSITION, position.x, position.y, position.z);
  166. checkALError("Set sound position");
  167. }
  168. void Sound::setSoundVelocity(Vector3 velocity) {
  169. if(isPositional)
  170. alSource3f(soundSource,AL_VELOCITY, velocity.x, velocity.y, velocity.z);
  171. checkALError("Set sound velocity");
  172. }
  173. void Sound::setSoundDirection(Vector3 direction) {
  174. if(isPositional)
  175. alSource3f(soundSource,AL_DIRECTION, direction.x, direction.y, direction.z);
  176. checkALError("Set sound direction");
  177. }
  178. void Sound::setOffset(int off) {
  179. alSourcei(soundSource, AL_SAMPLE_OFFSET, off);
  180. }
  181. Number Sound::getPlaybackTime() {
  182. float result = 0.0;
  183. alGetSourcef(soundSource, AL_SEC_OFFSET, &result);
  184. return result;
  185. }
  186. Number Sound::getPlaybackDuration() {
  187. ALint sizeInBytes;
  188. ALint channels;
  189. ALint bits;
  190. ALint bufferID;
  191. alGetSourcei(soundSource, AL_BUFFER, &bufferID);
  192. alGetBufferi(bufferID, AL_SIZE, &sizeInBytes);
  193. alGetBufferi(bufferID, AL_CHANNELS, &channels);
  194. alGetBufferi(bufferID, AL_BITS, &bits);
  195. int lengthInSamples = sizeInBytes * 8 / (channels * bits);
  196. ALint frequency;
  197. alGetBufferi(bufferID, AL_FREQUENCY, &frequency);
  198. Number durationInSeconds = (float)lengthInSamples / (float)frequency;
  199. return durationInSeconds;
  200. }
  201. int Sound::getOffset() {
  202. ALint off = -1;
  203. alGetSourcei(soundSource, AL_SAMPLE_OFFSET, &off);
  204. return off;
  205. }
  206. void Sound::seekTo(Number time) {
  207. if(time > getPlaybackDuration())
  208. return;
  209. alSourcef(soundSource, AL_SEC_OFFSET, time);
  210. checkALError("Seek");
  211. }
  212. int Sound::getSampleLength() {
  213. return sampleLength;
  214. }
  215. void Sound::setPositionalProperties(Number referenceDistance, Number maxDistance) {
  216. setReferenceDistance(referenceDistance);
  217. setMaxDistance(maxDistance);
  218. }
  219. void Sound::setReferenceDistance(Number referenceDistance) {
  220. this->referenceDistance = referenceDistance;
  221. alSourcef(soundSource, AL_REFERENCE_DISTANCE, referenceDistance);
  222. checkALError("Set reference distance");
  223. }
  224. void Sound::setMaxDistance(Number maxDistance) {
  225. this->maxDistance = maxDistance;
  226. alSourcef(soundSource,AL_MAX_DISTANCE, maxDistance);
  227. checkALError("Set max distance");
  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. if(isPositional) {
  238. alSourcei(soundSource, AL_SOURCE_RELATIVE, AL_FALSE);
  239. } else {
  240. alSourcei(soundSource, AL_SOURCE_RELATIVE, AL_TRUE);
  241. alSource3f(soundSource,AL_POSITION, 0,0,0);
  242. alSource3f(soundSource,AL_VELOCITY, 0,0,0);
  243. alSource3f(soundSource,AL_DIRECTION, 0,0,0);
  244. }
  245. checkALError("Set is-positional");
  246. }
  247. ALenum Sound::checkALError(const String& operation) {
  248. ALenum error = alGetError();
  249. if(error != AL_NO_ERROR) {
  250. switch(error) {
  251. case AL_INVALID_NAME:
  252. soundError(operation +": " + ALInvalidNameStr);
  253. break;
  254. case AL_INVALID_ENUM:
  255. soundError(operation + ": " +ALInvalidEnumStr);
  256. break;
  257. case AL_INVALID_VALUE:
  258. soundError(operation + ": " +ALInvalidValueStr);
  259. break;
  260. case AL_INVALID_OPERATION:
  261. soundError(operation + ": " +ALInvalidOpStr);
  262. break;
  263. case AL_OUT_OF_MEMORY:
  264. soundError(operation + ": " +ALOutOfMemoryStr);
  265. break;
  266. default:
  267. soundError(operation + ": " +ALOtherErrorStr);
  268. break;
  269. }
  270. }
  271. return error;
  272. }
  273. void Sound::Stop() {
  274. alSourceStop(soundSource);
  275. checkALError("Stop");
  276. }
  277. ALuint Sound::GenSource() {
  278. ALuint source;
  279. bool looping = false;
  280. ALfloat sourcePos[] = {0.0, 0.0, 0.0};
  281. ALfloat sourceVel[] = {0.0, 0.0, 0.0};
  282. alGetError();
  283. alGenSources(1, &source);
  284. checkALError("Generating sources");
  285. alSourcef(source, AL_PITCH, 1.0);
  286. alSourcef(source, AL_GAIN, 1.0);
  287. alSourcefv(source, AL_POSITION, sourcePos);
  288. alSourcefv(source, AL_VELOCITY, sourceVel);
  289. alSourcei(source, AL_LOOPING, looping);
  290. checkALError("Setting source properties");
  291. return source;
  292. }
  293. ALuint Sound::GenSource(ALuint buffer) {
  294. alGetError();
  295. ALuint source = GenSource();
  296. alSourcei(source, AL_BUFFER, buffer);
  297. checkALError("Setting source buffer");
  298. return source;
  299. }
  300. ALuint Sound::loadBytes(const char *data, int size, int freq, int channels, int bps, bool generateFloatBuffer) {
  301. ALenum format;
  302. if (channels == 1)
  303. format = (bps == 8) ? AL_FORMAT_MONO8 : AL_FORMAT_MONO16;
  304. else
  305. format = (bps == 8) ? AL_FORMAT_STEREO8 : AL_FORMAT_STEREO16;
  306. sampleLength = bps > 8 ? size / (bps/8) : -1;
  307. checkALError("LoadBytes: pre-generate buffer");
  308. alGenBuffers(1, &buffer);
  309. checkALError("LoadBytes: generate buffer");
  310. soundCheck(AL_NONE != buffer, "LoadBytes: Did not generate buffer");
  311. alBufferData(buffer, format, data, size, freq);
  312. checkALError("LoadBytes: load buffer data");
  313. if(generateFloatBuffer) {
  314. int32_t *ptr32 = (int32_t*) &data[0];
  315. for(int i=0; i < size/4; i++ ) {
  316. floatBuffer.push_back(((Number)ptr32[i])/((Number)INT32_MAX));
  317. }
  318. }
  319. return buffer;
  320. }
  321. ALuint Sound::loadOGG(const String& fileName, bool generateFloatBuffer) {
  322. // floatBuffer.clear();
  323. vector<char> data;
  324. alGenBuffers(1, &buffer);
  325. int endian = 0; // 0 for Little-Endian, 1 for Big-Endian
  326. int bitStream;
  327. long bytes;
  328. char array[BUFFER_SIZE]; // Local fixed size array
  329. OSFILE *f;
  330. ALenum format;
  331. ALsizei freq;
  332. // Open for binary reading
  333. f = OSBasics::open(fileName.c_str(), "rb");
  334. if(!f) {
  335. soundError("Error loading OGG file!\n");
  336. return buffer;
  337. }
  338. vorbis_info *pInfo;
  339. OggVorbis_File oggFile;
  340. ov_callbacks callbacks;
  341. callbacks.read_func = custom_readfunc;
  342. callbacks.seek_func = custom_seekfunc;
  343. callbacks.close_func = custom_closefunc;
  344. callbacks.tell_func = custom_tellfunc;
  345. ov_open_callbacks( (void*)f, &oggFile, NULL, 0, callbacks);
  346. // ov_open(f, &oggFile, NULL, 0);
  347. // Get some information about the OGG file
  348. pInfo = ov_info(&oggFile, -1);
  349. // Check the number of channels... always use 16-bit samples
  350. if (pInfo->channels == 1)
  351. format = AL_FORMAT_MONO16;
  352. else
  353. format = AL_FORMAT_STEREO16;
  354. // end if
  355. // The frequency of the sampling rate
  356. freq = pInfo->rate;
  357. do {
  358. // Read up to a buffer's worth of decoded sound data
  359. bytes = ov_read(&oggFile, array, BUFFER_SIZE, endian, 2, 1, &bitStream);
  360. // Append to end of buffer
  361. data.insert(data.end(), array, array + bytes);
  362. } while (bytes > 0);
  363. ov_clear(&oggFile);
  364. sampleLength = data.size() / sizeof(unsigned short);
  365. alBufferData(buffer, format, &data[0], static_cast<ALsizei>(data.size()), freq);
  366. if(generateFloatBuffer) {
  367. int32_t *ptr32 = (int32_t*) &data[0];
  368. for(int i=0; i < data.size()/4; i++ ) {
  369. floatBuffer.push_back(((Number)ptr32[i])/((Number)INT32_MAX));
  370. }
  371. }
  372. return buffer;
  373. }
  374. std::vector<float> *Sound::getFloatBuffer() {
  375. return &floatBuffer;
  376. }
  377. ALuint Sound::loadWAV(const String& fileName, bool generateFloatBuffer) {
  378. long bytes;
  379. vector <char> data;
  380. ALsizei freq;
  381. // Local resources
  382. OSFILE *f = NULL;
  383. char *array = NULL;
  384. checkALError("loadWAV: pre-generate buffer");
  385. // Open for binary reading
  386. f = OSBasics::open(fileName.c_str(), "rb");
  387. if (!f) {
  388. soundError("LoadWav: Could not load wav from " + fileName);
  389. return buffer;
  390. }
  391. // buffers
  392. char magic[5];
  393. magic[4] = '\0';
  394. unsigned char data32[4];
  395. unsigned char data16[2];
  396. // check magic
  397. soundCheck(OSBasics::read(magic,4,1,f) == 1, "LoadWav: Cannot read wav file "+ fileName );
  398. soundCheck(String(magic) == "RIFF", "LoadWav: Wrong wav file format. This file is not a .wav file (no RIFF magic): "+ fileName );
  399. // skip 4 bytes (file size)
  400. OSBasics::seek(f,4,SEEK_CUR);
  401. // check file format
  402. soundCheck(OSBasics::read(magic,4,1,f) == 1, "LoadWav: Cannot read wav file "+ fileName );
  403. soundCheck(String(magic) == "WAVE", "LoadWav: Wrong wav file format. This file is not a .wav file (no WAVE format): "+ fileName );
  404. // check 'fmt ' sub chunk (1)
  405. soundCheck(OSBasics::read(magic,4,1,f) == 1, "LoadWav: Cannot read wav file "+ fileName );
  406. soundCheck(String(magic) == "fmt ", "LoadWav: Wrong wav file format. This file is not a .wav file (no 'fmt ' subchunk): "+ fileName );
  407. // read (1)'s size
  408. soundCheck(OSBasics::read(data32,4,1,f) == 1, "LoadWav: Cannot read wav file "+ fileName );
  409. unsigned long subChunk1Size = readByte32(data32);
  410. soundCheck(subChunk1Size >= 16, "Wrong wav file format. This file is not a .wav file ('fmt ' chunk too small, truncated file?): "+ fileName );
  411. // check PCM audio format
  412. soundCheck(OSBasics::read(data16,2,1,f) == 1, "LoadWav: Cannot read wav file "+ fileName );
  413. unsigned short audioFormat = readByte16(data16);
  414. soundCheck(audioFormat == 1, "LoadWav: Wrong wav file format. This file is not a .wav file (audio format is not PCM): "+ fileName );
  415. // read number of channels
  416. soundCheck(OSBasics::read(data16,2,1,f) == 1, "LoadWav: Cannot read wav file "+ fileName );
  417. unsigned short channels = readByte16(data16);
  418. // read frequency (sample rate)
  419. soundCheck(OSBasics::read(data32,4,1,f) == 1, "LoadWav: Cannot read wav file "+ fileName );
  420. unsigned long frequency = readByte32(data32);
  421. // skip 6 bytes (Byte rate (4), Block align (2))
  422. OSBasics::seek(f,6,SEEK_CUR);
  423. // read bits per sample
  424. soundCheck(OSBasics::read(data16,2,1,f) == 1, "LoadWav: Cannot read wav file "+ fileName );
  425. unsigned short bps = readByte16(data16);
  426. // check 'data' sub chunk (2)
  427. soundCheck(OSBasics::read(magic,4,1,f) == 1, "LoadWav: Cannot read wav file "+ fileName );
  428. soundCheck(String(magic) == "data", "LoadWav: Wrong wav file format. This file is not a .wav file (no data subchunk): "+ fileName );
  429. soundCheck(OSBasics::read(data32,4,1,f) == 1, "LoadWav: Cannot read wav file "+ fileName );
  430. unsigned long subChunk2Size = readByte32(data32);
  431. // The frequency of the sampling rate
  432. freq = frequency;
  433. soundCheck(sizeof(freq) == sizeof(frequency), "LoadWav: freq and frequency different sizes");
  434. array = new char[BUFFER_SIZE];
  435. while (data.size() != subChunk2Size) {
  436. // Read up to a buffer's worth of decoded sound data
  437. bytes = OSBasics::read(array, 1, BUFFER_SIZE, f);
  438. if (bytes <= 0)
  439. break;
  440. if (data.size() + bytes > subChunk2Size)
  441. bytes = subChunk2Size - data.size();
  442. // Append to end of buffer
  443. data.insert(data.end(), array, array + bytes);
  444. };
  445. delete []array;
  446. array = NULL;
  447. OSBasics::close(f);
  448. f = NULL;
  449. return loadBytes(&data[0], data.size(), freq, channels, bps, generateFloatBuffer);
  450. // if (buffer)
  451. // if (alIsBuffer(buffer) == AL_TRUE)
  452. // alDeleteBuffers(1, &buffer);
  453. //
  454. // if (array)
  455. // delete []array;
  456. //
  457. // if (f)
  458. // OSBasics::close(f);
  459. //
  460. // throw (e);
  461. }