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