]> git.mxchange.org Git - simgear.git/blob - simgear/sound/soundmgr_openal.cxx
010b548d6a274caca07dae45a402b6fbe18d31fe
[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 *vendor = (char *)alGetString(AL_VENDOR);
160     const char *renderer = (char *)alGetString(AL_RENDERER);
161     if (  strcmp(vendor, "OpenAL Community") || strcmp(renderer, "Software")
162           || strcmp(renderer, "OpenAL Sample Implementation") ) {
163        _bad_doppler = true;
164     }
165
166     if (_free_sources.size() == 0) {
167         SG_LOG(SG_GENERAL, SG_ALERT, "Unable to grab any OpenAL sources!");
168     }
169 }
170
171 void SGSoundMgr::activate() {
172     if ( _working ) {
173         _active = true;
174         sample_group_map_iterator sample_grp_current = _sample_groups.begin();
175         sample_group_map_iterator sample_grp_end = _sample_groups.end();
176         for ( ; sample_grp_current != sample_grp_end; ++sample_grp_current ) {
177             SGSampleGroup *sgrp = sample_grp_current->second;
178             sgrp->activate();
179         }
180     }
181 }
182
183 // stop the sound manager
184 void SGSoundMgr::stop() {
185     if (_working) {
186         _working = false;
187         _active = false;
188
189         // clear any OpenAL buffers before shutting down
190         buffer_map_iterator buffers_current = _buffers.begin();
191         buffer_map_iterator buffers_end = _buffers.end();
192         for ( ; buffers_current != buffers_end; ++buffers_current ) {
193             refUint ref = buffers_current->second;
194             ALuint buffer = ref.id;
195             alDeleteBuffers(1, &buffer);
196         }
197         _buffers.clear();
198
199         _context = alcGetCurrentContext();
200         _device = alcGetContextsDevice(_context);
201         alcDestroyContext(_context);
202         alcCloseDevice(_device);
203     }
204 }
205
206 void SGSoundMgr::suspend() {
207     if (_working) {
208         sample_group_map_iterator sample_grp_current = _sample_groups.begin();
209         sample_group_map_iterator sample_grp_end = _sample_groups.end();
210         for ( ; sample_grp_current != sample_grp_end; ++sample_grp_current ) {
211             SGSampleGroup *sgrp = sample_grp_current->second;
212             sgrp->suspend();
213         }
214         _active = false;
215     }
216 }
217
218 void SGSoundMgr::resume() {
219     if (_working) {
220         sample_group_map_iterator sample_grp_current = _sample_groups.begin();
221         sample_group_map_iterator sample_grp_end = _sample_groups.end();
222         for ( ; sample_grp_current != sample_grp_end; ++sample_grp_current ) {
223             SGSampleGroup *sgrp = sample_grp_current->second;
224             sgrp->resume();
225         }
226         _active = true;
227     }
228 }
229
230 void SGSoundMgr::bind ()
231 {
232     _free_sources.clear();
233     _free_sources.reserve( MAX_SOURCES );
234     _sources_in_use.clear();
235     _sources_in_use.reserve( MAX_SOURCES );
236 }
237
238
239 void SGSoundMgr::unbind ()
240 {
241     _sample_groups.clear();
242
243     // delete free sources
244     for (unsigned int i=0; i<_free_sources.size(); i++) {
245         ALuint source = _free_sources[i];
246         alDeleteSources( 1 , &source );
247     }
248
249     _free_sources.clear();
250     _sources_in_use.clear();
251 }
252
253 // run the audio scheduler
254 void SGSoundMgr::update( double dt ) {
255     if (_active) {
256         if (_changed) {
257             update_pos_and_orientation();
258         }
259
260         sample_group_map_iterator sample_grp_current = _sample_groups.begin();
261         sample_group_map_iterator sample_grp_end = _sample_groups.end();
262         for ( ; sample_grp_current != sample_grp_end; ++sample_grp_current ) {
263             SGSampleGroup *sgrp = sample_grp_current->second;
264             sgrp->update(dt);
265         }
266
267         if (_changed) {
268 #if 0
269 if (isNaN(_at_up_vec)) printf("NaN in listener orientation\n");
270 if (isNaN(toVec3f(_absolute_pos).data())) printf("NaN in listener position\n");
271 if (isNaN(_velocity.data())) printf("NaN in listener velocity\n");
272 #endif
273             alListenerf( AL_GAIN, _volume );
274             alListenerfv( AL_ORIENTATION, _at_up_vec );
275             // alListenerfv( AL_POSITION, toVec3f(_absolute_pos).data() );
276
277             SGQuatd hlOr = SGQuatd::fromLonLat( _geod_pos );
278             SGVec3d velocity = SGVec3d::zeros();
279             if ( _velocity[0] || _velocity[1] || _velocity[2] ) {
280                 velocity = hlOr.backTransform(_velocity*SG_FEET_TO_METER);
281             }
282
283             if ( _bad_doppler ) {
284                 velocity *= 100.0f;
285             }
286
287             alListenerfv( AL_VELOCITY, toVec3f(velocity).data() );
288             // alDopplerVelocity(340.3);        // TODO: altitude dependent
289             testForALError("update");
290             _changed = false;
291         }
292     }
293 }
294
295 // add a sample group, return true if successful
296 bool SGSoundMgr::add( SGSampleGroup *sgrp, const string& refname )
297 {
298     sample_group_map_iterator sample_grp_it = _sample_groups.find( refname );
299     if ( sample_grp_it != _sample_groups.end() ) {
300         // sample group already exists
301         return false;
302     }
303
304     if (_active) sgrp->activate();
305     _sample_groups[refname] = sgrp;
306
307     return true;
308 }
309
310
311 // remove a sound effect, return true if successful
312 bool SGSoundMgr::remove( const string &refname )
313 {
314     sample_group_map_iterator sample_grp_it = _sample_groups.find( refname );
315     if ( sample_grp_it == _sample_groups.end() ) {
316         // sample group was not found.
317         return false;
318     }
319
320     _sample_groups.erase( sample_grp_it );
321
322     return true;
323 }
324
325
326 // return true of the specified sound exists in the sound manager system
327 bool SGSoundMgr::exists( const string &refname ) {
328     sample_group_map_iterator sample_grp_it = _sample_groups.find( refname );
329     if ( sample_grp_it == _sample_groups.end() ) {
330         // sample group was not found.
331         return false;
332     }
333
334     return true;
335 }
336
337
338 // return a pointer to the SGSampleGroup if the specified sound exists
339 // in the sound manager system, otherwise return NULL
340 SGSampleGroup *SGSoundMgr::find( const string &refname, bool create ) {
341     sample_group_map_iterator sample_grp_it = _sample_groups.find( refname );
342     if ( sample_grp_it == _sample_groups.end() ) {
343         // sample group was not found.
344         if (create) {
345             SGSampleGroup* sgrp = new SGSampleGroup(this, refname);
346             add( sgrp, refname );
347             return sgrp;
348         }
349         else 
350             return NULL;
351     }
352
353     return sample_grp_it->second;
354 }
355
356
357 void SGSoundMgr::set_volume( float v )
358 {
359     _volume = v;
360     if (_volume > 1.0) _volume = 1.0;
361     if (_volume < 0.0) _volume = 0.0;
362     _changed = true;
363 }
364
365 // Get an unused source id
366 //
367 // The Sound Manager should keep track of the sources in use, the distance
368 // of these sources to the listener and the volume (also based on audio cone
369 // and hence orientation) of the sources.
370 //
371 // The Sound Manager is (and should be) the only one knowing about source
372 // management. Sources further away should be suspendped to free resources for
373 // newly added sounds close by.
374 unsigned int SGSoundMgr::request_source()
375 {
376     unsigned int source = NO_SOURCE;
377
378     if (_free_sources.size() > 0) {
379        source = _free_sources.back();
380        _free_sources.pop_back();
381        _sources_in_use.push_back(source);
382     }
383     else
384        SG_LOG( SG_GENERAL, SG_INFO, "No more free sources available\n");
385
386     return source;
387 }
388
389 // Free up a source id for further use
390 void SGSoundMgr::release_source( unsigned int source )
391 {
392     vector<ALuint>::iterator it;
393
394     it = std::find(_sources_in_use.begin(), _sources_in_use.end(), source);
395     if ( it != _sources_in_use.end() ) {
396         ALint result;
397
398         alGetSourcei( source, AL_SOURCE_STATE, &result );
399         if ( result == AL_PLAYING )
400             alSourceStop( source );
401         testForALError("release source");
402
403         alSourcei( source, AL_BUFFER, 0 );
404         _free_sources.push_back( source );
405         _sources_in_use.erase( it );
406     }
407 }
408
409 unsigned int SGSoundMgr::request_buffer(SGSoundSample *sample)
410 {
411     ALuint buffer = NO_BUFFER;
412
413     if ( !sample->is_valid_buffer() ) {
414         // sample was not yet loaded or removed again
415         string sample_name = sample->get_sample_name();
416
417         // see if the sample name is already cached
418         buffer_map_iterator buffer_it = _buffers.find( sample_name );
419         if ( buffer_it != _buffers.end() ) {
420             buffer_it->second.refctr++;
421             buffer = buffer_it->second.id;
422             sample->set_buffer( buffer );
423             return buffer;
424         }
425
426         // sample name was not found in the buffer cache.
427         if ( sample->is_file() ) {
428             size_t size;
429             int freq, format;
430             void *data;
431
432             load(sample_name, &data, &format, &size, &freq);
433             sample->set_data( &data );
434             sample->set_frequency( freq );
435             sample->set_format( format );
436             sample->set_size( size );
437         }
438
439         // create an OpenAL buffer handle
440         alGenBuffers(1, &buffer);
441         if ( !testForALError("generate buffer") ) {
442             // Copy data to the internal OpenAL buffer
443
444             const ALvoid *data = sample->get_data();
445             ALenum format = sample->get_format();
446             ALsizei size = sample->get_size();
447             ALsizei freq = sample->get_frequency();
448             alBufferData( buffer, format, data, size, freq );
449
450             // If this sample was read from a file we have all the information
451             // needed to read it again. For data buffers provided by the
452             // program we don't; so don't delete it's data.
453             if ( sample->is_file() ) sample->free_data();
454
455             if ( !testForALError("buffer add data") ) {
456                 sample->set_buffer(buffer);
457                 _buffers[sample_name] = refUint(buffer);
458             }
459         }
460     }
461     else {
462         buffer = sample->get_buffer();
463 }
464
465     return buffer;
466 }
467
468 void SGSoundMgr::release_buffer(SGSoundSample *sample)
469 {
470     string sample_name = sample->get_sample_name();
471     buffer_map_iterator buffer_it = _buffers.find( sample_name );
472     if ( buffer_it == _buffers.end() ) {
473         // buffer was not found
474         return;
475     }
476
477     sample->no_valid_buffer();
478     buffer_it->second.refctr--;
479     if (buffer_it->second.refctr == 0) {
480         ALuint buffer = buffer_it->second.id;
481         alDeleteBuffers(1, &buffer);
482         _buffers.erase( buffer_it );
483         testForALError("release buffer");
484     }
485 }
486
487 void SGSoundMgr::update_pos_and_orientation() {
488     /**
489      * Description: ORIENTATION is a pair of 3-tuples representing the
490      * 'at' direction vector and 'up' direction of the Object in
491      * Cartesian space. AL expects two vectors that are orthogonal to
492      * each other. These vectors are not expected to be normalized. If
493      * one or more vectors have zero length, implementation behavior
494      * is undefined. If the two vectors are linearly dependent,
495      * behavior is undefined.
496      *
497      * This is in the same coordinate system as OpenGL; y=up, z=back, x=right.
498      */
499     SGVec3d sgv_at = _orientation.backTransform(-SGVec3d::e3());
500     SGVec3d sgv_up = _orientation.backTransform(SGVec3d::e2());
501     _at_up_vec[0] = sgv_at[0];
502     _at_up_vec[1] = sgv_at[1];
503     _at_up_vec[2] = sgv_at[2];
504     _at_up_vec[3] = sgv_up[0];
505     _at_up_vec[4] = sgv_up[1];
506     _at_up_vec[5] = sgv_up[2];
507
508     // static const SGQuatd q(-0.5, -0.5, 0.5, 0.5);
509     // SGQuatd hlOr = SGQuatd::fromLonLat(SGGeod::fromCart(_base_pos));
510     // SGQuatd ec2body = hlOr*_orientation;
511     _absolute_pos = _base_pos; // + ec2body.backTransform( _offset_pos );
512 }
513
514 bool SGSoundMgr::load(string &samplepath, void **dbuf, int *fmt,
515                                           size_t *sz, int *frq )
516 {
517     if ( !_working ) return false;
518
519     ALenum format;
520     ALsizei size;
521     ALsizei freq;
522     ALvoid *data;
523
524 #if defined(ALUT_API_MAJOR_VERSION) && ALUT_API_MAJOR_VERSION >= 1
525     ALfloat freqf;
526     data = alutLoadMemoryFromFile(samplepath.c_str(), &format, &size, &freqf );
527     freq = (ALsizei)freqf;
528     if (data == NULL) {
529         int error = alutGetError();
530         string msg = "Failed to load wav file: ";
531         msg.append(alutGetErrorString(error));
532         throw sg_io_exception(msg.c_str(), sg_location(samplepath));
533         return false;
534     }
535
536 #else
537     ALbyte *fname = (ALbyte *)samplepath.c_str();
538 # if defined (__APPLE__)
539     alutLoadWAVFile( fname, &format, &data, &size, &freq );
540 # else
541     ALboolean loop;
542     alutLoadWAVFile( fname, &format, &data, &size, &freq, &loop );
543 # endif
544     ALenum error =  alGetError();
545     if ( error != AL_NO_ERROR ) {
546         string msg = "Failed to load wav file: ";
547         msg.append(alGetString(error));
548         throw sg_io_exception(msg.c_str(), sg_location(samplepath));
549         return false;
550     }
551 #endif
552
553     *dbuf = (void *)data;
554     *fmt = (int)format;
555     *sz = (size_t)size;
556     *frq = (int)freq;
557
558     return true;
559 }
560
561
562 bool SGSoundMgr::testForError(void *p, string s)
563 {
564    if (p == NULL) {
565       SG_LOG( SG_GENERAL, SG_ALERT, "Error: " << s);
566       return true;
567    }
568    return false;
569 }
570
571
572 bool SGSoundMgr::testForALError(string s)
573 {
574     ALenum error = alGetError();
575     if (error != AL_NO_ERROR)  {
576        SG_LOG( SG_GENERAL, SG_ALERT, "AL Error (sound manager): "
577                                       << alGetString(error) << " at " << s);
578        return true;
579     }
580     return false;
581 }
582
583 bool SGSoundMgr::testForALCError(string s)
584 {
585     ALCenum error;
586     error = alcGetError(_device);
587     if (error != ALC_NO_ERROR) {
588         SG_LOG( SG_GENERAL, SG_ALERT, "ALC Error (sound manager): "
589                                        << alcGetString(_device, error) << " at "
590                                        << s);
591         return true;
592     }
593     return false;
594 }
595
596 bool SGSoundMgr::testForALUTError(string s)
597 {
598 #if defined(ALUT_API_MAJOR_VERSION) && ALUT_API_MAJOR_VERSION >= 1
599     ALenum error;
600     error =  alutGetError ();
601     if (error != ALUT_ERROR_NO_ERROR) {
602         SG_LOG( SG_GENERAL, SG_ALERT, "ALUT Error (sound manager): "
603                                        << alutGetErrorString(error) << " at "
604                                        << s);
605         return true;
606     }
607 #endif
608     return false;
609 }