PolySound.cpp 12 KB

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