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.
8 // Copyright (C) 2001 Curtis L. Olson - http://www.flightgear.org/~curt
10 // This program is free software; you can redistribute it and/or
11 // modify it under the terms of the GNU General Public License as
12 // published by the Free Software Foundation; either version 2 of the
13 // License, or (at your option) any later version.
15 // This program is distributed in the hope that it will be useful, but
16 // WITHOUT ANY WARRANTY; without even the implied warranty of
17 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 // General Public License for more details.
20 // You should have received a copy of the GNU General Public License
21 // along with this program; if not, write to the Free Software Foundation,
22 // Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
27 # include <simgear_config.h>
30 #if defined( __APPLE__ )
31 # include <OpenAL/alut.h>
39 #include "soundmgr_openal.hxx"
41 #include <simgear/structure/exception.hxx>
42 #include <simgear/debug/logstream.hxx>
43 #include <simgear/misc/sg_path.hxx>
44 #include <simgear/math/SGMath.hxx>
47 #define MAX_SOURCES 128
53 int SGSoundMgr::_alut_init = 0;
56 SGSoundMgr::SGSoundMgr() :
62 _position(SGVec3d::zeros()),
63 _velocity(SGVec3d::zeros()),
64 _orientation(SGQuatd::zeros()),
67 #if defined(ALUT_API_MAJOR_VERSION) && ALUT_API_MAJOR_VERSION >= 1
68 if (_alut_init == 0) {
69 if ( !alutInitWithoutContext(NULL, NULL) ) {
70 testForALUTError("alut initialization");
81 SGSoundMgr::~SGSoundMgr() {
84 #if defined(ALUT_API_MAJOR_VERSION) && ALUT_API_MAJOR_VERSION >= 1
86 if (_alut_init == 0) {
92 // initialize the sound manager
93 void SGSoundMgr::init() {
95 SG_LOG( SG_GENERAL, SG_INFO, "Initializing OpenAL sound manager" );
97 ALCdevice *device = alcOpenDevice(_devname);
98 if ( testForError(device, "No default audio device available.") ) {
102 ALCcontext *context = alcCreateContext(device, NULL);
103 if ( testForError(context, "Unable to create a valid context.") ) {
104 alcCloseDevice (device);
108 if ( !alcMakeContextCurrent(context) ) {
109 testForALCError("context initialization");
110 alcDestroyContext (context);
111 alcCloseDevice (device);
118 _at_up_vec[0] = 0.0; _at_up_vec[1] = 0.0; _at_up_vec[2] = -1.0;
119 _at_up_vec[3] = 0.0; _at_up_vec[4] = 1.0; _at_up_vec[5] = 0.0;
121 alListenerf( AL_GAIN, 0.2f );
122 alListenerfv( AL_ORIENTATION, _at_up_vec );
123 alListenerfv( AL_POSITION, SGVec3f::zeros().data() );
124 alListenerfv( AL_VELOCITY, SGVec3f::zeros().data() );
126 alDopplerFactor(1.0);
127 alDopplerVelocity(340.3); // speed of sound in meters per second.
129 if ( alIsExtensionPresent((const ALchar*)"EXT_exponent_distance") ) {
130 alDistanceModel(AL_EXPONENT_DISTANCE);
132 alDistanceModel(AL_INVERSE_DISTANCE);
135 testForALError("listener initialization");
137 // get a free source one at a time
138 // if an error is returned no more (hardware) sources are available
139 for (unsigned int i=0; i<MAX_SOURCES; i++) {
144 alGenSources(1, &source);
145 error = alGetError();
146 if ( error == AL_NO_ERROR ) {
147 _free_sources.push_back( source );
152 if (_free_sources.size() == 0) {
153 SG_LOG(SG_GENERAL, SG_ALERT, "Unable to grab any OpenAL sources!");
157 // suspend the sound manager
158 void SGSoundMgr::stop() {
162 // clear any OpenAL buffers before shutting down
163 buffer_map_iterator buffers_current;
164 while(_buffers.size()){
165 buffers_current = _buffers.begin();
166 refUint ref = buffers_current->second;
167 ALuint buffer = ref.id;
168 alDeleteBuffers(1, &buffer);
169 _buffers.erase( buffers_current );
172 _context = alcGetCurrentContext();
173 _device = alcGetContextsDevice(_context);
174 alcMakeContextCurrent(NULL);
175 alcDestroyContext(_context);
176 alcCloseDevice(_device);
180 void SGSoundMgr::suspend() {
182 sample_group_map_iterator sample_grp_current = _sample_groups.begin();
183 sample_group_map_iterator sample_grp_end = _sample_groups.end();
184 for ( ; sample_grp_current != sample_grp_end; ++sample_grp_current ) {
185 SGSampleGroup *sgrp = sample_grp_current->second;
192 void SGSoundMgr::bind ()
194 _free_sources.clear();
195 _free_sources.reserve( MAX_SOURCES );
196 _sources_in_use.clear();
197 _sources_in_use.reserve( MAX_SOURCES );
201 void SGSoundMgr::unbind ()
203 _sample_groups.clear();
205 // delete free sources
206 for (unsigned int i=0; i<_free_sources.size(); i++) {
207 ALuint source = _free_sources.at( i );
208 alDeleteSources( 1 , &source );
211 _free_sources.clear();
212 _sources_in_use.clear();
215 void SGSoundMgr::update( double dt )
217 // nothing to do in the regular update, everything is done on the following
222 // run the audio scheduler
223 void SGSoundMgr::update_late( double dt ) {
225 alcSuspendContext(_context);
227 sample_group_map_iterator sample_grp_current = _sample_groups.begin();
228 sample_group_map_iterator sample_grp_end = _sample_groups.end();
229 for ( ; sample_grp_current != sample_grp_end; ++sample_grp_current ) {
230 SGSampleGroup *sgrp = sample_grp_current->second;
235 alListenerf( AL_GAIN, _volume );
236 alListenerfv( AL_ORIENTATION, _at_up_vec );
237 alListenerfv( AL_POSITION, toVec3f(_position).data() );
238 alListenerfv( AL_VELOCITY, toVec3f(_velocity).data() );
239 // alDopplerVelocity(340.3); // TODO: altitude dependent
240 testForALError("update");
243 alcProcessContext(_context);
249 SGSoundMgr::resume ()
252 sample_group_map_iterator sample_grp_current = _sample_groups.begin();
253 sample_group_map_iterator sample_grp_end = _sample_groups.end();
254 for ( ; sample_grp_current != sample_grp_end; ++sample_grp_current ) {
255 SGSampleGroup *sgrp = sample_grp_current->second;
262 // add a sampel group, return true if successful
263 bool SGSoundMgr::add( SGSampleGroup *sgrp, const string& refname )
265 sample_group_map_iterator sample_grp_it = _sample_groups.find( refname );
266 if ( sample_grp_it != _sample_groups.end() ) {
267 // sample group already exists
271 _sample_groups[refname] = sgrp;
277 // remove a sound effect, return true if successful
278 bool SGSoundMgr::remove( const string &refname )
280 sample_group_map_iterator sample_grp_it = _sample_groups.find( refname );
281 if ( sample_grp_it == _sample_groups.end() ) {
282 // sample group was not found.
286 _sample_groups.erase( refname );
292 // return true of the specified sound exists in the sound manager system
293 bool SGSoundMgr::exists( 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.
304 // return a pointer to the SGSampleGroup if the specified sound exists
305 // in the sound manager system, otherwise return NULL
306 SGSampleGroup *SGSoundMgr::find( const string &refname, bool create ) {
307 sample_group_map_iterator sample_grp_it = _sample_groups.find( refname );
308 if ( sample_grp_it == _sample_groups.end() ) {
309 // sample group was not found.
311 SGSampleGroup* sgrp = new SGSampleGroup(this, refname);
318 return sample_grp_it->second;
322 void SGSoundMgr::set_volume( float v )
325 if (_volume > 1.0) _volume = 1.0;
326 if (_volume < 0.0) _volume = 0.0;
331 * set the orientation of the listener (in opengl coordinates)
333 * Description: ORIENTATION is a pair of 3-tuples representing the
334 * 'at' direction vector and 'up' direction of the Object in
335 * Cartesian space. AL expects two vectors that are orthogonal to
336 * each other. These vectors are not expected to be normalized. If
337 * one or more vectors have zero length, implementation behavior
338 * is undefined. If the two vectors are linearly dependent,
339 * behavior is undefined.
341 void SGSoundMgr::set_orientation( SGQuatd ori )
345 SGVec3d sgv_up = ori.rotate(SGVec3d::e2());
346 SGVec3d sgv_at = ori.rotate(SGVec3d::e3());
347 _at_up_vec[0] = sgv_at[0];
348 _at_up_vec[1] = sgv_at[1];
349 _at_up_vec[2] = sgv_at[2];
350 _at_up_vec[3] = sgv_up[0];
351 _at_up_vec[4] = sgv_up[1];
352 _at_up_vec[5] = sgv_up[2];
356 // Get an unused source id
358 // The Sound Manager should keep track of the sources in use, the distance
359 // of these sources to the listener and the volume (also based on audio cone
360 // and hence orientation) of the sources.
362 // The Sound Manager is (and should be) the only one knowing about source
363 // management. Sources further away should be suspendped to free resources for
364 // newly added sounds close by.
365 unsigned int SGSoundMgr::request_source()
367 unsigned int source = NO_SOURCE;
369 if (_free_sources.size() > 0) {
370 source = _free_sources.back();
371 _free_sources.pop_back();
372 _sources_in_use.push_back(source);
378 // Free up a source id for further use
379 void SGSoundMgr::release_source( unsigned int source )
381 vector<ALuint>::iterator it;
383 it = std::find(_sources_in_use.begin(), _sources_in_use.end(), source);
384 if ( it != _sources_in_use.end() ) {
387 alGetSourcei( source, AL_SOURCE_STATE, &result );
388 if ( result == AL_PLAYING )
389 alSourceStop( source );
390 testForALError("release source");
392 _free_sources.push_back(source);
393 _sources_in_use.erase(it, it+1);
397 unsigned int SGSoundMgr::request_buffer(SGSoundSample *sample)
399 ALuint buffer = NO_BUFFER;
401 if ( !sample->is_valid_buffer() ) {
402 // sample was not yet loaded or removed again
403 string sample_name = sample->get_sample_name();
405 // see if the sample name is already cached
406 buffer_map_iterator buffer_it = _buffers.find( sample_name );
407 if ( buffer_it != _buffers.end() ) {
408 buffer_it->second.refctr++;
409 buffer = buffer_it->second.id;
410 sample->set_buffer( buffer );
414 // sample name was not found in the buffer cache.
415 if ( sample->is_file() ) {
420 load(sample_name, &data, &format, &size, &freq);
421 sample->set_data( (unsigned char *)data );
422 sample->set_frequency( freq );
423 sample->set_format( format );
424 sample->set_size( size );
427 // create an OpenAL buffer handle
428 alGenBuffers(1, &buffer);
429 if ( !testForALError("generate buffer") ) {
430 // Copy data to the internal OpenAL buffer
432 const ALvoid *data = sample->get_data();
433 ALenum format = sample->get_format();
434 ALsizei size = sample->get_size();
435 ALsizei freq = sample->get_frequency();
436 alBufferData( buffer, format, data, size, freq );
439 if ( !testForALError("buffer add data") ) {
440 sample->set_buffer(buffer);
441 _buffers[sample_name] = refUint(buffer);
446 buffer = sample->get_buffer();
451 void SGSoundMgr::release_buffer(SGSoundSample *sample)
453 string sample_name = sample->get_sample_name();
455 buffer_map_iterator buffer_it = _buffers.find( sample_name );
456 if ( buffer_it == _buffers.end() ) {
457 // buffer was not found
461 sample->no_valid_buffer();
462 buffer_it->second.refctr--;
463 if (buffer_it->second.refctr == 0) {
464 ALuint buffer = buffer_it->second.id;
465 _buffers.erase( buffer_it );
466 alDeleteBuffers(1, &buffer);
467 testForALError("release buffer");
471 bool SGSoundMgr::load(string &samplepath, void **dbuf, int *fmt,
472 unsigned int *sz, int *frq )
474 ALenum format = (ALenum)*fmt;
475 ALsizei size = (ALsizei)*sz;
476 ALsizei freq = (ALsizei)*frq;
479 #if defined(ALUT_API_MAJOR_VERSION) && ALUT_API_MAJOR_VERSION >= 1
481 data = alutLoadMemoryFromFile(samplepath.c_str(), &format, &size, &freqf );
482 freq = (ALsizei)freqf;
484 int error = alutGetError();
485 string msg = "Failed to load wav file: ";
486 msg.append(alutGetErrorString(error));
487 throw sg_io_exception(msg.c_str(), sg_location(samplepath));
492 ALbyte *fname = (ALbyte *)samplepath.c_str();
493 # if defined (__APPLE__)
494 alutLoadWAVFile( fname, &format, &data, &size, &freq );
497 alutLoadWAVFile( fname, &format, &data, &size, &freq, &loop );
499 ALenum error = alutGetError();
500 if ( error != ALUT_ERROR_NO_ERROR ) {
501 string msg = "Failed to load wav file: ";
502 msg.append(alutGetErrorString(error));
503 throw sg_io_exception(msg.c_str(), sg_location(samplepath));
508 *dbuf = (void *)data;
510 *sz = (unsigned int)size;
517 bool SGSoundMgr::testForError(void *p, string s)
520 SG_LOG( SG_GENERAL, SG_ALERT, "Error: " << s);
527 bool SGSoundMgr::testForALError(string s)
529 ALenum error = alGetError();
530 if (error != AL_NO_ERROR) {
531 SG_LOG( SG_GENERAL, SG_ALERT, "AL Error (sound manager): "
532 << alGetString(error) << " at " << s);
538 bool SGSoundMgr::testForALCError(string s)
541 error = alcGetError(_device);
542 if (error != ALC_NO_ERROR) {
543 SG_LOG( SG_GENERAL, SG_ALERT, "ALC Error (sound manager): "
544 << alcGetString(_device, error) << " at "
551 bool SGSoundMgr::testForALUTError(string s)
553 #if defined(ALUT_API_MAJOR_VERSION) && ALUT_API_MAJOR_VERSION >= 1
555 error = alutGetError ();
556 if (error != ALUT_ERROR_NO_ERROR) {
557 SG_LOG( SG_GENERAL, SG_ALERT, "ALUT Error (sound manager): "
558 << alutGetErrorString(error) << " at "