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