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>
51 extern bool isNaN(float *v);
53 #define MAX_SOURCES 128
56 #ifndef ALC_ALL_DEVICES_SPECIFIER
57 # define ALC_ALL_DEVICES_SPECIFIER 0x1013
64 int SGSoundMgr::_alut_init = 0;
67 SGSoundMgr::SGSoundMgr() :
74 _absolute_pos(SGVec3d::zeros()),
75 _offset_pos(SGVec3d::zeros()),
76 _base_pos(SGVec3d::zeros()),
77 _geod_pos(SGGeod::fromCart(SGVec3d::zeros())),
78 _velocity(SGVec3d::zeros()),
79 _orientation(SGQuatd::zeros()),
84 #if defined(ALUT_API_MAJOR_VERSION) && ALUT_API_MAJOR_VERSION >= 1
85 if (_alut_init == 0) {
86 if ( !alutInitWithoutContext(NULL, NULL) ) {
87 testForALUTError("alut initialization");
93 //#error ALUT 1.1 required, ALUT 1.0 is no longer supported, please upgrade
99 SGSoundMgr::~SGSoundMgr() {
102 #if defined(ALUT_API_MAJOR_VERSION) && ALUT_API_MAJOR_VERSION >= 1
104 if (_alut_init == 0) {
110 // initialize the sound manager
111 void SGSoundMgr::init(const char *devname) {
113 SG_LOG( SG_GENERAL, SG_INFO, "Initializing OpenAL sound manager" );
115 ALCdevice *device = alcOpenDevice(devname);
116 if ( testForError(device, "Audio device not available, trying default") ) {
117 device = alcOpenDevice(NULL);
118 if (testForError(device, "Default Audio device not available.") ) {
124 ALCcontext *context = alcCreateContext(device, NULL);
125 testForALCError("context creation.");
126 if ( testForError(context, "Unable to create a valid context.") ) {
127 alcCloseDevice (device);
131 if ( !alcMakeContextCurrent(context) ) {
132 testForALCError("context initialization");
133 alcDestroyContext (context);
134 alcCloseDevice (device);
138 if (_context != NULL)
139 SG_LOG(SG_GENERAL, SG_ALERT, "context is already assigned");
143 _at_up_vec[0] = 0.0; _at_up_vec[1] = 0.0; _at_up_vec[2] = -1.0;
144 _at_up_vec[3] = 0.0; _at_up_vec[4] = 1.0; _at_up_vec[5] = 0.0;
146 alListenerf( AL_GAIN, 0.0f );
147 alListenerfv( AL_ORIENTATION, _at_up_vec );
148 alListenerfv( AL_POSITION, SGVec3f::zeros().data() );
149 alListenerfv( AL_VELOCITY, SGVec3f::zeros().data() );
151 alDopplerFactor(1.0);
152 alDopplerVelocity(340.3); // speed of sound in meters per second.
154 // gain = AL_REFERENCE_DISTANCE / (AL_REFERENCE_DISTANCE +
155 // AL_ROLLOFF_FACTOR * (distance - AL_REFERENCE_DISTANCE));
156 alDistanceModel(AL_INVERSE_DISTANCE_CLAMPED);
158 testForALError("listener initialization");
160 // get a free source one at a time
161 // if an error is returned no more (hardware) sources are available
162 for (unsigned int i=0; i<MAX_SOURCES; i++) {
167 alGenSources(1, &source);
168 error = alGetError();
169 if ( error == AL_NO_ERROR ) {
170 _free_sources.push_back( source );
175 _vendor = (const char *)alGetString(AL_VENDOR);
176 _renderer = (const char *)alGetString(AL_RENDERER);
178 if (_vendor == "Creative Labs Inc.") {
181 } else if (_vendor == "OpenAL Community" && _renderer == "OpenAL Soft") {
185 if (_free_sources.size() == 0) {
186 SG_LOG(SG_GENERAL, SG_ALERT, "Unable to grab any OpenAL sources!");
190 void SGSoundMgr::activate() {
193 sample_group_map_iterator sample_grp_current = _sample_groups.begin();
194 sample_group_map_iterator sample_grp_end = _sample_groups.end();
195 for ( ; sample_grp_current != sample_grp_end; ++sample_grp_current ) {
196 SGSampleGroup *sgrp = sample_grp_current->second;
202 // stop the sound manager
203 void SGSoundMgr::stop() {
205 // first stop all sample groups
206 sample_group_map_iterator sample_grp_current = _sample_groups.begin();
207 sample_group_map_iterator sample_grp_end = _sample_groups.end();
208 for ( ; sample_grp_current != sample_grp_end; ++sample_grp_current ) {
209 SGSampleGroup *sgrp = sample_grp_current->second;
213 // clear all OpenAL sources
214 for (unsigned int i=0; i<_free_sources.size(); i++) {
215 ALuint source = _free_sources[i];
216 alDeleteSources( 1 , &source );
218 _free_sources.clear();
220 // clear any OpenAL buffers before shutting down
221 buffer_map_iterator buffers_current = _buffers.begin();
222 buffer_map_iterator buffers_end = _buffers.end();
223 for ( ; buffers_current != buffers_end; ++buffers_current ) {
224 refUint ref = buffers_current->second;
225 ALuint buffer = ref.id;
226 alDeleteBuffers(1, &buffer);
233 _context = alcGetCurrentContext();
234 _device = alcGetContextsDevice(_context);
235 alcDestroyContext(_context);
236 alcCloseDevice(_device);
239 _renderer = "unknown";
244 void SGSoundMgr::suspend() {
246 sample_group_map_iterator sample_grp_current = _sample_groups.begin();
247 sample_group_map_iterator sample_grp_end = _sample_groups.end();
248 for ( ; sample_grp_current != sample_grp_end; ++sample_grp_current ) {
249 SGSampleGroup *sgrp = sample_grp_current->second;
256 void SGSoundMgr::resume() {
258 sample_group_map_iterator sample_grp_current = _sample_groups.begin();
259 sample_group_map_iterator sample_grp_end = _sample_groups.end();
260 for ( ; sample_grp_current != sample_grp_end; ++sample_grp_current ) {
261 SGSampleGroup *sgrp = sample_grp_current->second;
268 void SGSoundMgr::bind ()
270 _free_sources.clear();
271 _free_sources.reserve( MAX_SOURCES );
272 _sources_in_use.clear();
273 _sources_in_use.reserve( MAX_SOURCES );
277 void SGSoundMgr::unbind ()
279 _sample_groups.clear();
281 // delete free sources
282 for (unsigned int i=0; i<_free_sources.size(); i++) {
283 ALuint source = _free_sources[i];
284 alDeleteSources( 1 , &source );
287 _free_sources.clear();
288 _sources_in_use.clear();
291 // run the audio scheduler
292 void SGSoundMgr::update( double dt ) {
294 alcSuspendContext(_context);
297 update_pos_and_orientation();
300 sample_group_map_iterator sample_grp_current = _sample_groups.begin();
301 sample_group_map_iterator sample_grp_end = _sample_groups.end();
302 for ( ; sample_grp_current != sample_grp_end; ++sample_grp_current ) {
303 SGSampleGroup *sgrp = sample_grp_current->second;
309 if (isNaN(_at_up_vec)) printf("NaN in listener orientation\n");
310 if (isNaN(toVec3f(_absolute_pos).data())) printf("NaN in listener position\n");
311 if (isNaN(_velocity.data())) printf("NaN in listener velocity\n");
313 alListenerf( AL_GAIN, _volume );
314 alListenerfv( AL_ORIENTATION, _at_up_vec );
315 // alListenerfv( AL_POSITION, toVec3f(_absolute_pos).data() );
317 SGQuatd hlOr = SGQuatd::fromLonLat( _geod_pos );
318 SGVec3d velocity = SGVec3d::zeros();
319 if ( _velocity[0] || _velocity[1] || _velocity[2] ) {
320 velocity = hlOr.backTransform(_velocity*SG_FEET_TO_METER);
323 if ( _bad_doppler ) {
327 alListenerfv( AL_VELOCITY, toVec3f(velocity).data() );
328 // alDopplerVelocity(340.3); // TODO: altitude dependent
329 testForALError("update");
333 alcProcessContext(_context);
337 // add a sample group, return true if successful
338 bool SGSoundMgr::add( SGSampleGroup *sgrp, const string& refname )
340 sample_group_map_iterator sample_grp_it = _sample_groups.find( refname );
341 if ( sample_grp_it != _sample_groups.end() ) {
342 // sample group already exists
346 if (_active) sgrp->activate();
347 _sample_groups[refname] = sgrp;
353 // remove a sound effect, return true if successful
354 bool SGSoundMgr::remove( const string &refname )
356 sample_group_map_iterator sample_grp_it = _sample_groups.find( refname );
357 if ( sample_grp_it == _sample_groups.end() ) {
358 // sample group was not found.
362 _sample_groups.erase( sample_grp_it );
368 // return true of the specified sound exists in the sound manager system
369 bool SGSoundMgr::exists( const string &refname ) {
370 sample_group_map_iterator sample_grp_it = _sample_groups.find( refname );
371 if ( sample_grp_it == _sample_groups.end() ) {
372 // sample group was not found.
380 // return a pointer to the SGSampleGroup if the specified sound exists
381 // in the sound manager system, otherwise return NULL
382 SGSampleGroup *SGSoundMgr::find( const string &refname, bool create ) {
383 sample_group_map_iterator sample_grp_it = _sample_groups.find( refname );
384 if ( sample_grp_it == _sample_groups.end() ) {
385 // sample group was not found.
387 SGSampleGroup* sgrp = new SGSampleGroup(this, refname);
388 add( sgrp, refname );
395 return sample_grp_it->second;
399 void SGSoundMgr::set_volume( float v )
402 if (_volume > 1.0) _volume = 1.0;
403 if (_volume < 0.0) _volume = 0.0;
407 // Get an unused source id
409 // The Sound Manager should keep track of the sources in use, the distance
410 // of these sources to the listener and the volume (also based on audio cone
411 // and hence orientation) of the sources.
413 // The Sound Manager is (and should be) the only one knowing about source
414 // management. Sources further away should be suspendped to free resources for
415 // newly added sounds close by.
416 unsigned int SGSoundMgr::request_source()
418 unsigned int source = NO_SOURCE;
420 if (_free_sources.size() > 0) {
421 source = _free_sources.back();
422 _free_sources.pop_back();
423 _sources_in_use.push_back(source);
426 SG_LOG( SG_GENERAL, SG_INFO, "No more free sources available\n");
431 // Free up a source id for further use
432 void SGSoundMgr::release_source( unsigned int source )
434 vector<ALuint>::iterator it;
436 it = std::find(_sources_in_use.begin(), _sources_in_use.end(), source);
437 if ( it != _sources_in_use.end() ) {
440 alGetSourcei( source, AL_SOURCE_STATE, &result );
441 if ( result == AL_PLAYING ) {
442 alSourceStop( source );
445 alSourcei( source, AL_BUFFER, 0 ); // detach the associated buffer
446 testForALError("release_source");
447 _free_sources.push_back( source );
448 _sources_in_use.erase( it );
452 unsigned int SGSoundMgr::request_buffer(SGSoundSample *sample)
454 ALuint buffer = NO_BUFFER;
456 if ( !sample->is_valid_buffer() ) {
457 // sample was not yet loaded or removed again
458 string sample_name = sample->get_sample_name();
459 void *sample_data = NULL;
461 // see if the sample name is already cached
462 buffer_map_iterator buffer_it = _buffers.find( sample_name );
463 if ( buffer_it != _buffers.end() ) {
464 buffer_it->second.refctr++;
465 buffer = buffer_it->second.id;
466 sample->set_buffer( buffer );
470 // sample name was not found in the buffer cache.
471 if ( sample->is_file() ) {
476 bool res = load(sample_name, &sample_data, &format, &size, &freq);
477 if (res == false) return NO_BUFFER;
478 } catch (sg_exception& e) {
479 SG_LOG(SG_GENERAL, SG_ALERT,
480 "failed to load sound buffer:" << e.getFormattedMessage());
484 sample->set_frequency( freq );
485 sample->set_format( format );
486 sample->set_size( size );
489 sample_data = sample->get_data();
492 // create an OpenAL buffer handle
493 alGenBuffers(1, &buffer);
494 if ( !testForALError("generate buffer") ) {
495 // Copy data to the internal OpenAL buffer
497 ALenum format = sample->get_format();
498 ALsizei size = sample->get_size();
499 ALsizei freq = sample->get_frequency();
500 alBufferData( buffer, format, sample_data, size, freq );
502 if ( !testForALError("buffer add data") ) {
503 sample->set_buffer(buffer);
504 _buffers[sample_name] = refUint(buffer);
508 if ( sample->is_file() ) free(sample_data);
511 buffer = sample->get_buffer();
517 void SGSoundMgr::release_buffer(SGSoundSample *sample)
519 if ( !sample->is_queue() )
521 string sample_name = sample->get_sample_name();
522 buffer_map_iterator buffer_it = _buffers.find( sample_name );
523 if ( buffer_it == _buffers.end() ) {
524 // buffer was not found
528 sample->no_valid_buffer();
529 buffer_it->second.refctr--;
530 if (buffer_it->second.refctr == 0) {
531 ALuint buffer = buffer_it->second.id;
532 alDeleteBuffers(1, &buffer);
533 _buffers.erase( buffer_it );
534 testForALError("release buffer");
539 void SGSoundMgr::update_pos_and_orientation() {
541 * Description: ORIENTATION is a pair of 3-tuples representing the
542 * 'at' direction vector and 'up' direction of the Object in
543 * Cartesian space. AL expects two vectors that are orthogonal to
544 * each other. These vectors are not expected to be normalized. If
545 * one or more vectors have zero length, implementation behavior
546 * is undefined. If the two vectors are linearly dependent,
547 * behavior is undefined.
549 * This is in the same coordinate system as OpenGL; y=up, z=back, x=right.
551 SGVec3d sgv_at = _orientation.backTransform(-SGVec3d::e3());
552 SGVec3d sgv_up = _orientation.backTransform(SGVec3d::e2());
553 _at_up_vec[0] = sgv_at[0];
554 _at_up_vec[1] = sgv_at[1];
555 _at_up_vec[2] = sgv_at[2];
556 _at_up_vec[3] = sgv_up[0];
557 _at_up_vec[4] = sgv_up[1];
558 _at_up_vec[5] = sgv_up[2];
560 _absolute_pos = _base_pos;
563 bool SGSoundMgr::load(string &samplepath, void **dbuf, int *fmt,
564 size_t *sz, int *frq )
566 if ( !_working ) return false;
573 #if defined(ALUT_API_MAJOR_VERSION) && ALUT_API_MAJOR_VERSION >= 1
575 // ignore previous errors to prevent the system from halting on silly errors
577 alcGetError(_device);
578 data = alutLoadMemoryFromFile(samplepath.c_str(), &format, &size, &freqf );
579 freq = (ALsizei)freqf;
580 int error = alutGetError();
581 if (data == NULL || error != ALUT_ERROR_NO_ERROR) {
582 string msg = "Failed to load wav file: ";
583 msg.append(alutGetErrorString(error));
584 throw sg_io_exception(msg.c_str(), sg_location(samplepath));
589 ALbyte *fname = (ALbyte *)samplepath.c_str();
590 # if defined (__APPLE__)
591 alutLoadWAVFile( fname, &format, &data, &size, &freq );
594 alutLoadWAVFile( fname, &format, &data, &size, &freq, &loop );
596 ALenum error = alGetError();
597 if ( error != AL_NO_ERROR ) {
598 string msg = "Failed to load wav file: ";
599 const ALchar *errorString = alGetString(error);
601 msg.append(errorString);
603 // alGetString returns NULL when an unexpected or OS specific error
604 // occurs: e.g. -43 on Mac when file is not found.
605 // In this case, alGetString() sets 'Invalid Enum' error, so
606 // showing with the original error number is helpful.
608 ss << alGetString(alGetError()) << "(" << error << ")";
609 msg.append(ss.str());
611 throw sg_io_exception(msg.c_str(), sg_location(samplepath));
616 *dbuf = (void *)data;
624 vector<const char*> SGSoundMgr::get_available_devices()
626 vector<const char*> devices;
629 if (alcIsExtensionPresent(NULL, "ALC_enumerate_all_EXT") == AL_TRUE) {
630 s = alcGetString(NULL, ALC_ALL_DEVICES_SPECIFIER);
632 s = alcGetString(NULL, ALC_DEVICE_SPECIFIER);
636 ALCchar *nptr, *ptr = (ALCchar *)s;
639 while (*(nptr += strlen(ptr)+1) != 0)
641 devices.push_back(ptr);
644 devices.push_back(ptr);
651 bool SGSoundMgr::testForError(void *p, string s)
654 SG_LOG( SG_GENERAL, SG_ALERT, "Error: " << s);
661 bool SGSoundMgr::testForALError(string s)
663 ALenum error = alGetError();
664 if (error != AL_NO_ERROR) {
665 SG_LOG( SG_GENERAL, SG_ALERT, "AL Error (sound manager): "
666 << alGetString(error) << " at " << s);
672 bool SGSoundMgr::testForALCError(string s)
675 error = alcGetError(_device);
676 if (error != ALC_NO_ERROR) {
677 SG_LOG( SG_GENERAL, SG_ALERT, "ALC Error (sound manager): "
678 << alcGetString(_device, error) << " at "
685 bool SGSoundMgr::testForALUTError(string s)
687 #if defined(ALUT_API_MAJOR_VERSION) && ALUT_API_MAJOR_VERSION >= 1
689 error = alutGetError ();
690 if (error != ALUT_ERROR_NO_ERROR) {
691 SG_LOG( SG_GENERAL, SG_ALERT, "ALUT Error (sound manager): "
692 << alutGetErrorString(error) << " at "