]> git.mxchange.org Git - simgear.git/blob - simgear/sound/soundmgr_openal.cxx
It looks like the current version of OpenAL-Soft has better Doppler support
[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 #if 0
243     } else if (_vendor == "OpenAL Community" && _renderer == "OpenAL Soft") {
244        _bad_doppler = true;
245 #endif
246     }
247
248     if (d->_free_sources.empty()) {
249         SG_LOG(SG_SOUND, SG_ALERT, "Unable to grab any OpenAL sources!");
250     }
251 #endif
252 }
253
254 void SGSoundMgr::reinit()
255 {
256     bool was_active = _active;
257
258     if (was_active)
259     {
260         suspend();
261     }
262
263     SGSoundMgr::stop();
264     SGSoundMgr::init();
265
266     if (was_active)
267         resume();
268 }
269
270 void SGSoundMgr::activate()
271 {
272 #ifdef ENABLE_SOUND
273     if ( is_working() ) {
274         _active = true;
275                 
276         sample_group_map_iterator sample_grp_current = d->_sample_groups.begin();
277         sample_group_map_iterator sample_grp_end = d->_sample_groups.end();
278         for ( ; sample_grp_current != sample_grp_end; ++sample_grp_current ) {
279             SGSampleGroup *sgrp = sample_grp_current->second;
280             sgrp->activate();
281         }
282     }
283 #endif
284 }
285
286 // stop the sound manager
287 void SGSoundMgr::stop()
288 {
289 #ifdef ENABLE_SOUND
290     // first stop all sample groups
291     sample_group_map_iterator sample_grp_current = d->_sample_groups.begin();
292     sample_group_map_iterator sample_grp_end = d->_sample_groups.end();
293     for ( ; sample_grp_current != sample_grp_end; ++sample_grp_current ) {
294         SGSampleGroup *sgrp = sample_grp_current->second;
295         sgrp->stop();
296     }
297
298     // clear all OpenAL sources
299     BOOST_FOREACH(ALuint source, d->_free_sources) {
300         alDeleteSources( 1 , &source );
301         testForALError("SGSoundMgr::stop: delete sources");
302     }
303     d->_free_sources.clear();
304
305     // clear any OpenAL buffers before shutting down
306     buffer_map_iterator buffers_current = d->_buffers.begin();
307     buffer_map_iterator buffers_end = d->_buffers.end();
308     for ( ; buffers_current != buffers_end; ++buffers_current ) {
309         refUint ref = buffers_current->second;
310         ALuint buffer = ref.id;
311         alDeleteBuffers(1, &buffer);
312         testForALError("SGSoundMgr::stop: delete buffers");
313     }
314     
315     d->_buffers.clear();
316     d->_sources_in_use.clear();
317
318     if (is_working()) {
319         _active = false;
320         alcDestroyContext(d->_context);
321         alcCloseDevice(d->_device);
322         d->_context = NULL;
323         d->_device = NULL;
324
325         _renderer = "unknown";
326         _vendor = "unknown";
327     }
328 #endif
329 }
330
331 void SGSoundMgr::suspend()
332 {
333 #ifdef ENABLE_SOUND
334     if (is_working()) {
335         sample_group_map_iterator sample_grp_current = d->_sample_groups.begin();
336         sample_group_map_iterator sample_grp_end = d->_sample_groups.end();
337         for ( ; sample_grp_current != sample_grp_end; ++sample_grp_current ) {
338             SGSampleGroup *sgrp = sample_grp_current->second;
339             sgrp->stop();
340         }
341         _active = false;
342     }
343 #endif
344 }
345
346 void SGSoundMgr::resume()
347 {
348 #ifdef ENABLE_SOUND
349     if (is_working()) {
350         sample_group_map_iterator sample_grp_current = d->_sample_groups.begin();
351         sample_group_map_iterator sample_grp_end = d->_sample_groups.end();
352         for ( ; sample_grp_current != sample_grp_end; ++sample_grp_current ) {
353             SGSampleGroup *sgrp = sample_grp_current->second;
354             sgrp->resume();
355         }
356         _active = true;
357     }
358 #endif
359 }
360
361 // run the audio scheduler
362 void SGSoundMgr::update( double dt )
363 {
364 #ifdef ENABLE_SOUND
365     if (_active) {
366         alcSuspendContext(d->_context);
367
368         if (_changed) {
369             d->update_pos_and_orientation();
370         }
371
372         sample_group_map_iterator sample_grp_current = d->_sample_groups.begin();
373         sample_group_map_iterator sample_grp_end = d->_sample_groups.end();
374         for ( ; sample_grp_current != sample_grp_end; ++sample_grp_current ) {
375             SGSampleGroup *sgrp = sample_grp_current->second;
376             sgrp->update(dt);
377         }
378
379         if (_changed) {
380 #if 0
381 if (isNaN(_at_up_vec)) printf("NaN in listener orientation\n");
382 if (isNaN(toVec3f(_absolute_pos).data())) printf("NaN in listener position\n");
383 if (isNaN(_velocity.data())) printf("NaN in listener velocity\n");
384 #endif
385             alListenerf( AL_GAIN, _volume );
386             alListenerfv( AL_ORIENTATION, d->_at_up_vec );
387             // alListenerfv( AL_POSITION, toVec3f(_absolute_pos).data() );
388
389             SGQuatd hlOr = SGQuatd::fromLonLat( _geod_pos );
390             SGVec3d velocity = SGVec3d::zeros();
391             if ( _velocity[0] || _velocity[1] || _velocity[2] ) {
392                 velocity = hlOr.backTransform(_velocity*SG_FEET_TO_METER);
393             }
394
395             if ( _bad_doppler ) {
396                 velocity *= 100.0f;
397             }
398
399             alListenerfv( AL_VELOCITY, toVec3f(velocity).data() );
400             // alDopplerVelocity(340.3);        // TODO: altitude dependent
401             testForALError("update");
402             _changed = false;
403         }
404
405         alcProcessContext(d->_context);
406     }
407 #endif
408 }
409
410 // add a sample group, return true if successful
411 bool SGSoundMgr::add( SGSampleGroup *sgrp, const std::string& refname )
412 {
413     sample_group_map_iterator sample_grp_it = d->_sample_groups.find( refname );
414     if ( sample_grp_it != d->_sample_groups.end() ) {
415         // sample group already exists
416         return false;
417     }
418
419     if (_active) sgrp->activate();
420     d->_sample_groups[refname] = sgrp;
421
422     return true;
423 }
424
425
426 // remove a sound effect, return true if successful
427 bool SGSoundMgr::remove( const std::string &refname )
428 {
429     sample_group_map_iterator sample_grp_it = d->_sample_groups.find( refname );
430     if ( sample_grp_it == d->_sample_groups.end() ) {
431         // sample group was not found.
432         return false;
433     }
434
435     d->_sample_groups.erase( sample_grp_it );
436
437     return true;
438 }
439
440
441 // return true of the specified sound exists in the sound manager system
442 bool SGSoundMgr::exists( const std::string &refname ) {
443     sample_group_map_iterator sample_grp_it = d->_sample_groups.find( refname );
444     return ( sample_grp_it != d->_sample_groups.end() );
445 }
446
447
448 // return a pointer to the SGSampleGroup if the specified sound exists
449 // in the sound manager system, otherwise return NULL
450 SGSampleGroup *SGSoundMgr::find( const std::string &refname, bool create ) {
451     sample_group_map_iterator sample_grp_it = d->_sample_groups.find( refname );
452     if ( sample_grp_it == d->_sample_groups.end() ) {
453         // sample group was not found.
454         if (create) {
455             SGSampleGroup* sgrp = new SGSampleGroup(this, refname);
456             add( sgrp, refname );
457             return sgrp;
458         }
459         else 
460             return NULL;
461     }
462
463     return sample_grp_it->second;
464 }
465
466
467 void SGSoundMgr::set_volume( float v )
468 {
469     _volume = v;
470     SG_CLAMP_RANGE(_volume, 0.0f, 1.0f);
471     _changed = true;
472 }
473
474 // Get an unused source id
475 //
476 // The Sound Manager should keep track of the sources in use, the distance
477 // of these sources to the listener and the volume (also based on audio cone
478 // and hence orientation) of the sources.
479 //
480 // The Sound Manager is (and should be) the only one knowing about source
481 // management. Sources further away should be suspended to free resources for
482 // newly added sounds close by.
483 unsigned int SGSoundMgr::request_source()
484 {
485     unsigned int source = NO_SOURCE;
486
487     if (!d->_free_sources.empty()) {
488        source = d->_free_sources.back();
489        d->_free_sources.pop_back();
490        d->_sources_in_use.push_back(source);
491     }
492     else
493        SG_LOG( SG_SOUND, SG_BULK, "Sound manager: No more free sources available!\n");
494
495     return source;
496 }
497
498 // Free up a source id for further use
499 void SGSoundMgr::release_source( unsigned int source )
500 {
501     vector<ALuint>::iterator it;
502
503     it = std::find(d->_sources_in_use.begin(), d->_sources_in_use.end(), source);
504     if ( it != d->_sources_in_use.end() ) {
505   #ifdef ENABLE_SOUND
506         ALint result;
507
508         alGetSourcei( source, AL_SOURCE_STATE, &result );
509         if ( result == AL_PLAYING || result == AL_PAUSED ) {
510             alSourceStop( source );
511         }
512
513         alSourcei( source, AL_BUFFER, 0 );      // detach the associated buffer
514         testForALError("release_source");
515   #endif
516         d->_free_sources.push_back( source );
517         d->_sources_in_use.erase( it );
518     }
519 }
520
521 unsigned int SGSoundMgr::request_buffer(SGSoundSample *sample)
522 {
523     ALuint buffer = NO_BUFFER;
524 #ifdef ENABLE_SOUND
525     if ( !sample->is_valid_buffer() ) {
526         // sample was not yet loaded or removed again
527         std::string sample_name = sample->get_sample_name();
528         void *sample_data = NULL;
529
530         // see if the sample name is already cached
531         buffer_map_iterator buffer_it = d->_buffers.find( sample_name );
532         if ( buffer_it != d->_buffers.end() ) {
533             buffer_it->second.refctr++;
534             buffer = buffer_it->second.id;
535             sample->set_buffer( buffer );
536             return buffer;
537         }
538
539         // sample name was not found in the buffer cache.
540         if ( sample->is_file() ) {
541             int freq, format;
542             size_t size;
543
544             try {
545               bool res = load(sample_name, &sample_data, &format, &size, &freq);
546               if (res == false) return NO_BUFFER;
547             } catch (sg_exception& e) {
548               SG_LOG(SG_SOUND, SG_ALERT,
549                     "failed to load sound buffer: " << e.getFormattedMessage());
550               sample->set_buffer( SGSoundMgr::FAILED_BUFFER );
551               return FAILED_BUFFER;
552             }
553             
554             sample->set_frequency( freq );
555             sample->set_format( format );
556             sample->set_size( size );
557
558         } else {
559             sample_data = sample->get_data();
560         }
561
562         // create an OpenAL buffer handle
563         alGenBuffers(1, &buffer);
564         if ( !testForALError("generate buffer") ) {
565             // Copy data to the internal OpenAL buffer
566
567             ALenum format = sample->get_format();
568             ALsizei size = sample->get_size();
569             ALsizei freq = sample->get_frequency();
570             alBufferData( buffer, format, sample_data, size, freq );
571
572             if ( !testForALError("buffer add data") ) {
573                 sample->set_buffer(buffer);
574                 d->_buffers[sample_name] = refUint(buffer);
575             }
576         }
577
578         if ( sample->is_file() ) free(sample_data);
579     }
580     else {
581         buffer = sample->get_buffer();
582     }
583 #endif
584     return buffer;
585 }
586
587 void SGSoundMgr::release_buffer(SGSoundSample *sample)
588 {
589     if ( !sample->is_queue() )
590     {
591         std::string sample_name = sample->get_sample_name();
592         buffer_map_iterator buffer_it = d->_buffers.find( sample_name );
593         if ( buffer_it == d->_buffers.end() ) {
594             // buffer was not found
595             return;
596         }
597
598         sample->no_valid_buffer();
599         buffer_it->second.refctr--;
600         if (buffer_it->second.refctr == 0) {
601 #ifdef ENABLE_SOUND
602             ALuint buffer = buffer_it->second.id;
603             alDeleteBuffers(1, &buffer);
604 #endif
605             d->_buffers.erase( buffer_it );
606             testForALError("release buffer");
607         }
608     }
609 }
610
611 bool SGSoundMgr::load( const std::string &samplepath,
612                        void **dbuf,
613                        int *fmt,
614                        size_t *sz,
615                        int *frq )
616 {
617     if ( !is_working() )
618         return false;
619
620     ALenum format;
621     ALsizei size;
622     ALsizei freq;
623     ALvoid *data;
624
625     ALfloat freqf;
626
627     data = simgear::loadWAVFromFile(samplepath, format, size, freqf );
628     freq = (ALsizei)freqf;
629     if (data == NULL) {
630         throw sg_io_exception("Failed to load wav file", sg_location(samplepath));
631     }
632
633     if (format == AL_FORMAT_STEREO8 || format == AL_FORMAT_STEREO16) {
634         free(data);
635         throw sg_io_exception("Warning: STEREO files are not supported for 3D audio effects: " + samplepath);
636     }
637
638     *dbuf = (void *)data;
639     *fmt = (int)format;
640     *sz = (size_t)size;
641     *frq = (int)freq;
642
643     return true;
644 }
645
646 vector<const char*> SGSoundMgr::get_available_devices()
647 {
648     vector<const char*> devices;
649 #ifdef ENABLE_SOUND
650     const ALCchar *s;
651
652     if (alcIsExtensionPresent(NULL, "ALC_enumerate_all_EXT") == AL_TRUE) {
653         s = alcGetString(NULL, ALC_ALL_DEVICES_SPECIFIER);
654     } else {
655         s = alcGetString(NULL, ALC_DEVICE_SPECIFIER);
656     }
657
658     if (s) {
659         ALCchar *nptr, *ptr = (ALCchar *)s;
660
661         nptr = ptr;
662         while (*(nptr += strlen(ptr)+1) != 0)
663         {
664             devices.push_back(ptr);
665             ptr = nptr;
666         }
667         devices.push_back(ptr);
668     }
669 #endif
670     return devices;
671 }
672
673
674 bool SGSoundMgr::testForError(void *p, std::string s)
675 {
676    if (p == NULL) {
677       SG_LOG( SG_SOUND, SG_ALERT, "Error: " << s);
678       return true;
679    }
680    return false;
681 }
682
683
684 bool SGSoundMgr::testForALError(std::string s)
685 {
686 #ifdef ENABLE_SOUND
687     ALenum error = alGetError();
688     if (error != AL_NO_ERROR)  {
689        SG_LOG( SG_SOUND, SG_ALERT, "AL Error (sound manager): "
690                                       << alGetString(error) << " at " << s);
691        return true;
692     }
693 #endif
694     return false;
695 }
696
697 bool SGSoundMgr::testForALCError(std::string s)
698 {
699 #ifdef ENABLE_SOUND
700     ALCenum error;
701     error = alcGetError(d->_device);
702     if (error != ALC_NO_ERROR) {
703         SG_LOG( SG_SOUND, SG_ALERT, "ALC Error (sound manager): "
704                                        << alcGetString(d->_device, error) << " at "
705                                        << s);
706         return true;
707     }
708 #endif
709     return false;
710 }
711
712 bool SGSoundMgr::is_working() const 
713 {
714     return (d->_device != NULL);
715 }
716
717 const SGQuatd& SGSoundMgr::get_orientation() const
718 {
719     return d->_orientation;
720 }
721
722 void SGSoundMgr::set_orientation( const SGQuatd& ori )
723 {
724     d->_orientation = ori;
725     _changed = true;
726 }
727
728 const SGVec3d& SGSoundMgr::get_position() const
729
730     return d->_absolute_pos;
731 }
732
733 void SGSoundMgr::set_position( const SGVec3d& pos, const SGGeod& pos_geod )
734 {
735     d->_base_pos = pos; _geod_pos = pos_geod; _changed = true;
736 }
737
738 SGVec3f SGSoundMgr::get_direction() const
739 {
740     return SGVec3f(d->_at_up_vec[0], d->_at_up_vec[1], d->_at_up_vec[2]);
741 }