]> git.mxchange.org Git - simgear.git/blob - simgear/sound/soundmgr_openal.cxx
documentation, licensing, copyright and small api updates.
[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     _changed(true),
61     _volume(0.0),
62     _device(NULL),
63     _context(NULL),
64     _position(SGVec3d::zeros()),
65     _velocity(SGVec3d::zeros()),
66     _orientation(SGQuatd::zeros()),
67     _devname(NULL)
68 {
69 #if defined(ALUT_API_MAJOR_VERSION) && ALUT_API_MAJOR_VERSION >= 1
70     if (_alut_init == 0) {
71         if ( !alutInitWithoutContext(NULL, NULL) ) {
72             testForALUTError("alut initialization");
73             return;
74         }
75     }
76     _alut_init++;
77 #endif
78 }
79
80 // destructor
81
82 SGSoundMgr::~SGSoundMgr() {
83
84     stop();
85 #if defined(ALUT_API_MAJOR_VERSION) && ALUT_API_MAJOR_VERSION >= 1
86     _alut_init--;
87     if (_alut_init == 0) {
88         alutExit ();
89     }
90 #endif
91 }
92
93 // initialize the sound manager
94 void SGSoundMgr::init() {
95
96     SG_LOG( SG_GENERAL, SG_INFO, "Initializing OpenAL sound manager" );
97
98     ALCdevice *device = alcOpenDevice(_devname);
99     if ( testForError(device, "No default audio device available.") ) {
100         return;
101     }
102
103     ALCcontext *context = alcCreateContext(device, NULL);
104     if ( testForError(context, "Unable to create a valid context.") ) {
105         alcCloseDevice (device);
106         return;
107     }
108
109     if ( !alcMakeContextCurrent(context) ) {
110         testForALCError("context initialization");
111         alcDestroyContext (context);
112         alcCloseDevice (device);
113         return;
114     }
115
116     _context = context;
117     _working = true;
118
119     _at_up_vec[0] = 0.0; _at_up_vec[1] = 0.0; _at_up_vec[2] = -1.0;
120     _at_up_vec[3] = 0.0; _at_up_vec[4] = 1.0; _at_up_vec[5] = 0.0;
121
122     alListenerf( AL_GAIN, 0.2f );
123     alListenerfv( AL_ORIENTATION, _at_up_vec );
124     alListenerfv( AL_POSITION, SGVec3f::zeros().data() );
125     alListenerfv( AL_VELOCITY, SGVec3f::zeros().data() );
126
127     alDopplerFactor(1.0);
128     alDopplerVelocity(340.3);   // speed of sound in meters per second.
129
130     if ( alIsExtensionPresent((const ALchar*)"EXT_exponent_distance") ) {
131         alDistanceModel(AL_EXPONENT_DISTANCE);
132     } else {
133         alDistanceModel(AL_INVERSE_DISTANCE);
134     }
135
136     testForALError("listener initialization");
137
138     // get a free source one at a time
139     // if an error is returned no more (hardware) sources are available
140     for (unsigned int i=0; i<MAX_SOURCES; i++) {
141         ALuint source;
142         ALenum error;
143
144         alGetError();
145         alGenSources(1, &source);
146         error = alGetError();
147         if ( error == AL_NO_ERROR ) {
148             _free_sources.push_back( source );
149         }
150         else break;
151     }
152
153     if (_free_sources.size() == 0) {
154         SG_LOG(SG_GENERAL, SG_ALERT, "Unable to grab any OpenAL sources!");
155     }
156
157     sample_group_map_iterator sample_grp_current = _sample_groups.begin();
158     sample_group_map_iterator sample_grp_end = _sample_groups.end();
159     for ( ; sample_grp_current != sample_grp_end; ++sample_grp_current ) {
160         SGSampleGroup *sgrp = sample_grp_current->second;
161         sgrp->activate();
162     }
163 }
164
165 // suspend the sound manager
166 void SGSoundMgr::stop() {
167     if (_working) {
168         _working = false;
169
170         // clear any OpenAL buffers before shutting down
171         buffer_map_iterator buffers_current;
172         while(_buffers.size()){
173             buffers_current = _buffers.begin();
174             refUint ref = buffers_current->second;
175             ALuint buffer = ref.id;
176             alDeleteBuffers(1, &buffer);
177             _buffers.erase( buffers_current );
178         }
179
180         _context = alcGetCurrentContext();
181         _device = alcGetContextsDevice(_context);
182         alcMakeContextCurrent(NULL);
183         alcDestroyContext(_context);
184         alcCloseDevice(_device);
185     }
186 }
187
188 void SGSoundMgr::suspend() {
189     if (_working) {
190         sample_group_map_iterator sample_grp_current = _sample_groups.begin();
191         sample_group_map_iterator sample_grp_end = _sample_groups.end();
192         for ( ; sample_grp_current != sample_grp_end; ++sample_grp_current ) {
193             SGSampleGroup *sgrp = sample_grp_current->second;
194             sgrp->suspend();
195         }
196     }
197 }
198
199
200 void SGSoundMgr::bind ()
201 {
202     _free_sources.clear();
203     _free_sources.reserve( MAX_SOURCES );
204     _sources_in_use.clear();
205     _sources_in_use.reserve( MAX_SOURCES );
206 }
207
208
209 void SGSoundMgr::unbind ()
210 {
211     _sample_groups.clear();
212
213     // delete free sources
214     for (unsigned int i=0; i<_free_sources.size(); i++) {
215         ALuint source = _free_sources.at( i );
216         alDeleteSources( 1 , &source );
217     }
218
219     _free_sources.clear();
220     _sources_in_use.clear();
221 }
222
223 // run the audio scheduler
224 void SGSoundMgr::update_late( double dt ) {
225     if (_working) {
226         alcSuspendContext(_context);
227
228         sample_group_map_iterator sample_grp_current = _sample_groups.begin();
229         sample_group_map_iterator sample_grp_end = _sample_groups.end();
230         for ( ; sample_grp_current != sample_grp_end; ++sample_grp_current ) {
231             SGSampleGroup *sgrp = sample_grp_current->second;
232             sgrp->update(dt);
233         }
234
235         if (_changed) {
236             alListenerf( AL_GAIN, _volume );
237             alListenerfv( AL_ORIENTATION, _at_up_vec );
238             alListenerfv( AL_POSITION, toVec3f(_position).data() );
239             alListenerfv( AL_VELOCITY, toVec3f(_velocity).data() );
240             // alDopplerVelocity(340.3);        // TODO: altitude dependent
241             testForALError("update");
242             _changed = false;
243         }
244         alcProcessContext(_context);
245     }
246 }
247
248
249 void
250 SGSoundMgr::resume ()
251 {
252     if (_working) {
253         sample_group_map_iterator sample_grp_current = _sample_groups.begin();
254         sample_group_map_iterator sample_grp_end = _sample_groups.end();
255         for ( ; sample_grp_current != sample_grp_end; ++sample_grp_current ) {
256             SGSampleGroup *sgrp = sample_grp_current->second;
257             sgrp->resume();
258         }
259     }
260 }
261
262
263 // add a sampel group, return true if successful
264 bool SGSoundMgr::add( SGSampleGroup *sgrp, const string& refname )
265 {
266     sample_group_map_iterator sample_grp_it = _sample_groups.find( refname );
267     if ( sample_grp_it != _sample_groups.end() ) {
268         // sample group already exists
269         return false;
270     }
271
272     if (_working) sgrp->activate();
273     _sample_groups[refname] = sgrp;
274
275     return true;
276 }
277
278
279 // remove a sound effect, return true if successful
280 bool SGSoundMgr::remove( 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 was not found.
285         return false;
286     }
287
288     _sample_groups.erase( refname );
289
290     return true;
291 }
292
293
294 // return true of the specified sound exists in the sound manager system
295 bool SGSoundMgr::exists( const string &refname ) {
296     sample_group_map_iterator sample_grp_it = _sample_groups.find( refname );
297     if ( sample_grp_it == _sample_groups.end() ) {
298         // sample group was not found.
299         return false;
300     }
301
302     return true;
303 }
304
305
306 // return a pointer to the SGSampleGroup if the specified sound exists
307 // in the sound manager system, otherwise return NULL
308 SGSampleGroup *SGSoundMgr::find( const string &refname, bool create ) {
309     sample_group_map_iterator sample_grp_it = _sample_groups.find( refname );
310     if ( sample_grp_it == _sample_groups.end() ) {
311         // sample group was not found.
312         if (create) {
313             SGSampleGroup* sgrp = new SGSampleGroup(this, refname);
314             return sgrp;
315         }
316         else 
317             return NULL;
318     }
319
320     return sample_grp_it->second;
321 }
322
323
324 void SGSoundMgr::set_volume( float v )
325 {
326     _volume = v;
327     if (_volume > 1.0) _volume = 1.0;
328     if (_volume < 0.0) _volume = 0.0;
329     _changed = true;
330 }
331
332 /**
333  * set the orientation of the listener (in opengl coordinates)
334  *
335  * Description: ORIENTATION is a pair of 3-tuples representing the
336  * 'at' direction vector and 'up' direction of the Object in
337  * Cartesian space. AL expects two vectors that are orthogonal to
338  * each other. These vectors are not expected to be normalized. If
339  * one or more vectors have zero length, implementation behavior
340  * is undefined. If the two vectors are linearly dependent,
341  * behavior is undefined.
342  */
343 void SGSoundMgr::set_orientation( SGQuatd ori )
344 {
345     _orientation = ori;
346
347     SGVec3d sgv_up = ori.rotate(SGVec3d::e2());
348     SGVec3d sgv_at = ori.rotate(SGVec3d::e3());
349     _at_up_vec[0] = sgv_at[0];
350     _at_up_vec[1] = sgv_at[1];
351     _at_up_vec[2] = sgv_at[2];
352     _at_up_vec[3] = sgv_up[0];
353     _at_up_vec[4] = sgv_up[1];
354     _at_up_vec[5] = sgv_up[2];
355     _changed = true;
356 }
357
358 // Get an unused source id
359 //
360 // The Sound Manager should keep track of the sources in use, the distance
361 // of these sources to the listener and the volume (also based on audio cone
362 // and hence orientation) of the sources.
363 //
364 // The Sound Manager is (and should be) the only one knowing about source
365 // management. Sources further away should be suspendped to free resources for
366 // newly added sounds close by.
367 unsigned int SGSoundMgr::request_source()
368 {
369     unsigned int source = NO_SOURCE;
370
371     if (_free_sources.size() > 0) {
372        source = _free_sources.back();
373        _free_sources.pop_back();
374        _sources_in_use.push_back(source);
375     }
376
377     return source;
378 }
379
380 // Free up a source id for further use
381 void SGSoundMgr::release_source( unsigned int source )
382 {
383     vector<ALuint>::iterator it;
384
385     it = std::find(_sources_in_use.begin(), _sources_in_use.end(), source);
386     if ( it != _sources_in_use.end() ) {
387         ALint result;
388
389         alGetSourcei( source, AL_SOURCE_STATE, &result );
390         if ( result == AL_PLAYING )
391             alSourceStop( source );
392         testForALError("release source");
393
394         _free_sources.push_back(source);
395         _sources_in_use.erase(it, it+1);
396     }
397 }
398
399 unsigned int SGSoundMgr::request_buffer(SGSoundSample *sample)
400 {
401     ALuint buffer = NO_BUFFER;
402
403     if ( !sample->is_valid_buffer() ) {
404         // sample was not yet loaded or removed again
405         string sample_name = sample->get_sample_name();
406
407         // see if the sample name is already cached
408         buffer_map_iterator buffer_it = _buffers.find( sample_name );
409         if ( buffer_it != _buffers.end() ) {
410             buffer_it->second.refctr++;
411             buffer = buffer_it->second.id;
412             sample->set_buffer( buffer );
413             return buffer;
414         }
415
416         // sample name was not found in the buffer cache.
417         if ( sample->is_file() ) {
418             size_t size;
419             int freq, format;
420             void *data;
421
422             load(sample_name, &data, &format, &size, &freq);
423             sample->set_data( (unsigned char *)data );
424             sample->set_frequency( freq );
425             sample->set_format( format );
426             sample->set_size( size );
427         }
428
429         // create an OpenAL buffer handle
430         alGenBuffers(1, &buffer);
431         if ( !testForALError("generate buffer") ) {
432             // Copy data to the internal OpenAL buffer
433
434             const ALvoid *data = sample->get_data();
435             ALenum format = sample->get_format();
436             ALsizei size = sample->get_size();
437             ALsizei freq = sample->get_frequency();
438             alBufferData( buffer, format, data, size, freq );
439             sample->free_data();
440
441             if ( !testForALError("buffer add data") ) {
442                 sample->set_buffer(buffer);
443                 _buffers[sample_name] = refUint(buffer);
444             }
445         }
446     }
447     else
448         buffer = sample->get_buffer();
449
450     return buffer;
451 }
452
453 void SGSoundMgr::release_buffer(SGSoundSample *sample)
454 {
455     string sample_name = sample->get_sample_name();
456
457     buffer_map_iterator buffer_it = _buffers.find( sample_name );
458     if ( buffer_it == _buffers.end() ) {
459         // buffer was not found
460         return;
461     }
462
463     sample->no_valid_buffer();
464     buffer_it->second.refctr--;
465     if (buffer_it->second.refctr == 0) {
466         ALuint buffer = buffer_it->second.id;
467         _buffers.erase( buffer_it );
468         alDeleteBuffers(1, &buffer);
469         testForALError("release buffer");
470     }
471 }
472
473 bool SGSoundMgr::load(string &samplepath, void **dbuf, int *fmt,
474                                           size_t *sz, int *frq )
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(alutGetErrorString(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 }