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