PolySound.cpp 10 KB

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