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