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>
9 This program is free software; you can redistribute it and/or modify
10 it under the terms of the GNU Lesser General Public License as published by
11 the Free Software Foundation; either version 2.1 of the License, or
12 (at your option) any later version.
14 This program is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 GNU Lesser General Public License for more details.
19 You should have received a copy of the GNU Lesser General Public License along
20 with this program; ifnot, write to the Free Software Foundation, Inc.,
21 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
24 #include "sound_openal.h"
30 #elif defined(__APPLE__)
31 #include <OpenAL/al.h>
32 #include <OpenAL/alc.h>
33 //#include <OpenAL/alext.h>
39 #include <vorbis/vorbisfile.h>
42 #include "util/numeric.h" // myrand()
48 #define BUFFER_SIZE 30000
50 static const char *alcErrorString(ALCenum err)
55 case ALC_INVALID_DEVICE:
56 return "invalid device";
57 case ALC_INVALID_CONTEXT:
58 return "invalid context";
59 case ALC_INVALID_ENUM:
60 return "invalid enum";
61 case ALC_INVALID_VALUE:
62 return "invalid value";
63 case ALC_OUT_OF_MEMORY:
64 return "out of memory";
66 return "<unknown OpenAL error>";
70 static const char *alErrorString(ALenum err)
76 return "invalid name";
78 return "invalid enum";
79 case AL_INVALID_VALUE:
80 return "invalid value";
81 case AL_INVALID_OPERATION:
82 return "invalid operation";
83 case AL_OUT_OF_MEMORY:
84 return "out of memory";
86 return "<unknown OpenAL error>";
90 static ALenum warn_if_error(ALenum err, const char *desc)
92 if(err == AL_NO_ERROR)
94 warningstream<<desc<<": "<<alErrorString(err)<<std::endl;
98 void f3_set(ALfloat *f3, v3f v)
110 std::vector<char> buffer;
113 SoundBuffer *load_opened_ogg_file(OggVorbis_File *oggFile,
114 const std::string &filename_for_logging)
116 int endian = 0; // 0 for Little-Endian, 1 for Big-Endian
119 char array[BUFFER_SIZE]; // Local fixed size array
122 SoundBuffer *snd = new SoundBuffer;
124 // Get some information about the OGG file
125 pInfo = ov_info(oggFile, -1);
127 // Check the number of channels... always use 16-bit samples
128 if(pInfo->channels == 1)
129 snd->format = AL_FORMAT_MONO16;
131 snd->format = AL_FORMAT_STEREO16;
133 // The frequency of the sampling rate
134 snd->freq = pInfo->rate;
136 // Keep reading until all is read
139 // Read up to a buffer's worth of decoded sound data
140 bytes = ov_read(oggFile, array, BUFFER_SIZE, endian, 2, 1, &bitStream);
145 infostream << "Audio: Error decoding "
146 << filename_for_logging << std::endl;
150 // Append to end of buffer
151 snd->buffer.insert(snd->buffer.end(), array, array + bytes);
154 alGenBuffers(1, &snd->buffer_id);
155 alBufferData(snd->buffer_id, snd->format,
156 &(snd->buffer[0]), snd->buffer.size(),
159 ALenum error = alGetError();
161 if(error != AL_NO_ERROR){
162 infostream<<"Audio: OpenAL error: "<<alErrorString(error)
163 <<"preparing sound buffer"<<std::endl;
166 infostream << "Audio file "
167 << filename_for_logging << " loaded" << std::endl;
175 SoundBuffer *load_ogg_from_file(const std::string &path)
177 OggVorbis_File oggFile;
179 // Try opening the given file.
180 // This requires libvorbis >= 1.3.2, as
181 // previous versions expect a non-const char *
182 if (ov_fopen(path.c_str(), &oggFile) != 0) {
183 infostream << "Audio: Error opening " << path
184 << " for decoding" << std::endl;
188 return load_opened_ogg_file(&oggFile, path);
191 struct BufferSource {
197 size_t buffer_sound_read_func(void *ptr, size_t size, size_t nmemb, void *datasource)
199 BufferSource *s = (BufferSource *)datasource;
200 size_t copied_size = MYMIN(s->len - s->cur_offset, size);
201 memcpy(ptr, s->buf + s->cur_offset, copied_size);
202 s->cur_offset += copied_size;
206 int buffer_sound_seek_func(void *datasource, ogg_int64_t offset, int whence)
208 BufferSource *s = (BufferSource *)datasource;
209 if (whence == SEEK_SET) {
210 if (offset < 0 || (size_t)MYMAX(offset, 0) >= s->len) {
211 // offset out of bounds
214 s->cur_offset = offset;
216 } else if (whence == SEEK_CUR) {
217 if ((size_t)MYMIN(-offset, 0) > s->cur_offset
218 || s->cur_offset + offset > s->len) {
219 // offset out of bounds
222 s->cur_offset += offset;
225 // invalid whence param (SEEK_END doesn't have to be supported)
229 long BufferSourceell_func(void *datasource)
231 BufferSource *s = (BufferSource *)datasource;
232 return s->cur_offset;
235 static ov_callbacks g_buffer_ov_callbacks = {
236 &buffer_sound_read_func,
237 &buffer_sound_seek_func,
239 &BufferSourceell_func
242 SoundBuffer *load_ogg_from_buffer(const std::string &buf, const std::string &id_for_log)
244 OggVorbis_File oggFile;
251 if (ov_open_callbacks(&s, &oggFile, NULL, 0, g_buffer_ov_callbacks) != 0) {
252 infostream << "Audio: Error opening " << id_for_log
253 << " for decoding" << std::endl;
257 return load_opened_ogg_file(&oggFile, id_for_log);
266 class OpenALSoundManager: public ISoundManager
269 OnDemandSoundFetcher *m_fetcher;
271 ALCcontext *m_context;
274 std::map<std::string, std::vector<SoundBuffer*> > m_buffers;
275 std::map<int, PlayingSound*> m_sounds_playing;
278 bool m_is_initialized;
279 OpenALSoundManager(OnDemandSoundFetcher *fetcher):
285 m_is_initialized(false)
287 ALCenum error = ALC_NO_ERROR;
289 infostream<<"Audio: Initializing..."<<std::endl;
291 m_device = alcOpenDevice(NULL);
293 infostream<<"Audio: No audio device available, audio system "
294 <<"not initialized"<<std::endl;
298 if(alcIsExtensionPresent(m_device, "EXT_vorbis")){
299 infostream<<"Audio: Vorbis extension present"<<std::endl;
302 infostream<<"Audio: Vorbis extension NOT present"<<std::endl;
303 m_can_vorbis = false;
306 m_context = alcCreateContext(m_device, NULL);
308 error = alcGetError(m_device);
309 infostream<<"Audio: Unable to initialize audio context, "
310 <<"aborting audio initialization ("<<alcErrorString(error)
312 alcCloseDevice(m_device);
317 if(!alcMakeContextCurrent(m_context) ||
318 (error = alcGetError(m_device) != ALC_NO_ERROR))
320 infostream<<"Audio: Error setting audio context, aborting audio "
321 <<"initialization ("<<alcErrorString(error)<<")"<<std::endl;
322 alcDestroyContext(m_context);
324 alcCloseDevice(m_device);
329 alDistanceModel(AL_EXPONENT_DISTANCE);
331 infostream<<"Audio: Initialized: OpenAL "<<alGetString(AL_VERSION)
332 <<", using "<<alcGetString(m_device, ALC_DEVICE_SPECIFIER)
335 m_is_initialized = true;
338 ~OpenALSoundManager()
340 infostream<<"Audio: Deinitializing..."<<std::endl;
342 // TODO: Clear SoundBuffers
343 alcMakeContextCurrent(NULL);
344 alcDestroyContext(m_context);
346 alcCloseDevice(m_device);
349 for (std::map<std::string, std::vector<SoundBuffer*> >::iterator i = m_buffers.begin();
350 i != m_buffers.end(); ++i) {
351 for (std::vector<SoundBuffer*>::iterator iter = (*i).second.begin();
352 iter != (*i).second.end(); ++iter) {
358 infostream<<"Audio: Deinitialized."<<std::endl;
361 void addBuffer(const std::string &name, SoundBuffer *buf)
363 std::map<std::string, std::vector<SoundBuffer*> >::iterator i =
364 m_buffers.find(name);
365 if(i != m_buffers.end()){
366 i->second.push_back(buf);
369 std::vector<SoundBuffer*> bufs;
371 m_buffers[name] = bufs;
375 SoundBuffer* getBuffer(const std::string &name)
377 std::map<std::string, std::vector<SoundBuffer*> >::iterator i =
378 m_buffers.find(name);
379 if(i == m_buffers.end())
381 std::vector<SoundBuffer*> &bufs = i->second;
382 int j = myrand() % bufs.size();
386 PlayingSound* createPlayingSound(SoundBuffer *buf, bool loop,
389 infostream<<"OpenALSoundManager: Creating playing sound"<<std::endl;
391 PlayingSound *sound = new PlayingSound;
393 warn_if_error(alGetError(), "before createPlayingSound");
394 alGenSources(1, &sound->source_id);
395 alSourcei(sound->source_id, AL_BUFFER, buf->buffer_id);
396 alSourcei(sound->source_id, AL_SOURCE_RELATIVE, true);
397 alSource3f(sound->source_id, AL_POSITION, 0, 0, 0);
398 alSource3f(sound->source_id, AL_VELOCITY, 0, 0, 0);
399 alSourcei(sound->source_id, AL_LOOPING, loop ? AL_TRUE : AL_FALSE);
400 volume = MYMAX(0.0, volume);
401 alSourcef(sound->source_id, AL_GAIN, volume);
402 alSourcePlay(sound->source_id);
403 warn_if_error(alGetError(), "createPlayingSound");
407 PlayingSound* createPlayingSoundAt(SoundBuffer *buf, bool loop,
408 float volume, v3f pos)
410 infostream<<"OpenALSoundManager: Creating positional playing sound"
413 PlayingSound *sound = new PlayingSound;
415 warn_if_error(alGetError(), "before createPlayingSoundAt");
416 alGenSources(1, &sound->source_id);
417 alSourcei(sound->source_id, AL_BUFFER, buf->buffer_id);
418 alSourcei(sound->source_id, AL_SOURCE_RELATIVE, false);
419 alSource3f(sound->source_id, AL_POSITION, pos.X, pos.Y, pos.Z);
420 alSource3f(sound->source_id, AL_VELOCITY, 0, 0, 0);
421 //alSourcef(sound->source_id, AL_ROLLOFF_FACTOR, 0.7);
422 alSourcef(sound->source_id, AL_REFERENCE_DISTANCE, 30.0);
423 alSourcei(sound->source_id, AL_LOOPING, loop ? AL_TRUE : AL_FALSE);
424 volume = MYMAX(0.0, volume);
425 alSourcef(sound->source_id, AL_GAIN, volume);
426 alSourcePlay(sound->source_id);
427 warn_if_error(alGetError(), "createPlayingSoundAt");
431 int playSoundRaw(SoundBuffer *buf, bool loop, float volume)
434 PlayingSound *sound = createPlayingSound(buf, loop, volume);
437 int id = m_next_id++;
438 m_sounds_playing[id] = sound;
442 int playSoundRawAt(SoundBuffer *buf, bool loop, float volume, v3f pos)
445 PlayingSound *sound = createPlayingSoundAt(buf, loop, volume, pos);
448 int id = m_next_id++;
449 m_sounds_playing[id] = sound;
453 void deleteSound(int id)
455 std::map<int, PlayingSound*>::iterator i =
456 m_sounds_playing.find(id);
457 if(i == m_sounds_playing.end())
459 PlayingSound *sound = i->second;
461 alDeleteSources(1, &sound->source_id);
464 m_sounds_playing.erase(id);
467 /* If buffer does not exist, consult the fetcher */
468 SoundBuffer* getFetchBuffer(const std::string &name)
470 SoundBuffer *buf = getBuffer(name);
475 std::set<std::string> paths;
476 std::set<std::string> datas;
477 m_fetcher->fetchSounds(name, paths, datas);
478 for(std::set<std::string>::iterator i = paths.begin();
479 i != paths.end(); ++i){
480 loadSoundFile(name, *i);
482 for(std::set<std::string>::iterator i = datas.begin();
483 i != datas.end(); ++i){
484 loadSoundData(name, *i);
486 return getBuffer(name);
489 // Remove stopped sounds
492 verbosestream<<"OpenALSoundManager::maintain(): "
493 <<m_sounds_playing.size()<<" playing sounds, "
494 <<m_buffers.size()<<" sound names loaded"<<std::endl;
495 std::set<int> del_list;
496 for(std::map<int, PlayingSound*>::iterator
497 i = m_sounds_playing.begin();
498 i != m_sounds_playing.end(); ++i)
501 PlayingSound *sound = i->second;
502 // If not playing, remove it
505 alGetSourcei(sound->source_id, AL_SOURCE_STATE, &state);
506 if(state != AL_PLAYING){
511 if(!del_list.empty())
512 verbosestream<<"OpenALSoundManager::maintain(): deleting "
513 <<del_list.size()<<" playing sounds"<<std::endl;
514 for(std::set<int>::iterator i = del_list.begin();
515 i != del_list.end(); ++i)
523 bool loadSoundFile(const std::string &name,
524 const std::string &filepath)
526 SoundBuffer *buf = load_ogg_from_file(filepath);
528 addBuffer(name, buf);
531 bool loadSoundData(const std::string &name,
532 const std::string &filedata)
534 SoundBuffer *buf = load_ogg_from_buffer(filedata, name);
536 addBuffer(name, buf);
540 void updateListener(v3f pos, v3f vel, v3f at, v3f up)
542 m_listener_pos = pos;
543 alListener3f(AL_POSITION, pos.X, pos.Y, pos.Z);
544 alListener3f(AL_VELOCITY, vel.X, vel.Y, vel.Z);
548 alListenerfv(AL_ORIENTATION, f);
549 warn_if_error(alGetError(), "updateListener");
552 void setListenerGain(float gain)
554 alListenerf(AL_GAIN, gain);
557 int playSound(const std::string &name, bool loop, float volume)
562 SoundBuffer *buf = getFetchBuffer(name);
564 infostream<<"OpenALSoundManager: \""<<name<<"\" not found."
568 return playSoundRaw(buf, loop, volume);
570 int playSoundAt(const std::string &name, bool loop, float volume, v3f pos)
575 SoundBuffer *buf = getFetchBuffer(name);
577 infostream<<"OpenALSoundManager: \""<<name<<"\" not found."
581 return playSoundRawAt(buf, loop, volume, pos);
583 void stopSound(int sound)
588 bool soundExists(int sound)
591 return (m_sounds_playing.count(sound) != 0);
593 void updateSoundPosition(int id, v3f pos)
595 std::map<int, PlayingSound*>::iterator i =
596 m_sounds_playing.find(id);
597 if(i == m_sounds_playing.end())
599 PlayingSound *sound = i->second;
601 alSourcei(sound->source_id, AL_SOURCE_RELATIVE, false);
602 alSource3f(sound->source_id, AL_POSITION, pos.X, pos.Y, pos.Z);
603 alSource3f(sound->source_id, AL_VELOCITY, 0, 0, 0);
604 alSourcef(sound->source_id, AL_REFERENCE_DISTANCE, 30.0);
608 ISoundManager *createOpenALSoundManager(OnDemandSoundFetcher *fetcher)
610 OpenALSoundManager *m = new OpenALSoundManager(fetcher);
611 if(m->m_is_initialized)