sound_openal.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550
  1. /*
  2. Minetest
  3. Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
  4. OpenAL support based on work by:
  5. Copyright (C) 2011 Sebastian 'Bahamada' Rühl
  6. Copyright (C) 2011 Cyriaque 'Cisoun' Skrapits <cysoun@gmail.com>
  7. Copyright (C) 2011 Giuseppe Bilotta <giuseppe.bilotta@gmail.com>
  8. This program is free software; you can redistribute it and/or modify
  9. it under the terms of the GNU Lesser General Public License as published by
  10. the Free Software Foundation; either version 2.1 of the License, or
  11. (at your option) any later version.
  12. This program is distributed in the hope that it will be useful,
  13. but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. GNU Lesser General Public License for more details.
  16. You should have received a copy of the GNU Lesser General Public License along
  17. with this program; ifnot, write to the Free Software Foundation, Inc.,
  18. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  19. */
  20. #include "sound_openal.h"
  21. #if defined(_WIN32)
  22. #include <al.h>
  23. #include <alc.h>
  24. //#include <alext.h>
  25. #elif defined(__APPLE__)
  26. #include <OpenAL/al.h>
  27. #include <OpenAL/alc.h>
  28. //#include <OpenAL/alext.h>
  29. #else
  30. #include <AL/al.h>
  31. #include <AL/alc.h>
  32. #include <AL/alext.h>
  33. #endif
  34. #include <vorbis/vorbisfile.h>
  35. #include "log.h"
  36. #include "filesys.h"
  37. #include "util/numeric.h" // myrand()
  38. #include "debug.h" // assert()
  39. #include "porting.h"
  40. #include <map>
  41. #include <vector>
  42. #include <fstream>
  43. #define BUFFER_SIZE 30000
  44. static const char *alcErrorString(ALCenum err)
  45. {
  46. switch (err) {
  47. case ALC_NO_ERROR:
  48. return "no error";
  49. case ALC_INVALID_DEVICE:
  50. return "invalid device";
  51. case ALC_INVALID_CONTEXT:
  52. return "invalid context";
  53. case ALC_INVALID_ENUM:
  54. return "invalid enum";
  55. case ALC_INVALID_VALUE:
  56. return "invalid value";
  57. case ALC_OUT_OF_MEMORY:
  58. return "out of memory";
  59. default:
  60. return "<unknown OpenAL error>";
  61. }
  62. }
  63. static const char *alErrorString(ALenum err)
  64. {
  65. switch (err) {
  66. case AL_NO_ERROR:
  67. return "no error";
  68. case AL_INVALID_NAME:
  69. return "invalid name";
  70. case AL_INVALID_ENUM:
  71. return "invalid enum";
  72. case AL_INVALID_VALUE:
  73. return "invalid value";
  74. case AL_INVALID_OPERATION:
  75. return "invalid operation";
  76. case AL_OUT_OF_MEMORY:
  77. return "out of memory";
  78. default:
  79. return "<unknown OpenAL error>";
  80. }
  81. }
  82. static ALenum warn_if_error(ALenum err, const char *desc)
  83. {
  84. if(err == AL_NO_ERROR)
  85. return err;
  86. errorstream<<"WARNING: "<<desc<<": "<<alErrorString(err)<<std::endl;
  87. return err;
  88. }
  89. void f3_set(ALfloat *f3, v3f v)
  90. {
  91. f3[0] = v.X;
  92. f3[1] = v.Y;
  93. f3[2] = v.Z;
  94. }
  95. struct SoundBuffer
  96. {
  97. ALenum format;
  98. ALsizei freq;
  99. ALuint buffer_id;
  100. std::vector<char> buffer;
  101. };
  102. SoundBuffer* loadOggFile(const std::string &filepath)
  103. {
  104. int endian = 0; // 0 for Little-Endian, 1 for Big-Endian
  105. int bitStream;
  106. long bytes;
  107. char array[BUFFER_SIZE]; // Local fixed size array
  108. vorbis_info *pInfo;
  109. OggVorbis_File oggFile;
  110. // Do a dumb-ass static string copy for old versions of ov_fopen
  111. // because they expect a non-const char*
  112. char nonconst[10000];
  113. snprintf(nonconst, 10000, "%s", filepath.c_str());
  114. // Try opening the given file
  115. //if(ov_fopen(filepath.c_str(), &oggFile) != 0)
  116. if(ov_fopen(nonconst, &oggFile) != 0)
  117. {
  118. infostream<<"Audio: Error opening "<<filepath<<" for decoding"<<std::endl;
  119. return NULL;
  120. }
  121. SoundBuffer *snd = new SoundBuffer;
  122. // Get some information about the OGG file
  123. pInfo = ov_info(&oggFile, -1);
  124. // Check the number of channels... always use 16-bit samples
  125. if(pInfo->channels == 1)
  126. snd->format = AL_FORMAT_MONO16;
  127. else
  128. snd->format = AL_FORMAT_STEREO16;
  129. // The frequency of the sampling rate
  130. snd->freq = pInfo->rate;
  131. // Keep reading until all is read
  132. do
  133. {
  134. // Read up to a buffer's worth of decoded sound data
  135. bytes = ov_read(&oggFile, array, BUFFER_SIZE, endian, 2, 1, &bitStream);
  136. if(bytes < 0)
  137. {
  138. ov_clear(&oggFile);
  139. infostream<<"Audio: Error decoding "<<filepath<<std::endl;
  140. return NULL;
  141. }
  142. // Append to end of buffer
  143. snd->buffer.insert(snd->buffer.end(), array, array + bytes);
  144. } while (bytes > 0);
  145. alGenBuffers(1, &snd->buffer_id);
  146. alBufferData(snd->buffer_id, snd->format,
  147. &(snd->buffer[0]), snd->buffer.size(),
  148. snd->freq);
  149. ALenum error = alGetError();
  150. if(error != AL_NO_ERROR){
  151. infostream<<"Audio: OpenAL error: "<<alErrorString(error)
  152. <<"preparing sound buffer"<<std::endl;
  153. }
  154. infostream<<"Audio file "<<filepath<<" loaded"<<std::endl;
  155. // Clean up!
  156. ov_clear(&oggFile);
  157. return snd;
  158. }
  159. struct PlayingSound
  160. {
  161. ALuint source_id;
  162. bool loop;
  163. };
  164. class OpenALSoundManager: public ISoundManager
  165. {
  166. private:
  167. OnDemandSoundFetcher *m_fetcher;
  168. ALCdevice *m_device;
  169. ALCcontext *m_context;
  170. bool m_can_vorbis;
  171. int m_next_id;
  172. std::map<std::string, std::vector<SoundBuffer*> > m_buffers;
  173. std::map<int, PlayingSound*> m_sounds_playing;
  174. v3f m_listener_pos;
  175. public:
  176. bool m_is_initialized;
  177. OpenALSoundManager(OnDemandSoundFetcher *fetcher):
  178. m_fetcher(fetcher),
  179. m_device(NULL),
  180. m_context(NULL),
  181. m_can_vorbis(false),
  182. m_next_id(1),
  183. m_is_initialized(false)
  184. {
  185. ALCenum error = ALC_NO_ERROR;
  186. infostream<<"Audio: Initializing..."<<std::endl;
  187. m_device = alcOpenDevice(NULL);
  188. if(!m_device){
  189. infostream<<"Audio: No audio device available, audio system "
  190. <<"not initialized"<<std::endl;
  191. return;
  192. }
  193. if(alcIsExtensionPresent(m_device, "EXT_vorbis")){
  194. infostream<<"Audio: Vorbis extension present"<<std::endl;
  195. m_can_vorbis = true;
  196. } else{
  197. infostream<<"Audio: Vorbis extension NOT present"<<std::endl;
  198. m_can_vorbis = false;
  199. }
  200. m_context = alcCreateContext(m_device, NULL);
  201. if(!m_context){
  202. error = alcGetError(m_device);
  203. infostream<<"Audio: Unable to initialize audio context, "
  204. <<"aborting audio initialization ("<<alcErrorString(error)
  205. <<")"<<std::endl;
  206. alcCloseDevice(m_device);
  207. m_device = NULL;
  208. return;
  209. }
  210. if(!alcMakeContextCurrent(m_context) ||
  211. (error = alcGetError(m_device) != ALC_NO_ERROR))
  212. {
  213. infostream<<"Audio: Error setting audio context, aborting audio "
  214. <<"initialization ("<<alcErrorString(error)<<")"<<std::endl;
  215. alcDestroyContext(m_context);
  216. m_context = NULL;
  217. alcCloseDevice(m_device);
  218. m_device = NULL;
  219. return;
  220. }
  221. alDistanceModel(AL_EXPONENT_DISTANCE);
  222. infostream<<"Audio: Initialized: OpenAL "<<alGetString(AL_VERSION)
  223. <<", using "<<alcGetString(m_device, ALC_DEVICE_SPECIFIER)
  224. <<std::endl;
  225. m_is_initialized = true;
  226. }
  227. ~OpenALSoundManager()
  228. {
  229. infostream<<"Audio: Deinitializing..."<<std::endl;
  230. // KABOOM!
  231. // TODO: Clear SoundBuffers
  232. alcMakeContextCurrent(NULL);
  233. alcDestroyContext(m_context);
  234. m_context = NULL;
  235. alcCloseDevice(m_device);
  236. m_device = NULL;
  237. for (std::map<std::string, std::vector<SoundBuffer*> >::iterator i = m_buffers.begin();
  238. i != m_buffers.end(); i++) {
  239. for (std::vector<SoundBuffer*>::iterator iter = (*i).second.begin();
  240. iter != (*i).second.end(); iter++) {
  241. delete *iter;
  242. }
  243. (*i).second.clear();
  244. }
  245. m_buffers.clear();
  246. infostream<<"Audio: Deinitialized."<<std::endl;
  247. }
  248. void addBuffer(const std::string &name, SoundBuffer *buf)
  249. {
  250. std::map<std::string, std::vector<SoundBuffer*> >::iterator i =
  251. m_buffers.find(name);
  252. if(i != m_buffers.end()){
  253. i->second.push_back(buf);
  254. return;
  255. }
  256. std::vector<SoundBuffer*> bufs;
  257. bufs.push_back(buf);
  258. m_buffers[name] = bufs;
  259. return;
  260. }
  261. SoundBuffer* getBuffer(const std::string &name)
  262. {
  263. std::map<std::string, std::vector<SoundBuffer*> >::iterator i =
  264. m_buffers.find(name);
  265. if(i == m_buffers.end())
  266. return NULL;
  267. std::vector<SoundBuffer*> &bufs = i->second;
  268. int j = myrand() % bufs.size();
  269. return bufs[j];
  270. }
  271. PlayingSound* createPlayingSound(SoundBuffer *buf, bool loop,
  272. float volume)
  273. {
  274. infostream<<"OpenALSoundManager: Creating playing sound"<<std::endl;
  275. assert(buf);
  276. PlayingSound *sound = new PlayingSound;
  277. assert(sound);
  278. warn_if_error(alGetError(), "before createPlayingSound");
  279. alGenSources(1, &sound->source_id);
  280. alSourcei(sound->source_id, AL_BUFFER, buf->buffer_id);
  281. alSourcei(sound->source_id, AL_SOURCE_RELATIVE, true);
  282. alSource3f(sound->source_id, AL_POSITION, 0, 0, 0);
  283. alSource3f(sound->source_id, AL_VELOCITY, 0, 0, 0);
  284. alSourcei(sound->source_id, AL_LOOPING, loop ? AL_TRUE : AL_FALSE);
  285. volume = MYMAX(0.0, volume);
  286. alSourcef(sound->source_id, AL_GAIN, volume);
  287. alSourcePlay(sound->source_id);
  288. warn_if_error(alGetError(), "createPlayingSound");
  289. return sound;
  290. }
  291. PlayingSound* createPlayingSoundAt(SoundBuffer *buf, bool loop,
  292. float volume, v3f pos)
  293. {
  294. infostream<<"OpenALSoundManager: Creating positional playing sound"
  295. <<std::endl;
  296. assert(buf);
  297. PlayingSound *sound = new PlayingSound;
  298. assert(sound);
  299. warn_if_error(alGetError(), "before createPlayingSoundAt");
  300. alGenSources(1, &sound->source_id);
  301. alSourcei(sound->source_id, AL_BUFFER, buf->buffer_id);
  302. alSourcei(sound->source_id, AL_SOURCE_RELATIVE, false);
  303. alSource3f(sound->source_id, AL_POSITION, pos.X, pos.Y, pos.Z);
  304. alSource3f(sound->source_id, AL_VELOCITY, 0, 0, 0);
  305. //alSourcef(sound->source_id, AL_ROLLOFF_FACTOR, 0.7);
  306. alSourcef(sound->source_id, AL_REFERENCE_DISTANCE, 30.0);
  307. alSourcei(sound->source_id, AL_LOOPING, loop ? AL_TRUE : AL_FALSE);
  308. volume = MYMAX(0.0, volume);
  309. alSourcef(sound->source_id, AL_GAIN, volume);
  310. alSourcePlay(sound->source_id);
  311. warn_if_error(alGetError(), "createPlayingSoundAt");
  312. return sound;
  313. }
  314. int playSoundRaw(SoundBuffer *buf, bool loop, float volume)
  315. {
  316. assert(buf);
  317. PlayingSound *sound = createPlayingSound(buf, loop, volume);
  318. if(!sound)
  319. return -1;
  320. int id = m_next_id++;
  321. m_sounds_playing[id] = sound;
  322. return id;
  323. }
  324. int playSoundRawAt(SoundBuffer *buf, bool loop, float volume, v3f pos)
  325. {
  326. assert(buf);
  327. PlayingSound *sound = createPlayingSoundAt(buf, loop, volume, pos);
  328. if(!sound)
  329. return -1;
  330. int id = m_next_id++;
  331. m_sounds_playing[id] = sound;
  332. return id;
  333. }
  334. void deleteSound(int id)
  335. {
  336. std::map<int, PlayingSound*>::iterator i =
  337. m_sounds_playing.find(id);
  338. if(i == m_sounds_playing.end())
  339. return;
  340. PlayingSound *sound = i->second;
  341. alDeleteSources(1, &sound->source_id);
  342. delete sound;
  343. m_sounds_playing.erase(id);
  344. }
  345. /* If buffer does not exist, consult the fetcher */
  346. SoundBuffer* getFetchBuffer(const std::string &name)
  347. {
  348. SoundBuffer *buf = getBuffer(name);
  349. if(buf)
  350. return buf;
  351. if(!m_fetcher)
  352. return NULL;
  353. std::set<std::string> paths;
  354. std::set<std::string> datas;
  355. m_fetcher->fetchSounds(name, paths, datas);
  356. for(std::set<std::string>::iterator i = paths.begin();
  357. i != paths.end(); i++){
  358. loadSoundFile(name, *i);
  359. }
  360. for(std::set<std::string>::iterator i = datas.begin();
  361. i != datas.end(); i++){
  362. loadSoundData(name, *i);
  363. }
  364. return getBuffer(name);
  365. }
  366. // Remove stopped sounds
  367. void maintain()
  368. {
  369. verbosestream<<"OpenALSoundManager::maintain(): "
  370. <<m_sounds_playing.size()<<" playing sounds, "
  371. <<m_buffers.size()<<" sound names loaded"<<std::endl;
  372. std::set<int> del_list;
  373. for(std::map<int, PlayingSound*>::iterator
  374. i = m_sounds_playing.begin();
  375. i != m_sounds_playing.end(); i++)
  376. {
  377. int id = i->first;
  378. PlayingSound *sound = i->second;
  379. // If not playing, remove it
  380. {
  381. ALint state;
  382. alGetSourcei(sound->source_id, AL_SOURCE_STATE, &state);
  383. if(state != AL_PLAYING){
  384. del_list.insert(id);
  385. }
  386. }
  387. }
  388. if(del_list.size() != 0)
  389. verbosestream<<"OpenALSoundManager::maintain(): deleting "
  390. <<del_list.size()<<" playing sounds"<<std::endl;
  391. for(std::set<int>::iterator i = del_list.begin();
  392. i != del_list.end(); i++)
  393. {
  394. deleteSound(*i);
  395. }
  396. }
  397. /* Interface */
  398. bool loadSoundFile(const std::string &name,
  399. const std::string &filepath)
  400. {
  401. SoundBuffer *buf = loadOggFile(filepath);
  402. if(buf)
  403. addBuffer(name, buf);
  404. return false;
  405. }
  406. bool loadSoundData(const std::string &name,
  407. const std::string &filedata)
  408. {
  409. // The vorbis API sucks; just write it to a file and use vorbisfile
  410. // TODO: Actually load it directly from memory
  411. std::string basepath = porting::path_user + DIR_DELIM + "cache" +
  412. DIR_DELIM + "tmp";
  413. std::string path = basepath + DIR_DELIM + "tmp.ogg";
  414. verbosestream<<"OpenALSoundManager::loadSoundData(): Writing "
  415. <<"temporary file to ["<<path<<"]"<<std::endl;
  416. fs::CreateAllDirs(basepath);
  417. std::ofstream of(path.c_str(), std::ios::binary);
  418. of.write(filedata.c_str(), filedata.size());
  419. of.close();
  420. return loadSoundFile(name, path);
  421. }
  422. void updateListener(v3f pos, v3f vel, v3f at, v3f up)
  423. {
  424. m_listener_pos = pos;
  425. alListener3f(AL_POSITION, pos.X, pos.Y, pos.Z);
  426. alListener3f(AL_VELOCITY, vel.X, vel.Y, vel.Z);
  427. ALfloat f[6];
  428. f3_set(f, at);
  429. f3_set(f+3, -up);
  430. alListenerfv(AL_ORIENTATION, f);
  431. warn_if_error(alGetError(), "updateListener");
  432. }
  433. void setListenerGain(float gain)
  434. {
  435. alListenerf(AL_GAIN, gain);
  436. }
  437. int playSound(const std::string &name, bool loop, float volume)
  438. {
  439. maintain();
  440. if(name == "")
  441. return 0;
  442. SoundBuffer *buf = getFetchBuffer(name);
  443. if(!buf){
  444. infostream<<"OpenALSoundManager: \""<<name<<"\" not found."
  445. <<std::endl;
  446. return -1;
  447. }
  448. return playSoundRaw(buf, loop, volume);
  449. }
  450. int playSoundAt(const std::string &name, bool loop, float volume, v3f pos)
  451. {
  452. maintain();
  453. if(name == "")
  454. return 0;
  455. SoundBuffer *buf = getFetchBuffer(name);
  456. if(!buf){
  457. infostream<<"OpenALSoundManager: \""<<name<<"\" not found."
  458. <<std::endl;
  459. return -1;
  460. }
  461. return playSoundRawAt(buf, loop, volume, pos);
  462. }
  463. void stopSound(int sound)
  464. {
  465. maintain();
  466. deleteSound(sound);
  467. }
  468. bool soundExists(int sound)
  469. {
  470. maintain();
  471. return (m_sounds_playing.count(sound) != 0);
  472. }
  473. void updateSoundPosition(int id, v3f pos)
  474. {
  475. std::map<int, PlayingSound*>::iterator i =
  476. m_sounds_playing.find(id);
  477. if(i == m_sounds_playing.end())
  478. return;
  479. PlayingSound *sound = i->second;
  480. alSourcei(sound->source_id, AL_SOURCE_RELATIVE, false);
  481. alSource3f(sound->source_id, AL_POSITION, pos.X, pos.Y, pos.Z);
  482. alSource3f(sound->source_id, AL_VELOCITY, 0, 0, 0);
  483. alSourcef(sound->source_id, AL_REFERENCE_DISTANCE, 30.0);
  484. }
  485. };
  486. ISoundManager *createOpenALSoundManager(OnDemandSoundFetcher *fetcher)
  487. {
  488. OpenALSoundManager *m = new OpenALSoundManager(fetcher);
  489. if(m->m_is_initialized)
  490. return m;
  491. delete m;
  492. return NULL;
  493. };