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.") ) {
107 if ( !alcMakeContextCurrent(context) ) {
108 testForALCError("context initialization");
115 _at_up_vec[0] = 0.0; _at_up_vec[1] = 0.0; _at_up_vec[2] = -1.0;
116 _at_up_vec[3] = 0.0; _at_up_vec[4] = 1.0; _at_up_vec[5] = 0.0;
118 alListenerf( AL_GAIN, 0.2f );
119 alListenerfv( AL_POSITION, SGVec3f::zeros().data() );
120 alListenerfv( AL_ORIENTATION, _at_up_vec );
121 alListenerfv( AL_VELOCITY, toVec3f(_velocity).data() );
123 alDopplerFactor(0.5);
124 alDopplerVelocity(340.3); // speed of sound in meters per second.
126 if ( alIsExtensionPresent((const ALchar*)"EXT_exponent_distance") ) {
127 alDistanceModel(AL_EXPONENT_DISTANCE);
129 alDistanceModel(AL_INVERSE_DISTANCE);
132 testForALError("listener initialization");
134 alGetError(); // clear any undetetced error, just to be sure
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 );
152 // suspend the sound manager
153 void SGSoundMgr::stop() {
157 // clear any OpenAL buffers before shutting down
158 buffer_map_iterator buffers_current;
159 while(_buffers.size()){
160 buffers_current = _buffers.begin();
161 refUint ref = buffers_current->second;
162 ALuint buffer = ref.id;
163 alDeleteBuffers(1, &buffer);
164 _buffers.erase( buffers_current );
167 _context = alcGetCurrentContext();
168 _device = alcGetContextsDevice(_context);
169 alcMakeContextCurrent(NULL);
170 alcDestroyContext(_context);
171 alcCloseDevice(_device);
175 void SGSoundMgr::suspend() {
177 sample_group_map_iterator sample_grp_current = _sample_groups.begin();
178 sample_group_map_iterator sample_grp_end = _sample_groups.end();
179 for ( ; sample_grp_current != sample_grp_end; ++sample_grp_current ) {
180 SGSampleGroup *sgrp = sample_grp_current->second;
187 void SGSoundMgr::bind ()
189 _free_sources.clear();
190 _free_sources.reserve( MAX_SOURCES );
191 _sources_in_use.clear();
192 _sources_in_use.reserve( MAX_SOURCES );
196 void SGSoundMgr::unbind ()
198 _sample_groups.clear();
200 // delete free sources
201 for (unsigned int i=0; i<_free_sources.size(); i++) {
202 ALuint source = _free_sources.at( i );
203 alDeleteSources( 1 , &source );
206 _free_sources.clear();
207 _sources_in_use.clear();
210 void SGSoundMgr::update( double dt )
212 // nothing to do in the regular update, everything is done on the following
217 // run the audio scheduler
218 void SGSoundMgr::update_late( double dt ) {
220 alcSuspendContext(_context);
222 sample_group_map_iterator sample_grp_current = _sample_groups.begin();
223 sample_group_map_iterator sample_grp_end = _sample_groups.end();
224 for ( ; sample_grp_current != sample_grp_end; ++sample_grp_current ) {
225 SGSampleGroup *sgrp = sample_grp_current->second;
230 alListenerf( AL_GAIN, _volume );
231 alListenerfv( AL_ORIENTATION, _at_up_vec );
232 alListenerfv( AL_POSITION, toVec3f(_position).data() );
233 alListenerfv( AL_VELOCITY, toVec3f(_velocity).data() );
234 // alDopplerVelocity(340.3); // TODO: altitude dependent
235 testForALError("update");
238 alcProcessContext(_context);
244 SGSoundMgr::resume ()
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;
257 // add a sampel group, return true if successful
258 bool SGSoundMgr::add( SGSampleGroup *sgrp, const string& refname )
260 sample_group_map_iterator sample_grp_it = _sample_groups.find( refname );
261 if ( sample_grp_it != _sample_groups.end() ) {
262 // sample group already exists
266 _sample_groups[refname] = sgrp;
272 // remove a sound effect, return true if successful
273 bool SGSoundMgr::remove( 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 was not found.
281 _sample_groups.erase( refname );
287 // return true of the specified sound exists in the sound manager system
288 bool SGSoundMgr::exists( const string &refname ) {
289 sample_group_map_iterator sample_grp_it = _sample_groups.find( refname );
290 if ( sample_grp_it == _sample_groups.end() ) {
291 // sample group was not found.
299 // return a pointer to the SGSampleGroup if the specified sound exists
300 // in the sound manager system, otherwise return NULL
301 SGSampleGroup *SGSoundMgr::find( const string &refname, bool create ) {
302 sample_group_map_iterator sample_grp_it = _sample_groups.find( refname );
303 if ( sample_grp_it == _sample_groups.end() ) {
304 // sample group was not found.
306 SGSampleGroup* sgrp = new SGSampleGroup(this, refname);
313 return sample_grp_it->second;
317 void SGSoundMgr::set_volume( float v )
320 if (_volume > 1.0) _volume = 1.0;
321 if (_volume < 0.0) _volume = 0.0;
326 * set the orientation of the listener (in opengl coordinates)
328 * Description: ORIENTATION is a pair of 3-tuples representing the
329 * 'at' direction vector and 'up' direction of the Object in
330 * Cartesian space. AL expects two vectors that are orthogonal to
331 * each other. These vectors are not expected to be normalized. If
332 * one or more vectors have zero length, implementation behavior
333 * is undefined. If the two vectors are linearly dependent,
334 * behavior is undefined.
336 void SGSoundMgr::set_orientation( SGQuatd ori )
340 SGVec3d sgv_up = ori.rotate(SGVec3d::e2());
341 SGVec3d sgv_at = ori.rotate(SGVec3d::e3());
342 _at_up_vec[0] = sgv_at[0];
343 _at_up_vec[1] = sgv_at[1];
344 _at_up_vec[2] = sgv_at[2];
345 _at_up_vec[3] = sgv_up[0];
346 _at_up_vec[4] = sgv_up[1];
347 _at_up_vec[5] = sgv_up[2];
351 // Get an unused source id
353 // The Sound Manager should keep track of the sources in use, the distance
354 // of these sources to the listener and the volume (also based on audio cone
355 // and hence orientation) of the sources.
357 // The Sound Manager is (and should be) the only one knowing about source
358 // management. Sources further away should be suspendped to free resources for
359 // newly added sounds close by.
360 unsigned int SGSoundMgr::request_source()
362 unsigned int source = NO_SOURCE;
364 if (_free_sources.size() > 0) {
365 source = _free_sources.back();
366 _free_sources.pop_back();
367 _sources_in_use.push_back(source);
373 // Free up a source id for further use
374 void SGSoundMgr::release_source( unsigned int source )
376 vector<ALuint>::iterator it;
378 it = std::find(_sources_in_use.begin(), _sources_in_use.end(), source);
379 if ( it != _sources_in_use.end() ) {
382 alGetSourcei( source, AL_SOURCE_STATE, &result );
383 if ( result == AL_PLAYING )
384 alSourceStop( source );
385 testForALError("release source");
387 _free_sources.push_back(source);
388 _sources_in_use.erase(it, it+1);
392 unsigned int SGSoundMgr::request_buffer(SGSoundSample *sample)
394 ALuint buffer = NO_BUFFER;
396 if ( !sample->is_valid_buffer() ) {
397 // sample was not yet loaded or removed again
398 string sample_name = sample->get_sample_name();
400 // see if the sample name is already cached
401 buffer_map_iterator buffer_it = _buffers.find( sample_name );
402 if ( buffer_it != _buffers.end() ) {
403 buffer_it->second.refctr++;
404 buffer = buffer_it->second.id;
405 sample->set_buffer( buffer );
409 // sample name was not found in the buffer cache.
410 if ( sample->is_file() ) {
415 load(sample_name, &data, &format, &size, &freq);
416 sample->set_data( (unsigned char *)data );
417 sample->set_frequency( freq );
418 sample->set_format( format );
419 sample->set_size( size );
422 // create an OpenAL buffer handle
423 alGenBuffers(1, &buffer);
424 if ( !testForALError("generate buffer") ) {
425 // Copy data to the internal OpenAL buffer
427 const ALvoid *data = sample->get_data();
428 ALenum format = sample->get_format();
429 ALsizei size = sample->get_size();
430 ALsizei freq = sample->get_frequency();
431 alBufferData( buffer, format, data, size, freq );
434 if ( !testForALError("buffer add data") ) {
435 sample->set_buffer(buffer);
436 _buffers[sample_name] = refUint(buffer);
441 buffer = sample->get_buffer();
446 void SGSoundMgr::release_buffer(SGSoundSample *sample)
448 string sample_name = sample->get_sample_name();
450 buffer_map_iterator buffer_it = _buffers.find( sample_name );
451 if ( buffer_it == _buffers.end() ) {
452 // buffer was not found
456 sample->no_valid_buffer();
457 buffer_it->second.refctr--;
458 if (buffer_it->second.refctr == 0) {
459 ALuint buffer = buffer_it->second.id;
460 _buffers.erase( buffer_it );
461 alDeleteBuffers(1, &buffer);
462 testForALError("release buffer");
466 bool SGSoundMgr::load(string &samplepath, void **dbuf, int *fmt,
467 unsigned int *sz, int *frq )
469 ALenum format = (ALenum)*fmt;
470 ALsizei size = (ALsizei)*sz;
471 ALsizei freq = (ALsizei)*frq;
474 #if defined(ALUT_API_MAJOR_VERSION) && ALUT_API_MAJOR_VERSION >= 1
476 data = alutLoadMemoryFromFile(samplepath.c_str(), &format, &size, &freqf );
477 freq = (ALsizei)freqf;
479 int error = alutGetError();
480 string msg = "Failed to load wav file: ";
481 msg.append(alutGetErrorString(error));
482 throw sg_io_exception(msg.c_str(), sg_location(samplepath));
487 ALbyte *fname = (ALbyte *)samplepath.c_str();
488 # if defined (__APPLE__)
489 alutLoadWAVFile( fname, &format, &data, &size, &freq );
492 alutLoadWAVFile( fname, &format, &data, &size, &freq, &loop );
494 ALenum error = alutGetError();
495 if ( error != ALUT_ERROR_NO_ERROR ) {
496 string msg = "Failed to load wav file: ";
497 msg.append(alutGetErrorString(error));
498 throw sg_io_exception(msg.c_str(), sg_location(samplepath));
503 *dbuf = (void *)data;
505 *sz = (unsigned int)size;
512 bool SGSoundMgr::testForError(void *p, string s)
515 SG_LOG( SG_GENERAL, SG_ALERT, "Error: " << s);
522 bool SGSoundMgr::testForALError(string s)
524 ALenum error = alGetError();
525 if (error != AL_NO_ERROR) {
526 SG_LOG( SG_GENERAL, SG_ALERT, "AL Error (sound manager): "
527 << alGetString(error) << " at " << s);
533 bool SGSoundMgr::testForALCError(string s)
536 error = alcGetError(_device);
537 if (error != ALC_NO_ERROR) {
538 SG_LOG( SG_GENERAL, SG_ALERT, "ALC Error (sound manager): "
539 << alcGetString(_device, error) << " at "
546 bool SGSoundMgr::testForALUTError(string s)
548 #if defined(ALUT_API_MAJOR_VERSION) && ALUT_API_MAJOR_VERSION >= 1
550 error = alutGetError ();
551 if (error != ALUT_ERROR_NO_ERROR) {
552 SG_LOG( SG_GENERAL, SG_ALERT, "ALUT Error (sound manager): "
553 << alutGetErrorString(error) << " at "