]> git.mxchange.org Git - simgear.git/blob - simgear/sound/soundmgr_openal.cxx
Pass current-dir down through XMLSound
[simgear.git] / simgear / sound / soundmgr_openal.cxx
1 // soundmgr.cxx -- Sound effect management class
2 //
3 // Sound manager initially written by David Findlay
4 // <david_j_findlay@yahoo.com.au> 2001
5 //
6 // C++-ified by Curtis Olson, started March 2001.
7 // Modified for the new SoundSystem by Erik Hofman, October 2009
8 //
9 // Copyright (C) 2001  Curtis L. Olson - http://www.flightgear.org/~curt
10 // Copyright (C) 2009 Erik Hofman <erik@ehofman.com>
11 //
12 // This program is free software; you can redistribute it and/or
13 // modify it under the terms of the GNU General Public License as
14 // published by the Free Software Foundation; either version 2 of the
15 // License, or (at your option) any later version.
16 //
17 // This program is distributed in the hope that it will be useful, but
18 // WITHOUT ANY WARRANTY; without even the implied warranty of
19 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
20 // General Public License for more details.
21 //
22 // You should have received a copy of the GNU General Public License
23 // along with this program; if not, write to the Free Software Foundation,
24 // Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
25 //
26 // $Id$
27
28 #ifdef HAVE_CONFIG_H
29 #  include <simgear_config.h>
30 #endif
31
32 #if defined( __APPLE__ )
33 # include <ALUT/alut.h>
34 #else
35 # include <AL/alut.h>
36 #endif
37
38 #include <iostream>
39 #include <algorithm>
40 #include <cstring>
41
42 #include "soundmgr_openal.hxx"
43
44 #include <simgear/structure/exception.hxx>
45 #include <simgear/debug/logstream.hxx>
46 #include <simgear/misc/sg_path.hxx>
47 #include <simgear/math/SGMath.hxx>
48
49 using std::string;
50
51 extern bool isNaN(float *v);
52
53 #define MAX_SOURCES     128
54
55
56 #ifndef ALC_ALL_DEVICES_SPECIFIER
57 # define ALC_ALL_DEVICES_SPECIFIER      0x1013
58 #endif
59
60 //
61 // Sound Manager
62 //
63
64 int SGSoundMgr::_alut_init = 0;
65
66 // constructor
67 SGSoundMgr::SGSoundMgr() :
68     _working(false),
69     _active(false),
70     _changed(true),
71     _volume(0.0),
72     _device(NULL),
73     _context(NULL),
74     _absolute_pos(SGVec3d::zeros()),
75     _offset_pos(SGVec3d::zeros()),
76     _base_pos(SGVec3d::zeros()),
77     _geod_pos(SGGeod::fromCart(SGVec3d::zeros())),
78     _velocity(SGVec3d::zeros()),
79     _orientation(SGQuatd::zeros()),
80     _bad_doppler(false),
81     _renderer("unknown"),
82     _vendor("unknown")
83 {
84 #if defined(ALUT_API_MAJOR_VERSION) && ALUT_API_MAJOR_VERSION >= 1
85     if (_alut_init == 0) {
86         if ( !alutInitWithoutContext(NULL, NULL) ) {
87             testForALUTError("alut initialization");
88             return;
89         }
90     }
91     _alut_init++;
92 #else
93   //#error ALUT 1.1 required, ALUT 1.0 is no longer supported, please upgrade
94 #endif
95 }
96
97 // destructor
98
99 SGSoundMgr::~SGSoundMgr() {
100
101     stop();
102 #if defined(ALUT_API_MAJOR_VERSION) && ALUT_API_MAJOR_VERSION >= 1
103     _alut_init--;
104     if (_alut_init == 0) {
105         alutExit ();
106     }
107 #endif
108 }
109
110 // initialize the sound manager
111 void SGSoundMgr::init(const char *devname) {
112
113     SG_LOG( SG_GENERAL, SG_INFO, "Initializing OpenAL sound manager" );
114
115     ALCdevice *device = alcOpenDevice(devname);
116     if ( testForError(device, "Audio device not available, trying default") ) {
117         device = alcOpenDevice(NULL);
118         if (testForError(device, "Default Audio device not available.") ) {
119            return;
120         }
121     }
122
123     _device = device;
124     ALCcontext *context = alcCreateContext(device, NULL);
125     testForALCError("context creation.");
126     if ( testForError(context, "Unable to create a valid context.") ) {
127         alcCloseDevice (device);
128         return;
129     }
130
131     if ( !alcMakeContextCurrent(context) ) {
132         testForALCError("context initialization");
133         alcDestroyContext (context);
134         alcCloseDevice (device);
135         return;
136     }
137
138     if (_context != NULL)
139         SG_LOG(SG_GENERAL, SG_ALERT, "context is already assigned");
140     _context = context;
141     _working = true;
142
143     _at_up_vec[0] = 0.0; _at_up_vec[1] = 0.0; _at_up_vec[2] = -1.0;
144     _at_up_vec[3] = 0.0; _at_up_vec[4] = 1.0; _at_up_vec[5] = 0.0;
145
146     alListenerf( AL_GAIN, 0.0f );
147     alListenerfv( AL_ORIENTATION, _at_up_vec );
148     alListenerfv( AL_POSITION, SGVec3f::zeros().data() );
149     alListenerfv( AL_VELOCITY, SGVec3f::zeros().data() );
150
151     alDopplerFactor(1.0);
152     alDopplerVelocity(340.3);   // speed of sound in meters per second.
153
154     // gain = AL_REFERENCE_DISTANCE / (AL_REFERENCE_DISTANCE +
155     //        AL_ROLLOFF_FACTOR * (distance - AL_REFERENCE_DISTANCE));
156     alDistanceModel(AL_INVERSE_DISTANCE_CLAMPED);
157
158     testForALError("listener initialization");
159
160     // get a free source one at a time
161     // if an error is returned no more (hardware) sources are available
162     for (unsigned int i=0; i<MAX_SOURCES; i++) {
163         ALuint source;
164         ALenum error;
165
166         alGetError();
167         alGenSources(1, &source);
168         error = alGetError();
169         if ( error == AL_NO_ERROR ) {
170             _free_sources.push_back( source );
171         }
172         else break;
173     }
174
175     _vendor = (const char *)alGetString(AL_VENDOR);
176     _renderer = (const char *)alGetString(AL_RENDERER);
177     if ( (_vendor != "Adalin" && _vendor != "Apple Computer Inc.") &&
178           (_vendor != "OpenAL Community" || (_renderer != "Software" &&
179                         _renderer != "OpenAL Sample Implementation"))
180        )
181     {
182        _bad_doppler = true;
183     }
184
185     if (_free_sources.size() == 0) {
186         SG_LOG(SG_GENERAL, SG_ALERT, "Unable to grab any OpenAL sources!");
187     }
188 }
189
190 void SGSoundMgr::activate() {
191     if ( _working ) {
192         _active = true;
193         sample_group_map_iterator sample_grp_current = _sample_groups.begin();
194         sample_group_map_iterator sample_grp_end = _sample_groups.end();
195         for ( ; sample_grp_current != sample_grp_end; ++sample_grp_current ) {
196             SGSampleGroup *sgrp = sample_grp_current->second;
197             sgrp->activate();
198         }
199     }
200 }
201
202 // stop the sound manager
203 void SGSoundMgr::stop() {
204
205     // first stop all sample groups
206     sample_group_map_iterator sample_grp_current = _sample_groups.begin();
207     sample_group_map_iterator sample_grp_end = _sample_groups.end();
208     for ( ; sample_grp_current != sample_grp_end; ++sample_grp_current ) {
209         SGSampleGroup *sgrp = sample_grp_current->second;
210         sgrp->stop();
211     }
212
213     // clear all OpenAL sources
214     for (unsigned int i=0; i<_free_sources.size(); i++) {
215         ALuint source = _free_sources[i];
216         alDeleteSources( 1 , &source );
217     }
218     _free_sources.clear();
219
220     // clear any OpenAL buffers before shutting down
221     buffer_map_iterator buffers_current = _buffers.begin();
222     buffer_map_iterator buffers_end = _buffers.end();
223     for ( ; buffers_current != buffers_end; ++buffers_current ) {
224         refUint ref = buffers_current->second;
225         ALuint buffer = ref.id;
226         alDeleteBuffers(1, &buffer);
227     }
228     _buffers.clear();
229
230     if (_working) {
231         _working = false;
232         _active = false;
233         _context = alcGetCurrentContext();
234         _device = alcGetContextsDevice(_context);
235         alcDestroyContext(_context);
236         alcCloseDevice(_device);
237         _context = NULL;
238
239         _renderer = "unknown";
240         _vendor = "unknown";
241     }
242 }
243
244 void SGSoundMgr::suspend() {
245     if (_working) {
246         sample_group_map_iterator sample_grp_current = _sample_groups.begin();
247         sample_group_map_iterator sample_grp_end = _sample_groups.end();
248         for ( ; sample_grp_current != sample_grp_end; ++sample_grp_current ) {
249             SGSampleGroup *sgrp = sample_grp_current->second;
250             sgrp->stop();
251         }
252         _active = false;
253     }
254 }
255
256 void SGSoundMgr::resume() {
257     if (_working) {
258         sample_group_map_iterator sample_grp_current = _sample_groups.begin();
259         sample_group_map_iterator sample_grp_end = _sample_groups.end();
260         for ( ; sample_grp_current != sample_grp_end; ++sample_grp_current ) {
261             SGSampleGroup *sgrp = sample_grp_current->second;
262             sgrp->resume();
263         }
264         _active = true;
265     }
266 }
267
268 void SGSoundMgr::bind ()
269 {
270     _free_sources.clear();
271     _free_sources.reserve( MAX_SOURCES );
272     _sources_in_use.clear();
273     _sources_in_use.reserve( MAX_SOURCES );
274 }
275
276
277 void SGSoundMgr::unbind ()
278 {
279     _sample_groups.clear();
280
281     // delete free sources
282     for (unsigned int i=0; i<_free_sources.size(); i++) {
283         ALuint source = _free_sources[i];
284         alDeleteSources( 1 , &source );
285     }
286
287     _free_sources.clear();
288     _sources_in_use.clear();
289 }
290
291 // run the audio scheduler
292 void SGSoundMgr::update( double dt ) {
293     if (_active) {
294         alcSuspendContext(_context);
295
296         if (_changed) {
297             update_pos_and_orientation();
298         }
299
300         sample_group_map_iterator sample_grp_current = _sample_groups.begin();
301         sample_group_map_iterator sample_grp_end = _sample_groups.end();
302         for ( ; sample_grp_current != sample_grp_end; ++sample_grp_current ) {
303             SGSampleGroup *sgrp = sample_grp_current->second;
304             sgrp->update(dt);
305         }
306
307         if (_changed) {
308 #if 0
309 if (isNaN(_at_up_vec)) printf("NaN in listener orientation\n");
310 if (isNaN(toVec3f(_absolute_pos).data())) printf("NaN in listener position\n");
311 if (isNaN(_velocity.data())) printf("NaN in listener velocity\n");
312 #endif
313             alListenerf( AL_GAIN, _volume );
314             alListenerfv( AL_ORIENTATION, _at_up_vec );
315             // alListenerfv( AL_POSITION, toVec3f(_absolute_pos).data() );
316
317             SGQuatd hlOr = SGQuatd::fromLonLat( _geod_pos );
318             SGVec3d velocity = SGVec3d::zeros();
319             if ( _velocity[0] || _velocity[1] || _velocity[2] ) {
320                 velocity = hlOr.backTransform(_velocity*SG_FEET_TO_METER);
321             }
322
323             if ( _bad_doppler ) {
324                 velocity *= 100.0f;
325             }
326
327             alListenerfv( AL_VELOCITY, toVec3f(velocity).data() );
328             // alDopplerVelocity(340.3);        // TODO: altitude dependent
329             testForALError("update");
330             _changed = false;
331         }
332
333         alcProcessContext(_context);
334     }
335 }
336
337 // add a sample group, return true if successful
338 bool SGSoundMgr::add( SGSampleGroup *sgrp, const string& refname )
339 {
340     sample_group_map_iterator sample_grp_it = _sample_groups.find( refname );
341     if ( sample_grp_it != _sample_groups.end() ) {
342         // sample group already exists
343         return false;
344     }
345
346     if (_active) sgrp->activate();
347     _sample_groups[refname] = sgrp;
348
349     return true;
350 }
351
352
353 // remove a sound effect, return true if successful
354 bool SGSoundMgr::remove( const string &refname )
355 {
356     sample_group_map_iterator sample_grp_it = _sample_groups.find( refname );
357     if ( sample_grp_it == _sample_groups.end() ) {
358         // sample group was not found.
359         return false;
360     }
361
362     _sample_groups.erase( sample_grp_it );
363
364     return true;
365 }
366
367
368 // return true of the specified sound exists in the sound manager system
369 bool SGSoundMgr::exists( const string &refname ) {
370     sample_group_map_iterator sample_grp_it = _sample_groups.find( refname );
371     if ( sample_grp_it == _sample_groups.end() ) {
372         // sample group was not found.
373         return false;
374     }
375
376     return true;
377 }
378
379
380 // return a pointer to the SGSampleGroup if the specified sound exists
381 // in the sound manager system, otherwise return NULL
382 SGSampleGroup *SGSoundMgr::find( const string &refname, bool create ) {
383     sample_group_map_iterator sample_grp_it = _sample_groups.find( refname );
384     if ( sample_grp_it == _sample_groups.end() ) {
385         // sample group was not found.
386         if (create) {
387             SGSampleGroup* sgrp = new SGSampleGroup(this, refname);
388             add( sgrp, refname );
389             return sgrp;
390         }
391         else 
392             return NULL;
393     }
394
395     return sample_grp_it->second;
396 }
397
398
399 void SGSoundMgr::set_volume( float v )
400 {
401     _volume = v;
402     if (_volume > 1.0) _volume = 1.0;
403     if (_volume < 0.0) _volume = 0.0;
404     _changed = true;
405 }
406
407 // Get an unused source id
408 //
409 // The Sound Manager should keep track of the sources in use, the distance
410 // of these sources to the listener and the volume (also based on audio cone
411 // and hence orientation) of the sources.
412 //
413 // The Sound Manager is (and should be) the only one knowing about source
414 // management. Sources further away should be suspendped to free resources for
415 // newly added sounds close by.
416 unsigned int SGSoundMgr::request_source()
417 {
418     unsigned int source = NO_SOURCE;
419
420     if (_free_sources.size() > 0) {
421        source = _free_sources.back();
422        _free_sources.pop_back();
423        _sources_in_use.push_back(source);
424     }
425     else
426        SG_LOG( SG_GENERAL, SG_INFO, "No more free sources available\n");
427
428     return source;
429 }
430
431 // Free up a source id for further use
432 void SGSoundMgr::release_source( unsigned int source )
433 {
434     vector<ALuint>::iterator it;
435
436     it = std::find(_sources_in_use.begin(), _sources_in_use.end(), source);
437     if ( it != _sources_in_use.end() ) {
438         ALint result;
439
440         alGetSourcei( source, AL_SOURCE_STATE, &result );
441         if ( result == AL_PLAYING )
442             alSourceStop( source );
443         testForALError("release source");
444
445         alSourcei( source, AL_BUFFER, 0 );
446         _free_sources.push_back( source );
447         _sources_in_use.erase( it );
448     }
449 }
450
451 unsigned int SGSoundMgr::request_buffer(SGSoundSample *sample)
452 {
453     ALuint buffer = NO_BUFFER;
454
455     if ( !sample->is_valid_buffer() ) {
456         // sample was not yet loaded or removed again
457         string sample_name = sample->get_sample_name();
458         void *sample_data = NULL;
459
460         // see if the sample name is already cached
461         buffer_map_iterator buffer_it = _buffers.find( sample_name );
462         if ( buffer_it != _buffers.end() ) {
463             buffer_it->second.refctr++;
464             buffer = buffer_it->second.id;
465             sample->set_buffer( buffer );
466             return buffer;
467         }
468
469         // sample name was not found in the buffer cache.
470         if ( sample->is_file() ) {
471             int freq, format;
472             size_t size;
473
474             try {
475               bool res = load(sample_name, &sample_data, &format, &size, &freq);
476               if (res == false) return buffer;
477             } catch (sg_exception& e) {
478               SG_LOG(SG_GENERAL, SG_ALERT, "failed to load sound buffer:" << e.getFormattedMessage());
479               return NO_BUFFER;
480             }
481             
482             sample->set_frequency( freq );
483             sample->set_format( format );
484             sample->set_size( size );
485         }
486         else
487             sample_data = sample->get_data();
488
489         // create an OpenAL buffer handle
490         alGenBuffers(1, &buffer);
491         if ( !testForALError("generate buffer") ) {
492             // Copy data to the internal OpenAL buffer
493
494             ALenum format = sample->get_format();
495             ALsizei size = sample->get_size();
496             ALsizei freq = sample->get_frequency();
497             alBufferData( buffer, format, sample_data, size, freq );
498
499             if ( sample->is_file() ) free(sample_data);
500
501             if ( !testForALError("buffer add data") ) {
502                 sample->set_buffer(buffer);
503                 _buffers[sample_name] = refUint(buffer);
504             }
505         }
506     }
507     else {
508         buffer = sample->get_buffer();
509 }
510
511     return buffer;
512 }
513
514 void SGSoundMgr::release_buffer(SGSoundSample *sample)
515 {
516     if ( !sample->is_queue() )
517     {
518         string sample_name = sample->get_sample_name();
519         buffer_map_iterator buffer_it = _buffers.find( sample_name );
520         if ( buffer_it == _buffers.end() ) {
521             // buffer was not found
522             return;
523         }
524
525         sample->no_valid_buffer();
526         buffer_it->second.refctr--;
527         if (buffer_it->second.refctr == 0) {
528             ALuint buffer = buffer_it->second.id;
529             alDeleteBuffers(1, &buffer);
530             _buffers.erase( buffer_it );
531             testForALError("release buffer");
532         }
533     }
534 }
535
536 void SGSoundMgr::update_pos_and_orientation() {
537     /**
538      * Description: ORIENTATION is a pair of 3-tuples representing the
539      * 'at' direction vector and 'up' direction of the Object in
540      * Cartesian space. AL expects two vectors that are orthogonal to
541      * each other. These vectors are not expected to be normalized. If
542      * one or more vectors have zero length, implementation behavior
543      * is undefined. If the two vectors are linearly dependent,
544      * behavior is undefined.
545      *
546      * This is in the same coordinate system as OpenGL; y=up, z=back, x=right.
547      */
548     SGVec3d sgv_at = _orientation.backTransform(-SGVec3d::e3());
549     SGVec3d sgv_up = _orientation.backTransform(SGVec3d::e2());
550     _at_up_vec[0] = sgv_at[0];
551     _at_up_vec[1] = sgv_at[1];
552     _at_up_vec[2] = sgv_at[2];
553     _at_up_vec[3] = sgv_up[0];
554     _at_up_vec[4] = sgv_up[1];
555     _at_up_vec[5] = sgv_up[2];
556
557     // static const SGQuatd q(-0.5, -0.5, 0.5, 0.5);
558     // SGQuatd hlOr = SGQuatd::fromLonLat(SGGeod::fromCart(_base_pos));
559     // SGQuatd ec2body = hlOr*_orientation;
560     _absolute_pos = _base_pos; // + ec2body.backTransform( _offset_pos );
561 }
562
563 bool SGSoundMgr::load(string &samplepath, void **dbuf, int *fmt,
564                                           size_t *sz, int *frq )
565 {
566     if ( !_working ) return false;
567
568     ALenum format;
569     ALsizei size;
570     ALsizei freq;
571     ALvoid *data;
572
573 #if defined(ALUT_API_MAJOR_VERSION) && ALUT_API_MAJOR_VERSION >= 1
574     ALfloat freqf;
575     // ignore previous errors to prevent the system from halting on silly errors
576     alGetError();
577     alcGetError(_device);
578     data = alutLoadMemoryFromFile(samplepath.c_str(), &format, &size, &freqf );
579     freq = (ALsizei)freqf;
580     int error = alutGetError();
581     if (data == NULL || error != ALUT_ERROR_NO_ERROR) {
582         string msg = "Failed to load wav file: ";
583          msg.append(alutGetErrorString(error));
584         throw sg_io_exception(msg.c_str(), sg_location(samplepath));
585         return false;
586     }
587
588 #else
589     ALbyte *fname = (ALbyte *)samplepath.c_str();
590 # if defined (__APPLE__)
591     alutLoadWAVFile( fname, &format, &data, &size, &freq );
592 # else
593     ALboolean loop;
594     alutLoadWAVFile( fname, &format, &data, &size, &freq, &loop );
595 # endif
596     ALenum error =  alGetError();
597     if ( error != AL_NO_ERROR ) {
598         string msg = "Failed to load wav file: ";
599         const ALchar *errorString = alGetString(error);
600         if (errorString) {
601             msg.append(errorString);
602         } else {
603             // alGetString returns NULL when an unexpected or OS specific error
604             // occurs: e.g. -43 on Mac when file is not found.
605             // In this case, alGetString() sets 'Invalid Enum' error, so
606             // showing with the original error number is helpful.
607             stringstream ss;
608             ss << alGetString(alGetError()) << "(" << error << ")";
609             msg.append(ss.str());
610         }
611         throw sg_io_exception(msg.c_str(), sg_location(samplepath));
612         return false;
613     }
614 #endif
615
616     *dbuf = (void *)data;
617     *fmt = (int)format;
618     *sz = (size_t)size;
619     *frq = (int)freq;
620
621     return true;
622 }
623
624 vector<const char*> SGSoundMgr::get_available_devices()
625 {
626     vector<const char*> devices;
627     const ALCchar *s;
628
629     if (alcIsExtensionPresent(NULL, "ALC_enumerate_all_EXT") == AL_TRUE) {
630         s = alcGetString(NULL, ALC_ALL_DEVICES_SPECIFIER);
631     } else {
632         s = alcGetString(NULL, ALC_DEVICE_SPECIFIER);
633     }
634
635     if (s) {
636         ALCchar *nptr, *ptr = (ALCchar *)s;
637
638         nptr = ptr;
639         while (*(nptr += strlen(ptr)+1) != 0)
640         {
641             devices.push_back(ptr);
642             ptr = nptr;
643         }
644         devices.push_back(ptr);
645     }
646
647     return devices;
648 }
649
650
651 bool SGSoundMgr::testForError(void *p, string s)
652 {
653    if (p == NULL) {
654       SG_LOG( SG_GENERAL, SG_ALERT, "Error: " << s);
655       return true;
656    }
657    return false;
658 }
659
660
661 bool SGSoundMgr::testForALError(string s)
662 {
663     ALenum error = alGetError();
664     if (error != AL_NO_ERROR)  {
665        SG_LOG( SG_GENERAL, SG_ALERT, "AL Error (sound manager): "
666                                       << alGetString(error) << " at " << s);
667        return true;
668     }
669     return false;
670 }
671
672 bool SGSoundMgr::testForALCError(string s)
673 {
674     ALCenum error;
675     error = alcGetError(_device);
676     if (error != ALC_NO_ERROR) {
677         SG_LOG( SG_GENERAL, SG_ALERT, "ALC Error (sound manager): "
678                                        << alcGetString(_device, error) << " at "
679                                        << s);
680         return true;
681     }
682     return false;
683 }
684
685 bool SGSoundMgr::testForALUTError(string s)
686 {
687 #if defined(ALUT_API_MAJOR_VERSION) && ALUT_API_MAJOR_VERSION >= 1
688     ALenum error;
689     error =  alutGetError ();
690     if (error != ALUT_ERROR_NO_ERROR) {
691         SG_LOG( SG_GENERAL, SG_ALERT, "ALUT Error (sound manager): "
692                                        << alutGetErrorString(error) << " at "
693                                        << s);
694         return true;
695     }
696 #endif
697     return false;
698 }