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