PolySound.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535
  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. alDeleteSources(1,&soundSource);
  102. checkALError("destroying sound");
  103. alDeleteBuffers(1, &buffer);
  104. checkALError("deleting buffer");
  105. }
  106. void Sound::soundCheck(bool result, const String& err) {
  107. if(!result)
  108. soundError(err);
  109. }
  110. void Sound::soundError(const String& err) {
  111. Logger::log("SOUND ERROR: %s\n", err.c_str());
  112. }
  113. unsigned long Sound::readByte32(const unsigned char data[4]) {
  114. #if TAU_BIG_ENDIAN
  115. return (data[0] << 24) + (data[1] << 16) + (data[2] << 8) + data[3];
  116. #else
  117. return (data[3] << 24) + (data[2] << 16) + (data[1] << 8) + data[0];
  118. #endif
  119. }
  120. unsigned short Sound::readByte16(const unsigned char data[2]) {
  121. #if TAU_BIG_ENDIAN
  122. return (data[0] << 8) + data[1];
  123. #else
  124. return (data[1] << 8) + data[0];
  125. #endif
  126. }
  127. void Sound::Play(bool loop) {
  128. if(!loop) {
  129. alSourcei(soundSource, AL_LOOPING, AL_FALSE);
  130. } else {
  131. alSourcei(soundSource, AL_LOOPING, AL_TRUE);
  132. }
  133. checkALError("Play: loop");
  134. alSourcePlay(soundSource);
  135. checkALError("Play: play");
  136. }
  137. bool Sound::isPlaying() {
  138. ALenum state;
  139. alGetSourcei(soundSource, AL_SOURCE_STATE, &state);
  140. return (state == AL_PLAYING);
  141. }
  142. void Sound::setVolume(Number newVolume) {
  143. this->volume = newVolume;
  144. alSourcef(soundSource, AL_GAIN, newVolume);
  145. }
  146. void Sound::setPitch(Number newPitch) {
  147. this->pitch = newPitch;
  148. alSourcef(soundSource, AL_PITCH, newPitch);
  149. }
  150. void Sound::setSoundPosition(Vector3 position) {
  151. if(isPositional)
  152. alSource3f(soundSource,AL_POSITION, position.x, position.y, position.z);
  153. }
  154. void Sound::setSoundVelocity(Vector3 velocity) {
  155. if(isPositional)
  156. alSource3f(soundSource,AL_VELOCITY, velocity.x, velocity.y, velocity.z);
  157. }
  158. void Sound::setSoundDirection(Vector3 direction) {
  159. if(isPositional)
  160. alSource3f(soundSource,AL_DIRECTION, direction.x, direction.y, direction.z);
  161. }
  162. void Sound::setOffset(int off) {
  163. alSourcei(soundSource, AL_SAMPLE_OFFSET, off);
  164. }
  165. Number Sound::getPlaybackTime() {
  166. float result = 0.0;
  167. alGetSourcef(soundSource, AL_SEC_OFFSET, &result);
  168. return result;
  169. }
  170. Number Sound::getPlaybackDuration() {
  171. ALint sizeInBytes;
  172. ALint channels;
  173. ALint bits;
  174. ALint bufferID;
  175. alGetSourcei(soundSource, AL_BUFFER, &bufferID);
  176. alGetBufferi(bufferID, AL_SIZE, &sizeInBytes);
  177. alGetBufferi(bufferID, AL_CHANNELS, &channels);
  178. alGetBufferi(bufferID, AL_BITS, &bits);
  179. int lengthInSamples = sizeInBytes * 8 / (channels * bits);
  180. ALint frequency;
  181. alGetBufferi(bufferID, AL_FREQUENCY, &frequency);
  182. Number durationInSeconds = (float)lengthInSamples / (float)frequency;
  183. return durationInSeconds;
  184. }
  185. int Sound::getOffset() {
  186. ALint off = -1;
  187. alGetSourcei(soundSource, AL_SAMPLE_OFFSET, &off);
  188. return off;
  189. }
  190. void Sound::seekTo(Number time) {
  191. if(time > getPlaybackDuration())
  192. return;
  193. alSourcef(soundSource, AL_SEC_OFFSET, time);
  194. }
  195. int Sound::getSampleLength() {
  196. return sampleLength;
  197. }
  198. void Sound::setPositionalProperties(Number referenceDistance, Number maxDistance) {
  199. setReferenceDistance(referenceDistance);
  200. setMaxDistance(maxDistance);
  201. }
  202. void Sound::setReferenceDistance(Number referenceDistance) {
  203. this->referenceDistance = referenceDistance;
  204. alSourcef(soundSource,AL_REFERENCE_DISTANCE, referenceDistance);
  205. }
  206. void Sound::setMaxDistance(Number maxDistance) {
  207. this->maxDistance = maxDistance;
  208. alSourcef(soundSource,AL_MAX_DISTANCE, maxDistance);
  209. }
  210. Number Sound::getReferenceDistance() {
  211. return referenceDistance;
  212. }
  213. Number Sound::getMaxDistance() {
  214. return maxDistance;
  215. }
  216. void Sound::setIsPositional(bool isPositional) {
  217. this->isPositional = isPositional;
  218. if(isPositional) {
  219. alSourcei(soundSource, AL_SOURCE_RELATIVE, AL_FALSE);
  220. } else {
  221. alSourcei(soundSource, AL_SOURCE_RELATIVE, AL_TRUE);
  222. alSource3f(soundSource,AL_POSITION, 0,0,0);
  223. alSource3f(soundSource,AL_VELOCITY, 0,0,0);
  224. alSource3f(soundSource,AL_DIRECTION, 0,0,0);
  225. }
  226. }
  227. ALenum Sound::checkALError(const String& operation) {
  228. ALenum error = alGetError();
  229. if(error != AL_NO_ERROR) {
  230. switch(error) {
  231. case AL_INVALID_NAME:
  232. soundError(operation +": " + ALInvalidNameStr);
  233. break;
  234. case AL_INVALID_ENUM:
  235. soundError(operation + ": " +ALInvalidEnumStr);
  236. break;
  237. case AL_INVALID_VALUE:
  238. soundError(operation + ": " +ALInvalidValueStr);
  239. break;
  240. case AL_INVALID_OPERATION:
  241. soundError(operation + ": " +ALInvalidOpStr);
  242. break;
  243. case AL_OUT_OF_MEMORY:
  244. soundError(operation + ": " +ALOutOfMemoryStr);
  245. break;
  246. default:
  247. soundError(operation + ": " +ALOtherErrorStr);
  248. break;
  249. }
  250. }
  251. return error;
  252. }
  253. void Sound::Stop() {
  254. alSourceStop(soundSource);
  255. checkALError("Stop");
  256. }
  257. ALuint Sound::GenSource() {
  258. ALuint source;
  259. bool looping = false;
  260. ALfloat sourcePos[] = {0.0, 0.0, 0.0};
  261. ALfloat sourceVel[] = {0.0, 0.0, 0.0};
  262. alGetError();
  263. alGenSources(1, &source);
  264. checkALError("Generating sources");
  265. alSourcef(source, AL_PITCH, 1.0);
  266. alSourcef(source, AL_GAIN, 1.0);
  267. alSourcefv(source, AL_POSITION, sourcePos);
  268. alSourcefv(source, AL_VELOCITY, sourceVel);
  269. alSourcei(source, AL_LOOPING, looping);
  270. checkALError("Setting source properties");
  271. return source;
  272. }
  273. ALuint Sound::GenSource(ALuint buffer) {
  274. alGetError();
  275. ALuint source = GenSource();
  276. alSourcei(source, AL_BUFFER, buffer);
  277. checkALError("Setting source buffer");
  278. return source;
  279. }
  280. ALuint Sound::loadBytes(const char *data, int size, int freq, int channels, int bps) {
  281. ALenum format;
  282. if (channels == 1)
  283. format = (bps == 8) ? AL_FORMAT_MONO8 : AL_FORMAT_MONO16;
  284. else
  285. format = (bps == 8) ? AL_FORMAT_STEREO8 : AL_FORMAT_STEREO16;
  286. sampleLength = bps > 8 ? size / (bps/8) : -1;
  287. checkALError("LoadBytes: pre-generate buffer");
  288. alGenBuffers(1, &buffer);
  289. checkALError("LoadBytes: generate buffer");
  290. soundCheck(AL_NONE != buffer, "LoadBytes: Did not generate buffer");
  291. alBufferData(buffer, format, data, size, freq);
  292. checkALError("LoadBytes: load buffer data");
  293. return buffer;
  294. }
  295. ALuint Sound::loadOGG(const String& fileName) {
  296. vector<char> data;
  297. alGenBuffers(1, &buffer);
  298. int endian = 0; // 0 for Little-Endian, 1 for Big-Endian
  299. int bitStream;
  300. long bytes;
  301. char array[BUFFER_SIZE]; // Local fixed size array
  302. OSFILE *f;
  303. ALenum format;
  304. ALsizei freq;
  305. // Open for binary reading
  306. f = OSBasics::open(fileName.c_str(), "rb");
  307. if(!f) {
  308. soundError("Error loading OGG file!\n");
  309. return buffer;
  310. }
  311. vorbis_info *pInfo;
  312. OggVorbis_File oggFile;
  313. ov_callbacks callbacks;
  314. callbacks.read_func = custom_readfunc;
  315. callbacks.seek_func = custom_seekfunc;
  316. callbacks.close_func = custom_closefunc;
  317. callbacks.tell_func = custom_tellfunc;
  318. ov_open_callbacks( (void*)f, &oggFile, NULL, 0, callbacks);
  319. // ov_open(f, &oggFile, NULL, 0);
  320. // Get some information about the OGG file
  321. pInfo = ov_info(&oggFile, -1);
  322. // Check the number of channels... always use 16-bit samples
  323. if (pInfo->channels == 1)
  324. format = AL_FORMAT_MONO16;
  325. else
  326. format = AL_FORMAT_STEREO16;
  327. // end if
  328. // The frequency of the sampling rate
  329. freq = pInfo->rate;
  330. do {
  331. // Read up to a buffer's worth of decoded sound data
  332. bytes = ov_read(&oggFile, array, BUFFER_SIZE, endian, 2, 1, &bitStream);
  333. // Append to end of buffer
  334. data.insert(data.end(), array, array + bytes);
  335. } while (bytes > 0);
  336. ov_clear(&oggFile);
  337. sampleLength = data.size() / sizeof(unsigned short);
  338. alBufferData(buffer, format, &data[0], static_cast<ALsizei>(data.size()), freq);
  339. return buffer;
  340. }
  341. ALuint Sound::loadWAV(const String& fileName) {
  342. long bytes;
  343. vector <char> data;
  344. ALsizei freq;
  345. // Local resources
  346. OSFILE *f = NULL;
  347. char *array = NULL;
  348. checkALError("loadWAV: pre-generate buffer");
  349. // Open for binary reading
  350. f = OSBasics::open(fileName.c_str(), "rb");
  351. if (!f) {
  352. soundError("LoadWav: Could not load wav from " + fileName);
  353. return buffer;
  354. }
  355. // buffers
  356. char magic[5];
  357. magic[4] = '\0';
  358. unsigned char data32[4];
  359. unsigned char data16[2];
  360. // check magic
  361. soundCheck(OSBasics::read(magic,4,1,f) == 1, "LoadWav: Cannot read wav file "+ fileName );
  362. soundCheck(String(magic) == "RIFF", "LoadWav: Wrong wav file format. This file is not a .wav file (no RIFF magic): "+ fileName );
  363. // skip 4 bytes (file size)
  364. OSBasics::seek(f,4,SEEK_CUR);
  365. // check file format
  366. soundCheck(OSBasics::read(magic,4,1,f) == 1, "LoadWav: Cannot read wav file "+ fileName );
  367. soundCheck(String(magic) == "WAVE", "LoadWav: Wrong wav file format. This file is not a .wav file (no WAVE format): "+ fileName );
  368. // check 'fmt ' sub chunk (1)
  369. soundCheck(OSBasics::read(magic,4,1,f) == 1, "LoadWav: Cannot read wav file "+ fileName );
  370. soundCheck(String(magic) == "fmt ", "LoadWav: Wrong wav file format. This file is not a .wav file (no 'fmt ' subchunk): "+ fileName );
  371. // read (1)'s size
  372. soundCheck(OSBasics::read(data32,4,1,f) == 1, "LoadWav: Cannot read wav file "+ fileName );
  373. unsigned long subChunk1Size = readByte32(data32);
  374. soundCheck(subChunk1Size >= 16, "Wrong wav file format. This file is not a .wav file ('fmt ' chunk too small, truncated file?): "+ fileName );
  375. // check PCM audio format
  376. soundCheck(OSBasics::read(data16,2,1,f) == 1, "LoadWav: Cannot read wav file "+ fileName );
  377. unsigned short audioFormat = readByte16(data16);
  378. soundCheck(audioFormat == 1, "LoadWav: Wrong wav file format. This file is not a .wav file (audio format is not PCM): "+ fileName );
  379. // read number of channels
  380. soundCheck(OSBasics::read(data16,2,1,f) == 1, "LoadWav: Cannot read wav file "+ fileName );
  381. unsigned short channels = readByte16(data16);
  382. // read frequency (sample rate)
  383. soundCheck(OSBasics::read(data32,4,1,f) == 1, "LoadWav: Cannot read wav file "+ fileName );
  384. unsigned long frequency = readByte32(data32);
  385. // skip 6 bytes (Byte rate (4), Block align (2))
  386. OSBasics::seek(f,6,SEEK_CUR);
  387. // read bits per sample
  388. soundCheck(OSBasics::read(data16,2,1,f) == 1, "LoadWav: Cannot read wav file "+ fileName );
  389. unsigned short bps = readByte16(data16);
  390. // check 'data' sub chunk (2)
  391. soundCheck(OSBasics::read(magic,4,1,f) == 1, "LoadWav: Cannot read wav file "+ fileName );
  392. soundCheck(String(magic) == "data", "LoadWav: Wrong wav file format. This file is not a .wav file (no data subchunk): "+ fileName );
  393. soundCheck(OSBasics::read(data32,4,1,f) == 1, "LoadWav: Cannot read wav file "+ fileName );
  394. unsigned long subChunk2Size = readByte32(data32);
  395. // The frequency of the sampling rate
  396. freq = frequency;
  397. soundCheck(sizeof(freq) == sizeof(frequency), "LoadWav: freq and frequency different sizes");
  398. array = new char[BUFFER_SIZE];
  399. while (data.size() != subChunk2Size) {
  400. // Read up to a buffer's worth of decoded sound data
  401. bytes = OSBasics::read(array, 1, BUFFER_SIZE, f);
  402. if (bytes <= 0)
  403. break;
  404. if (data.size() + bytes > subChunk2Size)
  405. bytes = subChunk2Size - data.size();
  406. // Append to end of buffer
  407. data.insert(data.end(), array, array + bytes);
  408. };
  409. delete []array;
  410. array = NULL;
  411. OSBasics::close(f);
  412. f = NULL;
  413. return loadBytes(&data[0], data.size(), freq, channels, bps);
  414. // if (buffer)
  415. // if (alIsBuffer(buffer) == AL_TRUE)
  416. // alDeleteBuffers(1, &buffer);
  417. //
  418. // if (array)
  419. // delete []array;
  420. //
  421. // if (f)
  422. // OSBasics::close(f);
  423. //
  424. // throw (e);
  425. }