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