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 _position_geod(SGGeod::fromDeg(0,0)),
67 _absolute_pos(SGVec3d::zeros()),
68 _velocity(SGVec3d::zeros()),
69 _orientation(SGQuatd::zeros()),
72 #if defined(ALUT_API_MAJOR_VERSION) && ALUT_API_MAJOR_VERSION >= 1
73 if (_alut_init == 0) {
74 if ( !alutInitWithoutContext(NULL, NULL) ) {
75 testForALUTError("alut initialization");
85 SGSoundMgr::~SGSoundMgr() {
88 #if defined(ALUT_API_MAJOR_VERSION) && ALUT_API_MAJOR_VERSION >= 1
90 if (_alut_init == 0) {
96 // initialize the sound manager
97 void SGSoundMgr::init() {
99 SG_LOG( SG_GENERAL, SG_INFO, "Initializing OpenAL sound manager" );
101 ALCdevice *device = alcOpenDevice(_devname);
102 if ( testForError(device, "No default audio device available.") ) {
106 ALCcontext *context = alcCreateContext(device, NULL);
107 if ( testForError(context, "Unable to create a valid context.") ) {
108 alcCloseDevice (device);
112 if ( !alcMakeContextCurrent(context) ) {
113 testForALCError("context initialization");
114 alcDestroyContext (context);
115 alcCloseDevice (device);
119 if (_context != NULL)
120 SG_LOG(SG_GENERAL, SG_ALERT, "context is already assigned");
124 _at_up_vec[0] = 0.0; _at_up_vec[1] = 0.0; _at_up_vec[2] = -1.0;
125 _at_up_vec[3] = 0.0; _at_up_vec[4] = 1.0; _at_up_vec[5] = 0.0;
127 alListenerf( AL_GAIN, 0.0f );
128 alListenerfv( AL_ORIENTATION, _at_up_vec );
129 alListenerfv( AL_POSITION, SGVec3f::zeros().data() );
130 alListenerfv( AL_VELOCITY, SGVec3f::zeros().data() );
132 alDopplerFactor(1.0);
133 alDopplerVelocity(340.3); // speed of sound in meters per second.
135 if ( alIsExtensionPresent((const ALchar*)"EXT_exponent_distance") ) {
136 alDistanceModel(AL_EXPONENT_DISTANCE);
138 alDistanceModel(AL_INVERSE_DISTANCE);
141 testForALError("listener initialization");
143 // get a free source one at a time
144 // if an error is returned no more (hardware) sources are available
145 for (unsigned int i=0; i<MAX_SOURCES; i++) {
150 alGenSources(1, &source);
151 error = alGetError();
152 if ( error == AL_NO_ERROR ) {
153 _free_sources.push_back( source );
158 if (_free_sources.size() == 0) {
159 SG_LOG(SG_GENERAL, SG_ALERT, "Unable to grab any OpenAL sources!");
163 void SGSoundMgr::activate() {
166 sample_group_map_iterator sample_grp_current = _sample_groups.begin();
167 sample_group_map_iterator sample_grp_end = _sample_groups.end();
168 for ( ; sample_grp_current != sample_grp_end; ++sample_grp_current ) {
169 SGSampleGroup *sgrp = sample_grp_current->second;
175 // stop the sound manager
176 void SGSoundMgr::stop() {
181 // clear any OpenAL buffers before shutting down
182 buffer_map_iterator buffers_current = _buffers.begin();
183 buffer_map_iterator buffers_end = _buffers.end();
184 for ( ; buffers_current != buffers_end; ++buffers_current ) {
185 refUint ref = buffers_current->second;
186 ALuint buffer = ref.id;
187 alDeleteBuffers(1, &buffer);
191 _context = alcGetCurrentContext();
192 _device = alcGetContextsDevice(_context);
193 alcDestroyContext(_context);
194 alcCloseDevice(_device);
198 void SGSoundMgr::suspend() {
200 sample_group_map_iterator sample_grp_current = _sample_groups.begin();
201 sample_group_map_iterator sample_grp_end = _sample_groups.end();
202 for ( ; sample_grp_current != sample_grp_end; ++sample_grp_current ) {
203 SGSampleGroup *sgrp = sample_grp_current->second;
210 void SGSoundMgr::resume() {
212 sample_group_map_iterator sample_grp_current = _sample_groups.begin();
213 sample_group_map_iterator sample_grp_end = _sample_groups.end();
214 for ( ; sample_grp_current != sample_grp_end; ++sample_grp_current ) {
215 SGSampleGroup *sgrp = sample_grp_current->second;
222 void SGSoundMgr::bind ()
224 _free_sources.clear();
225 _free_sources.reserve( MAX_SOURCES );
226 _sources_in_use.clear();
227 _sources_in_use.reserve( MAX_SOURCES );
231 void SGSoundMgr::unbind ()
233 _sample_groups.clear();
235 // delete free sources
236 for (unsigned int i=0; i<_free_sources.size(); i++) {
237 ALuint source = _free_sources[i];
238 alDeleteSources( 1 , &source );
241 _free_sources.clear();
242 _sources_in_use.clear();
245 // run the audio scheduler
246 void SGSoundMgr::update( double dt ) {
248 sample_group_map_iterator sample_grp_current = _sample_groups.begin();
249 sample_group_map_iterator sample_grp_end = _sample_groups.end();
250 for ( ; sample_grp_current != sample_grp_end; ++sample_grp_current ) {
251 SGSampleGroup *sgrp = sample_grp_current->second;
257 if (isNaN(_at_up_vec)) printf("NaN in listener orientation\n");
258 if (isNaN(toVec3f(_absolute_pos).data())) printf("NaN in listener position\n");
259 if (isNaN(_velocity.data())) printf("NaN in listener velocity\n");
261 update_pos_and_orientation();
262 alListenerf( AL_GAIN, _volume );
263 alListenerfv( AL_ORIENTATION, _at_up_vec );
264 // alListenerfv( AL_POSITION, toVec3f(_absolute_pos).data() );
265 alListenerfv( AL_VELOCITY, _velocity.data() );
266 // alDopplerVelocity(340.3); // TODO: altitude dependent
267 testForALError("update");
273 // add a sample group, return true if successful
274 bool SGSoundMgr::add( SGSampleGroup *sgrp, const string& refname )
276 sample_group_map_iterator sample_grp_it = _sample_groups.find( refname );
277 if ( sample_grp_it != _sample_groups.end() ) {
278 // sample group already exists
282 if (_active) sgrp->activate();
283 _sample_groups[refname] = sgrp;
289 // remove a sound effect, return true if successful
290 bool SGSoundMgr::remove( const string &refname )
292 sample_group_map_iterator sample_grp_it = _sample_groups.find( refname );
293 if ( sample_grp_it == _sample_groups.end() ) {
294 // sample group was not found.
298 _sample_groups.erase( sample_grp_it );
304 // return true of the specified sound exists in the sound manager system
305 bool SGSoundMgr::exists( const string &refname ) {
306 sample_group_map_iterator sample_grp_it = _sample_groups.find( refname );
307 if ( sample_grp_it == _sample_groups.end() ) {
308 // sample group was not found.
316 // return a pointer to the SGSampleGroup if the specified sound exists
317 // in the sound manager system, otherwise return NULL
318 SGSampleGroup *SGSoundMgr::find( const string &refname, bool create ) {
319 sample_group_map_iterator sample_grp_it = _sample_groups.find( refname );
320 if ( sample_grp_it == _sample_groups.end() ) {
321 // sample group was not found.
323 SGSampleGroup* sgrp = new SGSampleGroup(this, refname);
330 return sample_grp_it->second;
334 void SGSoundMgr::set_volume( float v )
337 if (_volume > 1.0) _volume = 1.0;
338 if (_volume < 0.0) _volume = 0.0;
342 // Get an unused source id
344 // The Sound Manager should keep track of the sources in use, the distance
345 // of these sources to the listener and the volume (also based on audio cone
346 // and hence orientation) of the sources.
348 // The Sound Manager is (and should be) the only one knowing about source
349 // management. Sources further away should be suspendped to free resources for
350 // newly added sounds close by.
351 unsigned int SGSoundMgr::request_source()
353 unsigned int source = NO_SOURCE;
355 if (_free_sources.size() > 0) {
356 source = _free_sources.back();
357 _free_sources.pop_back();
358 _sources_in_use.push_back(source);
361 SG_LOG( SG_GENERAL, SG_INFO, "No more free sources available\n");
366 // Free up a source id for further use
367 void SGSoundMgr::release_source( unsigned int source )
369 vector<ALuint>::iterator it;
371 it = std::find(_sources_in_use.begin(), _sources_in_use.end(), source);
372 if ( it != _sources_in_use.end() ) {
375 alGetSourcei( source, AL_SOURCE_STATE, &result );
376 if ( result == AL_PLAYING )
377 alSourceStop( source );
378 testForALError("release source");
380 alSourcei( source, AL_BUFFER, 0 );
381 _free_sources.push_back( source );
382 _sources_in_use.erase( it );
386 unsigned int SGSoundMgr::request_buffer(SGSoundSample *sample)
388 ALuint buffer = NO_BUFFER;
390 if ( !sample->is_valid_buffer() ) {
391 // sample was not yet loaded or removed again
392 string sample_name = sample->get_sample_name();
394 // see if the sample name is already cached
395 buffer_map_iterator buffer_it = _buffers.find( sample_name );
396 if ( buffer_it != _buffers.end() ) {
397 buffer_it->second.refctr++;
398 buffer = buffer_it->second.id;
399 sample->set_buffer( buffer );
403 // sample name was not found in the buffer cache.
404 if ( sample->is_file() ) {
409 load(sample_name, &data, &format, &size, &freq);
410 sample->set_data( &data );
411 sample->set_frequency( freq );
412 sample->set_format( format );
413 sample->set_size( size );
416 // create an OpenAL buffer handle
417 alGenBuffers(1, &buffer);
418 if ( !testForALError("generate buffer") ) {
419 // Copy data to the internal OpenAL buffer
421 const ALvoid *data = sample->get_data();
422 ALenum format = sample->get_format();
423 ALsizei size = sample->get_size();
424 ALsizei freq = sample->get_frequency();
425 alBufferData( buffer, format, data, size, freq );
427 // If this sample was read from a file we have all the information
428 // needed to read it again. For data buffers provided by the
429 // program we don't; so don't delete it's data.
430 if ( sample->is_file() ) sample->free_data();
432 if ( !testForALError("buffer add data") ) {
433 sample->set_buffer(buffer);
434 _buffers[sample_name] = refUint(buffer);
439 buffer = sample->get_buffer();
445 void SGSoundMgr::release_buffer(SGSoundSample *sample)
447 string sample_name = sample->get_sample_name();
448 buffer_map_iterator buffer_it = _buffers.find( sample_name );
449 if ( buffer_it == _buffers.end() ) {
450 // buffer was not found
454 sample->no_valid_buffer();
455 buffer_it->second.refctr--;
456 if (buffer_it->second.refctr == 0) {
457 ALuint buffer = buffer_it->second.id;
458 alDeleteBuffers(1, &buffer);
459 _buffers.erase( buffer_it );
460 testForALError("release buffer");
464 void SGSoundMgr::update_pos_and_orientation() {
465 // cartesian position of the listener
466 _absolute_pos = SGVec3d::fromGeod( _position_geod );
469 * Description: ORIENTATION is a pair of 3-tuples representing the
470 * 'at' direction vector and 'up' direction of the Object in
471 * Cartesian space. AL expects two vectors that are orthogonal to
472 * each other. These vectors are not expected to be normalized. If
473 * one or more vectors have zero length, implementation behavior
474 * is undefined. If the two vectors are linearly dependent,
475 * 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];
488 bool SGSoundMgr::load(string &samplepath, void **dbuf, int *fmt,
489 size_t *sz, int *frq )
491 if ( !_working ) return false;
498 #if defined(ALUT_API_MAJOR_VERSION) && ALUT_API_MAJOR_VERSION >= 1
500 data = alutLoadMemoryFromFile(samplepath.c_str(), &format, &size, &freqf );
501 freq = (ALsizei)freqf;
503 int error = alutGetError();
504 string msg = "Failed to load wav file: ";
505 msg.append(alutGetErrorString(error));
506 throw sg_io_exception(msg.c_str(), sg_location(samplepath));
511 ALbyte *fname = (ALbyte *)samplepath.c_str();
512 # if defined (__APPLE__)
513 alutLoadWAVFile( fname, &format, &data, &size, &freq );
516 alutLoadWAVFile( fname, &format, &data, &size, &freq, &loop );
518 ALenum error = alGetError();
519 if ( error != AL_NO_ERROR ) {
520 string msg = "Failed to load wav file: ";
521 msg.append(alGetString(error));
522 throw sg_io_exception(msg.c_str(), sg_location(samplepath));
527 *dbuf = (void *)data;
536 bool SGSoundMgr::testForError(void *p, string s)
539 SG_LOG( SG_GENERAL, SG_ALERT, "Error: " << s);
546 bool SGSoundMgr::testForALError(string s)
548 ALenum error = alGetError();
549 if (error != AL_NO_ERROR) {
550 SG_LOG( SG_GENERAL, SG_ALERT, "AL Error (sound manager): "
551 << alGetString(error) << " at " << s);
557 bool SGSoundMgr::testForALCError(string s)
560 error = alcGetError(_device);
561 if (error != ALC_NO_ERROR) {
562 SG_LOG( SG_GENERAL, SG_ALERT, "ALC Error (sound manager): "
563 << alcGetString(_device, error) << " at "
570 bool SGSoundMgr::testForALUTError(string s)
572 #if defined(ALUT_API_MAJOR_VERSION) && ALUT_API_MAJOR_VERSION >= 1
574 error = alutGetError ();
575 if (error != ALUT_ERROR_NO_ERROR) {
576 SG_LOG( SG_GENERAL, SG_ALERT, "ALUT Error (sound manager): "
577 << alutGetErrorString(error) << " at "