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