PolySound.cpp 11 KB

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