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()
46 #include "util/cpp11_container.h"
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;
151 // Append to end of buffer
152 snd->buffer.insert(snd->buffer.end(), array, array + bytes);
155 alGenBuffers(1, &snd->buffer_id);
156 alBufferData(snd->buffer_id, snd->format,
157 &(snd->buffer[0]), snd->buffer.size(),
160 ALenum error = alGetError();
162 if(error != AL_NO_ERROR){
163 infostream<<"Audio: OpenAL error: "<<alErrorString(error)
164 <<"preparing sound buffer"<<std::endl;
167 infostream << "Audio file "
168 << filename_for_logging << " loaded" << std::endl;
176 SoundBuffer *load_ogg_from_file(const std::string &path)
178 OggVorbis_File oggFile;
180 // Try opening the given file.
181 // This requires libvorbis >= 1.3.2, as
182 // previous versions expect a non-const char *
183 if (ov_fopen(path.c_str(), &oggFile) != 0) {
184 infostream << "Audio: Error opening " << path
185 << " for decoding" << std::endl;
189 return load_opened_ogg_file(&oggFile, path);
192 struct BufferSource {
198 size_t buffer_sound_read_func(void *ptr, size_t size, size_t nmemb, void *datasource)
200 BufferSource *s = (BufferSource *)datasource;
201 size_t copied_size = MYMIN(s->len - s->cur_offset, size);
202 memcpy(ptr, s->buf + s->cur_offset, copied_size);
203 s->cur_offset += copied_size;
207 int buffer_sound_seek_func(void *datasource, ogg_int64_t offset, int whence)
209 BufferSource *s = (BufferSource *)datasource;
210 if (whence == SEEK_SET) {
211 if (offset < 0 || (size_t)MYMAX(offset, 0) >= s->len) {
212 // offset out of bounds
215 s->cur_offset = offset;
217 } else if (whence == SEEK_CUR) {
218 if ((size_t)MYMIN(-offset, 0) > s->cur_offset
219 || s->cur_offset + offset > s->len) {
220 // offset out of bounds
223 s->cur_offset += offset;
226 // invalid whence param (SEEK_END doesn't have to be supported)
230 long BufferSourceell_func(void *datasource)
232 BufferSource *s = (BufferSource *)datasource;
233 return s->cur_offset;
236 static ov_callbacks g_buffer_ov_callbacks = {
237 &buffer_sound_read_func,
238 &buffer_sound_seek_func,
240 &BufferSourceell_func
243 SoundBuffer *load_ogg_from_buffer(const std::string &buf, const std::string &id_for_log)
245 OggVorbis_File oggFile;
252 if (ov_open_callbacks(&s, &oggFile, NULL, 0, g_buffer_ov_callbacks) != 0) {
253 infostream << "Audio: Error opening " << id_for_log
254 << " for decoding" << std::endl;
258 return load_opened_ogg_file(&oggFile, id_for_log);
267 class OpenALSoundManager: public ISoundManager
270 OnDemandSoundFetcher *m_fetcher;
272 ALCcontext *m_context;
274 UNORDERED_MAP<std::string, std::vector<SoundBuffer*> > m_buffers;
275 UNORDERED_MAP<int, PlayingSound*> m_sounds_playing;
279 FadeState(float step, float current_gain, float target_gain):
281 current_gain(current_gain),
282 target_gain(target_gain) {}
288 UNORDERED_MAP<int, FadeState> m_sounds_fading;
291 bool m_is_initialized;
292 OpenALSoundManager(OnDemandSoundFetcher *fetcher):
298 m_is_initialized(false)
300 ALCenum error = ALC_NO_ERROR;
302 infostream<<"Audio: Initializing..."<<std::endl;
304 m_device = alcOpenDevice(NULL);
306 infostream<<"Audio: No audio device available, audio system "
307 <<"not initialized"<<std::endl;
311 m_context = alcCreateContext(m_device, NULL);
313 error = alcGetError(m_device);
314 infostream<<"Audio: Unable to initialize audio context, "
315 <<"aborting audio initialization ("<<alcErrorString(error)
317 alcCloseDevice(m_device);
322 if(!alcMakeContextCurrent(m_context) ||
323 (error = alcGetError(m_device) != ALC_NO_ERROR))
325 infostream<<"Audio: Error setting audio context, aborting audio "
326 <<"initialization ("<<alcErrorString(error)<<")"<<std::endl;
327 alcDestroyContext(m_context);
329 alcCloseDevice(m_device);
334 alDistanceModel(AL_INVERSE_DISTANCE);
336 infostream<<"Audio: Initialized: OpenAL "<<alGetString(AL_VERSION)
337 <<", using "<<alcGetString(m_device, ALC_DEVICE_SPECIFIER)
340 m_is_initialized = true;
343 ~OpenALSoundManager()
345 infostream<<"Audio: Deinitializing..."<<std::endl;
347 // TODO: Clear SoundBuffers
348 alcMakeContextCurrent(NULL);
349 alcDestroyContext(m_context);
351 alcCloseDevice(m_device);
354 for (UNORDERED_MAP<std::string, std::vector<SoundBuffer*> >::iterator i = m_buffers.begin();
355 i != m_buffers.end(); ++i) {
356 for (std::vector<SoundBuffer*>::iterator iter = (*i).second.begin();
357 iter != (*i).second.end(); ++iter) {
363 infostream<<"Audio: Deinitialized."<<std::endl;
366 void step(float dtime)
371 void addBuffer(const std::string &name, SoundBuffer *buf)
373 UNORDERED_MAP<std::string, std::vector<SoundBuffer*> >::iterator i =
374 m_buffers.find(name);
375 if(i != m_buffers.end()){
376 i->second.push_back(buf);
379 std::vector<SoundBuffer*> bufs;
381 m_buffers[name] = bufs;
385 SoundBuffer* getBuffer(const std::string &name)
387 UNORDERED_MAP<std::string, std::vector<SoundBuffer*> >::iterator i =
388 m_buffers.find(name);
389 if(i == m_buffers.end())
391 std::vector<SoundBuffer*> &bufs = i->second;
392 int j = myrand() % bufs.size();
396 PlayingSound* createPlayingSound(SoundBuffer *buf, bool loop,
399 infostream<<"OpenALSoundManager: Creating playing sound"<<std::endl;
401 PlayingSound *sound = new PlayingSound;
403 warn_if_error(alGetError(), "before createPlayingSound");
404 alGenSources(1, &sound->source_id);
405 alSourcei(sound->source_id, AL_BUFFER, buf->buffer_id);
406 alSourcei(sound->source_id, AL_SOURCE_RELATIVE, true);
407 alSource3f(sound->source_id, AL_POSITION, 0, 0, 0);
408 alSource3f(sound->source_id, AL_VELOCITY, 0, 0, 0);
409 alSourcei(sound->source_id, AL_LOOPING, loop ? AL_TRUE : AL_FALSE);
410 volume = MYMAX(0.0, volume);
411 alSourcef(sound->source_id, AL_GAIN, volume);
412 alSourcePlay(sound->source_id);
413 warn_if_error(alGetError(), "createPlayingSound");
417 PlayingSound* createPlayingSoundAt(SoundBuffer *buf, bool loop,
418 float volume, v3f pos)
420 infostream<<"OpenALSoundManager: Creating positional playing sound"
423 PlayingSound *sound = new PlayingSound;
425 warn_if_error(alGetError(), "before createPlayingSoundAt");
426 alGenSources(1, &sound->source_id);
427 alSourcei(sound->source_id, AL_BUFFER, buf->buffer_id);
428 alSourcei(sound->source_id, AL_SOURCE_RELATIVE, false);
429 alSource3f(sound->source_id, AL_POSITION, pos.X, pos.Y, pos.Z);
430 alSource3f(sound->source_id, AL_VELOCITY, 0, 0, 0);
431 alSourcef(sound->source_id, AL_REFERENCE_DISTANCE, 30.0);
432 alSourcei(sound->source_id, AL_LOOPING, loop ? AL_TRUE : AL_FALSE);
433 volume = MYMAX(0.0, volume);
434 alSourcef(sound->source_id, AL_GAIN, volume);
435 alSourcePlay(sound->source_id);
436 warn_if_error(alGetError(), "createPlayingSoundAt");
440 int playSoundRaw(SoundBuffer *buf, bool loop, float volume)
443 PlayingSound *sound = createPlayingSound(buf, loop, volume);
446 int id = m_next_id++;
447 m_sounds_playing[id] = sound;
451 int playSoundRawAt(SoundBuffer *buf, bool loop, float volume, v3f pos)
454 PlayingSound *sound = createPlayingSoundAt(buf, loop, volume, pos);
457 int id = m_next_id++;
458 m_sounds_playing[id] = sound;
462 void deleteSound(int id)
464 UNORDERED_MAP<int, PlayingSound*>::iterator i = m_sounds_playing.find(id);
465 if(i == m_sounds_playing.end())
467 PlayingSound *sound = i->second;
469 alDeleteSources(1, &sound->source_id);
472 m_sounds_playing.erase(id);
475 /* If buffer does not exist, consult the fetcher */
476 SoundBuffer* getFetchBuffer(const std::string &name)
478 SoundBuffer *buf = getBuffer(name);
483 std::set<std::string> paths;
484 std::set<std::string> datas;
485 m_fetcher->fetchSounds(name, paths, datas);
486 for(std::set<std::string>::iterator i = paths.begin();
487 i != paths.end(); ++i){
488 loadSoundFile(name, *i);
490 for(std::set<std::string>::iterator i = datas.begin();
491 i != datas.end(); ++i){
492 loadSoundData(name, *i);
494 return getBuffer(name);
497 // Remove stopped sounds
500 verbosestream<<"OpenALSoundManager::maintain(): "
501 <<m_sounds_playing.size()<<" playing sounds, "
502 <<m_buffers.size()<<" sound names loaded"<<std::endl;
503 std::set<int> del_list;
504 for(UNORDERED_MAP<int, PlayingSound*>::iterator i = m_sounds_playing.begin();
505 i != m_sounds_playing.end(); ++i) {
507 PlayingSound *sound = i->second;
508 // If not playing, remove it
511 alGetSourcei(sound->source_id, AL_SOURCE_STATE, &state);
512 if(state != AL_PLAYING){
517 if(!del_list.empty())
518 verbosestream<<"OpenALSoundManager::maintain(): deleting "
519 <<del_list.size()<<" playing sounds"<<std::endl;
520 for(std::set<int>::iterator i = del_list.begin();
521 i != del_list.end(); ++i)
529 bool loadSoundFile(const std::string &name,
530 const std::string &filepath)
532 SoundBuffer *buf = load_ogg_from_file(filepath);
534 addBuffer(name, buf);
538 bool loadSoundData(const std::string &name,
539 const std::string &filedata)
541 SoundBuffer *buf = load_ogg_from_buffer(filedata, name);
543 addBuffer(name, buf);
547 void updateListener(v3f pos, v3f vel, v3f at, v3f up)
549 m_listener_pos = pos;
550 alListener3f(AL_POSITION, pos.X, pos.Y, pos.Z);
551 alListener3f(AL_VELOCITY, vel.X, vel.Y, vel.Z);
555 alListenerfv(AL_ORIENTATION, f);
556 warn_if_error(alGetError(), "updateListener");
559 void setListenerGain(float gain)
561 alListenerf(AL_GAIN, gain);
564 int playSound(const std::string &name, bool loop, float volume, float fade)
569 SoundBuffer *buf = getFetchBuffer(name);
571 infostream<<"OpenALSoundManager: \""<<name<<"\" not found."
577 handle = playSoundRaw(buf, loop, 0);
578 fadeSound(handle, fade, volume);
580 handle = playSoundRaw(buf, loop, volume);
585 int playSoundAt(const std::string &name, bool loop, float volume, v3f pos)
590 SoundBuffer *buf = getFetchBuffer(name);
592 infostream<<"OpenALSoundManager: \""<<name<<"\" not found."
596 return playSoundRawAt(buf, loop, volume, pos);
599 void stopSound(int sound)
605 void fadeSound(int soundid, float step, float gain)
607 m_sounds_fading[soundid] = FadeState(step, getSoundGain(soundid), gain);
610 void doFades(float dtime)
612 m_fade_delay += dtime;
614 if (m_fade_delay < 0.1f)
618 for (UNORDERED_MAP<int, FadeState>::iterator i = m_sounds_fading.begin();
619 i != m_sounds_fading.end();) {
620 if (i->second.step < 0.f)
621 chkGain = -(i->second.current_gain);
623 chkGain = i->second.current_gain;
625 if (chkGain < i->second.target_gain) {
626 i->second.current_gain += (i->second.step * m_fade_delay);
627 i->second.current_gain = rangelim(i->second.current_gain, 0, 1);
629 updateSoundGain(i->first, i->second.current_gain);
632 if (i->second.target_gain <= 0.f)
635 m_sounds_fading.erase(i++);
641 bool soundExists(int sound)
644 return (m_sounds_playing.count(sound) != 0);
647 void updateSoundPosition(int id, v3f pos)
649 UNORDERED_MAP<int, PlayingSound*>::iterator i = m_sounds_playing.find(id);
650 if (i == m_sounds_playing.end())
652 PlayingSound *sound = i->second;
654 alSourcei(sound->source_id, AL_SOURCE_RELATIVE, false);
655 alSource3f(sound->source_id, AL_POSITION, pos.X, pos.Y, pos.Z);
656 alSource3f(sound->source_id, AL_VELOCITY, 0, 0, 0);
657 alSourcef(sound->source_id, AL_REFERENCE_DISTANCE, 30.0);
660 bool updateSoundGain(int id, float gain)
662 UNORDERED_MAP<int, PlayingSound*>::iterator i = m_sounds_playing.find(id);
663 if (i == m_sounds_playing.end())
666 PlayingSound *sound = i->second;
667 alSourcef(sound->source_id, AL_GAIN, gain);
671 float getSoundGain(int id)
673 UNORDERED_MAP<int, PlayingSound*>::iterator i = m_sounds_playing.find(id);
674 if (i == m_sounds_playing.end())
677 PlayingSound *sound = i->second;
679 alGetSourcef(sound->source_id, AL_GAIN, &gain);
684 ISoundManager *createOpenALSoundManager(OnDemandSoundFetcher *fetcher)
686 OpenALSoundManager *m = new OpenALSoundManager(fetcher);
687 if(m->m_is_initialized)