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 _position_offs(SGVec3d::zeros()),
68 _absolute_pos(SGVec3d::zeros()),
69 _velocity(SGVec3d::zeros()),
70 _orientation(SGQuatd::zeros()),
71 _orient_offs(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() {
101 SG_LOG( SG_GENERAL, SG_INFO, "Initializing OpenAL sound manager" );
103 ALCdevice *device = alcOpenDevice(_devname);
104 if ( testForError(device, "No default audio device available.") ) {
108 ALCcontext *context = alcCreateContext(device, NULL);
109 if ( testForError(context, "Unable to create a valid context.") ) {
110 alcCloseDevice (device);
114 if ( !alcMakeContextCurrent(context) ) {
115 testForALCError("context initialization");
116 alcDestroyContext (context);
117 alcCloseDevice (device);
121 if (_context != NULL)
122 SG_LOG(SG_GENERAL, SG_ALERT, "context is already assigned");
126 _at_up_vec[0] = 0.0; _at_up_vec[1] = 0.0; _at_up_vec[2] = -1.0;
127 _at_up_vec[3] = 0.0; _at_up_vec[4] = 1.0; _at_up_vec[5] = 0.0;
129 alListenerf( AL_GAIN, 0.0f );
130 alListenerfv( AL_ORIENTATION, _at_up_vec );
131 alListenerfv( AL_POSITION, SGVec3f::zeros().data() );
132 alListenerfv( AL_VELOCITY, SGVec3f::zeros().data() );
134 alDopplerFactor(1.0);
135 alDopplerVelocity(340.3); // speed of sound in meters per second.
137 if ( alIsExtensionPresent((const ALchar*)"EXT_exponent_distance") ) {
138 alDistanceModel(AL_EXPONENT_DISTANCE);
140 alDistanceModel(AL_INVERSE_DISTANCE);
143 testForALError("listener initialization");
145 // get a free source one at a time
146 // if an error is returned no more (hardware) sources are available
147 for (unsigned int i=0; i<MAX_SOURCES; i++) {
152 alGenSources(1, &source);
153 error = alGetError();
154 if ( error == AL_NO_ERROR ) {
155 _free_sources.push_back( source );
160 if (_free_sources.size() == 0) {
161 SG_LOG(SG_GENERAL, SG_ALERT, "Unable to grab any OpenAL sources!");
165 void SGSoundMgr::activate() {
168 sample_group_map_iterator sample_grp_current = _sample_groups.begin();
169 sample_group_map_iterator sample_grp_end = _sample_groups.end();
170 for ( ; sample_grp_current != sample_grp_end; ++sample_grp_current ) {
171 SGSampleGroup *sgrp = sample_grp_current->second;
177 // stop the sound manager
178 void SGSoundMgr::stop() {
183 // clear any OpenAL buffers before shutting down
184 buffer_map_iterator buffers_current = _buffers.begin();
185 buffer_map_iterator buffers_end = _buffers.end();
186 for ( ; buffers_current != buffers_end; ++buffers_current ) {
187 refUint ref = buffers_current->second;
188 ALuint buffer = ref.id;
189 alDeleteBuffers(1, &buffer);
193 _context = alcGetCurrentContext();
194 _device = alcGetContextsDevice(_context);
195 alcDestroyContext(_context);
196 alcCloseDevice(_device);
200 void SGSoundMgr::suspend() {
202 sample_group_map_iterator sample_grp_current = _sample_groups.begin();
203 sample_group_map_iterator sample_grp_end = _sample_groups.end();
204 for ( ; sample_grp_current != sample_grp_end; ++sample_grp_current ) {
205 SGSampleGroup *sgrp = sample_grp_current->second;
212 void SGSoundMgr::resume() {
214 sample_group_map_iterator sample_grp_current = _sample_groups.begin();
215 sample_group_map_iterator sample_grp_end = _sample_groups.end();
216 for ( ; sample_grp_current != sample_grp_end; ++sample_grp_current ) {
217 SGSampleGroup *sgrp = sample_grp_current->second;
224 void SGSoundMgr::bind ()
226 _free_sources.clear();
227 _free_sources.reserve( MAX_SOURCES );
228 _sources_in_use.clear();
229 _sources_in_use.reserve( MAX_SOURCES );
233 void SGSoundMgr::unbind ()
235 _sample_groups.clear();
237 // delete free sources
238 for (unsigned int i=0; i<_free_sources.size(); i++) {
239 ALuint source = _free_sources[i];
240 alDeleteSources( 1 , &source );
243 _free_sources.clear();
244 _sources_in_use.clear();
247 // run the audio scheduler
248 void SGSoundMgr::update( double dt ) {
250 sample_group_map_iterator sample_grp_current = _sample_groups.begin();
251 sample_group_map_iterator sample_grp_end = _sample_groups.end();
252 for ( ; sample_grp_current != sample_grp_end; ++sample_grp_current ) {
253 SGSampleGroup *sgrp = sample_grp_current->second;
258 if (isNaN(_at_up_vec)) printf("NaN in listener orientation\n");
259 if (isNaN(toVec3f(_absolute_pos).data())) printf("NaN in listener position\n");
260 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 // The rotation rotating from the earth centerd frame to
466 // the horizontal local frame
467 SGQuatd hlOr = SGQuatd::fromLonLat( _position_geod );
469 // Compute the listeners orientation and position
470 // wrt the earth centered frame - that is global coorinates
471 SGQuatd lc2body = hlOr*_orientation;
473 // cartesian position of the listener
474 SGVec3d position = SGVec3d::fromGeod( _position_geod );
476 // This is rotates the x-forward, y-right, z-down coordinate system where
477 // simulation runs into the OpenGL camera system with x-right, y-up, z-back.
478 SGQuatd q(-0.5, -0.5, 0.5, 0.5);
480 _absolute_pos = position + (lc2body*q).backTransform( _position_offs );
483 * Description: ORIENTATION is a pair of 3-tuples representing the
484 * 'at' direction vector and 'up' direction of the Object in
485 * Cartesian space. AL expects two vectors that are orthogonal to
486 * each other. These vectors are not expected to be normalized. If
487 * one or more vectors have zero length, implementation behavior
488 * is undefined. If the two vectors are linearly dependent,
489 * behavior is undefined.
490 * This is in the same coordinate system as OpenGL; y=up, z=back, x=right.
492 SGQuatd lViewOrientation = lc2body*_orient_offs*q;
493 SGVec3d sgv_up = lViewOrientation.rotate(SGVec3d::e2());
494 SGVec3d sgv_at = lViewOrientation.rotate(SGVec3d::e3());
495 _at_up_vec[0] = sgv_at[0];
496 _at_up_vec[1] = sgv_at[1];
497 _at_up_vec[2] = sgv_at[2];
498 _at_up_vec[3] = sgv_up[0];
499 _at_up_vec[4] = sgv_up[1];
500 _at_up_vec[5] = sgv_up[2];
503 bool SGSoundMgr::load(string &samplepath, void **dbuf, int *fmt,
504 size_t *sz, int *frq )
506 if ( !_working ) return false;
513 #if defined(ALUT_API_MAJOR_VERSION) && ALUT_API_MAJOR_VERSION >= 1
515 data = alutLoadMemoryFromFile(samplepath.c_str(), &format, &size, &freqf );
516 freq = (ALsizei)freqf;
518 int error = alutGetError();
519 string msg = "Failed to load wav file: ";
520 msg.append(alutGetErrorString(error));
521 throw sg_io_exception(msg.c_str(), sg_location(samplepath));
526 ALbyte *fname = (ALbyte *)samplepath.c_str();
527 # if defined (__APPLE__)
528 alutLoadWAVFile( fname, &format, &data, &size, &freq );
531 alutLoadWAVFile( fname, &format, &data, &size, &freq, &loop );
533 ALenum error = alGetError();
534 if ( error != AL_NO_ERROR ) {
535 string msg = "Failed to load wav file: ";
536 msg.append(alGetString(error));
537 throw sg_io_exception(msg.c_str(), sg_location(samplepath));
542 *dbuf = (void *)data;
551 bool SGSoundMgr::testForError(void *p, string s)
554 SG_LOG( SG_GENERAL, SG_ALERT, "Error: " << s);
561 bool SGSoundMgr::testForALError(string s)
563 ALenum error = alGetError();
564 if (error != AL_NO_ERROR) {
565 SG_LOG( SG_GENERAL, SG_ALERT, "AL Error (sound manager): "
566 << alGetString(error) << " at " << s);
572 bool SGSoundMgr::testForALCError(string s)
575 error = alcGetError(_device);
576 if (error != ALC_NO_ERROR) {
577 SG_LOG( SG_GENERAL, SG_ALERT, "ALC Error (sound manager): "
578 << alcGetString(_device, error) << " at "
585 bool SGSoundMgr::testForALUTError(string s)
587 #if defined(ALUT_API_MAJOR_VERSION) && ALUT_API_MAJOR_VERSION >= 1
589 error = alutGetError ();
590 if (error != ALUT_ERROR_NO_ERROR) {
591 SG_LOG( SG_GENERAL, SG_ALERT, "ALUT Error (sound manager): "
592 << alutGetErrorString(error) << " at "