]> git.mxchange.org Git - simgear.git/blob - simgear/sound/soundmgr_openal.cxx
7b18d61f65a52bfe238632e50dcf12974bfc9496
[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     _bad_doppler(false),
73     _renderer("unknown"),
74     _vendor("unknown")
75 {
76 #if defined(ALUT_API_MAJOR_VERSION) && ALUT_API_MAJOR_VERSION >= 1
77     if (_alut_init == 0) {
78         if ( !alutInitWithoutContext(NULL, NULL) ) {
79             testForALUTError("alut initialization");
80             return;
81         }
82     }
83     _alut_init++;
84 #endif
85 }
86
87 // destructor
88
89 SGSoundMgr::~SGSoundMgr() {
90
91     stop();
92 #if defined(ALUT_API_MAJOR_VERSION) && ALUT_API_MAJOR_VERSION >= 1
93     _alut_init--;
94     if (_alut_init == 0) {
95         alutExit ();
96     }
97 #endif
98 }
99
100 // initialize the sound manager
101 void SGSoundMgr::init(const char *devname) {
102
103     SG_LOG( SG_GENERAL, SG_INFO, "Initializing OpenAL sound manager" );
104
105     ALCdevice *device = alcOpenDevice(devname);
106     if ( testForError(device, "Audio device not available, trying default") ) {
107         device = alcOpenDevice(NULL);
108         if (testForError(device, "Default Audio device not available.") ) {
109            return;
110         }
111     }
112
113     ALCcontext *context = alcCreateContext(device, NULL);
114     if ( testForError(context, "Unable to create a valid context.") ) {
115         alcCloseDevice (device);
116         return;
117     }
118
119     if ( !alcMakeContextCurrent(context) ) {
120         testForALCError("context initialization");
121         alcDestroyContext (context);
122         alcCloseDevice (device);
123         return;
124     }
125
126     if (_context != NULL)
127         SG_LOG(SG_GENERAL, SG_ALERT, "context is already assigned");
128     _context = context;
129     _working = true;
130
131     _at_up_vec[0] = 0.0; _at_up_vec[1] = 0.0; _at_up_vec[2] = -1.0;
132     _at_up_vec[3] = 0.0; _at_up_vec[4] = 1.0; _at_up_vec[5] = 0.0;
133
134     alListenerf( AL_GAIN, 0.0f );
135     alListenerfv( AL_ORIENTATION, _at_up_vec );
136     alListenerfv( AL_POSITION, SGVec3f::zeros().data() );
137     alListenerfv( AL_VELOCITY, SGVec3f::zeros().data() );
138
139     alDopplerFactor(1.0);
140     alDopplerVelocity(340.3);   // speed of sound in meters per second.
141
142     // gain = AL_REFERENCE_DISTANCE / (AL_REFERENCE_DISTANCE +
143     //        AL_ROLLOFF_FACTOR * (distance - AL_REFERENCE_DISTANCE));
144     alDistanceModel(AL_INVERSE_DISTANCE_CLAMPED);
145
146     testForALError("listener initialization");
147
148     // get a free source one at a time
149     // if an error is returned no more (hardware) sources are available
150     for (unsigned int i=0; i<MAX_SOURCES; i++) {
151         ALuint source;
152         ALenum error;
153
154         alGetError();
155         alGenSources(1, &source);
156         error = alGetError();
157         if ( error == AL_NO_ERROR ) {
158             _free_sources.push_back( source );
159         }
160         else break;
161     }
162
163     _vendor = (const char *)alGetString(AL_VENDOR);
164     _renderer = (const char *)alGetString(AL_RENDERER);
165     if ( _vendor != "OpenAL Community" ||
166         (_renderer != "Software" && _renderer != "OpenAL Sample Implementation")
167        )
168     {
169        _bad_doppler = true;
170     }
171
172     if (_free_sources.size() == 0) {
173         SG_LOG(SG_GENERAL, SG_ALERT, "Unable to grab any OpenAL sources!");
174     }
175 }
176
177 void SGSoundMgr::activate() {
178     if ( _working ) {
179         _active = true;
180         sample_group_map_iterator sample_grp_current = _sample_groups.begin();
181         sample_group_map_iterator sample_grp_end = _sample_groups.end();
182         for ( ; sample_grp_current != sample_grp_end; ++sample_grp_current ) {
183             SGSampleGroup *sgrp = sample_grp_current->second;
184             sgrp->activate();
185         }
186     }
187 }
188
189 // stop the sound manager
190 void SGSoundMgr::stop() {
191
192     // first stop all sample groups
193     sample_group_map_iterator sample_grp_current = _sample_groups.begin();
194     sample_group_map_iterator sample_grp_end = _sample_groups.end();
195     for ( ; sample_grp_current != sample_grp_end; ++sample_grp_current ) {
196         SGSampleGroup *sgrp = sample_grp_current->second;
197         sgrp->stop();
198     }
199
200     // clear all OpenAL sources
201     for (unsigned int i=0; i<_free_sources.size(); i++) {
202         ALuint source = _free_sources[i];
203         alDeleteSources( 1 , &source );
204     }
205     _free_sources.clear();
206
207     // clear any OpenAL buffers before shutting down
208     buffer_map_iterator buffers_current = _buffers.begin();
209     buffer_map_iterator buffers_end = _buffers.end();
210     for ( ; buffers_current != buffers_end; ++buffers_current ) {
211         refUint ref = buffers_current->second;
212         ALuint buffer = ref.id;
213         alDeleteBuffers(1, &buffer);
214     }
215     _buffers.clear();
216
217     if (_working) {
218         _working = false;
219         _active = false;
220         _context = alcGetCurrentContext();
221         _device = alcGetContextsDevice(_context);
222         alcDestroyContext(_context);
223         alcCloseDevice(_device);
224         _context = NULL;
225
226         _renderer = "unknown";
227         _vendor = "unknown";
228     }
229 }
230
231 void SGSoundMgr::suspend() {
232     if (_working) {
233         sample_group_map_iterator sample_grp_current = _sample_groups.begin();
234         sample_group_map_iterator sample_grp_end = _sample_groups.end();
235         for ( ; sample_grp_current != sample_grp_end; ++sample_grp_current ) {
236             SGSampleGroup *sgrp = sample_grp_current->second;
237             sgrp->stop();
238         }
239         _active = false;
240     }
241 }
242
243 void SGSoundMgr::resume() {
244     if (_working) {
245         sample_group_map_iterator sample_grp_current = _sample_groups.begin();
246         sample_group_map_iterator sample_grp_end = _sample_groups.end();
247         for ( ; sample_grp_current != sample_grp_end; ++sample_grp_current ) {
248             SGSampleGroup *sgrp = sample_grp_current->second;
249             sgrp->resume();
250         }
251         _active = true;
252     }
253 }
254
255 void SGSoundMgr::bind ()
256 {
257     _free_sources.clear();
258     _free_sources.reserve( MAX_SOURCES );
259     _sources_in_use.clear();
260     _sources_in_use.reserve( MAX_SOURCES );
261 }
262
263
264 void SGSoundMgr::unbind ()
265 {
266     _sample_groups.clear();
267
268     // delete free sources
269     for (unsigned int i=0; i<_free_sources.size(); i++) {
270         ALuint source = _free_sources[i];
271         alDeleteSources( 1 , &source );
272     }
273
274     _free_sources.clear();
275     _sources_in_use.clear();
276 }
277
278 // run the audio scheduler
279 void SGSoundMgr::update( double dt ) {
280     if (_active) {
281         alcSuspendContext(_context);
282
283         if (_changed) {
284             update_pos_and_orientation();
285         }
286
287         sample_group_map_iterator sample_grp_current = _sample_groups.begin();
288         sample_group_map_iterator sample_grp_end = _sample_groups.end();
289         for ( ; sample_grp_current != sample_grp_end; ++sample_grp_current ) {
290             SGSampleGroup *sgrp = sample_grp_current->second;
291             sgrp->update(dt);
292         }
293
294         if (_changed) {
295 #if 0
296 if (isNaN(_at_up_vec)) printf("NaN in listener orientation\n");
297 if (isNaN(toVec3f(_absolute_pos).data())) printf("NaN in listener position\n");
298 if (isNaN(_velocity.data())) printf("NaN in listener velocity\n");
299 #endif
300             alListenerf( AL_GAIN, _volume );
301             alListenerfv( AL_ORIENTATION, _at_up_vec );
302             // alListenerfv( AL_POSITION, toVec3f(_absolute_pos).data() );
303
304             SGQuatd hlOr = SGQuatd::fromLonLat( _geod_pos );
305             SGVec3d velocity = SGVec3d::zeros();
306             if ( _velocity[0] || _velocity[1] || _velocity[2] ) {
307                 velocity = hlOr.backTransform(_velocity*SG_FEET_TO_METER);
308             }
309
310             if ( _bad_doppler ) {
311                 velocity *= 100.0f;
312             }
313
314             alListenerfv( AL_VELOCITY, toVec3f(velocity).data() );
315             // alDopplerVelocity(340.3);        // TODO: altitude dependent
316             testForALError("update");
317             _changed = false;
318         }
319
320         alcProcessContext(_context);
321     }
322 }
323
324 // add a sample group, return true if successful
325 bool SGSoundMgr::add( SGSampleGroup *sgrp, const string& refname )
326 {
327     sample_group_map_iterator sample_grp_it = _sample_groups.find( refname );
328     if ( sample_grp_it != _sample_groups.end() ) {
329         // sample group already exists
330         return false;
331     }
332
333     if (_active) sgrp->activate();
334     _sample_groups[refname] = sgrp;
335
336     return true;
337 }
338
339
340 // remove a sound effect, return true if successful
341 bool SGSoundMgr::remove( const string &refname )
342 {
343     sample_group_map_iterator sample_grp_it = _sample_groups.find( refname );
344     if ( sample_grp_it == _sample_groups.end() ) {
345         // sample group was not found.
346         return false;
347     }
348
349     _sample_groups.erase( sample_grp_it );
350
351     return true;
352 }
353
354
355 // return true of the specified sound exists in the sound manager system
356 bool SGSoundMgr::exists( const string &refname ) {
357     sample_group_map_iterator sample_grp_it = _sample_groups.find( refname );
358     if ( sample_grp_it == _sample_groups.end() ) {
359         // sample group was not found.
360         return false;
361     }
362
363     return true;
364 }
365
366
367 // return a pointer to the SGSampleGroup if the specified sound exists
368 // in the sound manager system, otherwise return NULL
369 SGSampleGroup *SGSoundMgr::find( const string &refname, bool create ) {
370     sample_group_map_iterator sample_grp_it = _sample_groups.find( refname );
371     if ( sample_grp_it == _sample_groups.end() ) {
372         // sample group was not found.
373         if (create) {
374             SGSampleGroup* sgrp = new SGSampleGroup(this, refname);
375             add( sgrp, refname );
376             return sgrp;
377         }
378         else 
379             return NULL;
380     }
381
382     return sample_grp_it->second;
383 }
384
385
386 void SGSoundMgr::set_volume( float v )
387 {
388     _volume = v;
389     if (_volume > 1.0) _volume = 1.0;
390     if (_volume < 0.0) _volume = 0.0;
391     _changed = true;
392 }
393
394 // Get an unused source id
395 //
396 // The Sound Manager should keep track of the sources in use, the distance
397 // of these sources to the listener and the volume (also based on audio cone
398 // and hence orientation) of the sources.
399 //
400 // The Sound Manager is (and should be) the only one knowing about source
401 // management. Sources further away should be suspendped to free resources for
402 // newly added sounds close by.
403 unsigned int SGSoundMgr::request_source()
404 {
405     unsigned int source = NO_SOURCE;
406
407     if (_free_sources.size() > 0) {
408        source = _free_sources.back();
409        _free_sources.pop_back();
410        _sources_in_use.push_back(source);
411     }
412     else
413        SG_LOG( SG_GENERAL, SG_INFO, "No more free sources available\n");
414
415     return source;
416 }
417
418 // Free up a source id for further use
419 void SGSoundMgr::release_source( unsigned int source )
420 {
421     vector<ALuint>::iterator it;
422
423     it = std::find(_sources_in_use.begin(), _sources_in_use.end(), source);
424     if ( it != _sources_in_use.end() ) {
425         ALint result;
426
427         alGetSourcei( source, AL_SOURCE_STATE, &result );
428         if ( result == AL_PLAYING )
429             alSourceStop( source );
430         testForALError("release source");
431
432         alSourcei( source, AL_BUFFER, 0 );
433         _free_sources.push_back( source );
434         _sources_in_use.erase( it );
435     }
436 }
437
438 unsigned int SGSoundMgr::request_buffer(SGSoundSample *sample)
439 {
440     ALuint buffer = NO_BUFFER;
441
442     if ( !sample->is_valid_buffer() ) {
443         // sample was not yet loaded or removed again
444         string sample_name = sample->get_sample_name();
445         void *sample_data = NULL;
446
447         // see if the sample name is already cached
448         buffer_map_iterator buffer_it = _buffers.find( sample_name );
449         if ( buffer_it != _buffers.end() ) {
450             buffer_it->second.refctr++;
451             buffer = buffer_it->second.id;
452             sample->set_buffer( buffer );
453             return buffer;
454         }
455
456         // sample name was not found in the buffer cache.
457         if ( sample->is_file() ) {
458             int freq, format;
459             size_t size;
460             bool res;
461
462             res = load(sample_name, &sample_data, &format, &size, &freq);
463             if (res == false) return buffer;
464
465             sample->set_frequency( freq );
466             sample->set_format( format );
467             sample->set_size( size );
468         }
469         else
470             sample_data = sample->get_data();
471
472         // create an OpenAL buffer handle
473         alGenBuffers(1, &buffer);
474         if ( !testForALError("generate buffer") ) {
475             // Copy data to the internal OpenAL buffer
476
477             ALenum format = sample->get_format();
478             ALsizei size = sample->get_size();
479             ALsizei freq = sample->get_frequency();
480             alBufferData( buffer, format, sample_data, size, freq );
481
482             if ( sample->is_file() ) free(sample_data);
483
484             if ( !testForALError("buffer add data") ) {
485                 sample->set_buffer(buffer);
486                 _buffers[sample_name] = refUint(buffer);
487             }
488         }
489     }
490     else {
491         buffer = sample->get_buffer();
492 }
493
494     return buffer;
495 }
496
497 void SGSoundMgr::release_buffer(SGSoundSample *sample)
498 {
499     string sample_name = sample->get_sample_name();
500     buffer_map_iterator buffer_it = _buffers.find( sample_name );
501     if ( buffer_it == _buffers.end() ) {
502         // buffer was not found
503         return;
504     }
505
506     sample->no_valid_buffer();
507     buffer_it->second.refctr--;
508     if (buffer_it->second.refctr == 0) {
509         ALuint buffer = buffer_it->second.id;
510         alDeleteBuffers(1, &buffer);
511         _buffers.erase( buffer_it );
512         testForALError("release buffer");
513     }
514 }
515
516 void SGSoundMgr::update_pos_and_orientation() {
517     /**
518      * Description: ORIENTATION is a pair of 3-tuples representing the
519      * 'at' direction vector and 'up' direction of the Object in
520      * Cartesian space. AL expects two vectors that are orthogonal to
521      * each other. These vectors are not expected to be normalized. If
522      * one or more vectors have zero length, implementation behavior
523      * is undefined. If the two vectors are linearly dependent,
524      * behavior is undefined.
525      *
526      * This is in the same coordinate system as OpenGL; y=up, z=back, x=right.
527      */
528     SGVec3d sgv_at = _orientation.backTransform(-SGVec3d::e3());
529     SGVec3d sgv_up = _orientation.backTransform(SGVec3d::e2());
530     _at_up_vec[0] = sgv_at[0];
531     _at_up_vec[1] = sgv_at[1];
532     _at_up_vec[2] = sgv_at[2];
533     _at_up_vec[3] = sgv_up[0];
534     _at_up_vec[4] = sgv_up[1];
535     _at_up_vec[5] = sgv_up[2];
536
537     // static const SGQuatd q(-0.5, -0.5, 0.5, 0.5);
538     // SGQuatd hlOr = SGQuatd::fromLonLat(SGGeod::fromCart(_base_pos));
539     // SGQuatd ec2body = hlOr*_orientation;
540     _absolute_pos = _base_pos; // + ec2body.backTransform( _offset_pos );
541 }
542
543 bool SGSoundMgr::load(string &samplepath, void **dbuf, int *fmt,
544                                           size_t *sz, int *frq )
545 {
546     if ( !_working ) return false;
547
548     ALenum format;
549     ALsizei size;
550     ALsizei freq;
551     ALvoid *data;
552
553 #if defined(ALUT_API_MAJOR_VERSION) && ALUT_API_MAJOR_VERSION >= 1
554     ALfloat freqf;
555     data = alutLoadMemoryFromFile(samplepath.c_str(), &format, &size, &freqf );
556     freq = (ALsizei)freqf;
557     if (data == NULL) {
558         int error = alutGetError();
559         string msg = "Failed to load wav file: ";
560         msg.append(alutGetErrorString(error));
561         throw sg_io_exception(msg.c_str(), sg_location(samplepath));
562         return false;
563     }
564
565 #else
566     ALbyte *fname = (ALbyte *)samplepath.c_str();
567 # if defined (__APPLE__)
568     alutLoadWAVFile( fname, &format, &data, &size, &freq );
569 # else
570     ALboolean loop;
571     alutLoadWAVFile( fname, &format, &data, &size, &freq, &loop );
572 # endif
573     ALenum error =  alGetError();
574     if ( error != AL_NO_ERROR ) {
575         string msg = "Failed to load wav file: ";
576         msg.append(alGetString(error));
577         throw sg_io_exception(msg.c_str(), sg_location(samplepath));
578         return false;
579     }
580 #endif
581
582     *dbuf = (void *)data;
583     *fmt = (int)format;
584     *sz = (size_t)size;
585     *frq = (int)freq;
586
587     return true;
588 }
589
590 vector<const char*> SGSoundMgr::get_available_devices()
591 {
592     vector<const char*> devices;
593     const ALCchar *s;
594
595     if (alcIsExtensionPresent(NULL, "ALC_enumerate_all_EXT") == AL_TRUE) {
596         s = alcGetString(NULL, ALC_ALL_DEVICES_SPECIFIER);
597     } else {
598         s = alcGetString(NULL, ALC_DEVICE_SPECIFIER);
599     }
600
601     if (s) {
602         ALCchar *nptr, *ptr = (ALCchar *)s;
603
604         nptr = ptr;
605         while (*(nptr += strlen(ptr)+1) != 0)
606         {
607             devices.push_back(ptr);
608             ptr = nptr;
609         }
610         devices.push_back(ptr);
611     }
612
613     return devices;
614 }
615
616
617 bool SGSoundMgr::testForError(void *p, string s)
618 {
619    if (p == NULL) {
620       SG_LOG( SG_GENERAL, SG_ALERT, "Error: " << s);
621       return true;
622    }
623    return false;
624 }
625
626
627 bool SGSoundMgr::testForALError(string s)
628 {
629     ALenum error = alGetError();
630     if (error != AL_NO_ERROR)  {
631        SG_LOG( SG_GENERAL, SG_ALERT, "AL Error (sound manager): "
632                                       << alGetString(error) << " at " << s);
633        return true;
634     }
635     return false;
636 }
637
638 bool SGSoundMgr::testForALCError(string s)
639 {
640     ALCenum error;
641     error = alcGetError(_device);
642     if (error != ALC_NO_ERROR) {
643         SG_LOG( SG_GENERAL, SG_ALERT, "ALC Error (sound manager): "
644                                        << alcGetString(_device, error) << " at "
645                                        << s);
646         return true;
647     }
648     return false;
649 }
650
651 bool SGSoundMgr::testForALUTError(string s)
652 {
653 #if defined(ALUT_API_MAJOR_VERSION) && ALUT_API_MAJOR_VERSION >= 1
654     ALenum error;
655     error =  alutGetError ();
656     if (error != ALUT_ERROR_NO_ERROR) {
657         SG_LOG( SG_GENERAL, SG_ALERT, "ALUT Error (sound manager): "
658                                        << alutGetErrorString(error) << " at "
659                                        << s);
660         return true;
661     }
662 #endif
663     return false;
664 }