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