PolySound.cpp 14 KB

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