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 _velocity(SGVec3d::zeros()),
68 _orientation(SGQuatd::zeros()),
71 #if defined(ALUT_API_MAJOR_VERSION) && ALUT_API_MAJOR_VERSION >= 1
72 if (_alut_init == 0) {
73 if ( !alutInitWithoutContext(NULL, NULL) ) {
74 testForALUTError("alut initialization");
84 SGSoundMgr::~SGSoundMgr() {
87 #if defined(ALUT_API_MAJOR_VERSION) && ALUT_API_MAJOR_VERSION >= 1
89 if (_alut_init == 0) {
95 // initialize the sound manager
96 void SGSoundMgr::init() {
98 SG_LOG( SG_GENERAL, SG_INFO, "Initializing OpenAL sound manager" );
100 ALCdevice *device = alcOpenDevice(_devname);
101 if ( testForError(device, "No default audio device available.") ) {
105 ALCcontext *context = alcCreateContext(device, NULL);
106 if ( testForError(context, "Unable to create a valid context.") ) {
107 alcCloseDevice (device);
111 if ( !alcMakeContextCurrent(context) ) {
112 testForALCError("context initialization");
113 alcDestroyContext (context);
114 alcCloseDevice (device);
118 if (_context != NULL)
119 SG_LOG(SG_GENERAL, SG_ALERT, "context is already assigned");
123 _at_up_vec[0] = 0.0; _at_up_vec[1] = 0.0; _at_up_vec[2] = -1.0;
124 _at_up_vec[3] = 0.0; _at_up_vec[4] = 1.0; _at_up_vec[5] = 0.0;
126 alListenerf( AL_GAIN, 0.0f );
127 alListenerfv( AL_ORIENTATION, _at_up_vec );
128 alListenerfv( AL_POSITION, SGVec3f::zeros().data() );
129 alListenerfv( AL_VELOCITY, SGVec3f::zeros().data() );
131 alDopplerFactor(1.0);
132 alDopplerVelocity(340.3); // speed of sound in meters per second.
134 if ( alIsExtensionPresent((const ALchar*)"EXT_exponent_distance") ) {
135 alDistanceModel(AL_EXPONENT_DISTANCE);
137 alDistanceModel(AL_INVERSE_DISTANCE);
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 ) {
247 sample_group_map_iterator sample_grp_current = _sample_groups.begin();
248 sample_group_map_iterator sample_grp_end = _sample_groups.end();
249 for ( ; sample_grp_current != sample_grp_end; ++sample_grp_current ) {
250 SGSampleGroup *sgrp = sample_grp_current->second;
256 if (isNaN(_at_up_vec)) printf("NaN in listener orientation\n");
257 if (isNaN(toVec3f(_absolute_pos).data())) printf("NaN in listener position\n");
258 if (isNaN(_velocity.data())) printf("NaN in listener velocity\n");
260 update_pos_and_orientation();
261 alListenerf( AL_GAIN, _volume );
262 alListenerfv( AL_ORIENTATION, _at_up_vec );
263 // alListenerfv( AL_POSITION, toVec3f(_absolute_pos).data() );
264 alListenerfv( AL_VELOCITY, _velocity.data() );
265 // alDopplerVelocity(340.3); // TODO: altitude dependent
266 testForALError("update");
272 // add a sample group, return true if successful
273 bool SGSoundMgr::add( SGSampleGroup *sgrp, const string& refname )
275 sample_group_map_iterator sample_grp_it = _sample_groups.find( refname );
276 if ( sample_grp_it != _sample_groups.end() ) {
277 // sample group already exists
281 if (_active) sgrp->activate();
282 _sample_groups[refname] = sgrp;
288 // remove a sound effect, return true if successful
289 bool SGSoundMgr::remove( const string &refname )
291 sample_group_map_iterator sample_grp_it = _sample_groups.find( refname );
292 if ( sample_grp_it == _sample_groups.end() ) {
293 // sample group was not found.
297 _sample_groups.erase( sample_grp_it );
303 // return true of the specified sound exists in the sound manager system
304 bool SGSoundMgr::exists( const string &refname ) {
305 sample_group_map_iterator sample_grp_it = _sample_groups.find( refname );
306 if ( sample_grp_it == _sample_groups.end() ) {
307 // sample group was not found.
315 // return a pointer to the SGSampleGroup if the specified sound exists
316 // in the sound manager system, otherwise return NULL
317 SGSampleGroup *SGSoundMgr::find( const string &refname, bool create ) {
318 sample_group_map_iterator sample_grp_it = _sample_groups.find( refname );
319 if ( sample_grp_it == _sample_groups.end() ) {
320 // sample group was not found.
322 SGSampleGroup* sgrp = new SGSampleGroup(this, refname);
329 return sample_grp_it->second;
333 void SGSoundMgr::set_volume( float v )
336 if (_volume > 1.0) _volume = 1.0;
337 if (_volume < 0.0) _volume = 0.0;
341 // Get an unused source id
343 // The Sound Manager should keep track of the sources in use, the distance
344 // of these sources to the listener and the volume (also based on audio cone
345 // and hence orientation) of the sources.
347 // The Sound Manager is (and should be) the only one knowing about source
348 // management. Sources further away should be suspendped to free resources for
349 // newly added sounds close by.
350 unsigned int SGSoundMgr::request_source()
352 unsigned int source = NO_SOURCE;
354 if (_free_sources.size() > 0) {
355 source = _free_sources.back();
356 _free_sources.pop_back();
357 _sources_in_use.push_back(source);
360 SG_LOG( SG_GENERAL, SG_INFO, "No more free sources available\n");
365 // Free up a source id for further use
366 void SGSoundMgr::release_source( unsigned int source )
368 vector<ALuint>::iterator it;
370 it = std::find(_sources_in_use.begin(), _sources_in_use.end(), source);
371 if ( it != _sources_in_use.end() ) {
374 alGetSourcei( source, AL_SOURCE_STATE, &result );
375 if ( result == AL_PLAYING )
376 alSourceStop( source );
377 testForALError("release source");
379 alSourcei( source, AL_BUFFER, 0 );
380 _free_sources.push_back( source );
381 _sources_in_use.erase( it );
385 unsigned int SGSoundMgr::request_buffer(SGSoundSample *sample)
387 ALuint buffer = NO_BUFFER;
389 if ( !sample->is_valid_buffer() ) {
390 // sample was not yet loaded or removed again
391 string sample_name = sample->get_sample_name();
393 // see if the sample name is already cached
394 buffer_map_iterator buffer_it = _buffers.find( sample_name );
395 if ( buffer_it != _buffers.end() ) {
396 buffer_it->second.refctr++;
397 buffer = buffer_it->second.id;
398 sample->set_buffer( buffer );
402 // sample name was not found in the buffer cache.
403 if ( sample->is_file() ) {
408 load(sample_name, &data, &format, &size, &freq);
409 sample->set_data( &data );
410 sample->set_frequency( freq );
411 sample->set_format( format );
412 sample->set_size( size );
415 // create an OpenAL buffer handle
416 alGenBuffers(1, &buffer);
417 if ( !testForALError("generate buffer") ) {
418 // Copy data to the internal OpenAL buffer
420 const ALvoid *data = sample->get_data();
421 ALenum format = sample->get_format();
422 ALsizei size = sample->get_size();
423 ALsizei freq = sample->get_frequency();
424 alBufferData( buffer, format, data, size, freq );
426 // If this sample was read from a file we have all the information
427 // needed to read it again. For data buffers provided by the
428 // program we don't; so don't delete it's data.
429 if ( sample->is_file() ) sample->free_data();
431 if ( !testForALError("buffer add data") ) {
432 sample->set_buffer(buffer);
433 _buffers[sample_name] = refUint(buffer);
438 buffer = sample->get_buffer();
444 void SGSoundMgr::release_buffer(SGSoundSample *sample)
446 string sample_name = sample->get_sample_name();
447 buffer_map_iterator buffer_it = _buffers.find( sample_name );
448 if ( buffer_it == _buffers.end() ) {
449 // buffer was not found
453 sample->no_valid_buffer();
454 buffer_it->second.refctr--;
455 if (buffer_it->second.refctr == 0) {
456 ALuint buffer = buffer_it->second.id;
457 alDeleteBuffers(1, &buffer);
458 _buffers.erase( buffer_it );
459 testForALError("release buffer");
463 void SGSoundMgr::update_pos_and_orientation() {
465 * Description: ORIENTATION is a pair of 3-tuples representing the
466 * 'at' direction vector and 'up' direction of the Object in
467 * Cartesian space. AL expects two vectors that are orthogonal to
468 * each other. These vectors are not expected to be normalized. If
469 * one or more vectors have zero length, implementation behavior
470 * is undefined. If the two vectors are linearly dependent,
471 * behavior is undefined.
472 * This is in the same coordinate system as OpenGL; y=up, z=back, x=right.
474 SGVec3d sgv_at = _orientation.backTransform(-SGVec3d::e3());
475 SGVec3d sgv_up = _orientation.backTransform(SGVec3d::e2());
476 _at_up_vec[0] = sgv_at[0];
477 _at_up_vec[1] = sgv_at[1];
478 _at_up_vec[2] = sgv_at[2];
479 _at_up_vec[3] = sgv_up[0];
480 _at_up_vec[4] = sgv_up[1];
481 _at_up_vec[5] = sgv_up[2];
484 bool SGSoundMgr::load(string &samplepath, void **dbuf, int *fmt,
485 size_t *sz, int *frq )
487 if ( !_working ) return false;
494 #if defined(ALUT_API_MAJOR_VERSION) && ALUT_API_MAJOR_VERSION >= 1
496 data = alutLoadMemoryFromFile(samplepath.c_str(), &format, &size, &freqf );
497 freq = (ALsizei)freqf;
499 int error = alutGetError();
500 string msg = "Failed to load wav file: ";
501 msg.append(alutGetErrorString(error));
502 throw sg_io_exception(msg.c_str(), sg_location(samplepath));
507 ALbyte *fname = (ALbyte *)samplepath.c_str();
508 # if defined (__APPLE__)
509 alutLoadWAVFile( fname, &format, &data, &size, &freq );
512 alutLoadWAVFile( fname, &format, &data, &size, &freq, &loop );
514 ALenum error = alGetError();
515 if ( error != AL_NO_ERROR ) {
516 string msg = "Failed to load wav file: ";
517 msg.append(alGetString(error));
518 throw sg_io_exception(msg.c_str(), sg_location(samplepath));
523 *dbuf = (void *)data;
532 bool SGSoundMgr::testForError(void *p, string s)
535 SG_LOG( SG_GENERAL, SG_ALERT, "Error: " << s);
542 bool SGSoundMgr::testForALError(string s)
544 ALenum error = alGetError();
545 if (error != AL_NO_ERROR) {
546 SG_LOG( SG_GENERAL, SG_ALERT, "AL Error (sound manager): "
547 << alGetString(error) << " at " << s);
553 bool SGSoundMgr::testForALCError(string s)
556 error = alcGetError(_device);
557 if (error != ALC_NO_ERROR) {
558 SG_LOG( SG_GENERAL, SG_ALERT, "ALC Error (sound manager): "
559 << alcGetString(_device, error) << " at "
566 bool SGSoundMgr::testForALUTError(string s)
568 #if defined(ALUT_API_MAJOR_VERSION) && ALUT_API_MAJOR_VERSION >= 1
570 error = alutGetError ();
571 if (error != ALUT_ERROR_NO_ERROR) {
572 SG_LOG( SG_GENERAL, SG_ALERT, "ALUT Error (sound manager): "
573 << alutGetErrorString(error) << " at "