]> git.mxchange.org Git - simgear.git/blob - simgear/sound/soundmgr_openal.cxx
ce415e295a5644be753076bc02b19bd88ab64df1
[simgear.git] / simgear / sound / soundmgr_openal.cxx
1 // soundmgr.cxx -- Sound effect management class
2 //
3 // Sound manager initially written by David Findlay
4 // <david_j_findlay@yahoo.com.au> 2001
5 //
6 // C++-ified by Curtis Olson, started March 2001.
7 // Modified for the new SoundSystem by Erik Hofman, October 2009
8 //
9 // Copyright (C) 2001  Curtis L. Olson - http://www.flightgear.org/~curt
10 // Copyright (C) 2009 Erik Hofman <erik@ehofman.com>
11 //
12 // This program is free software; you can redistribute it and/or
13 // modify it under the terms of the GNU General Public License as
14 // published by the Free Software Foundation; either version 2 of the
15 // License, or (at your option) any later version.
16 //
17 // This program is distributed in the hope that it will be useful, but
18 // WITHOUT ANY WARRANTY; without even the implied warranty of
19 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
20 // General Public License for more details.
21 //
22 // You should have received a copy of the GNU General Public License
23 // along with this program; if not, write to the Free Software Foundation,
24 // Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
25 //
26 // $Id$
27
28 #ifdef HAVE_CONFIG_H
29 #  include <simgear_config.h>
30 #endif
31
32 #if defined( __APPLE__ )
33 # include <OpenAL/alut.h>
34 #else
35 # include <AL/alut.h>
36 #endif
37
38 #include <iostream>
39 #include <algorithm>
40
41 #include "soundmgr_openal.hxx"
42
43 #include <simgear/structure/exception.hxx>
44 #include <simgear/debug/logstream.hxx>
45 #include <simgear/misc/sg_path.hxx>
46 #include <simgear/math/SGMath.hxx>
47
48 extern bool isNaN(float *v);
49
50 #define MAX_SOURCES     128
51
52 //
53 // Sound Manager
54 //
55
56 int SGSoundMgr::_alut_init = 0;
57
58 // constructor
59 SGSoundMgr::SGSoundMgr() :
60     _working(false),
61     _active(false),
62     _changed(true),
63     _volume(0.0),
64     _device(NULL),
65     _context(NULL),
66     _absolute_pos(SGVec3d::zeros()),
67     _offset_pos(SGVec3d::zeros()),
68     _base_pos(SGVec3d::zeros()),
69     _geod_pos(SGGeod::fromCart(SGVec3d::zeros())),
70     _velocity(SGVec3d::zeros()),
71     _orientation(SGQuatd::zeros()),
72     _devname(NULL), 
73     _bad_doppler(false)
74 {
75 #if defined(ALUT_API_MAJOR_VERSION) && ALUT_API_MAJOR_VERSION >= 1
76     if (_alut_init == 0) {
77         if ( !alutInitWithoutContext(NULL, NULL) ) {
78             testForALUTError("alut initialization");
79             return;
80         }
81     }
82     _alut_init++;
83 #endif
84 }
85
86 // destructor
87
88 SGSoundMgr::~SGSoundMgr() {
89
90     stop();
91 #if defined(ALUT_API_MAJOR_VERSION) && ALUT_API_MAJOR_VERSION >= 1
92     _alut_init--;
93     if (_alut_init == 0) {
94         alutExit ();
95     }
96 #endif
97 }
98
99 // initialize the sound manager
100 void SGSoundMgr::init() {
101
102     SG_LOG( SG_GENERAL, SG_INFO, "Initializing OpenAL sound manager" );
103
104     ALCdevice *device = alcOpenDevice(_devname);
105     if ( testForError(device, "No default audio device available.") ) {
106         return;
107     }
108
109     ALCcontext *context = alcCreateContext(device, NULL);
110     if ( testForError(context, "Unable to create a valid context.") ) {
111         alcCloseDevice (device);
112         return;
113     }
114
115     if ( !alcMakeContextCurrent(context) ) {
116         testForALCError("context initialization");
117         alcDestroyContext (context);
118         alcCloseDevice (device);
119         return;
120     }
121
122     if (_context != NULL)
123         SG_LOG(SG_GENERAL, SG_ALERT, "context is already assigned");
124     _context = context;
125     _working = true;
126
127     _at_up_vec[0] = 0.0; _at_up_vec[1] = 0.0; _at_up_vec[2] = -1.0;
128     _at_up_vec[3] = 0.0; _at_up_vec[4] = 1.0; _at_up_vec[5] = 0.0;
129
130     alListenerf( AL_GAIN, 0.0f );
131     alListenerfv( AL_ORIENTATION, _at_up_vec );
132     alListenerfv( AL_POSITION, SGVec3f::zeros().data() );
133     alListenerfv( AL_VELOCITY, SGVec3f::zeros().data() );
134
135     alDopplerFactor(1.0);
136     alDopplerVelocity(340.3);   // speed of sound in meters per second.
137
138     // gain = AL_REFERENCE_DISTANCE / (AL_REFERENCE_DISTANCE +
139     //        AL_ROLLOFF_FACTOR * (distance - AL_REFERENCE_DISTANCE));
140     alDistanceModel(AL_INVERSE_DISTANCE_CLAMPED);
141
142     testForALError("listener initialization");
143
144     // get a free source one at a time
145     // if an error is returned no more (hardware) sources are available
146     for (unsigned int i=0; i<MAX_SOURCES; i++) {
147         ALuint source;
148         ALenum error;
149
150         alGetError();
151         alGenSources(1, &source);
152         error = alGetError();
153         if ( error == AL_NO_ERROR ) {
154             _free_sources.push_back( source );
155         }
156         else break;
157     }
158
159     const char *renderer = (char *)alGetString(AL_RENDERER);
160     if (  strcmp(renderer, "OpenAL Sample Implementation") ) {
161        _bad_doppler = true;
162     }
163
164     if (_free_sources.size() == 0) {
165         SG_LOG(SG_GENERAL, SG_ALERT, "Unable to grab any OpenAL sources!");
166     }
167 }
168
169 void SGSoundMgr::activate() {
170     if ( _working ) {
171         _active = true;
172         sample_group_map_iterator sample_grp_current = _sample_groups.begin();
173         sample_group_map_iterator sample_grp_end = _sample_groups.end();
174         for ( ; sample_grp_current != sample_grp_end; ++sample_grp_current ) {
175             SGSampleGroup *sgrp = sample_grp_current->second;
176             sgrp->activate();
177         }
178     }
179 }
180
181 // stop the sound manager
182 void SGSoundMgr::stop() {
183     if (_working) {
184         _working = false;
185         _active = false;
186
187         // clear any OpenAL buffers before shutting down
188         buffer_map_iterator buffers_current = _buffers.begin();
189         buffer_map_iterator buffers_end = _buffers.end();
190         for ( ; buffers_current != buffers_end; ++buffers_current ) {
191             refUint ref = buffers_current->second;
192             ALuint buffer = ref.id;
193             alDeleteBuffers(1, &buffer);
194         }
195         _buffers.clear();
196
197         _context = alcGetCurrentContext();
198         _device = alcGetContextsDevice(_context);
199         alcDestroyContext(_context);
200         alcCloseDevice(_device);
201     }
202 }
203
204 void SGSoundMgr::suspend() {
205     if (_working) {
206         sample_group_map_iterator sample_grp_current = _sample_groups.begin();
207         sample_group_map_iterator sample_grp_end = _sample_groups.end();
208         for ( ; sample_grp_current != sample_grp_end; ++sample_grp_current ) {
209             SGSampleGroup *sgrp = sample_grp_current->second;
210             sgrp->suspend();
211         }
212         _active = false;
213     }
214 }
215
216 void SGSoundMgr::resume() {
217     if (_working) {
218         sample_group_map_iterator sample_grp_current = _sample_groups.begin();
219         sample_group_map_iterator sample_grp_end = _sample_groups.end();
220         for ( ; sample_grp_current != sample_grp_end; ++sample_grp_current ) {
221             SGSampleGroup *sgrp = sample_grp_current->second;
222             sgrp->resume();
223         }
224         _active = true;
225     }
226 }
227
228 void SGSoundMgr::bind ()
229 {
230     _free_sources.clear();
231     _free_sources.reserve( MAX_SOURCES );
232     _sources_in_use.clear();
233     _sources_in_use.reserve( MAX_SOURCES );
234 }
235
236
237 void SGSoundMgr::unbind ()
238 {
239     _sample_groups.clear();
240
241     // delete free sources
242     for (unsigned int i=0; i<_free_sources.size(); i++) {
243         ALuint source = _free_sources[i];
244         alDeleteSources( 1 , &source );
245     }
246
247     _free_sources.clear();
248     _sources_in_use.clear();
249 }
250
251 // run the audio scheduler
252 void SGSoundMgr::update( double dt ) {
253     if (_active) {
254         if (_changed) {
255             update_pos_and_orientation();
256         }
257
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;
262             sgrp->update(dt);
263         }
264
265         if (_changed) {
266 #if 0
267 if (isNaN(_at_up_vec)) printf("NaN in listener orientation\n");
268 if (isNaN(toVec3f(_absolute_pos).data())) printf("NaN in listener position\n");
269 if (isNaN(_velocity.data())) printf("NaN in listener velocity\n");
270 #endif
271             alListenerf( AL_GAIN, _volume );
272             alListenerfv( AL_ORIENTATION, _at_up_vec );
273             // alListenerfv( AL_POSITION, toVec3f(_absolute_pos).data() );
274
275             SGQuatd hlOr = SGQuatd::fromLonLat( _geod_pos );
276             SGVec3d velocity = SGVec3d::zeros();
277             if ( _velocity[0] || _velocity[1] || _velocity[2] ) {
278                 velocity = hlOr.backTransform(_velocity*SG_FEET_TO_METER);
279             }
280             alListenerfv( AL_VELOCITY, toVec3f(velocity).data() );
281             // alDopplerVelocity(340.3);        // TODO: altitude dependent
282             testForALError("update");
283             _changed = false;
284         }
285     }
286 }
287
288 // add a sample group, return true if successful
289 bool SGSoundMgr::add( SGSampleGroup *sgrp, const string& refname )
290 {
291     sample_group_map_iterator sample_grp_it = _sample_groups.find( refname );
292     if ( sample_grp_it != _sample_groups.end() ) {
293         // sample group already exists
294         return false;
295     }
296
297     if (_active) sgrp->activate();
298     _sample_groups[refname] = sgrp;
299
300     return true;
301 }
302
303
304 // remove a sound effect, return true if successful
305 bool SGSoundMgr::remove( const string &refname )
306 {
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.
310         return false;
311     }
312
313     _sample_groups.erase( sample_grp_it );
314
315     return true;
316 }
317
318
319 // return true of the specified sound exists in the sound manager system
320 bool SGSoundMgr::exists( const string &refname ) {
321     sample_group_map_iterator sample_grp_it = _sample_groups.find( refname );
322     if ( sample_grp_it == _sample_groups.end() ) {
323         // sample group was not found.
324         return false;
325     }
326
327     return true;
328 }
329
330
331 // return a pointer to the SGSampleGroup if the specified sound exists
332 // in the sound manager system, otherwise return NULL
333 SGSampleGroup *SGSoundMgr::find( const string &refname, bool create ) {
334     sample_group_map_iterator sample_grp_it = _sample_groups.find( refname );
335     if ( sample_grp_it == _sample_groups.end() ) {
336         // sample group was not found.
337         if (create) {
338             SGSampleGroup* sgrp = new SGSampleGroup(this, refname);
339             add( sgrp, refname );
340             return sgrp;
341         }
342         else 
343             return NULL;
344     }
345
346     return sample_grp_it->second;
347 }
348
349
350 void SGSoundMgr::set_volume( float v )
351 {
352     _volume = v;
353     if (_volume > 1.0) _volume = 1.0;
354     if (_volume < 0.0) _volume = 0.0;
355     _changed = true;
356 }
357
358 // Get an unused source id
359 //
360 // The Sound Manager should keep track of the sources in use, the distance
361 // of these sources to the listener and the volume (also based on audio cone
362 // and hence orientation) of the sources.
363 //
364 // The Sound Manager is (and should be) the only one knowing about source
365 // management. Sources further away should be suspendped to free resources for
366 // newly added sounds close by.
367 unsigned int SGSoundMgr::request_source()
368 {
369     unsigned int source = NO_SOURCE;
370
371     if (_free_sources.size() > 0) {
372        source = _free_sources.back();
373        _free_sources.pop_back();
374        _sources_in_use.push_back(source);
375     }
376     else
377        SG_LOG( SG_GENERAL, SG_INFO, "No more free sources available\n");
378
379     return source;
380 }
381
382 // Free up a source id for further use
383 void SGSoundMgr::release_source( unsigned int source )
384 {
385     vector<ALuint>::iterator it;
386
387     it = std::find(_sources_in_use.begin(), _sources_in_use.end(), source);
388     if ( it != _sources_in_use.end() ) {
389         ALint result;
390
391         alGetSourcei( source, AL_SOURCE_STATE, &result );
392         if ( result == AL_PLAYING )
393             alSourceStop( source );
394         testForALError("release source");
395
396         alSourcei( source, AL_BUFFER, 0 );
397         _free_sources.push_back( source );
398         _sources_in_use.erase( it );
399     }
400 }
401
402 unsigned int SGSoundMgr::request_buffer(SGSoundSample *sample)
403 {
404     ALuint buffer = NO_BUFFER;
405
406     if ( !sample->is_valid_buffer() ) {
407         // sample was not yet loaded or removed again
408         string sample_name = sample->get_sample_name();
409
410         // see if the sample name is already cached
411         buffer_map_iterator buffer_it = _buffers.find( sample_name );
412         if ( buffer_it != _buffers.end() ) {
413             buffer_it->second.refctr++;
414             buffer = buffer_it->second.id;
415             sample->set_buffer( buffer );
416             return buffer;
417         }
418
419         // sample name was not found in the buffer cache.
420         if ( sample->is_file() ) {
421             size_t size;
422             int freq, format;
423             void *data;
424
425             load(sample_name, &data, &format, &size, &freq);
426             sample->set_data( &data );
427             sample->set_frequency( freq );
428             sample->set_format( format );
429             sample->set_size( size );
430         }
431
432         // create an OpenAL buffer handle
433         alGenBuffers(1, &buffer);
434         if ( !testForALError("generate buffer") ) {
435             // Copy data to the internal OpenAL buffer
436
437             const ALvoid *data = sample->get_data();
438             ALenum format = sample->get_format();
439             ALsizei size = sample->get_size();
440             ALsizei freq = sample->get_frequency();
441             alBufferData( buffer, format, data, size, freq );
442
443             // If this sample was read from a file we have all the information
444             // needed to read it again. For data buffers provided by the
445             // program we don't; so don't delete it's data.
446             if ( sample->is_file() ) sample->free_data();
447
448             if ( !testForALError("buffer add data") ) {
449                 sample->set_buffer(buffer);
450                 _buffers[sample_name] = refUint(buffer);
451             }
452         }
453     }
454     else {
455         buffer = sample->get_buffer();
456 }
457
458     return buffer;
459 }
460
461 void SGSoundMgr::release_buffer(SGSoundSample *sample)
462 {
463     string sample_name = sample->get_sample_name();
464     buffer_map_iterator buffer_it = _buffers.find( sample_name );
465     if ( buffer_it == _buffers.end() ) {
466         // buffer was not found
467         return;
468     }
469
470     sample->no_valid_buffer();
471     buffer_it->second.refctr--;
472     if (buffer_it->second.refctr == 0) {
473         ALuint buffer = buffer_it->second.id;
474         alDeleteBuffers(1, &buffer);
475         _buffers.erase( buffer_it );
476         testForALError("release buffer");
477     }
478 }
479
480 void SGSoundMgr::update_pos_and_orientation() {
481     /**
482      * Description: ORIENTATION is a pair of 3-tuples representing the
483      * 'at' direction vector and 'up' direction of the Object in
484      * Cartesian space. AL expects two vectors that are orthogonal to
485      * each other. These vectors are not expected to be normalized. If
486      * one or more vectors have zero length, implementation behavior
487      * is undefined. If the two vectors are linearly dependent,
488      * behavior is undefined.
489      *
490      * This is in the same coordinate system as OpenGL; y=up, z=back, x=right.
491      */
492     SGVec3d sgv_at = _orientation.backTransform(-SGVec3d::e3());
493     SGVec3d sgv_up = _orientation.backTransform(SGVec3d::e2());
494     _at_up_vec[0] = sgv_at[0];
495     _at_up_vec[1] = sgv_at[1];
496     _at_up_vec[2] = sgv_at[2];
497     _at_up_vec[3] = sgv_up[0];
498     _at_up_vec[4] = sgv_up[1];
499     _at_up_vec[5] = sgv_up[2];
500
501     // static const SGQuatd q(-0.5, -0.5, 0.5, 0.5);
502     // SGQuatd hlOr = SGQuatd::fromLonLat(SGGeod::fromCart(_base_pos));
503     // SGQuatd ec2body = hlOr*_orientation;
504     _absolute_pos = _base_pos; // + ec2body.backTransform( _offset_pos );
505 }
506
507 bool SGSoundMgr::load(string &samplepath, void **dbuf, int *fmt,
508                                           size_t *sz, int *frq )
509 {
510     if ( !_working ) return false;
511
512     ALenum format;
513     ALsizei size;
514     ALsizei freq;
515     ALvoid *data;
516
517 #if defined(ALUT_API_MAJOR_VERSION) && ALUT_API_MAJOR_VERSION >= 1
518     ALfloat freqf;
519     data = alutLoadMemoryFromFile(samplepath.c_str(), &format, &size, &freqf );
520     freq = (ALsizei)freqf;
521     if (data == NULL) {
522         int error = alutGetError();
523         string msg = "Failed to load wav file: ";
524         msg.append(alutGetErrorString(error));
525         throw sg_io_exception(msg.c_str(), sg_location(samplepath));
526         return false;
527     }
528
529 #else
530     ALbyte *fname = (ALbyte *)samplepath.c_str();
531 # if defined (__APPLE__)
532     alutLoadWAVFile( fname, &format, &data, &size, &freq );
533 # else
534     ALboolean loop;
535     alutLoadWAVFile( fname, &format, &data, &size, &freq, &loop );
536 # endif
537     ALenum error =  alGetError();
538     if ( error != AL_NO_ERROR ) {
539         string msg = "Failed to load wav file: ";
540         msg.append(alGetString(error));
541         throw sg_io_exception(msg.c_str(), sg_location(samplepath));
542         return false;
543     }
544 #endif
545
546     *dbuf = (void *)data;
547     *fmt = (int)format;
548     *sz = (size_t)size;
549     *frq = (int)freq;
550
551     return true;
552 }
553
554
555 bool SGSoundMgr::testForError(void *p, string s)
556 {
557    if (p == NULL) {
558       SG_LOG( SG_GENERAL, SG_ALERT, "Error: " << s);
559       return true;
560    }
561    return false;
562 }
563
564
565 bool SGSoundMgr::testForALError(string s)
566 {
567     ALenum error = alGetError();
568     if (error != AL_NO_ERROR)  {
569        SG_LOG( SG_GENERAL, SG_ALERT, "AL Error (sound manager): "
570                                       << alGetString(error) << " at " << s);
571        return true;
572     }
573     return false;
574 }
575
576 bool SGSoundMgr::testForALCError(string s)
577 {
578     ALCenum error;
579     error = alcGetError(_device);
580     if (error != ALC_NO_ERROR) {
581         SG_LOG( SG_GENERAL, SG_ALERT, "ALC Error (sound manager): "
582                                        << alcGetString(_device, error) << " at "
583                                        << s);
584         return true;
585     }
586     return false;
587 }
588
589 bool SGSoundMgr::testForALUTError(string s)
590 {
591 #if defined(ALUT_API_MAJOR_VERSION) && ALUT_API_MAJOR_VERSION >= 1
592     ALenum error;
593     error =  alutGetError ();
594     if (error != ALUT_ERROR_NO_ERROR) {
595         SG_LOG( SG_GENERAL, SG_ALERT, "ALUT Error (sound manager): "
596                                        << alutGetErrorString(error) << " at "
597                                        << s);
598         return true;
599     }
600 #endif
601     return false;
602 }