]> git.mxchange.org Git - simgear.git/blob - simgear/sound/soundmgr_openal.cxx
Some basic C++/Nasal binding helpers
[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::string;
49 using std::vector;
50
51
52 #define MAX_SOURCES     128
53
54
55 #ifndef ALC_ALL_DEVICES_SPECIFIER
56 # define ALC_ALL_DEVICES_SPECIFIER      0x1013
57 #endif
58
59 class SGSoundMgr::SoundManagerPrivate
60 {
61 public:
62     SoundManagerPrivate() :
63         _device(NULL),
64         _context(NULL),
65         _absolute_pos(SGVec3d::zeros()),
66         _base_pos(SGVec3d::zeros()),
67         _orientation(SGQuatd::zeros())
68     {
69         
70         
71     }
72     
73     void init()
74     {
75         _at_up_vec[0] = 0.0; _at_up_vec[1] = 0.0; _at_up_vec[2] = -1.0;
76         _at_up_vec[3] = 0.0; _at_up_vec[4] = 1.0; _at_up_vec[5] = 0.0;
77     }
78     
79     void update_pos_and_orientation()
80     {
81         /**
82          * Description: ORIENTATION is a pair of 3-tuples representing the
83          * 'at' direction vector and 'up' direction of the Object in
84          * Cartesian space. AL expects two vectors that are orthogonal to
85          * each other. These vectors are not expected to be normalized. If
86          * one or more vectors have zero length, implementation behavior
87          * is undefined. If the two vectors are linearly dependent,
88          * behavior is undefined.
89          *
90          * This is in the same coordinate system as OpenGL; y=up, z=back, x=right.
91          */
92         SGVec3d sgv_at = _orientation.backTransform(-SGVec3d::e3());
93         SGVec3d sgv_up = _orientation.backTransform(SGVec3d::e2());
94         _at_up_vec[0] = sgv_at[0];
95         _at_up_vec[1] = sgv_at[1];
96         _at_up_vec[2] = sgv_at[2];
97         _at_up_vec[3] = sgv_up[0];
98         _at_up_vec[4] = sgv_up[1];
99         _at_up_vec[5] = sgv_up[2];
100
101         _absolute_pos = _base_pos;
102     }
103         
104     ALCdevice *_device;
105     ALCcontext *_context;
106     
107     std::vector<ALuint> _free_sources;
108     std::vector<ALuint> _sources_in_use;
109     
110     SGVec3d _absolute_pos;
111     SGVec3d _base_pos;
112     SGQuatd _orientation;
113     // Orientation of the listener. 
114     // first 3 elements are "at" vector, second 3 are "up" vector
115     ALfloat _at_up_vec[6];
116     
117     sample_group_map _sample_groups;
118     buffer_map _buffers;
119 };
120
121
122 //
123 // Sound Manager
124 //
125
126 // constructor
127 SGSoundMgr::SGSoundMgr() :
128     _active(false),
129     _changed(true),
130     _volume(0.0),
131     _offset_pos(SGVec3d::zeros()),
132     _geod_pos(SGGeod::fromCart(SGVec3d::zeros())),
133     _velocity(SGVec3d::zeros()),
134     _bad_doppler(false),
135     _renderer("unknown"),
136     _vendor("unknown")
137 {
138     d.reset(new SoundManagerPrivate);
139 }
140
141 // destructor
142
143 SGSoundMgr::~SGSoundMgr() {
144
145     if (is_working())
146         stop();
147     d->_sample_groups.clear();
148 }
149
150 // initialize the sound manager
151 void SGSoundMgr::init() {
152
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 }
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     if ( is_working() ) {
270         _active = true;
271                 
272         sample_group_map_iterator sample_grp_current = d->_sample_groups.begin();
273         sample_group_map_iterator sample_grp_end = d->_sample_groups.end();
274         for ( ; sample_grp_current != sample_grp_end; ++sample_grp_current ) {
275             SGSampleGroup *sgrp = sample_grp_current->second;
276             sgrp->activate();
277         }
278     }
279 }
280
281 // stop the sound manager
282 void SGSoundMgr::stop() {
283
284     // first stop all sample groups
285     sample_group_map_iterator sample_grp_current = d->_sample_groups.begin();
286     sample_group_map_iterator sample_grp_end = d->_sample_groups.end();
287     for ( ; sample_grp_current != sample_grp_end; ++sample_grp_current ) {
288         SGSampleGroup *sgrp = sample_grp_current->second;
289         sgrp->stop();
290     }
291
292     // clear all OpenAL sources
293     BOOST_FOREACH(ALuint source, d->_free_sources) {
294         alDeleteSources( 1 , &source );
295         testForALError("SGSoundMgr::stop: delete sources");
296     }
297     d->_free_sources.clear();
298
299     // clear any OpenAL buffers before shutting down
300     buffer_map_iterator buffers_current = d->_buffers.begin();
301     buffer_map_iterator buffers_end = d->_buffers.end();
302     for ( ; buffers_current != buffers_end; ++buffers_current ) {
303         refUint ref = buffers_current->second;
304         ALuint buffer = ref.id;
305         alDeleteBuffers(1, &buffer);
306         testForALError("SGSoundMgr::stop: delete buffers");
307     }
308     
309     d->_buffers.clear();
310     d->_sources_in_use.clear();
311
312     if (is_working()) {
313         _active = false;
314         alcDestroyContext(d->_context);
315         alcCloseDevice(d->_device);
316         d->_context = NULL;
317         d->_device = NULL;
318
319         _renderer = "unknown";
320         _vendor = "unknown";
321     }
322 }
323
324 void SGSoundMgr::suspend() {
325     if (is_working()) {
326         sample_group_map_iterator sample_grp_current = d->_sample_groups.begin();
327         sample_group_map_iterator sample_grp_end = d->_sample_groups.end();
328         for ( ; sample_grp_current != sample_grp_end; ++sample_grp_current ) {
329             SGSampleGroup *sgrp = sample_grp_current->second;
330             sgrp->stop();
331         }
332         _active = false;
333     }
334 }
335
336 void SGSoundMgr::resume() {
337     if (is_working()) {
338         sample_group_map_iterator sample_grp_current = d->_sample_groups.begin();
339         sample_group_map_iterator sample_grp_end = d->_sample_groups.end();
340         for ( ; sample_grp_current != sample_grp_end; ++sample_grp_current ) {
341             SGSampleGroup *sgrp = sample_grp_current->second;
342             sgrp->resume();
343         }
344         _active = true;
345     }
346 }
347
348 // run the audio scheduler
349 void SGSoundMgr::update( double dt ) {
350     if (_active) {
351         alcSuspendContext(d->_context);
352
353         if (_changed) {
354             d->update_pos_and_orientation();
355         }
356
357         sample_group_map_iterator sample_grp_current = d->_sample_groups.begin();
358         sample_group_map_iterator sample_grp_end = d->_sample_groups.end();
359         for ( ; sample_grp_current != sample_grp_end; ++sample_grp_current ) {
360             SGSampleGroup *sgrp = sample_grp_current->second;
361             sgrp->update(dt);
362         }
363
364         if (_changed) {
365 #if 0
366 if (isNaN(_at_up_vec)) printf("NaN in listener orientation\n");
367 if (isNaN(toVec3f(_absolute_pos).data())) printf("NaN in listener position\n");
368 if (isNaN(_velocity.data())) printf("NaN in listener velocity\n");
369 #endif
370             alListenerf( AL_GAIN, _volume );
371             alListenerfv( AL_ORIENTATION, d->_at_up_vec );
372             // alListenerfv( AL_POSITION, toVec3f(_absolute_pos).data() );
373
374             SGQuatd hlOr = SGQuatd::fromLonLat( _geod_pos );
375             SGVec3d velocity = SGVec3d::zeros();
376             if ( _velocity[0] || _velocity[1] || _velocity[2] ) {
377                 velocity = hlOr.backTransform(_velocity*SG_FEET_TO_METER);
378             }
379
380             if ( _bad_doppler ) {
381                 velocity *= 100.0f;
382             }
383
384             alListenerfv( AL_VELOCITY, toVec3f(velocity).data() );
385             // alDopplerVelocity(340.3);        // TODO: altitude dependent
386             testForALError("update");
387             _changed = false;
388         }
389
390         alcProcessContext(d->_context);
391     }
392 }
393
394 // add a sample group, return true if successful
395 bool SGSoundMgr::add( SGSampleGroup *sgrp, const string& refname )
396 {
397     sample_group_map_iterator sample_grp_it = d->_sample_groups.find( refname );
398     if ( sample_grp_it != d->_sample_groups.end() ) {
399         // sample group already exists
400         return false;
401     }
402
403     if (_active) sgrp->activate();
404     d->_sample_groups[refname] = sgrp;
405
406     return true;
407 }
408
409
410 // remove a sound effect, return true if successful
411 bool SGSoundMgr::remove( const 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 was not found.
416         return false;
417     }
418
419     d->_sample_groups.erase( sample_grp_it );
420
421     return true;
422 }
423
424
425 // return true of the specified sound exists in the sound manager system
426 bool SGSoundMgr::exists( const string &refname ) {
427     sample_group_map_iterator sample_grp_it = d->_sample_groups.find( refname );
428     return ( sample_grp_it != d->_sample_groups.end() );
429 }
430
431
432 // return a pointer to the SGSampleGroup if the specified sound exists
433 // in the sound manager system, otherwise return NULL
434 SGSampleGroup *SGSoundMgr::find( const string &refname, bool create ) {
435     sample_group_map_iterator sample_grp_it = d->_sample_groups.find( refname );
436     if ( sample_grp_it == d->_sample_groups.end() ) {
437         // sample group was not found.
438         if (create) {
439             SGSampleGroup* sgrp = new SGSampleGroup(this, refname);
440             add( sgrp, refname );
441             return sgrp;
442         }
443         else 
444             return NULL;
445     }
446
447     return sample_grp_it->second;
448 }
449
450
451 void SGSoundMgr::set_volume( float v )
452 {
453     _volume = v;
454     SG_CLAMP_RANGE(_volume, 0.0f, 1.0f);
455     _changed = true;
456 }
457
458 // Get an unused source id
459 //
460 // The Sound Manager should keep track of the sources in use, the distance
461 // of these sources to the listener and the volume (also based on audio cone
462 // and hence orientation) of the sources.
463 //
464 // The Sound Manager is (and should be) the only one knowing about source
465 // management. Sources further away should be suspended to free resources for
466 // newly added sounds close by.
467 unsigned int SGSoundMgr::request_source()
468 {
469     unsigned int source = NO_SOURCE;
470
471     if (!d->_free_sources.empty()) {
472        source = d->_free_sources.back();
473        d->_free_sources.pop_back();
474        d->_sources_in_use.push_back(source);
475     }
476     else
477        SG_LOG( SG_SOUND, SG_BULK, "Sound manager: No more free sources available!\n");
478
479     return source;
480 }
481
482 // Free up a source id for further use
483 void SGSoundMgr::release_source( unsigned int source )
484 {
485     vector<ALuint>::iterator it;
486
487     it = std::find(d->_sources_in_use.begin(), d->_sources_in_use.end(), source);
488     if ( it != d->_sources_in_use.end() ) {
489         ALint result;
490
491         alGetSourcei( source, AL_SOURCE_STATE, &result );
492         if ( result == AL_PLAYING || result == AL_PAUSED ) {
493             alSourceStop( source );
494         }
495
496         alSourcei( source, AL_BUFFER, 0 );      // detach the associated buffer
497         testForALError("release_source");
498         d->_free_sources.push_back( source );
499         d->_sources_in_use.erase( it );
500     }
501 }
502
503 unsigned int SGSoundMgr::request_buffer(SGSoundSample *sample)
504 {
505     ALuint buffer = NO_BUFFER;
506
507     if ( !sample->is_valid_buffer() ) {
508         // sample was not yet loaded or removed again
509         string sample_name = sample->get_sample_name();
510         void *sample_data = NULL;
511
512         // see if the sample name is already cached
513         buffer_map_iterator buffer_it = d->_buffers.find( sample_name );
514         if ( buffer_it != d->_buffers.end() ) {
515             buffer_it->second.refctr++;
516             buffer = buffer_it->second.id;
517             sample->set_buffer( buffer );
518             return buffer;
519         }
520
521         // sample name was not found in the buffer cache.
522         if ( sample->is_file() ) {
523             int freq, format;
524             size_t size;
525
526             try {
527               bool res = load(sample_name, &sample_data, &format, &size, &freq);
528               if (res == false) return NO_BUFFER;
529             } catch (sg_exception& e) {
530               SG_LOG(SG_SOUND, SG_ALERT,
531                     "failed to load sound buffer: " << e.getFormattedMessage());
532               sample->set_buffer( SGSoundMgr::FAILED_BUFFER );
533               return FAILED_BUFFER;
534             }
535             
536             sample->set_frequency( freq );
537             sample->set_format( format );
538             sample->set_size( size );
539
540         } else {
541             sample_data = sample->get_data();
542         }
543
544         // create an OpenAL buffer handle
545         alGenBuffers(1, &buffer);
546         if ( !testForALError("generate buffer") ) {
547             // Copy data to the internal OpenAL buffer
548
549             ALenum format = sample->get_format();
550             ALsizei size = sample->get_size();
551             ALsizei freq = sample->get_frequency();
552             alBufferData( buffer, format, sample_data, size, freq );
553
554             if ( !testForALError("buffer add data") ) {
555                 sample->set_buffer(buffer);
556                 d->_buffers[sample_name] = refUint(buffer);
557             }
558         }
559
560         if ( sample->is_file() ) free(sample_data);
561     }
562     else {
563         buffer = sample->get_buffer();
564     }
565
566     return buffer;
567 }
568
569 void SGSoundMgr::release_buffer(SGSoundSample *sample)
570 {
571     if ( !sample->is_queue() )
572     {
573         string sample_name = sample->get_sample_name();
574         buffer_map_iterator buffer_it = d->_buffers.find( sample_name );
575         if ( buffer_it == d->_buffers.end() ) {
576             // buffer was not found
577             return;
578         }
579
580         sample->no_valid_buffer();
581         buffer_it->second.refctr--;
582         if (buffer_it->second.refctr == 0) {
583             ALuint buffer = buffer_it->second.id;
584             alDeleteBuffers(1, &buffer);
585             d->_buffers.erase( buffer_it );
586             testForALError("release buffer");
587         }
588     }
589 }
590
591 bool SGSoundMgr::load(const string &samplepath, void **dbuf, int *fmt,
592                                           size_t *sz, int *frq )
593 {
594     if ( !is_working() )
595         return false;
596
597     ALenum format;
598     ALsizei size;
599     ALsizei freq;
600     ALvoid *data;
601
602     ALfloat freqf;
603
604     data = simgear::loadWAVFromFile(samplepath, format, size, freqf );
605     freq = (ALsizei)freqf;
606     if (data == NULL) {
607         throw sg_io_exception("Failed to load wav file", sg_location(samplepath));
608     }
609
610     if (format == AL_FORMAT_STEREO8 || format == AL_FORMAT_STEREO16) {
611         free(data);
612         throw sg_io_exception("Warning: STEREO files are not supported for 3D audio effects: " + samplepath);
613     }
614
615     *dbuf = (void *)data;
616     *fmt = (int)format;
617     *sz = (size_t)size;
618     *frq = (int)freq;
619
620     return true;
621 }
622
623 vector<const char*> SGSoundMgr::get_available_devices()
624 {
625     vector<const char*> devices;
626     const ALCchar *s;
627
628     if (alcIsExtensionPresent(NULL, "ALC_enumerate_all_EXT") == AL_TRUE) {
629         s = alcGetString(NULL, ALC_ALL_DEVICES_SPECIFIER);
630     } else {
631         s = alcGetString(NULL, ALC_DEVICE_SPECIFIER);
632     }
633
634     if (s) {
635         ALCchar *nptr, *ptr = (ALCchar *)s;
636
637         nptr = ptr;
638         while (*(nptr += strlen(ptr)+1) != 0)
639         {
640             devices.push_back(ptr);
641             ptr = nptr;
642         }
643         devices.push_back(ptr);
644     }
645
646     return devices;
647 }
648
649
650 bool SGSoundMgr::testForError(void *p, string s)
651 {
652    if (p == NULL) {
653       SG_LOG( SG_SOUND, SG_ALERT, "Error: " << s);
654       return true;
655    }
656    return false;
657 }
658
659
660 bool SGSoundMgr::testForALError(string s)
661 {
662     ALenum error = alGetError();
663     if (error != AL_NO_ERROR)  {
664        SG_LOG( SG_SOUND, SG_ALERT, "AL Error (sound manager): "
665                                       << alGetString(error) << " at " << s);
666        return true;
667     }
668     return false;
669 }
670
671 bool SGSoundMgr::testForALCError(string s)
672 {
673     ALCenum error;
674     error = alcGetError(d->_device);
675     if (error != ALC_NO_ERROR) {
676         SG_LOG( SG_SOUND, SG_ALERT, "ALC Error (sound manager): "
677                                        << alcGetString(d->_device, error) << " at "
678                                        << s);
679         return true;
680     }
681     return false;
682 }
683
684 bool SGSoundMgr::is_working() const 
685 {
686     return (d->_device != NULL);
687 }
688
689 const SGQuatd& SGSoundMgr::get_orientation() const
690 {
691     return d->_orientation;
692 }
693
694 void SGSoundMgr::set_orientation( const SGQuatd& ori )
695 {
696     d->_orientation = ori;
697     _changed = true;
698 }
699
700 const SGVec3d& SGSoundMgr::get_position() const
701
702     return d->_absolute_pos;
703 }
704
705 void SGSoundMgr::set_position( const SGVec3d& pos, const SGGeod& pos_geod )
706 {
707     d->_base_pos = pos; _geod_pos = pos_geod; _changed = true;
708 }
709
710 SGVec3f SGSoundMgr::get_direction() const
711 {
712     return SGVec3f(d->_at_up_vec[0], d->_at_up_vec[1], d->_at_up_vec[2]);
713 }