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 _listener_pos(SGVec3d::zeros().data()),
63 _listener_vel(SGVec3f::zeros().data()),
66 #if defined(ALUT_API_MAJOR_VERSION) && ALUT_API_MAJOR_VERSION >= 1
67 if (_alut_init == 0) {
68 if ( !alutInitWithoutContext(NULL, NULL) ) {
69 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.") ) {
106 if ( !alcMakeContextCurrent(context) ) {
107 testForALCError("context initialization");
114 _listener_ori[0] = 0.0; _listener_ori[1] = 0.0; _listener_ori[2] = -1.0;
115 _listener_ori[3] = 0.0; _listener_ori[4] = 1.0; _listener_ori[5] = 0.0;
117 alListenerf( AL_GAIN, 0.2f );
118 alListenerfv( AL_POSITION, toVec3f(_listener_pos).data() );
119 alListenerfv( AL_ORIENTATION, _listener_ori );
120 alListenerfv( AL_VELOCITY, _listener_vel.data() );
122 alDopplerFactor(1.0);
123 alDopplerVelocity(340.3); // speed of sound in meters per second.
125 if ( alIsExtensionPresent((const ALchar*)"EXT_exponent_distance") ) {
126 alDistanceModel(AL_EXPONENT_DISTANCE);
128 alDistanceModel(AL_INVERSE_DISTANCE);
131 testForALError("listener initialization");
133 alGetError(); // clear any undetetced error, just to be sure
135 // get a free source one at a time
136 // if an error is returned no more (hardware) sources are available
137 for (unsigned int i=0; i<MAX_SOURCES; i++) {
142 alGenSources(1, &source);
143 error = alGetError();
144 if ( error == AL_NO_ERROR ) {
145 _free_sources.push_back( source );
151 // suspend the sound manager
152 void SGSoundMgr::stop() {
156 // clear any OpenAL buffers before shutting down
157 buffer_map_iterator buffers_current = _buffers.begin();
158 buffer_map_iterator buffers_end = _buffers.end();
159 for ( ; buffers_current != buffers_end; ++buffers_current ) {
160 refUint ref = buffers_current->second;
161 ALuint buffer = ref.id;
162 alDeleteBuffers(1, &buffer);
163 _buffers.erase( buffers_current );
166 _context = alcGetCurrentContext();
167 _device = alcGetContextsDevice(_context);
168 alcMakeContextCurrent(NULL);
169 alcDestroyContext(_context);
170 alcCloseDevice(_device);
174 void SGSoundMgr::suspend() {
176 sample_group_map_iterator sample_grp_current = _sample_groups.begin();
177 sample_group_map_iterator sample_grp_end = _sample_groups.end();
178 for ( ; sample_grp_current != sample_grp_end; ++sample_grp_current ) {
179 SGSampleGroup *sgrp = sample_grp_current->second;
186 void SGSoundMgr::bind ()
188 _free_sources.clear();
189 _free_sources.reserve( MAX_SOURCES );
190 _sources_in_use.clear();
191 _sources_in_use.reserve( MAX_SOURCES );
195 void SGSoundMgr::unbind ()
197 _sample_groups.clear();
199 // delete free sources
200 for (unsigned int i=0; i<_free_sources.size(); i++) {
201 ALuint source = _free_sources.at( i );
202 alDeleteSources( 1 , &source );
205 _free_sources.clear();
206 _sources_in_use.clear();
209 void SGSoundMgr::update( double dt )
211 // nothing to do in the regular update, everything is done on the following
216 // run the audio scheduler
217 void SGSoundMgr::update_late( double dt ) {
219 alcSuspendContext(_context);
221 sample_group_map_iterator sample_grp_current = _sample_groups.begin();
222 sample_group_map_iterator sample_grp_end = _sample_groups.end();
223 for ( ; sample_grp_current != sample_grp_end; ++sample_grp_current ) {
224 SGSampleGroup *sgrp = sample_grp_current->second;
229 alListenerf( AL_GAIN, _volume );
230 alListenerfv( AL_VELOCITY, _listener_vel.data() );
231 alListenerfv( AL_ORIENTATION, _listener_ori );
232 alListenerfv( AL_POSITION, toVec3f(_listener_pos).data() );
233 // alDopplerVelocity(340.3); // TODO: altitude dependent
234 testForALError("update");
237 alcProcessContext(_context);
243 SGSoundMgr::resume ()
246 sample_group_map_iterator sample_grp_current = _sample_groups.begin();
247 sample_group_map_iterator sample_grp_end = _sample_groups.end();
248 for ( ; sample_grp_current != sample_grp_end; ++sample_grp_current ) {
249 SGSampleGroup *sgrp = sample_grp_current->second;
256 // add a sampel group, return true if successful
257 bool SGSoundMgr::add( SGSampleGroup *sgrp, const string& refname )
259 sample_group_map_iterator sample_grp_it = _sample_groups.find( refname );
260 if ( sample_grp_it != _sample_groups.end() ) {
261 // sample group already exists
265 _sample_groups[refname] = sgrp;
271 // remove a sound effect, return true if successful
272 bool SGSoundMgr::remove( const string &refname )
274 sample_group_map_iterator sample_grp_it = _sample_groups.find( refname );
275 if ( sample_grp_it == _sample_groups.end() ) {
276 // sample group was not found.
280 _sample_groups.erase( refname );
286 // return true of the specified sound exists in the sound manager system
287 bool SGSoundMgr::exists( const string &refname ) {
288 sample_group_map_iterator sample_grp_it = _sample_groups.find( refname );
289 if ( sample_grp_it == _sample_groups.end() ) {
290 // sample group was not found.
298 // return a pointer to the SGSampleGroup if the specified sound exists
299 // in the sound manager system, otherwise return NULL
300 SGSampleGroup *SGSoundMgr::find( const string &refname, bool create ) {
301 sample_group_map_iterator sample_grp_it = _sample_groups.find( refname );
302 if ( sample_grp_it == _sample_groups.end() ) {
303 // sample group was not found.
305 SGSampleGroup* sgrp = new SGSampleGroup(this, refname);
312 return sample_grp_it->second;
316 void SGSoundMgr::set_volume( float v )
319 if (_volume > 1.0) _volume = 1.0;
320 if (_volume < 0.0) _volume = 0.0;
324 // Get an unused source id
326 // The Sound Manager should keep track of the sources in use, the distance
327 // of these sources to the listener and the volume (also based on audio cone
328 // and hence orientation) of the sources.
330 // The Sound Manager is (and should be) the only one knowing about source
331 // management. Sources further away should be suspendped to free resources for
332 // newly added sounds close by.
333 unsigned int SGSoundMgr::request_source()
335 unsigned int source = NO_SOURCE;
337 if (_free_sources.size() > 0) {
338 source = _free_sources.back();
339 _free_sources.pop_back();
340 _sources_in_use.push_back(source);
346 // Free up a source id for further use
347 void SGSoundMgr::release_source( unsigned int source )
349 vector<ALuint>::iterator it;
351 it = std::find(_sources_in_use.begin(), _sources_in_use.end(), source);
352 if ( it != _sources_in_use.end() ) {
355 alGetSourcei( source, AL_SOURCE_STATE, &result );
356 if ( result == AL_PLAYING )
357 alSourceStop( source );
358 testForALError("release source");
360 _free_sources.push_back(source);
361 _sources_in_use.erase(it, it+1);
365 unsigned int SGSoundMgr::request_buffer(SGSoundSample *sample)
367 ALuint buffer = NO_BUFFER;
369 if ( !sample->is_valid_buffer() ) {
370 // sample was not yet loaded or removed again
371 string sample_name = sample->get_sample_name();
373 // see if the sample name is already cached
374 buffer_map_iterator buffer_it = _buffers.find( sample_name );
375 if ( buffer_it != _buffers.end() ) {
376 buffer_it->second.refctr++;
377 buffer = buffer_it->second.id;
378 sample->set_buffer( buffer );
382 // sample name was not found in the buffer cache.
383 if ( sample->is_file() ) {
388 load(sample_name, &data, &format, &size, &freq);
389 sample->set_data( (unsigned char *)data );
390 sample->set_frequency( freq );
391 sample->set_format( format );
392 sample->set_size( size );
395 // create an OpenAL buffer handle
396 alGenBuffers(1, &buffer);
397 if ( !testForALError("generate buffer") ) {
398 // Copy data to the internal OpenAL buffer
400 const ALvoid *data = sample->get_data();
401 ALenum format = sample->get_format();
402 ALsizei size = sample->get_size();
403 ALsizei freq = sample->get_frequency();
404 alBufferData( buffer, format, data, size, freq );
407 if ( !testForALError("buffer add data") ) {
408 sample->set_buffer(buffer);
409 _buffers[sample_name] = refUint(buffer);
414 buffer = sample->get_buffer();
419 void SGSoundMgr::release_buffer(SGSoundSample *sample)
421 string sample_name = sample->get_sample_name();
423 buffer_map_iterator buffer_it = _buffers.find( sample_name );
424 if ( buffer_it == _buffers.end() ) {
425 // buffer was not found
429 sample->no_valid_buffer();
430 buffer_it->second.refctr--;
431 if (buffer_it->second.refctr == 0) {
432 ALuint buffer = buffer_it->second.id;
433 _buffers.erase( buffer_it );
434 alDeleteBuffers(1, &buffer);
435 testForALError("release buffer");
439 bool SGSoundMgr::load(string &samplepath, void **dbuf, int *fmt,
440 unsigned int *sz, int *frq )
442 ALenum format = (ALenum)*fmt;
443 ALsizei size = (ALsizei)*sz;
444 ALsizei freq = (ALsizei)*frq;
447 #if defined(ALUT_API_MAJOR_VERSION) && ALUT_API_MAJOR_VERSION >= 1
449 data = alutLoadMemoryFromFile(samplepath.c_str(), &format, &size, &freqf );
450 freq = (ALsizei)freqf;
452 int error = alutGetError();
453 string msg = "Failed to load wav file: ";
454 msg.append(alutGetErrorString(error));
455 throw sg_io_exception(msg.c_str(), sg_location(samplepath));
460 ALbyte *fname = (ALbyte *)samplepath.c_str();
461 # if defined (__APPLE__)
462 alutLoadWAVFile( fname, &format, &data, &size, &freq );
465 alutLoadWAVFile( fname, &format, &data, &size, &freq, &loop );
467 ALenum error = alutGetError();
468 if ( error != ALUT_ERROR_NO_ERROR ) {
469 string msg = "Failed to load wav file: ";
470 msg.append(alutGetErrorString(error));
471 throw sg_io_exception(msg.c_str(), sg_location(samplepath));
476 *dbuf = (void *)data;
478 *sz = (unsigned int)size;
486 * set the orientation of the listener (in opengl coordinates)
488 * Description: ORIENTATION is a pair of 3-tuples representing the
489 * 'at' direction vector and 'up' direction of the Object in
490 * Cartesian space. AL expects two vectors that are orthogonal to
491 * each other. These vectors are not expected to be normalized. If
492 * one or more vectors have zero length, implementation behavior
493 * is undefined. If the two vectors are linearly dependent,
494 * behavior is undefined.
496 void SGSoundMgr::set_orientation( SGQuatd ori )
498 SGVec3d sgv_up = ori.rotate(SGVec3d::e3());
499 SGVec3d sgv_at = ori.rotate(SGVec3d::e2());
500 for (int i=0; i<3; i++) {
501 _listener_ori[i] = sgv_at[i];
502 _listener_ori[i+3] = sgv_up[i];
508 bool SGSoundMgr::testForError(void *p, string s)
511 SG_LOG( SG_GENERAL, SG_ALERT, "Error: " << s);
518 bool SGSoundMgr::testForALError(string s)
520 ALenum error = alGetError();
521 if (error != AL_NO_ERROR) {
522 SG_LOG( SG_GENERAL, SG_ALERT, "AL Error (sound manager): "
523 << alGetString(error) << " at " << s);
529 bool SGSoundMgr::testForALCError(string s)
532 error = alcGetError(_device);
533 if (error != ALC_NO_ERROR) {
534 SG_LOG( SG_GENERAL, SG_ALERT, "ALC Error (sound manager): "
535 << alcGetString(_device, error) << " at "
542 bool SGSoundMgr::testForALUTError(string s)
544 #if defined(ALUT_API_MAJOR_VERSION) && ALUT_API_MAJOR_VERSION >= 1
546 error = alutGetError ();
547 if (error != ALUT_ERROR_NO_ERROR) {
548 SG_LOG( SG_GENERAL, SG_ALERT, "ALUT Error (sound manager): "
549 << alutGetErrorString(error) << " at "