PolySound.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  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. using namespace Polycode;
  21. size_t custom_readfunc(void *ptr, size_t size, size_t nmemb, void *datasource) {
  22. OSFILE *file = (OSFILE*) datasource;
  23. return OSBasics::read(ptr, size, nmemb, file);
  24. }
  25. int custom_seekfunc(void *datasource, ogg_int64_t offset, int whence){
  26. OSFILE *file = (OSFILE*) datasource;
  27. return OSBasics::seek(file, offset, whence);
  28. }
  29. int custom_closefunc(void *datasource) {
  30. OSFILE *file = (OSFILE*) datasource;
  31. return OSBasics::close(file);
  32. }
  33. long custom_tellfunc(void *datasource) {
  34. OSFILE *file = (OSFILE*) datasource;
  35. return OSBasics::tell(file);
  36. }
  37. Sound::Sound(String fileName) {
  38. String extension;
  39. size_t found;
  40. found=fileName.rfind(".");
  41. if (found!=string::npos) {
  42. extension = fileName.substr(found+1);
  43. } else {
  44. extension = "";
  45. }
  46. ALuint buffer;
  47. if(extension == "wav" || extension == "WAV") {
  48. buffer = loadWAV(fileName);
  49. } else if(extension == "ogg" || extension == "OGG") {
  50. buffer = loadOGG(fileName);
  51. }
  52. soundSource = GenSource(buffer);
  53. setIsPositional(false);
  54. }
  55. Sound::~Sound() {
  56. Logger::log("destroying sound...\n");
  57. alDeleteSources(1,&soundSource);
  58. }
  59. void Sound::soundCheck(bool result, String err) {
  60. if(!result)
  61. soundError(err);
  62. }
  63. void Sound::soundError(String err) {
  64. Logger::log("SOUND ERROR: %s\n", err.c_str());
  65. }
  66. unsigned long Sound::readByte32(const unsigned char buffer[4]) {
  67. #if TAU_BIG_ENDIAN
  68. return (buffer[0] << 24) + (buffer[1] << 16) + (buffer[2] << 8) + buffer[3];
  69. #else
  70. return (buffer[3] << 24) + (buffer[2] << 16) + (buffer[1] << 8) + buffer[0];
  71. #endif
  72. }
  73. unsigned short Sound::readByte16(const unsigned char buffer[2]) {
  74. #if TAU_BIG_ENDIAN
  75. return (buffer[0] << 8) + buffer[1];
  76. #else
  77. return (buffer[1] << 8) + buffer[0];
  78. #endif
  79. }
  80. void Sound::Play(bool loop) {
  81. if(!loop) {
  82. alSourcei(soundSource, AL_LOOPING, AL_FALSE);
  83. } else {
  84. alSourcei(soundSource, AL_LOOPING, AL_TRUE);
  85. }
  86. alSourcePlay(soundSource);
  87. }
  88. void Sound::setVolume(Number newVolume) {
  89. alSourcef(soundSource, AL_GAIN, newVolume);
  90. }
  91. void Sound::setPitch(Number newPitch) {
  92. alSourcef(soundSource, AL_PITCH, newPitch);
  93. }
  94. void Sound::setSoundPosition(Vector3 position) {
  95. if(isPositional)
  96. alSource3f(soundSource,AL_POSITION, position.x, position.y, position.z);
  97. }
  98. void Sound::setSoundVelocity(Vector3 velocity) {
  99. if(isPositional)
  100. alSource3f(soundSource,AL_VELOCITY, velocity.x, velocity.y, velocity.z);
  101. }
  102. void Sound::setSoundDirection(Vector3 direction) {
  103. if(isPositional)
  104. alSource3f(soundSource,AL_DIRECTION, direction.x, direction.y, direction.z);
  105. }
  106. void Sound::setPositionalProperties(Number referenceDistance, Number maxDistance) {
  107. alSourcef(soundSource,AL_REFERENCE_DISTANCE, referenceDistance);
  108. alSourcef(soundSource,AL_MAX_DISTANCE, maxDistance);
  109. }
  110. void Sound::setIsPositional(bool isPositional) {
  111. this->isPositional = isPositional;
  112. if(isPositional) {
  113. alSourcei(soundSource, AL_SOURCE_RELATIVE, AL_FALSE);
  114. } else {
  115. alSourcei(soundSource, AL_SOURCE_RELATIVE, AL_TRUE);
  116. alSource3f(soundSource,AL_POSITION, 0,0,0);
  117. alSource3f(soundSource,AL_VELOCITY, 0,0,0);
  118. alSource3f(soundSource,AL_DIRECTION, 0,0,0);
  119. }
  120. }
  121. void Sound::checkALError(String operation) {
  122. ALenum error = alGetError();
  123. if(error != AL_NO_ERROR) {
  124. switch(error) {
  125. case AL_NO_ERROR:
  126. soundError(operation + ": " +ALNoErrorStr);
  127. break;
  128. case AL_INVALID_NAME:
  129. soundError(operation +": " + ALInvalidNameStr);
  130. break;
  131. case AL_INVALID_ENUM:
  132. soundError(operation + ": " +ALInvalidEnumStr);
  133. break;
  134. case AL_INVALID_VALUE:
  135. soundError(operation + ": " +ALInvalidValueStr);
  136. break;
  137. case AL_INVALID_OPERATION:
  138. soundError(operation + ": " +ALInvalidOpStr);
  139. break;
  140. case AL_OUT_OF_MEMORY:
  141. soundError(operation + ": " +ALOutOfMemoryStr);
  142. break;
  143. default:
  144. soundError(operation + ": " +ALOtherErrorStr);
  145. break;
  146. }
  147. }
  148. }
  149. void Sound::Stop() {
  150. alSourceStop(soundSource);
  151. }
  152. ALuint Sound::GenSource() {
  153. ALuint source;
  154. bool looping = false;
  155. ALfloat sourcePos[] = {0.0, 0.0, 0.0};
  156. ALfloat sourceVel[] = {0.0, 0.0, 0.0};
  157. alGetError();
  158. alGenSources(1, &source);
  159. checkALError("Generating sources");
  160. alSourcef(source, AL_PITCH, 1.0);
  161. alSourcef(source, AL_GAIN, 1.0);
  162. alSourcefv(source, AL_POSITION, sourcePos);
  163. alSourcefv(source, AL_VELOCITY, sourceVel);
  164. alSourcei(source, AL_LOOPING, looping);
  165. checkALError("Setting source properties");
  166. return source;
  167. }
  168. ALuint Sound::GenSource(ALuint buffer) {
  169. alGetError();
  170. ALuint source = GenSource();
  171. alSourcei(source, AL_BUFFER, buffer);
  172. checkALError("Setting source buffer");
  173. return source;
  174. }
  175. ALuint Sound::loadOGG(String fileName) {
  176. vector<char> buffer;
  177. ALuint bufferID = AL_NONE;
  178. alGenBuffers(1, &bufferID);
  179. int endian = 0; // 0 for Little-Endian, 1 for Big-Endian
  180. int bitStream;
  181. long bytes;
  182. char array[BUFFER_SIZE]; // Local fixed size array
  183. OSFILE *f;
  184. ALenum format;
  185. ALsizei freq;
  186. // Open for binary reading
  187. f = OSBasics::open(fileName.c_str(), "rb");
  188. if(!f) {
  189. soundError("Error loading OGG file!\n");
  190. return bufferID;
  191. }
  192. vorbis_info *pInfo;
  193. OggVorbis_File oggFile;
  194. ov_callbacks callbacks;
  195. callbacks.read_func = custom_readfunc;
  196. callbacks.seek_func = custom_seekfunc;
  197. callbacks.close_func = custom_closefunc;
  198. callbacks.tell_func = custom_tellfunc;
  199. ov_open_callbacks( (void*)f, &oggFile, NULL, 0, callbacks);
  200. // ov_open(f, &oggFile, NULL, 0);
  201. // Get some information about the OGG file
  202. pInfo = ov_info(&oggFile, -1);
  203. // Check the number of channels... always use 16-bit samples
  204. if (pInfo->channels == 1)
  205. format = AL_FORMAT_MONO16;
  206. else
  207. format = AL_FORMAT_STEREO16;
  208. // end if
  209. // The frequency of the sampling rate
  210. freq = pInfo->rate;
  211. do {
  212. // Read up to a buffer's worth of decoded sound data
  213. bytes = ov_read(&oggFile, array, BUFFER_SIZE, endian, 2, 1, &bitStream);
  214. // Append to end of buffer
  215. buffer.insert(buffer.end(), array, array + bytes);
  216. } while (bytes > 0);
  217. ov_clear(&oggFile);
  218. alBufferData(bufferID, format, &buffer[0], static_cast<ALsizei>(buffer.size()), freq);
  219. return bufferID;
  220. }
  221. ALuint Sound::loadWAV(String fileName) {
  222. long bytes;
  223. vector <char> data;
  224. ALenum format;
  225. ALsizei freq;
  226. // Local resources
  227. OSFILE *f = NULL;
  228. char *array = NULL;
  229. ALuint buffer = AL_NONE;
  230. alGetError();
  231. // Open for binary reading
  232. f = OSBasics::open(fileName.c_str(), "rb");
  233. if (!f)
  234. soundError("LoadWav: Could not load wav from " + fileName);
  235. // buffers
  236. char magic[5];
  237. magic[4] = '\0';
  238. unsigned char buffer32[4];
  239. unsigned char buffer16[2];
  240. // check magic
  241. soundCheck(OSBasics::read(magic,4,1,f) == 1, "LoadWav: Cannot read wav file "+ fileName );
  242. soundCheck(String(magic) == "RIFF", "LoadWav: Wrong wav file format. This file is not a .wav file (no RIFF magic): "+ fileName );
  243. // skip 4 bytes (file size)
  244. OSBasics::seek(f,4,SEEK_CUR);
  245. // check file format
  246. soundCheck(OSBasics::read(magic,4,1,f) == 1, "LoadWav: Cannot read wav file "+ fileName );
  247. soundCheck(String(magic) == "WAVE", "LoadWav: Wrong wav file format. This file is not a .wav file (no WAVE format): "+ fileName );
  248. // check 'fmt ' sub chunk (1)
  249. soundCheck(OSBasics::read(magic,4,1,f) == 1, "LoadWav: Cannot read wav file "+ fileName );
  250. soundCheck(String(magic) == "fmt ", "LoadWav: Wrong wav file format. This file is not a .wav file (no 'fmt ' subchunk): "+ fileName );
  251. // read (1)'s size
  252. soundCheck(OSBasics::read(buffer32,4,1,f) == 1, "LoadWav: Cannot read wav file "+ fileName );
  253. unsigned long subChunk1Size = readByte32(buffer32);
  254. soundCheck(subChunk1Size >= 16, "Wrong wav file format. This file is not a .wav file ('fmt ' chunk too small, truncated file?): "+ fileName );
  255. // check PCM audio format
  256. soundCheck(OSBasics::read(buffer16,2,1,f) == 1, "LoadWav: Cannot read wav file "+ fileName );
  257. unsigned short audioFormat = readByte16(buffer16);
  258. soundCheck(audioFormat == 1, "LoadWav: Wrong wav file format. This file is not a .wav file (audio format is not PCM): "+ fileName );
  259. // read number of channels
  260. soundCheck(OSBasics::read(buffer16,2,1,f) == 1, "LoadWav: Cannot read wav file "+ fileName );
  261. unsigned short channels = readByte16(buffer16);
  262. // read frequency (sample rate)
  263. soundCheck(OSBasics::read(buffer32,4,1,f) == 1, "LoadWav: Cannot read wav file "+ fileName );
  264. unsigned long frequency = readByte32(buffer32);
  265. // skip 6 bytes (Byte rate (4), Block align (2))
  266. OSBasics::seek(f,6,SEEK_CUR);
  267. // read bits per sample
  268. soundCheck(OSBasics::read(buffer16,2,1,f) == 1, "LoadWav: Cannot read wav file "+ fileName );
  269. unsigned short bps = readByte16(buffer16);
  270. if (channels == 1)
  271. format = (bps == 8) ? AL_FORMAT_MONO8 : AL_FORMAT_MONO16;
  272. else
  273. format = (bps == 8) ? AL_FORMAT_STEREO8 : AL_FORMAT_STEREO16;
  274. // check 'data' sub chunk (2)
  275. soundCheck(OSBasics::read(magic,4,1,f) == 1, "LoadWav: Cannot read wav file "+ fileName );
  276. soundCheck(String(magic) == "data", "LoadWav: Wrong wav file format. This file is not a .wav file (no data subchunk): "+ fileName );
  277. soundCheck(OSBasics::read(buffer32,4,1,f) == 1, "LoadWav: Cannot read wav file "+ fileName );
  278. unsigned long subChunk2Size = readByte32(buffer32);
  279. // The frequency of the sampling rate
  280. freq = frequency;
  281. soundCheck(sizeof(freq) == sizeof(frequency), "LoadWav: freq and frequency different sizes");
  282. array = new char[BUFFER_SIZE];
  283. while (data.size() != subChunk2Size) {
  284. // Read up to a buffer's worth of decoded sound data
  285. bytes = OSBasics::read(array, 1, BUFFER_SIZE, f);
  286. if (bytes <= 0)
  287. break;
  288. if (data.size() + bytes > subChunk2Size)
  289. bytes = subChunk2Size - data.size();
  290. // Append to end of buffer
  291. data.insert(data.end(), array, array + bytes);
  292. };
  293. delete []array;
  294. array = NULL;
  295. OSBasics::close(f);
  296. f = NULL;
  297. alGenBuffers(1, &buffer);
  298. soundCheck(alGetError() == AL_NO_ERROR, "LoadWav: Could not generate buffer");
  299. soundCheck(AL_NONE != buffer, "LoadWav: Could not generate buffer");
  300. alBufferData(buffer, format, &data[0], data.size(), freq);
  301. soundCheck(alGetError() == AL_NO_ERROR, "LoadWav: Could not load buffer data");
  302. return buffer;
  303. // if (buffer)
  304. // if (alIsBuffer(buffer) == AL_TRUE)
  305. // alDeleteBuffers(1, &buffer);
  306. //
  307. // if (array)
  308. // delete []array;
  309. //
  310. // if (f)
  311. // OSBasics::close(f);
  312. //
  313. // throw (e);
  314. }