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().data()),
63 _velocity(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 _orientation[0] = 0.0; _orientation[1] = 0.0; _orientation[2] = -1.0;
115 _orientation[3] = 0.0; _orientation[4] = 1.0; _orientation[5] = 0.0;
117 alListenerf( AL_GAIN, 0.2f );
118 alListenerfv( AL_POSITION, toVec3f(_position).data() );
119 alListenerfv( AL_ORIENTATION, _orientation );
120 alListenerfv( AL_VELOCITY, _velocity.data() );
122 alDopplerFactor(0.5);
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;
158 while(_buffers.size()){
159 buffers_current = _buffers.begin();
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, _velocity.data() );
231 alListenerfv( AL_ORIENTATION, _orientation );
232 alListenerfv( AL_POSITION, toVec3f(_position).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;
325 * set the orientation of the listener (in opengl coordinates)
327 * Description: ORIENTATION is a pair of 3-tuples representing the
328 * 'at' direction vector and 'up' direction of the Object in
329 * Cartesian space. AL expects two vectors that are orthogonal to
330 * each other. These vectors are not expected to be normalized. If
331 * one or more vectors have zero length, implementation behavior
332 * is undefined. If the two vectors are linearly dependent,
333 * behavior is undefined.
335 void SGSoundMgr::set_orientation( SGQuatd ori )
337 SGVec3d sgv_up = ori.rotate(SGVec3d::e2());
338 SGVec3d sgv_at = ori.rotate(SGVec3d::e3());
339 _orientation[0] = sgv_at[0];
340 _orientation[1] = sgv_at[1];
341 _orientation[2] = sgv_at[2];
342 _orientation[3] = sgv_up[0];
343 _orientation[4] = sgv_up[1];
344 _orientation[5] = sgv_up[2];
348 // Get an unused source id
350 // The Sound Manager should keep track of the sources in use, the distance
351 // of these sources to the listener and the volume (also based on audio cone
352 // and hence orientation) of the sources.
354 // The Sound Manager is (and should be) the only one knowing about source
355 // management. Sources further away should be suspendped to free resources for
356 // newly added sounds close by.
357 unsigned int SGSoundMgr::request_source()
359 unsigned int source = NO_SOURCE;
361 if (_free_sources.size() > 0) {
362 source = _free_sources.back();
363 _free_sources.pop_back();
364 _sources_in_use.push_back(source);
370 // Free up a source id for further use
371 void SGSoundMgr::release_source( unsigned int source )
373 vector<ALuint>::iterator it;
375 it = std::find(_sources_in_use.begin(), _sources_in_use.end(), source);
376 if ( it != _sources_in_use.end() ) {
379 alGetSourcei( source, AL_SOURCE_STATE, &result );
380 if ( result == AL_PLAYING )
381 alSourceStop( source );
382 testForALError("release source");
384 _free_sources.push_back(source);
385 _sources_in_use.erase(it, it+1);
389 unsigned int SGSoundMgr::request_buffer(SGSoundSample *sample)
391 ALuint buffer = NO_BUFFER;
393 if ( !sample->is_valid_buffer() ) {
394 // sample was not yet loaded or removed again
395 string sample_name = sample->get_sample_name();
397 // see if the sample name is already cached
398 buffer_map_iterator buffer_it = _buffers.find( sample_name );
399 if ( buffer_it != _buffers.end() ) {
400 buffer_it->second.refctr++;
401 buffer = buffer_it->second.id;
402 sample->set_buffer( buffer );
406 // sample name was not found in the buffer cache.
407 if ( sample->is_file() ) {
412 load(sample_name, &data, &format, &size, &freq);
413 sample->set_data( (unsigned char *)data );
414 sample->set_frequency( freq );
415 sample->set_format( format );
416 sample->set_size( size );
419 // create an OpenAL buffer handle
420 alGenBuffers(1, &buffer);
421 if ( !testForALError("generate buffer") ) {
422 // Copy data to the internal OpenAL buffer
424 const ALvoid *data = sample->get_data();
425 ALenum format = sample->get_format();
426 ALsizei size = sample->get_size();
427 ALsizei freq = sample->get_frequency();
428 alBufferData( buffer, format, data, size, freq );
431 if ( !testForALError("buffer add data") ) {
432 sample->set_buffer(buffer);
433 _buffers[sample_name] = refUint(buffer);
438 buffer = sample->get_buffer();
443 void SGSoundMgr::release_buffer(SGSoundSample *sample)
445 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 _buffers.erase( buffer_it );
458 alDeleteBuffers(1, &buffer);
459 testForALError("release buffer");
463 bool SGSoundMgr::load(string &samplepath, void **dbuf, int *fmt,
464 unsigned int *sz, int *frq )
466 ALenum format = (ALenum)*fmt;
467 ALsizei size = (ALsizei)*sz;
468 ALsizei freq = (ALsizei)*frq;
471 #if defined(ALUT_API_MAJOR_VERSION) && ALUT_API_MAJOR_VERSION >= 1
473 data = alutLoadMemoryFromFile(samplepath.c_str(), &format, &size, &freqf );
474 freq = (ALsizei)freqf;
476 int error = alutGetError();
477 string msg = "Failed to load wav file: ";
478 msg.append(alutGetErrorString(error));
479 throw sg_io_exception(msg.c_str(), sg_location(samplepath));
484 ALbyte *fname = (ALbyte *)samplepath.c_str();
485 # if defined (__APPLE__)
486 alutLoadWAVFile( fname, &format, &data, &size, &freq );
489 alutLoadWAVFile( fname, &format, &data, &size, &freq, &loop );
491 ALenum error = alutGetError();
492 if ( error != ALUT_ERROR_NO_ERROR ) {
493 string msg = "Failed to load wav file: ";
494 msg.append(alutGetErrorString(error));
495 throw sg_io_exception(msg.c_str(), sg_location(samplepath));
500 *dbuf = (void *)data;
502 *sz = (unsigned int)size;
509 bool SGSoundMgr::testForError(void *p, string s)
512 SG_LOG( SG_GENERAL, SG_ALERT, "Error: " << s);
519 bool SGSoundMgr::testForALError(string s)
521 ALenum error = alGetError();
522 if (error != AL_NO_ERROR) {
523 SG_LOG( SG_GENERAL, SG_ALERT, "AL Error (sound manager): "
524 << alGetString(error) << " at " << s);
530 bool SGSoundMgr::testForALCError(string s)
533 error = alcGetError(_device);
534 if (error != ALC_NO_ERROR) {
535 SG_LOG( SG_GENERAL, SG_ALERT, "ALC Error (sound manager): "
536 << alcGetString(_device, error) << " at "
543 bool SGSoundMgr::testForALUTError(string s)
545 #if defined(ALUT_API_MAJOR_VERSION) && ALUT_API_MAJOR_VERSION >= 1
547 error = alutGetError ();
548 if (error != ALUT_ERROR_NO_ERROR) {
549 SG_LOG( SG_GENERAL, SG_ALERT, "ALUT Error (sound manager): "
550 << alutGetErrorString(error) << " at "