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 <OpenAL/alut.h>
41 #include "soundmgr_openal.hxx"
43 #include <simgear/structure/exception.hxx>
44 #include <simgear/debug/logstream.hxx>
45 #include <simgear/misc/sg_path.hxx>
46 #include <simgear/math/SGMath.hxx>
48 extern bool isNaN(float *v);
50 #define MAX_SOURCES 128
56 int SGSoundMgr::_alut_init = 0;
59 SGSoundMgr::SGSoundMgr() :
66 _absolute_pos(SGVec3d::zeros()),
67 _offset_pos(SGVec3d::zeros()),
68 _base_pos(SGVec3d::zeros()),
69 _geod_pos(SGGeod::fromCart(SGVec3d::zeros())),
70 _velocity(SGVec3d::zeros()),
71 _orientation(SGQuatd::zeros()),
74 #if defined(ALUT_API_MAJOR_VERSION) && ALUT_API_MAJOR_VERSION >= 1
75 if (_alut_init == 0) {
76 if ( !alutInitWithoutContext(NULL, NULL) ) {
77 testForALUTError("alut initialization");
87 SGSoundMgr::~SGSoundMgr() {
90 #if defined(ALUT_API_MAJOR_VERSION) && ALUT_API_MAJOR_VERSION >= 1
92 if (_alut_init == 0) {
98 // initialize the sound manager
99 void SGSoundMgr::init(const char *devname) {
101 SG_LOG( SG_GENERAL, SG_INFO, "Initializing OpenAL sound manager" );
103 ALCdevice *device = alcOpenDevice(devname);
104 if ( testForError(device, "Audio device not available, trying default") ) {
105 device = alcOpenDevice(NULL);
106 if (testForError(device, "Default Audio device not available.") ) {
111 ALCcontext *context = alcCreateContext(device, NULL);
112 if ( testForError(context, "Unable to create a valid context.") ) {
113 alcCloseDevice (device);
117 if ( !alcMakeContextCurrent(context) ) {
118 testForALCError("context initialization");
119 alcDestroyContext (context);
120 alcCloseDevice (device);
124 if (_context != NULL)
125 SG_LOG(SG_GENERAL, SG_ALERT, "context is already assigned");
129 _at_up_vec[0] = 0.0; _at_up_vec[1] = 0.0; _at_up_vec[2] = -1.0;
130 _at_up_vec[3] = 0.0; _at_up_vec[4] = 1.0; _at_up_vec[5] = 0.0;
132 alListenerf( AL_GAIN, 0.0f );
133 alListenerfv( AL_ORIENTATION, _at_up_vec );
134 alListenerfv( AL_POSITION, SGVec3f::zeros().data() );
135 alListenerfv( AL_VELOCITY, SGVec3f::zeros().data() );
137 alDopplerFactor(1.0);
138 alDopplerVelocity(340.3); // speed of sound in meters per second.
140 // gain = AL_REFERENCE_DISTANCE / (AL_REFERENCE_DISTANCE +
141 // AL_ROLLOFF_FACTOR * (distance - AL_REFERENCE_DISTANCE));
142 alDistanceModel(AL_INVERSE_DISTANCE_CLAMPED);
144 testForALError("listener initialization");
146 // get a free source one at a time
147 // if an error is returned no more (hardware) sources are available
148 for (unsigned int i=0; i<MAX_SOURCES; i++) {
153 alGenSources(1, &source);
154 error = alGetError();
155 if ( error == AL_NO_ERROR ) {
156 _free_sources.push_back( source );
161 string vendor = alGetString(AL_VENDOR);
162 string renderer = alGetString(AL_RENDERER);
163 if ( vendor != "OpenAL Community" ||
164 (renderer != "Software" && renderer != "OpenAL Sample Implementation")
170 if (_free_sources.size() == 0) {
171 SG_LOG(SG_GENERAL, SG_ALERT, "Unable to grab any OpenAL sources!");
175 void SGSoundMgr::activate() {
178 sample_group_map_iterator sample_grp_current = _sample_groups.begin();
179 sample_group_map_iterator sample_grp_end = _sample_groups.end();
180 for ( ; sample_grp_current != sample_grp_end; ++sample_grp_current ) {
181 SGSampleGroup *sgrp = sample_grp_current->second;
187 // stop the sound manager
188 void SGSoundMgr::stop() {
190 // first stop all sample groups
191 sample_group_map_iterator sample_grp_current = _sample_groups.begin();
192 sample_group_map_iterator sample_grp_end = _sample_groups.end();
193 for ( ; sample_grp_current != sample_grp_end; ++sample_grp_current ) {
194 SGSampleGroup *sgrp = sample_grp_current->second;
198 // clear all OpenAL sources
199 for (unsigned int i=0; i<_free_sources.size(); i++) {
200 ALuint source = _free_sources[i];
201 alDeleteSources( 1 , &source );
203 _free_sources.clear();
205 // clear any OpenAL buffers before shutting down
206 buffer_map_iterator buffers_current = _buffers.begin();
207 buffer_map_iterator buffers_end = _buffers.end();
208 for ( ; buffers_current != buffers_end; ++buffers_current ) {
209 refUint ref = buffers_current->second;
210 ALuint buffer = ref.id;
211 alDeleteBuffers(1, &buffer);
212 _buffers.erase( buffers_current );
219 _context = alcGetCurrentContext();
220 _device = alcGetContextsDevice(_context);
221 alcDestroyContext(_context);
222 alcCloseDevice(_device);
227 void SGSoundMgr::suspend() {
229 sample_group_map_iterator sample_grp_current = _sample_groups.begin();
230 sample_group_map_iterator sample_grp_end = _sample_groups.end();
231 for ( ; sample_grp_current != sample_grp_end; ++sample_grp_current ) {
232 SGSampleGroup *sgrp = sample_grp_current->second;
239 void SGSoundMgr::resume() {
241 sample_group_map_iterator sample_grp_current = _sample_groups.begin();
242 sample_group_map_iterator sample_grp_end = _sample_groups.end();
243 for ( ; sample_grp_current != sample_grp_end; ++sample_grp_current ) {
244 SGSampleGroup *sgrp = sample_grp_current->second;
251 void SGSoundMgr::bind ()
253 _free_sources.clear();
254 _free_sources.reserve( MAX_SOURCES );
255 _sources_in_use.clear();
256 _sources_in_use.reserve( MAX_SOURCES );
260 void SGSoundMgr::unbind ()
262 _sample_groups.clear();
264 // delete free sources
265 for (unsigned int i=0; i<_free_sources.size(); i++) {
266 ALuint source = _free_sources[i];
267 alDeleteSources( 1 , &source );
270 _free_sources.clear();
271 _sources_in_use.clear();
274 // run the audio scheduler
275 void SGSoundMgr::update( double dt ) {
278 update_pos_and_orientation();
281 sample_group_map_iterator sample_grp_current = _sample_groups.begin();
282 sample_group_map_iterator sample_grp_end = _sample_groups.end();
283 for ( ; sample_grp_current != sample_grp_end; ++sample_grp_current ) {
284 SGSampleGroup *sgrp = sample_grp_current->second;
290 if (isNaN(_at_up_vec)) printf("NaN in listener orientation\n");
291 if (isNaN(toVec3f(_absolute_pos).data())) printf("NaN in listener position\n");
292 if (isNaN(_velocity.data())) printf("NaN in listener velocity\n");
294 alListenerf( AL_GAIN, _volume );
295 alListenerfv( AL_ORIENTATION, _at_up_vec );
296 // alListenerfv( AL_POSITION, toVec3f(_absolute_pos).data() );
298 SGQuatd hlOr = SGQuatd::fromLonLat( _geod_pos );
299 SGVec3d velocity = SGVec3d::zeros();
300 if ( _velocity[0] || _velocity[1] || _velocity[2] ) {
301 velocity = hlOr.backTransform(_velocity*SG_FEET_TO_METER);
304 if ( _bad_doppler ) {
308 alListenerfv( AL_VELOCITY, toVec3f(velocity).data() );
309 // alDopplerVelocity(340.3); // TODO: altitude dependent
310 testForALError("update");
316 // add a sample group, return true if successful
317 bool SGSoundMgr::add( SGSampleGroup *sgrp, const string& refname )
319 sample_group_map_iterator sample_grp_it = _sample_groups.find( refname );
320 if ( sample_grp_it != _sample_groups.end() ) {
321 // sample group already exists
325 if (_active) sgrp->activate();
326 _sample_groups[refname] = sgrp;
332 // remove a sound effect, return true if successful
333 bool SGSoundMgr::remove( const string &refname )
335 sample_group_map_iterator sample_grp_it = _sample_groups.find( refname );
336 if ( sample_grp_it == _sample_groups.end() ) {
337 // sample group was not found.
341 _sample_groups.erase( sample_grp_it );
347 // return true of the specified sound exists in the sound manager system
348 bool SGSoundMgr::exists( const string &refname ) {
349 sample_group_map_iterator sample_grp_it = _sample_groups.find( refname );
350 if ( sample_grp_it == _sample_groups.end() ) {
351 // sample group was not found.
359 // return a pointer to the SGSampleGroup if the specified sound exists
360 // in the sound manager system, otherwise return NULL
361 SGSampleGroup *SGSoundMgr::find( const string &refname, bool create ) {
362 sample_group_map_iterator sample_grp_it = _sample_groups.find( refname );
363 if ( sample_grp_it == _sample_groups.end() ) {
364 // sample group was not found.
366 SGSampleGroup* sgrp = new SGSampleGroup(this, refname);
367 add( sgrp, refname );
374 return sample_grp_it->second;
378 void SGSoundMgr::set_volume( float v )
381 if (_volume > 1.0) _volume = 1.0;
382 if (_volume < 0.0) _volume = 0.0;
386 // Get an unused source id
388 // The Sound Manager should keep track of the sources in use, the distance
389 // of these sources to the listener and the volume (also based on audio cone
390 // and hence orientation) of the sources.
392 // The Sound Manager is (and should be) the only one knowing about source
393 // management. Sources further away should be suspendped to free resources for
394 // newly added sounds close by.
395 unsigned int SGSoundMgr::request_source()
397 unsigned int source = NO_SOURCE;
399 if (_free_sources.size() > 0) {
400 source = _free_sources.back();
401 _free_sources.pop_back();
402 _sources_in_use.push_back(source);
405 SG_LOG( SG_GENERAL, SG_INFO, "No more free sources available\n");
410 // Free up a source id for further use
411 void SGSoundMgr::release_source( unsigned int source )
413 vector<ALuint>::iterator it;
415 it = std::find(_sources_in_use.begin(), _sources_in_use.end(), source);
416 if ( it != _sources_in_use.end() ) {
419 alGetSourcei( source, AL_SOURCE_STATE, &result );
420 if ( result == AL_PLAYING )
421 alSourceStop( source );
422 testForALError("release source");
424 alSourcei( source, AL_BUFFER, 0 );
425 _free_sources.push_back( source );
426 _sources_in_use.erase( it );
430 unsigned int SGSoundMgr::request_buffer(SGSoundSample *sample)
432 ALuint buffer = NO_BUFFER;
434 if ( !sample->is_valid_buffer() ) {
435 // sample was not yet loaded or removed again
436 string sample_name = sample->get_sample_name();
438 // see if the sample name is already cached
439 buffer_map_iterator buffer_it = _buffers.find( sample_name );
440 if ( buffer_it != _buffers.end() ) {
441 buffer_it->second.refctr++;
442 buffer = buffer_it->second.id;
443 sample->set_buffer( buffer );
447 // sample name was not found in the buffer cache.
448 if ( sample->is_file() ) {
453 load(sample_name, &data, &format, &size, &freq);
454 sample->set_data( &data );
455 sample->set_frequency( freq );
456 sample->set_format( format );
457 sample->set_size( size );
460 // create an OpenAL buffer handle
461 alGenBuffers(1, &buffer);
462 if ( !testForALError("generate buffer") ) {
463 // Copy data to the internal OpenAL buffer
465 const ALvoid *data = sample->get_data();
466 ALenum format = sample->get_format();
467 ALsizei size = sample->get_size();
468 ALsizei freq = sample->get_frequency();
469 alBufferData( buffer, format, data, size, freq );
471 // If this sample was read from a file we have all the information
472 // needed to read it again. For data buffers provided by the
473 // program we don't; so don't delete it's data.
474 if ( sample->is_file() ) sample->free_data();
476 if ( !testForALError("buffer add data") ) {
477 sample->set_buffer(buffer);
478 _buffers[sample_name] = refUint(buffer);
483 buffer = sample->get_buffer();
489 void SGSoundMgr::release_buffer(SGSoundSample *sample)
491 string sample_name = sample->get_sample_name();
492 buffer_map_iterator buffer_it = _buffers.find( sample_name );
493 if ( buffer_it == _buffers.end() ) {
494 // buffer was not found
498 sample->no_valid_buffer();
499 buffer_it->second.refctr--;
500 if (buffer_it->second.refctr == 0) {
501 ALuint buffer = buffer_it->second.id;
502 alDeleteBuffers(1, &buffer);
503 _buffers.erase( buffer_it );
504 testForALError("release buffer");
508 void SGSoundMgr::update_pos_and_orientation() {
510 * Description: ORIENTATION is a pair of 3-tuples representing the
511 * 'at' direction vector and 'up' direction of the Object in
512 * Cartesian space. AL expects two vectors that are orthogonal to
513 * each other. These vectors are not expected to be normalized. If
514 * one or more vectors have zero length, implementation behavior
515 * is undefined. If the two vectors are linearly dependent,
516 * behavior is undefined.
518 * This is in the same coordinate system as OpenGL; y=up, z=back, x=right.
520 SGVec3d sgv_at = _orientation.backTransform(-SGVec3d::e3());
521 SGVec3d sgv_up = _orientation.backTransform(SGVec3d::e2());
522 _at_up_vec[0] = sgv_at[0];
523 _at_up_vec[1] = sgv_at[1];
524 _at_up_vec[2] = sgv_at[2];
525 _at_up_vec[3] = sgv_up[0];
526 _at_up_vec[4] = sgv_up[1];
527 _at_up_vec[5] = sgv_up[2];
529 // static const SGQuatd q(-0.5, -0.5, 0.5, 0.5);
530 // SGQuatd hlOr = SGQuatd::fromLonLat(SGGeod::fromCart(_base_pos));
531 // SGQuatd ec2body = hlOr*_orientation;
532 _absolute_pos = _base_pos; // + ec2body.backTransform( _offset_pos );
535 bool SGSoundMgr::load(string &samplepath, void **dbuf, int *fmt,
536 size_t *sz, int *frq )
538 if ( !_working ) return false;
545 #if defined(ALUT_API_MAJOR_VERSION) && ALUT_API_MAJOR_VERSION >= 1
547 data = alutLoadMemoryFromFile(samplepath.c_str(), &format, &size, &freqf );
548 freq = (ALsizei)freqf;
550 int error = alutGetError();
551 string msg = "Failed to load wav file: ";
552 msg.append(alutGetErrorString(error));
553 throw sg_io_exception(msg.c_str(), sg_location(samplepath));
558 ALbyte *fname = (ALbyte *)samplepath.c_str();
559 # if defined (__APPLE__)
560 alutLoadWAVFile( fname, &format, &data, &size, &freq );
563 alutLoadWAVFile( fname, &format, &data, &size, &freq, &loop );
565 ALenum error = alGetError();
566 if ( error != AL_NO_ERROR ) {
567 string msg = "Failed to load wav file: ";
568 msg.append(alGetString(error));
569 throw sg_io_exception(msg.c_str(), sg_location(samplepath));
574 *dbuf = (void *)data;
582 vector<const char*> SGSoundMgr::get_available_devices()
584 vector<const char*> devices;
587 if (alcIsExtensionPresent(NULL, "ALC_enumerate_all_EXT") == AL_TRUE) {
588 s = alcGetString(NULL, ALC_ALL_DEVICES_SPECIFIER);
590 s = alcGetString(NULL, ALC_DEVICE_SPECIFIER);
594 ALCchar *nptr, *ptr = (ALCchar *)s;
597 while (*(nptr += strlen(ptr)+1) != 0)
599 devices.push_back(ptr);
602 devices.push_back(ptr);
609 bool SGSoundMgr::testForError(void *p, string s)
612 SG_LOG( SG_GENERAL, SG_ALERT, "Error: " << s);
619 bool SGSoundMgr::testForALError(string s)
621 ALenum error = alGetError();
622 if (error != AL_NO_ERROR) {
623 SG_LOG( SG_GENERAL, SG_ALERT, "AL Error (sound manager): "
624 << alGetString(error) << " at " << s);
630 bool SGSoundMgr::testForALCError(string s)
633 error = alcGetError(_device);
634 if (error != ALC_NO_ERROR) {
635 SG_LOG( SG_GENERAL, SG_ALERT, "ALC Error (sound manager): "
636 << alcGetString(_device, error) << " at "
643 bool SGSoundMgr::testForALUTError(string s)
645 #if defined(ALUT_API_MAJOR_VERSION) && ALUT_API_MAJOR_VERSION >= 1
647 error = alutGetError ();
648 if (error != ALUT_ERROR_NO_ERROR) {
649 SG_LOG( SG_GENERAL, SG_ALERT, "ALUT Error (sound manager): "
650 << alutGetErrorString(error) << " at "