PolySound.cpp 15 KB

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