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