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