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 _velocity(SGVec3d::zeros()),
70 _orientation(SGQuatd::zeros()),
73 #if defined(ALUT_API_MAJOR_VERSION) && ALUT_API_MAJOR_VERSION >= 1
74 if (_alut_init == 0) {
75 if ( !alutInitWithoutContext(NULL, NULL) ) {
76 testForALUTError("alut initialization");
86 SGSoundMgr::~SGSoundMgr() {
89 #if defined(ALUT_API_MAJOR_VERSION) && ALUT_API_MAJOR_VERSION >= 1
91 if (_alut_init == 0) {
97 // initialize the sound manager
98 void SGSoundMgr::init() {
100 SG_LOG( SG_GENERAL, SG_INFO, "Initializing OpenAL sound manager" );
102 ALCdevice *device = alcOpenDevice(_devname);
103 if ( testForError(device, "No default audio device available.") ) {
107 ALCcontext *context = alcCreateContext(device, NULL);
108 if ( testForError(context, "Unable to create a valid context.") ) {
109 alcCloseDevice (device);
113 if ( !alcMakeContextCurrent(context) ) {
114 testForALCError("context initialization");
115 alcDestroyContext (context);
116 alcCloseDevice (device);
120 if (_context != NULL)
121 SG_LOG(SG_GENERAL, SG_ALERT, "context is already assigned");
125 _at_up_vec[0] = 0.0; _at_up_vec[1] = 0.0; _at_up_vec[2] = -1.0;
126 _at_up_vec[3] = 0.0; _at_up_vec[4] = 1.0; _at_up_vec[5] = 0.0;
128 alListenerf( AL_GAIN, 0.0f );
129 alListenerfv( AL_ORIENTATION, _at_up_vec );
130 alListenerfv( AL_POSITION, SGVec3f::zeros().data() );
131 alListenerfv( AL_VELOCITY, SGVec3f::zeros().data() );
133 alDopplerFactor(1.0);
134 alDopplerVelocity(340.3); // speed of sound in meters per second.
136 // gain = AL_REFERENCE_DISTANCE / (AL_REFERENCE_DISTANCE +
137 // AL_ROLLOFF_FACTOR * (distance - AL_REFERENCE_DISTANCE));
138 alDistanceModel(AL_INVERSE_DISTANCE_CLAMPED);
140 testForALError("listener initialization");
142 // get a free source one at a time
143 // if an error is returned no more (hardware) sources are available
144 for (unsigned int i=0; i<MAX_SOURCES; i++) {
149 alGenSources(1, &source);
150 error = alGetError();
151 if ( error == AL_NO_ERROR ) {
152 _free_sources.push_back( source );
157 if (_free_sources.size() == 0) {
158 SG_LOG(SG_GENERAL, SG_ALERT, "Unable to grab any OpenAL sources!");
162 void SGSoundMgr::activate() {
165 sample_group_map_iterator sample_grp_current = _sample_groups.begin();
166 sample_group_map_iterator sample_grp_end = _sample_groups.end();
167 for ( ; sample_grp_current != sample_grp_end; ++sample_grp_current ) {
168 SGSampleGroup *sgrp = sample_grp_current->second;
174 // stop the sound manager
175 void SGSoundMgr::stop() {
180 // clear any OpenAL buffers before shutting down
181 buffer_map_iterator buffers_current = _buffers.begin();
182 buffer_map_iterator buffers_end = _buffers.end();
183 for ( ; buffers_current != buffers_end; ++buffers_current ) {
184 refUint ref = buffers_current->second;
185 ALuint buffer = ref.id;
186 alDeleteBuffers(1, &buffer);
190 _context = alcGetCurrentContext();
191 _device = alcGetContextsDevice(_context);
192 alcDestroyContext(_context);
193 alcCloseDevice(_device);
197 void SGSoundMgr::suspend() {
199 sample_group_map_iterator sample_grp_current = _sample_groups.begin();
200 sample_group_map_iterator sample_grp_end = _sample_groups.end();
201 for ( ; sample_grp_current != sample_grp_end; ++sample_grp_current ) {
202 SGSampleGroup *sgrp = sample_grp_current->second;
209 void SGSoundMgr::resume() {
211 sample_group_map_iterator sample_grp_current = _sample_groups.begin();
212 sample_group_map_iterator sample_grp_end = _sample_groups.end();
213 for ( ; sample_grp_current != sample_grp_end; ++sample_grp_current ) {
214 SGSampleGroup *sgrp = sample_grp_current->second;
221 void SGSoundMgr::bind ()
223 _free_sources.clear();
224 _free_sources.reserve( MAX_SOURCES );
225 _sources_in_use.clear();
226 _sources_in_use.reserve( MAX_SOURCES );
230 void SGSoundMgr::unbind ()
232 _sample_groups.clear();
234 // delete free sources
235 for (unsigned int i=0; i<_free_sources.size(); i++) {
236 ALuint source = _free_sources[i];
237 alDeleteSources( 1 , &source );
240 _free_sources.clear();
241 _sources_in_use.clear();
244 // run the audio scheduler
245 void SGSoundMgr::update( double dt ) {
248 update_pos_and_orientation();
251 sample_group_map_iterator sample_grp_current = _sample_groups.begin();
252 sample_group_map_iterator sample_grp_end = _sample_groups.end();
253 for ( ; sample_grp_current != sample_grp_end; ++sample_grp_current ) {
254 SGSampleGroup *sgrp = sample_grp_current->second;
260 if (isNaN(_at_up_vec)) printf("NaN in listener orientation\n");
261 if (isNaN(toVec3f(_absolute_pos).data())) printf("NaN in listener position\n");
262 if (isNaN(_velocity.data())) printf("NaN in listener velocity\n");
264 alListenerf( AL_GAIN, _volume );
265 alListenerfv( AL_ORIENTATION, _at_up_vec );
266 // alListenerfv( AL_POSITION, toVec3f(_absolute_pos).data() );
267 alListenerfv( AL_VELOCITY, _velocity.data() );
268 // alDopplerVelocity(340.3); // TODO: altitude dependent
269 testForALError("update");
275 // add a sample group, return true if successful
276 bool SGSoundMgr::add( SGSampleGroup *sgrp, const string& refname )
278 sample_group_map_iterator sample_grp_it = _sample_groups.find( refname );
279 if ( sample_grp_it != _sample_groups.end() ) {
280 // sample group already exists
284 if (_active) sgrp->activate();
285 _sample_groups[refname] = sgrp;
291 // remove a sound effect, return true if successful
292 bool SGSoundMgr::remove( const string &refname )
294 sample_group_map_iterator sample_grp_it = _sample_groups.find( refname );
295 if ( sample_grp_it == _sample_groups.end() ) {
296 // sample group was not found.
300 _sample_groups.erase( sample_grp_it );
306 // return true of the specified sound exists in the sound manager system
307 bool SGSoundMgr::exists( const string &refname ) {
308 sample_group_map_iterator sample_grp_it = _sample_groups.find( refname );
309 if ( sample_grp_it == _sample_groups.end() ) {
310 // sample group was not found.
318 // return a pointer to the SGSampleGroup if the specified sound exists
319 // in the sound manager system, otherwise return NULL
320 SGSampleGroup *SGSoundMgr::find( const string &refname, bool create ) {
321 sample_group_map_iterator sample_grp_it = _sample_groups.find( refname );
322 if ( sample_grp_it == _sample_groups.end() ) {
323 // sample group was not found.
325 SGSampleGroup* sgrp = new SGSampleGroup(this, refname);
332 return sample_grp_it->second;
336 void SGSoundMgr::set_volume( float v )
339 if (_volume > 1.0) _volume = 1.0;
340 if (_volume < 0.0) _volume = 0.0;
344 // Get an unused source id
346 // The Sound Manager should keep track of the sources in use, the distance
347 // of these sources to the listener and the volume (also based on audio cone
348 // and hence orientation) of the sources.
350 // The Sound Manager is (and should be) the only one knowing about source
351 // management. Sources further away should be suspendped to free resources for
352 // newly added sounds close by.
353 unsigned int SGSoundMgr::request_source()
355 unsigned int source = NO_SOURCE;
357 if (_free_sources.size() > 0) {
358 source = _free_sources.back();
359 _free_sources.pop_back();
360 _sources_in_use.push_back(source);
363 SG_LOG( SG_GENERAL, SG_INFO, "No more free sources available\n");
368 // Free up a source id for further use
369 void SGSoundMgr::release_source( unsigned int source )
371 vector<ALuint>::iterator it;
373 it = std::find(_sources_in_use.begin(), _sources_in_use.end(), source);
374 if ( it != _sources_in_use.end() ) {
377 alGetSourcei( source, AL_SOURCE_STATE, &result );
378 if ( result == AL_PLAYING )
379 alSourceStop( source );
380 testForALError("release source");
382 alSourcei( source, AL_BUFFER, 0 );
383 _free_sources.push_back( source );
384 _sources_in_use.erase( it );
388 unsigned int SGSoundMgr::request_buffer(SGSoundSample *sample)
390 ALuint buffer = NO_BUFFER;
392 if ( !sample->is_valid_buffer() ) {
393 // sample was not yet loaded or removed again
394 string sample_name = sample->get_sample_name();
396 // see if the sample name is already cached
397 buffer_map_iterator buffer_it = _buffers.find( sample_name );
398 if ( buffer_it != _buffers.end() ) {
399 buffer_it->second.refctr++;
400 buffer = buffer_it->second.id;
401 sample->set_buffer( buffer );
405 // sample name was not found in the buffer cache.
406 if ( sample->is_file() ) {
411 load(sample_name, &data, &format, &size, &freq);
412 sample->set_data( &data );
413 sample->set_frequency( freq );
414 sample->set_format( format );
415 sample->set_size( size );
418 // create an OpenAL buffer handle
419 alGenBuffers(1, &buffer);
420 if ( !testForALError("generate buffer") ) {
421 // Copy data to the internal OpenAL buffer
423 const ALvoid *data = sample->get_data();
424 ALenum format = sample->get_format();
425 ALsizei size = sample->get_size();
426 ALsizei freq = sample->get_frequency();
427 alBufferData( buffer, format, data, size, freq );
429 // If this sample was read from a file we have all the information
430 // needed to read it again. For data buffers provided by the
431 // program we don't; so don't delete it's data.
432 if ( sample->is_file() ) sample->free_data();
434 if ( !testForALError("buffer add data") ) {
435 sample->set_buffer(buffer);
436 _buffers[sample_name] = refUint(buffer);
441 buffer = sample->get_buffer();
447 void SGSoundMgr::release_buffer(SGSoundSample *sample)
449 string sample_name = sample->get_sample_name();
450 buffer_map_iterator buffer_it = _buffers.find( sample_name );
451 if ( buffer_it == _buffers.end() ) {
452 // buffer was not found
456 sample->no_valid_buffer();
457 buffer_it->second.refctr--;
458 if (buffer_it->second.refctr == 0) {
459 ALuint buffer = buffer_it->second.id;
460 alDeleteBuffers(1, &buffer);
461 _buffers.erase( buffer_it );
462 testForALError("release buffer");
466 void SGSoundMgr::update_pos_and_orientation() {
468 * Description: ORIENTATION is a pair of 3-tuples representing the
469 * 'at' direction vector and 'up' direction of the Object in
470 * Cartesian space. AL expects two vectors that are orthogonal to
471 * each other. These vectors are not expected to be normalized. If
472 * one or more vectors have zero length, implementation behavior
473 * is undefined. If the two vectors are linearly dependent,
474 * behavior is undefined.
476 * This is in the same coordinate system as OpenGL; y=up, z=back, x=right.
478 SGVec3d sgv_at = _orientation.backTransform(-SGVec3d::e3());
479 SGVec3d sgv_up = _orientation.backTransform(SGVec3d::e2());
480 _at_up_vec[0] = sgv_at[0];
481 _at_up_vec[1] = sgv_at[1];
482 _at_up_vec[2] = sgv_at[2];
483 _at_up_vec[3] = sgv_up[0];
484 _at_up_vec[4] = sgv_up[1];
485 _at_up_vec[5] = sgv_up[2];
487 // static const SGQuatd q(-0.5, -0.5, 0.5, 0.5);
488 // SGQuatd hlOr = SGQuatd::fromLonLat(SGGeod::fromCart(_base_pos));
489 // SGQuatd ec2body = hlOr*_orientation;
490 _absolute_pos = _base_pos; // + ec2body.backTransform( _offset_pos );
493 bool SGSoundMgr::load(string &samplepath, void **dbuf, int *fmt,
494 size_t *sz, int *frq )
496 if ( !_working ) return false;
503 #if defined(ALUT_API_MAJOR_VERSION) && ALUT_API_MAJOR_VERSION >= 1
505 data = alutLoadMemoryFromFile(samplepath.c_str(), &format, &size, &freqf );
506 freq = (ALsizei)freqf;
508 int error = alutGetError();
509 string msg = "Failed to load wav file: ";
510 msg.append(alutGetErrorString(error));
511 throw sg_io_exception(msg.c_str(), sg_location(samplepath));
516 ALbyte *fname = (ALbyte *)samplepath.c_str();
517 # if defined (__APPLE__)
518 alutLoadWAVFile( fname, &format, &data, &size, &freq );
521 alutLoadWAVFile( fname, &format, &data, &size, &freq, &loop );
523 ALenum error = alGetError();
524 if ( error != AL_NO_ERROR ) {
525 string msg = "Failed to load wav file: ";
526 msg.append(alGetString(error));
527 throw sg_io_exception(msg.c_str(), sg_location(samplepath));
532 *dbuf = (void *)data;
541 bool SGSoundMgr::testForError(void *p, string s)
544 SG_LOG( SG_GENERAL, SG_ALERT, "Error: " << s);
551 bool SGSoundMgr::testForALError(string s)
553 ALenum error = alGetError();
554 if (error != AL_NO_ERROR) {
555 SG_LOG( SG_GENERAL, SG_ALERT, "AL Error (sound manager): "
556 << alGetString(error) << " at " << s);
562 bool SGSoundMgr::testForALCError(string s)
565 error = alcGetError(_device);
566 if (error != ALC_NO_ERROR) {
567 SG_LOG( SG_GENERAL, SG_ALERT, "ALC Error (sound manager): "
568 << alcGetString(_device, error) << " at "
575 bool SGSoundMgr::testForALUTError(string s)
577 #if defined(ALUT_API_MAJOR_VERSION) && ALUT_API_MAJOR_VERSION >= 1
579 error = alutGetError ();
580 if (error != ALUT_ERROR_NO_ERROR) {
581 SG_LOG( SG_GENERAL, SG_ALERT, "ALUT Error (sound manager): "
582 << alutGetErrorString(error) << " at "