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");
80 SGSoundMgr::~SGSoundMgr() {
83 #if defined(ALUT_API_MAJOR_VERSION) && ALUT_API_MAJOR_VERSION >= 1
85 if (_alut_init == 0) {
91 // initialize the sound manager
92 void SGSoundMgr::init() {
94 SG_LOG( SG_GENERAL, SG_INFO, "Initializing OpenAL sound manager" );
96 ALCdevice *device = alcOpenDevice(_devname);
97 if ( testForError(device, "No default audio device available.") ) {
101 ALCcontext *context = alcCreateContext(device, NULL);
102 if ( testForError(context, "Unable to create a valid context.") ) {
103 alcCloseDevice (device);
107 if ( !alcMakeContextCurrent(context) ) {
108 testForALCError("context initialization");
109 alcDestroyContext (context);
110 alcCloseDevice (device);
117 _at_up_vec[0] = 0.0; _at_up_vec[1] = 0.0; _at_up_vec[2] = -1.0;
118 _at_up_vec[3] = 0.0; _at_up_vec[4] = 1.0; _at_up_vec[5] = 0.0;
120 alListenerf( AL_GAIN, 0.2f );
121 alListenerfv( AL_ORIENTATION, _at_up_vec );
122 alListenerfv( AL_POSITION, SGVec3f::zeros().data() );
123 alListenerfv( AL_VELOCITY, SGVec3f::zeros().data() );
125 alDopplerFactor(1.0);
126 alDopplerVelocity(340.3); // speed of sound in meters per second.
128 if ( alIsExtensionPresent((const ALchar*)"EXT_exponent_distance") ) {
129 alDistanceModel(AL_EXPONENT_DISTANCE);
131 alDistanceModel(AL_INVERSE_DISTANCE);
134 testForALError("listener initialization");
136 // get a free source one at a time
137 // if an error is returned no more (hardware) sources are available
138 for (unsigned int i=0; i<MAX_SOURCES; i++) {
143 alGenSources(1, &source);
144 error = alGetError();
145 if ( error == AL_NO_ERROR ) {
146 _free_sources.push_back( source );
151 if (_free_sources.size() == 0) {
152 SG_LOG(SG_GENERAL, SG_ALERT, "Unable to grab any OpenAL sources!");
155 sample_group_map_iterator sample_grp_current = _sample_groups.begin();
156 sample_group_map_iterator sample_grp_end = _sample_groups.end();
157 for ( ; sample_grp_current != sample_grp_end; ++sample_grp_current ) {
158 SGSampleGroup *sgrp = sample_grp_current->second;
163 // suspend the sound manager
164 void SGSoundMgr::stop() {
168 // clear any OpenAL buffers before shutting down
169 buffer_map_iterator buffers_current;
170 while(_buffers.size()){
171 buffers_current = _buffers.begin();
172 refUint ref = buffers_current->second;
173 ALuint buffer = ref.id;
174 alDeleteBuffers(1, &buffer);
175 _buffers.erase( buffers_current );
178 _context = alcGetCurrentContext();
179 _device = alcGetContextsDevice(_context);
180 alcMakeContextCurrent(NULL);
181 alcDestroyContext(_context);
182 alcCloseDevice(_device);
186 void SGSoundMgr::suspend() {
188 sample_group_map_iterator sample_grp_current = _sample_groups.begin();
189 sample_group_map_iterator sample_grp_end = _sample_groups.end();
190 for ( ; sample_grp_current != sample_grp_end; ++sample_grp_current ) {
191 SGSampleGroup *sgrp = sample_grp_current->second;
198 void SGSoundMgr::bind ()
200 _free_sources.clear();
201 _free_sources.reserve( MAX_SOURCES );
202 _sources_in_use.clear();
203 _sources_in_use.reserve( MAX_SOURCES );
207 void SGSoundMgr::unbind ()
209 _sample_groups.clear();
211 // delete free sources
212 for (unsigned int i=0; i<_free_sources.size(); i++) {
213 ALuint source = _free_sources.at( i );
214 alDeleteSources( 1 , &source );
217 _free_sources.clear();
218 _sources_in_use.clear();
221 void SGSoundMgr::update( double dt )
223 // nothing to do in the regular update, everything is done on the following
228 // run the audio scheduler
229 void SGSoundMgr::update_late( double dt ) {
231 alcSuspendContext(_context);
233 sample_group_map_iterator sample_grp_current = _sample_groups.begin();
234 sample_group_map_iterator sample_grp_end = _sample_groups.end();
235 for ( ; sample_grp_current != sample_grp_end; ++sample_grp_current ) {
236 SGSampleGroup *sgrp = sample_grp_current->second;
241 alListenerf( AL_GAIN, _volume );
242 alListenerfv( AL_ORIENTATION, _at_up_vec );
243 alListenerfv( AL_POSITION, toVec3f(_position).data() );
244 alListenerfv( AL_VELOCITY, toVec3f(_velocity).data() );
245 // alDopplerVelocity(340.3); // TODO: altitude dependent
246 testForALError("update");
249 alcProcessContext(_context);
255 SGSoundMgr::resume ()
258 sample_group_map_iterator sample_grp_current = _sample_groups.begin();
259 sample_group_map_iterator sample_grp_end = _sample_groups.end();
260 for ( ; sample_grp_current != sample_grp_end; ++sample_grp_current ) {
261 SGSampleGroup *sgrp = sample_grp_current->second;
268 // add a sampel group, return true if successful
269 bool SGSoundMgr::add( SGSampleGroup *sgrp, const string& refname )
271 sample_group_map_iterator sample_grp_it = _sample_groups.find( refname );
272 if ( sample_grp_it != _sample_groups.end() ) {
273 // sample group already exists
277 _sample_groups[refname] = sgrp;
283 // remove a sound effect, return true if successful
284 bool SGSoundMgr::remove( const string &refname )
286 sample_group_map_iterator sample_grp_it = _sample_groups.find( refname );
287 if ( sample_grp_it == _sample_groups.end() ) {
288 // sample group was not found.
292 _sample_groups.erase( refname );
298 // return true of the specified sound exists in the sound manager system
299 bool SGSoundMgr::exists( const string &refname ) {
300 sample_group_map_iterator sample_grp_it = _sample_groups.find( refname );
301 if ( sample_grp_it == _sample_groups.end() ) {
302 // sample group was not found.
310 // return a pointer to the SGSampleGroup if the specified sound exists
311 // in the sound manager system, otherwise return NULL
312 SGSampleGroup *SGSoundMgr::find( const string &refname, bool create ) {
313 sample_group_map_iterator sample_grp_it = _sample_groups.find( refname );
314 if ( sample_grp_it == _sample_groups.end() ) {
315 // sample group was not found.
317 SGSampleGroup* sgrp = new SGSampleGroup(this, refname);
324 return sample_grp_it->second;
328 void SGSoundMgr::set_volume( float v )
331 if (_volume > 1.0) _volume = 1.0;
332 if (_volume < 0.0) _volume = 0.0;
337 * set the orientation of the listener (in opengl coordinates)
339 * Description: ORIENTATION is a pair of 3-tuples representing the
340 * 'at' direction vector and 'up' direction of the Object in
341 * Cartesian space. AL expects two vectors that are orthogonal to
342 * each other. These vectors are not expected to be normalized. If
343 * one or more vectors have zero length, implementation behavior
344 * is undefined. If the two vectors are linearly dependent,
345 * behavior is undefined.
347 void SGSoundMgr::set_orientation( SGQuatd ori )
351 SGVec3d sgv_up = ori.rotate(SGVec3d::e2());
352 SGVec3d sgv_at = ori.rotate(SGVec3d::e3());
353 _at_up_vec[0] = sgv_at[0];
354 _at_up_vec[1] = sgv_at[1];
355 _at_up_vec[2] = sgv_at[2];
356 _at_up_vec[3] = sgv_up[0];
357 _at_up_vec[4] = sgv_up[1];
358 _at_up_vec[5] = sgv_up[2];
362 // Get an unused source id
364 // The Sound Manager should keep track of the sources in use, the distance
365 // of these sources to the listener and the volume (also based on audio cone
366 // and hence orientation) of the sources.
368 // The Sound Manager is (and should be) the only one knowing about source
369 // management. Sources further away should be suspendped to free resources for
370 // newly added sounds close by.
371 unsigned int SGSoundMgr::request_source()
373 unsigned int source = NO_SOURCE;
375 if (_free_sources.size() > 0) {
376 source = _free_sources.back();
377 _free_sources.pop_back();
378 _sources_in_use.push_back(source);
384 // Free up a source id for further use
385 void SGSoundMgr::release_source( unsigned int source )
387 vector<ALuint>::iterator it;
389 it = std::find(_sources_in_use.begin(), _sources_in_use.end(), source);
390 if ( it != _sources_in_use.end() ) {
393 alGetSourcei( source, AL_SOURCE_STATE, &result );
394 if ( result == AL_PLAYING )
395 alSourceStop( source );
396 testForALError("release source");
398 _free_sources.push_back(source);
399 _sources_in_use.erase(it, it+1);
403 unsigned int SGSoundMgr::request_buffer(SGSoundSample *sample)
405 ALuint buffer = NO_BUFFER;
407 if ( !sample->is_valid_buffer() ) {
408 // sample was not yet loaded or removed again
409 string sample_name = sample->get_sample_name();
411 // see if the sample name is already cached
412 buffer_map_iterator buffer_it = _buffers.find( sample_name );
413 if ( buffer_it != _buffers.end() ) {
414 buffer_it->second.refctr++;
415 buffer = buffer_it->second.id;
416 sample->set_buffer( buffer );
420 // sample name was not found in the buffer cache.
421 if ( sample->is_file() ) {
426 load(sample_name, &data, &format, &size, &freq);
427 sample->set_data( (unsigned char *)data );
428 sample->set_frequency( freq );
429 sample->set_format( format );
430 sample->set_size( size );
433 // create an OpenAL buffer handle
434 alGenBuffers(1, &buffer);
435 if ( !testForALError("generate buffer") ) {
436 // Copy data to the internal OpenAL buffer
438 const ALvoid *data = sample->get_data();
439 ALenum format = sample->get_format();
440 ALsizei size = sample->get_size();
441 ALsizei freq = sample->get_frequency();
442 alBufferData( buffer, format, data, size, freq );
445 if ( !testForALError("buffer add data") ) {
446 sample->set_buffer(buffer);
447 _buffers[sample_name] = refUint(buffer);
452 buffer = sample->get_buffer();
457 void SGSoundMgr::release_buffer(SGSoundSample *sample)
459 string sample_name = sample->get_sample_name();
461 buffer_map_iterator buffer_it = _buffers.find( sample_name );
462 if ( buffer_it == _buffers.end() ) {
463 // buffer was not found
467 sample->no_valid_buffer();
468 buffer_it->second.refctr--;
469 if (buffer_it->second.refctr == 0) {
470 ALuint buffer = buffer_it->second.id;
471 _buffers.erase( buffer_it );
472 alDeleteBuffers(1, &buffer);
473 testForALError("release buffer");
477 bool SGSoundMgr::load(string &samplepath, void **dbuf, int *fmt,
478 unsigned int *sz, int *frq )
485 #if defined(ALUT_API_MAJOR_VERSION) && ALUT_API_MAJOR_VERSION >= 1
487 data = alutLoadMemoryFromFile(samplepath.c_str(), &format, &size, &freqf );
488 freq = (ALsizei)freqf;
490 int error = alutGetError();
491 string msg = "Failed to load wav file: ";
492 msg.append(alutGetErrorString(error));
493 throw sg_io_exception(msg.c_str(), sg_location(samplepath));
498 ALbyte *fname = (ALbyte *)samplepath.c_str();
499 # if defined (__APPLE__)
500 alutLoadWAVFile( fname, &format, &data, &size, &freq );
503 alutLoadWAVFile( fname, &format, &data, &size, &freq, &loop );
505 ALenum error = alutGetError();
506 if ( error != ALUT_ERROR_NO_ERROR ) {
507 string msg = "Failed to load wav file: ";
508 msg.append(alutGetErrorString(error));
509 throw sg_io_exception(msg.c_str(), sg_location(samplepath));
514 *dbuf = (void *)data;
516 *sz = (unsigned int)size;
523 bool SGSoundMgr::testForError(void *p, string s)
526 SG_LOG( SG_GENERAL, SG_ALERT, "Error: " << s);
533 bool SGSoundMgr::testForALError(string s)
535 ALenum error = alGetError();
536 if (error != AL_NO_ERROR) {
537 SG_LOG( SG_GENERAL, SG_ALERT, "AL Error (sound manager): "
538 << alGetString(error) << " at " << s);
544 bool SGSoundMgr::testForALCError(string s)
547 error = alcGetError(_device);
548 if (error != ALC_NO_ERROR) {
549 SG_LOG( SG_GENERAL, SG_ALERT, "ALC Error (sound manager): "
550 << alcGetString(_device, error) << " at "
557 bool SGSoundMgr::testForALUTError(string s)
559 #if defined(ALUT_API_MAJOR_VERSION) && ALUT_API_MAJOR_VERSION >= 1
561 error = alutGetError ();
562 if (error != ALUT_ERROR_NO_ERROR) {
563 SG_LOG( SG_GENERAL, SG_ALERT, "ALUT Error (sound manager): "
564 << alutGetErrorString(error) << " at "