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