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