1 // soundmgr.cxx -- Sound effect management class
3 // Sound manager initially written by David Findlay
4 // <david_j_findlay@yahoo.com.au> 2001
6 // C++-ified by Curtis Olson, started March 2001.
7 // Modified for the new SoundSystem by Erik Hofman, October 2009
9 // Copyright (C) 2001 Curtis L. Olson - http://www.flightgear.org/~curt
10 // Copyright (C) 2009 Erik Hofman <erik@ehofman.com>
12 // This program is free software; you can redistribute it and/or
13 // modify it under the terms of the GNU General Public License as
14 // published by the Free Software Foundation; either version 2 of the
15 // License, or (at your option) any later version.
17 // This program is distributed in the hope that it will be useful, but
18 // WITHOUT ANY WARRANTY; without even the implied warranty of
19 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 // General Public License for more details.
22 // You should have received a copy of the GNU General Public License
23 // along with this program; if not, write to the Free Software Foundation,
24 // Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
29 # include <simgear_config.h>
32 #if defined( __APPLE__ )
33 # include <ALUT/alut.h>
42 #include "soundmgr_openal.hxx"
44 #include <simgear/structure/exception.hxx>
45 #include <simgear/debug/logstream.hxx>
46 #include <simgear/misc/sg_path.hxx>
47 #include <simgear/math/SGMath.hxx>
52 extern bool isNaN(float *v);
54 #define MAX_SOURCES 128
57 #ifndef ALC_ALL_DEVICES_SPECIFIER
58 # define ALC_ALL_DEVICES_SPECIFIER 0x1013
65 int SGSoundMgr::_alut_init = 0;
68 SGSoundMgr::SGSoundMgr() :
75 _absolute_pos(SGVec3d::zeros()),
76 _offset_pos(SGVec3d::zeros()),
77 _base_pos(SGVec3d::zeros()),
78 _geod_pos(SGGeod::fromCart(SGVec3d::zeros())),
79 _velocity(SGVec3d::zeros()),
80 _orientation(SGQuatd::zeros()),
85 #if defined(ALUT_API_MAJOR_VERSION) && ALUT_API_MAJOR_VERSION >= 1
86 if (_alut_init == 0) {
87 if ( !alutInitWithoutContext(NULL, NULL) ) {
88 testForALUTError("alut initialization");
94 //#error ALUT 1.1 required, ALUT 1.0 is no longer supported, please upgrade
100 SGSoundMgr::~SGSoundMgr() {
103 #if defined(ALUT_API_MAJOR_VERSION) && ALUT_API_MAJOR_VERSION >= 1
105 if (_alut_init == 0) {
111 // initialize the sound manager
112 void SGSoundMgr::init(const char *devname) {
114 SG_LOG( SG_GENERAL, SG_INFO, "Initializing OpenAL sound manager" );
116 ALCdevice *device = alcOpenDevice(devname);
117 if ( testForError(device, "Audio device not available, trying default") ) {
118 device = alcOpenDevice(NULL);
119 if (testForError(device, "Default Audio device not available.") ) {
125 ALCcontext *context = alcCreateContext(device, NULL);
126 testForALCError("context creation.");
127 if ( testForError(context, "Unable to create a valid context.") ) {
128 alcCloseDevice (device);
132 if ( !alcMakeContextCurrent(context) ) {
133 testForALCError("context initialization");
134 alcDestroyContext (context);
135 alcCloseDevice (device);
139 if (_context != NULL)
140 SG_LOG(SG_GENERAL, SG_ALERT, "context is already assigned");
144 _at_up_vec[0] = 0.0; _at_up_vec[1] = 0.0; _at_up_vec[2] = -1.0;
145 _at_up_vec[3] = 0.0; _at_up_vec[4] = 1.0; _at_up_vec[5] = 0.0;
147 alListenerf( AL_GAIN, 0.0f );
148 alListenerfv( AL_ORIENTATION, _at_up_vec );
149 alListenerfv( AL_POSITION, SGVec3f::zeros().data() );
150 alListenerfv( AL_VELOCITY, SGVec3f::zeros().data() );
152 alDopplerFactor(1.0);
153 alDopplerVelocity(340.3); // speed of sound in meters per second.
155 // gain = AL_REFERENCE_DISTANCE / (AL_REFERENCE_DISTANCE +
156 // AL_ROLLOFF_FACTOR * (distance - AL_REFERENCE_DISTANCE));
157 alDistanceModel(AL_INVERSE_DISTANCE_CLAMPED);
159 testForALError("listener initialization");
161 // get a free source one at a time
162 // if an error is returned no more (hardware) sources are available
163 for (unsigned int i=0; i<MAX_SOURCES; i++) {
168 alGenSources(1, &source);
169 error = alGetError();
170 if ( error == AL_NO_ERROR ) {
171 _free_sources.push_back( source );
176 _vendor = (const char *)alGetString(AL_VENDOR);
177 _renderer = (const char *)alGetString(AL_RENDERER);
179 if (_vendor == "Creative Labs Inc.") {
182 } else if (_vendor == "OpenAL Community" && _renderer == "OpenAL Soft") {
186 if (_free_sources.size() == 0) {
187 SG_LOG(SG_GENERAL, SG_ALERT, "Unable to grab any OpenAL sources!");
191 void SGSoundMgr::activate() {
194 sample_group_map_iterator sample_grp_current = _sample_groups.begin();
195 sample_group_map_iterator sample_grp_end = _sample_groups.end();
196 for ( ; sample_grp_current != sample_grp_end; ++sample_grp_current ) {
197 SGSampleGroup *sgrp = sample_grp_current->second;
203 // stop the sound manager
204 void SGSoundMgr::stop() {
206 // first stop all sample groups
207 sample_group_map_iterator sample_grp_current = _sample_groups.begin();
208 sample_group_map_iterator sample_grp_end = _sample_groups.end();
209 for ( ; sample_grp_current != sample_grp_end; ++sample_grp_current ) {
210 SGSampleGroup *sgrp = sample_grp_current->second;
214 // clear all OpenAL sources
215 for (unsigned int i=0; i<_free_sources.size(); i++) {
216 ALuint source = _free_sources[i];
217 alDeleteSources( 1 , &source );
219 _free_sources.clear();
221 // clear any OpenAL buffers before shutting down
222 buffer_map_iterator buffers_current = _buffers.begin();
223 buffer_map_iterator buffers_end = _buffers.end();
224 for ( ; buffers_current != buffers_end; ++buffers_current ) {
225 refUint ref = buffers_current->second;
226 ALuint buffer = ref.id;
227 alDeleteBuffers(1, &buffer);
234 _context = alcGetCurrentContext();
235 _device = alcGetContextsDevice(_context);
236 alcDestroyContext(_context);
237 alcCloseDevice(_device);
240 _renderer = "unknown";
245 void SGSoundMgr::suspend() {
247 sample_group_map_iterator sample_grp_current = _sample_groups.begin();
248 sample_group_map_iterator sample_grp_end = _sample_groups.end();
249 for ( ; sample_grp_current != sample_grp_end; ++sample_grp_current ) {
250 SGSampleGroup *sgrp = sample_grp_current->second;
257 void SGSoundMgr::resume() {
259 sample_group_map_iterator sample_grp_current = _sample_groups.begin();
260 sample_group_map_iterator sample_grp_end = _sample_groups.end();
261 for ( ; sample_grp_current != sample_grp_end; ++sample_grp_current ) {
262 SGSampleGroup *sgrp = sample_grp_current->second;
269 void SGSoundMgr::bind ()
271 _free_sources.clear();
272 _free_sources.reserve( MAX_SOURCES );
273 _sources_in_use.clear();
274 _sources_in_use.reserve( MAX_SOURCES );
278 void SGSoundMgr::unbind ()
280 _sample_groups.clear();
282 // delete free sources
283 for (unsigned int i=0; i<_free_sources.size(); i++) {
284 ALuint source = _free_sources[i];
285 alDeleteSources( 1 , &source );
288 _free_sources.clear();
289 _sources_in_use.clear();
292 // run the audio scheduler
293 void SGSoundMgr::update( double dt ) {
295 alcSuspendContext(_context);
298 update_pos_and_orientation();
301 sample_group_map_iterator sample_grp_current = _sample_groups.begin();
302 sample_group_map_iterator sample_grp_end = _sample_groups.end();
303 for ( ; sample_grp_current != sample_grp_end; ++sample_grp_current ) {
304 SGSampleGroup *sgrp = sample_grp_current->second;
310 if (isNaN(_at_up_vec)) printf("NaN in listener orientation\n");
311 if (isNaN(toVec3f(_absolute_pos).data())) printf("NaN in listener position\n");
312 if (isNaN(_velocity.data())) printf("NaN in listener velocity\n");
314 alListenerf( AL_GAIN, _volume );
315 alListenerfv( AL_ORIENTATION, _at_up_vec );
316 // alListenerfv( AL_POSITION, toVec3f(_absolute_pos).data() );
318 SGQuatd hlOr = SGQuatd::fromLonLat( _geod_pos );
319 SGVec3d velocity = SGVec3d::zeros();
320 if ( _velocity[0] || _velocity[1] || _velocity[2] ) {
321 velocity = hlOr.backTransform(_velocity*SG_FEET_TO_METER);
324 if ( _bad_doppler ) {
328 alListenerfv( AL_VELOCITY, toVec3f(velocity).data() );
329 // alDopplerVelocity(340.3); // TODO: altitude dependent
330 testForALError("update");
334 alcProcessContext(_context);
338 // add a sample group, return true if successful
339 bool SGSoundMgr::add( SGSampleGroup *sgrp, const string& refname )
341 sample_group_map_iterator sample_grp_it = _sample_groups.find( refname );
342 if ( sample_grp_it != _sample_groups.end() ) {
343 // sample group already exists
347 if (_active) sgrp->activate();
348 _sample_groups[refname] = sgrp;
354 // remove a sound effect, return true if successful
355 bool SGSoundMgr::remove( const string &refname )
357 sample_group_map_iterator sample_grp_it = _sample_groups.find( refname );
358 if ( sample_grp_it == _sample_groups.end() ) {
359 // sample group was not found.
363 _sample_groups.erase( sample_grp_it );
369 // return true of the specified sound exists in the sound manager system
370 bool SGSoundMgr::exists( const string &refname ) {
371 sample_group_map_iterator sample_grp_it = _sample_groups.find( refname );
372 if ( sample_grp_it == _sample_groups.end() ) {
373 // sample group was not found.
381 // return a pointer to the SGSampleGroup if the specified sound exists
382 // in the sound manager system, otherwise return NULL
383 SGSampleGroup *SGSoundMgr::find( const string &refname, bool create ) {
384 sample_group_map_iterator sample_grp_it = _sample_groups.find( refname );
385 if ( sample_grp_it == _sample_groups.end() ) {
386 // sample group was not found.
388 SGSampleGroup* sgrp = new SGSampleGroup(this, refname);
389 add( sgrp, refname );
396 return sample_grp_it->second;
400 void SGSoundMgr::set_volume( float v )
403 if (_volume > 1.0) _volume = 1.0;
404 if (_volume < 0.0) _volume = 0.0;
408 // Get an unused source id
410 // The Sound Manager should keep track of the sources in use, the distance
411 // of these sources to the listener and the volume (also based on audio cone
412 // and hence orientation) of the sources.
414 // The Sound Manager is (and should be) the only one knowing about source
415 // management. Sources further away should be suspendped to free resources for
416 // newly added sounds close by.
417 unsigned int SGSoundMgr::request_source()
419 unsigned int source = NO_SOURCE;
421 if (_free_sources.size() > 0) {
422 source = _free_sources.back();
423 _free_sources.pop_back();
424 _sources_in_use.push_back(source);
427 SG_LOG( SG_GENERAL, SG_INFO, "No more free sources available\n");
432 // Free up a source id for further use
433 void SGSoundMgr::release_source( unsigned int source )
435 vector<ALuint>::iterator it;
437 it = std::find(_sources_in_use.begin(), _sources_in_use.end(), source);
438 if ( it != _sources_in_use.end() ) {
441 alGetSourcei( source, AL_SOURCE_STATE, &result );
442 if ( result == AL_PLAYING ) {
443 alSourceStop( source );
446 alSourcei( source, AL_BUFFER, 0 ); // detach the associated buffer
447 testForALError("release_source");
448 _free_sources.push_back( source );
449 _sources_in_use.erase( it );
453 unsigned int SGSoundMgr::request_buffer(SGSoundSample *sample)
455 ALuint buffer = NO_BUFFER;
457 if ( !sample->is_valid_buffer() ) {
458 // sample was not yet loaded or removed again
459 string sample_name = sample->get_sample_name();
460 void *sample_data = NULL;
462 // see if the sample name is already cached
463 buffer_map_iterator buffer_it = _buffers.find( sample_name );
464 if ( buffer_it != _buffers.end() ) {
465 buffer_it->second.refctr++;
466 buffer = buffer_it->second.id;
467 sample->set_buffer( buffer );
471 // sample name was not found in the buffer cache.
472 if ( sample->is_file() ) {
477 bool res = load(sample_name, &sample_data, &format, &size, &freq);
478 if (res == false) return NO_BUFFER;
479 } catch (sg_exception& e) {
480 SG_LOG(SG_GENERAL, SG_ALERT,
481 "failed to load sound buffer:" << e.getFormattedMessage());
485 sample->set_frequency( freq );
486 sample->set_format( format );
487 sample->set_size( size );
490 sample_data = sample->get_data();
493 // create an OpenAL buffer handle
494 alGenBuffers(1, &buffer);
495 if ( !testForALError("generate buffer") ) {
496 // Copy data to the internal OpenAL buffer
498 ALenum format = sample->get_format();
499 ALsizei size = sample->get_size();
500 ALsizei freq = sample->get_frequency();
501 alBufferData( buffer, format, sample_data, size, freq );
503 if ( !testForALError("buffer add data") ) {
504 sample->set_buffer(buffer);
505 _buffers[sample_name] = refUint(buffer);
509 if ( sample->is_file() ) free(sample_data);
512 buffer = sample->get_buffer();
518 void SGSoundMgr::release_buffer(SGSoundSample *sample)
520 if ( !sample->is_queue() )
522 string sample_name = sample->get_sample_name();
523 buffer_map_iterator buffer_it = _buffers.find( sample_name );
524 if ( buffer_it == _buffers.end() ) {
525 // buffer was not found
529 sample->no_valid_buffer();
530 buffer_it->second.refctr--;
531 if (buffer_it->second.refctr == 0) {
532 ALuint buffer = buffer_it->second.id;
533 alDeleteBuffers(1, &buffer);
534 _buffers.erase( buffer_it );
535 testForALError("release buffer");
540 void SGSoundMgr::update_pos_and_orientation() {
542 * Description: ORIENTATION is a pair of 3-tuples representing the
543 * 'at' direction vector and 'up' direction of the Object in
544 * Cartesian space. AL expects two vectors that are orthogonal to
545 * each other. These vectors are not expected to be normalized. If
546 * one or more vectors have zero length, implementation behavior
547 * is undefined. If the two vectors are linearly dependent,
548 * behavior is undefined.
550 * This is in the same coordinate system as OpenGL; y=up, z=back, x=right.
552 SGVec3d sgv_at = _orientation.backTransform(-SGVec3d::e3());
553 SGVec3d sgv_up = _orientation.backTransform(SGVec3d::e2());
554 _at_up_vec[0] = sgv_at[0];
555 _at_up_vec[1] = sgv_at[1];
556 _at_up_vec[2] = sgv_at[2];
557 _at_up_vec[3] = sgv_up[0];
558 _at_up_vec[4] = sgv_up[1];
559 _at_up_vec[5] = sgv_up[2];
561 _absolute_pos = _base_pos;
564 bool SGSoundMgr::load(string &samplepath, void **dbuf, int *fmt,
565 size_t *sz, int *frq )
567 if ( !_working ) return false;
574 #if defined(ALUT_API_MAJOR_VERSION) && ALUT_API_MAJOR_VERSION >= 1
576 // ignore previous errors to prevent the system from halting on silly errors
578 alcGetError(_device);
579 data = alutLoadMemoryFromFile(samplepath.c_str(), &format, &size, &freqf );
580 freq = (ALsizei)freqf;
581 int error = alutGetError();
582 if (data == NULL || error != ALUT_ERROR_NO_ERROR) {
583 string msg = "Failed to load wav file: ";
584 msg.append(alutGetErrorString(error));
585 throw sg_io_exception(msg.c_str(), sg_location(samplepath));
590 ALbyte *fname = (ALbyte *)samplepath.c_str();
591 # if defined (__APPLE__)
592 alutLoadWAVFile( fname, &format, &data, &size, &freq );
595 alutLoadWAVFile( fname, &format, &data, &size, &freq, &loop );
597 ALenum error = alGetError();
598 if ( error != AL_NO_ERROR ) {
599 string msg = "Failed to load wav file: ";
600 const ALchar *errorString = alGetString(error);
602 msg.append(errorString);
604 // alGetString returns NULL when an unexpected or OS specific error
605 // occurs: e.g. -43 on Mac when file is not found.
606 // In this case, alGetString() sets 'Invalid Enum' error, so
607 // showing with the original error number is helpful.
608 std::stringstream ss;
609 ss << alGetString(alGetError()) << "(" << error << ")";
610 msg.append(ss.str());
612 throw sg_io_exception(msg.c_str(), sg_location(samplepath));
617 *dbuf = (void *)data;
625 vector<const char*> SGSoundMgr::get_available_devices()
627 vector<const char*> devices;
630 if (alcIsExtensionPresent(NULL, "ALC_enumerate_all_EXT") == AL_TRUE) {
631 s = alcGetString(NULL, ALC_ALL_DEVICES_SPECIFIER);
633 s = alcGetString(NULL, ALC_DEVICE_SPECIFIER);
637 ALCchar *nptr, *ptr = (ALCchar *)s;
640 while (*(nptr += strlen(ptr)+1) != 0)
642 devices.push_back(ptr);
645 devices.push_back(ptr);
652 bool SGSoundMgr::testForError(void *p, string s)
655 SG_LOG( SG_GENERAL, SG_ALERT, "Error: " << s);
662 bool SGSoundMgr::testForALError(string s)
664 ALenum error = alGetError();
665 if (error != AL_NO_ERROR) {
666 SG_LOG( SG_GENERAL, SG_ALERT, "AL Error (sound manager): "
667 << alGetString(error) << " at " << s);
673 bool SGSoundMgr::testForALCError(string s)
676 error = alcGetError(_device);
677 if (error != ALC_NO_ERROR) {
678 SG_LOG( SG_GENERAL, SG_ALERT, "ALC Error (sound manager): "
679 << alcGetString(_device, error) << " at "
686 bool SGSoundMgr::testForALUTError(string s)
688 #if defined(ALUT_API_MAJOR_VERSION) && ALUT_API_MAJOR_VERSION >= 1
690 error = alutGetError ();
691 if (error != ALUT_ERROR_NO_ERROR) {
692 SG_LOG( SG_GENERAL, SG_ALERT, "ALUT Error (sound manager): "
693 << alutGetErrorString(error) << " at "