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