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