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