]> git.mxchange.org Git - simgear.git/blob - simgear/sound/soundmgr_openal.cxx
Alut < 1.0 fixes and finaly fix the sound orientation
[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 //
8 // Copyright (C) 2001  Curtis L. Olson - http://www.flightgear.org/~curt
9 //
10 // This program is free software; you can redistribute it and/or
11 // modify it under the terms of the GNU General Public License as
12 // published by the Free Software Foundation; either version 2 of the
13 // License, or (at your option) any later version.
14 //
15 // This program is distributed in the hope that it will be useful, but
16 // WITHOUT ANY WARRANTY; without even the implied warranty of
17 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18 // General Public License for more details.
19 //
20 // You should have received a copy of the GNU General Public License
21 // along with this program; if not, write to the Free Software Foundation,
22 // Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
23 //
24 // $Id$
25
26 #ifdef HAVE_CONFIG_H
27 #  include <simgear_config.h>
28 #endif
29
30 #if defined( __APPLE__ )
31 # include <OpenAL/alut.h>
32 #else
33 # include <AL/alut.h>
34 #endif
35
36 #include <iostream>
37 #include <algorithm>
38
39 #include "soundmgr_openal.hxx"
40
41 #include <simgear/structure/exception.hxx>
42 #include <simgear/debug/logstream.hxx>
43 #include <simgear/misc/sg_path.hxx>
44 #include <simgear/math/SGMath.hxx>
45
46
47 #define MAX_SOURCES     128
48
49 //
50 // Sound Manager
51 //
52
53 int SGSoundMgr::_alut_init = 0;
54
55 // constructor
56 SGSoundMgr::SGSoundMgr() :
57     _working(false),
58     _changed(true),
59     _volume(0.0),
60     _device(NULL),
61     _context(NULL),
62     _position(SGVec3d::zeros()),
63     _velocity(SGVec3d::zeros()),
64     _orientation(SGQuatd::zeros()),
65     _devname(NULL)
66 {
67 #if defined(ALUT_API_MAJOR_VERSION) && ALUT_API_MAJOR_VERSION >= 1
68     if (_alut_init == 0) {
69         if ( !alutInitWithoutContext(NULL, NULL) ) {
70             testForALUTError("alut initialization");
71             return;
72         }
73     }
74     _alut_init++;
75 #endif
76 }
77
78 // destructor
79
80 SGSoundMgr::~SGSoundMgr() {
81
82     stop();
83 #if defined(ALUT_API_MAJOR_VERSION) && ALUT_API_MAJOR_VERSION >= 1
84     _alut_init--;
85     if (_alut_init == 0) {
86         alutExit ();
87     }
88 #endif
89 }
90
91 // initialize the sound manager
92 void SGSoundMgr::init() {
93
94     SG_LOG( SG_GENERAL, SG_INFO, "Initializing OpenAL sound manager" );
95
96     ALCdevice *device = alcOpenDevice(_devname);
97     if ( testForError(device, "No default audio device available.") ) {
98         return;
99     }
100
101     ALCcontext *context = alcCreateContext(device, NULL);
102     if ( testForError(context, "Unable to create a valid context.") ) {
103         alcCloseDevice (device);
104         return;
105     }
106
107     if ( !alcMakeContextCurrent(context) ) {
108         testForALCError("context initialization");
109         alcDestroyContext (context);
110         alcCloseDevice (device);
111         return;
112     }
113
114     _context = context;
115     _working = true;
116
117     _at_up_vec[0] = 0.0; _at_up_vec[1] = 0.0; _at_up_vec[2] = -1.0;
118     _at_up_vec[3] = 0.0; _at_up_vec[4] = 1.0; _at_up_vec[5] = 0.0;
119
120     alListenerf( AL_GAIN, 0.2f );
121     alListenerfv( AL_ORIENTATION, _at_up_vec );
122     alListenerfv( AL_POSITION, SGVec3f::zeros().data() );
123     alListenerfv( AL_VELOCITY, SGVec3f::zeros().data() );
124
125     alDopplerFactor(1.0);
126     alDopplerVelocity(340.3);   // speed of sound in meters per second.
127
128     if ( alIsExtensionPresent((const ALchar*)"EXT_exponent_distance") ) {
129         alDistanceModel(AL_EXPONENT_DISTANCE);
130     } else {
131         alDistanceModel(AL_INVERSE_DISTANCE);
132     }
133
134     testForALError("listener initialization");
135
136     // get a free source one at a time
137     // if an error is returned no more (hardware) sources are available
138     for (unsigned int i=0; i<MAX_SOURCES; i++) {
139         ALuint source;
140         ALenum error;
141
142         alGetError();
143         alGenSources(1, &source);
144         error = alGetError();
145         if ( error == AL_NO_ERROR ) {
146             _free_sources.push_back( source );
147         }
148         else break;
149     }
150
151     if (_free_sources.size() == 0) {
152         SG_LOG(SG_GENERAL, SG_ALERT, "Unable to grab any OpenAL sources!");
153     }
154
155     sample_group_map_iterator sample_grp_current = _sample_groups.begin();
156     sample_group_map_iterator sample_grp_end = _sample_groups.end();
157     for ( ; sample_grp_current != sample_grp_end; ++sample_grp_current ) {
158         SGSampleGroup *sgrp = sample_grp_current->second;
159         sgrp->activate();
160     }
161 }
162
163 // suspend the sound manager
164 void SGSoundMgr::stop() {
165     if (_working) {
166         _working = false;
167
168         // clear any OpenAL buffers before shutting down
169         buffer_map_iterator buffers_current;
170         while(_buffers.size()){
171             buffers_current = _buffers.begin();
172             refUint ref = buffers_current->second;
173             ALuint buffer = ref.id;
174             alDeleteBuffers(1, &buffer);
175             _buffers.erase( buffers_current );
176         }
177
178         _context = alcGetCurrentContext();
179         _device = alcGetContextsDevice(_context);
180         alcMakeContextCurrent(NULL);
181         alcDestroyContext(_context);
182         alcCloseDevice(_device);
183     }
184 }
185
186 void SGSoundMgr::suspend() {
187     if (_working) {
188         sample_group_map_iterator sample_grp_current = _sample_groups.begin();
189         sample_group_map_iterator sample_grp_end = _sample_groups.end();
190         for ( ; sample_grp_current != sample_grp_end; ++sample_grp_current ) {
191             SGSampleGroup *sgrp = sample_grp_current->second;
192             sgrp->suspend();
193         }
194     }
195 }
196
197
198 void SGSoundMgr::bind ()
199 {
200     _free_sources.clear();
201     _free_sources.reserve( MAX_SOURCES );
202     _sources_in_use.clear();
203     _sources_in_use.reserve( MAX_SOURCES );
204 }
205
206
207 void SGSoundMgr::unbind ()
208 {
209     _sample_groups.clear();
210
211     // delete free sources
212     for (unsigned int i=0; i<_free_sources.size(); i++) {
213         ALuint source = _free_sources.at( i );
214         alDeleteSources( 1 , &source );
215     }
216
217     _free_sources.clear();
218     _sources_in_use.clear();
219 }
220
221 void SGSoundMgr::update( double dt )
222 {
223     // nothing to do in the regular update, everything is done on the following
224     // function
225 }
226
227
228 // run the audio scheduler
229 void SGSoundMgr::update_late( double dt ) {
230     if (_working) {
231         alcSuspendContext(_context);
232
233         sample_group_map_iterator sample_grp_current = _sample_groups.begin();
234         sample_group_map_iterator sample_grp_end = _sample_groups.end();
235         for ( ; sample_grp_current != sample_grp_end; ++sample_grp_current ) {
236             SGSampleGroup *sgrp = sample_grp_current->second;
237             sgrp->update(dt);
238         }
239
240         if (_changed) {
241             alListenerf( AL_GAIN, _volume );
242             alListenerfv( AL_ORIENTATION, _at_up_vec );
243             alListenerfv( AL_POSITION, toVec3f(_position).data() );
244             alListenerfv( AL_VELOCITY, toVec3f(_velocity).data() );
245             // alDopplerVelocity(340.3);        // TODO: altitude dependent
246             testForALError("update");
247             _changed = false;
248         }
249         alcProcessContext(_context);
250     }
251 }
252
253
254 void
255 SGSoundMgr::resume ()
256 {
257     if (_working) {
258         sample_group_map_iterator sample_grp_current = _sample_groups.begin();
259         sample_group_map_iterator sample_grp_end = _sample_groups.end();
260         for ( ; sample_grp_current != sample_grp_end; ++sample_grp_current ) {
261             SGSampleGroup *sgrp = sample_grp_current->second;
262             sgrp->resume();
263         }
264     }
265 }
266
267
268 // add a sampel group, return true if successful
269 bool SGSoundMgr::add( SGSampleGroup *sgrp, const string& refname )
270 {
271     sample_group_map_iterator sample_grp_it = _sample_groups.find( refname );
272     if ( sample_grp_it != _sample_groups.end() ) {
273         // sample group already exists
274         return false;
275     }
276
277     if (_working) sgrp->activate();
278     _sample_groups[refname] = sgrp;
279
280     return true;
281 }
282
283
284 // remove a sound effect, return true if successful
285 bool SGSoundMgr::remove( const string &refname )
286 {
287     sample_group_map_iterator sample_grp_it = _sample_groups.find( refname );
288     if ( sample_grp_it == _sample_groups.end() ) {
289         // sample group was not found.
290         return false;
291     }
292
293     _sample_groups.erase( refname );
294
295     return true;
296 }
297
298
299 // return true of the specified sound exists in the sound manager system
300 bool SGSoundMgr::exists( const string &refname ) {
301     sample_group_map_iterator sample_grp_it = _sample_groups.find( refname );
302     if ( sample_grp_it == _sample_groups.end() ) {
303         // sample group was not found.
304         return false;
305     }
306
307     return true;
308 }
309
310
311 // return a pointer to the SGSampleGroup if the specified sound exists
312 // in the sound manager system, otherwise return NULL
313 SGSampleGroup *SGSoundMgr::find( const string &refname, bool create ) {
314     sample_group_map_iterator sample_grp_it = _sample_groups.find( refname );
315     if ( sample_grp_it == _sample_groups.end() ) {
316         // sample group was not found.
317         if (create) {
318             SGSampleGroup* sgrp = new SGSampleGroup(this, refname);
319             return sgrp;
320         }
321         else 
322             return NULL;
323     }
324
325     return sample_grp_it->second;
326 }
327
328
329 void SGSoundMgr::set_volume( float v )
330 {
331     _volume = v;
332     if (_volume > 1.0) _volume = 1.0;
333     if (_volume < 0.0) _volume = 0.0;
334     _changed = true;
335 }
336
337 /**
338  * set the orientation of the listener (in opengl coordinates)
339  *
340  * Description: ORIENTATION is a pair of 3-tuples representing the
341  * 'at' direction vector and 'up' direction of the Object in
342  * Cartesian space. AL expects two vectors that are orthogonal to
343  * each other. These vectors are not expected to be normalized. If
344  * one or more vectors have zero length, implementation behavior
345  * is undefined. If the two vectors are linearly dependent,
346  * behavior is undefined.
347  */
348 void SGSoundMgr::set_orientation( SGQuatd ori )
349 {
350     _orientation = ori;
351
352     SGVec3d sgv_up = ori.rotate(SGVec3d::e2());
353     SGVec3d sgv_at = ori.rotate(SGVec3d::e3());
354     _at_up_vec[0] = sgv_at[0];
355     _at_up_vec[1] = sgv_at[1];
356     _at_up_vec[2] = sgv_at[2];
357     _at_up_vec[3] = sgv_up[0];
358     _at_up_vec[4] = sgv_up[1];
359     _at_up_vec[5] = sgv_up[2];
360     _changed = true;
361 }
362
363 // Get an unused source id
364 //
365 // The Sound Manager should keep track of the sources in use, the distance
366 // of these sources to the listener and the volume (also based on audio cone
367 // and hence orientation) of the sources.
368 //
369 // The Sound Manager is (and should be) the only one knowing about source
370 // management. Sources further away should be suspendped to free resources for
371 // newly added sounds close by.
372 unsigned int SGSoundMgr::request_source()
373 {
374     unsigned int source = NO_SOURCE;
375
376     if (_free_sources.size() > 0) {
377        source = _free_sources.back();
378        _free_sources.pop_back();
379        _sources_in_use.push_back(source);
380     }
381
382     return source;
383 }
384
385 // Free up a source id for further use
386 void SGSoundMgr::release_source( unsigned int source )
387 {
388     vector<ALuint>::iterator it;
389
390     it = std::find(_sources_in_use.begin(), _sources_in_use.end(), source);
391     if ( it != _sources_in_use.end() ) {
392         ALint result;
393
394         alGetSourcei( source, AL_SOURCE_STATE, &result );
395         if ( result == AL_PLAYING )
396             alSourceStop( source );
397         testForALError("release source");
398
399         _free_sources.push_back(source);
400         _sources_in_use.erase(it, it+1);
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             unsigned int size;
424             int freq, format;
425             void *data;
426
427             load(sample_name, &data, &format, &size, &freq);
428             sample->set_data( (unsigned char *)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             sample->free_data();
445
446             if ( !testForALError("buffer add data") ) {
447                 sample->set_buffer(buffer);
448                 _buffers[sample_name] = refUint(buffer);
449             }
450         }
451     }
452     else
453         buffer = sample->get_buffer();
454
455     return buffer;
456 }
457
458 void SGSoundMgr::release_buffer(SGSoundSample *sample)
459 {
460     string sample_name = sample->get_sample_name();
461
462     buffer_map_iterator buffer_it = _buffers.find( sample_name );
463     if ( buffer_it == _buffers.end() ) {
464         // buffer was not found
465         return;
466     }
467
468     sample->no_valid_buffer();
469     buffer_it->second.refctr--;
470     if (buffer_it->second.refctr == 0) {
471         ALuint buffer = buffer_it->second.id;
472         _buffers.erase( buffer_it );
473         alDeleteBuffers(1, &buffer);
474         testForALError("release buffer");
475     }
476 }
477
478 bool SGSoundMgr::load(string &samplepath, void **dbuf, int *fmt,
479                                           unsigned int *sz, int *frq )
480 {
481     ALenum format;
482     ALsizei size;
483     ALsizei freq;
484     ALvoid *data;
485
486 #if defined(ALUT_API_MAJOR_VERSION) && ALUT_API_MAJOR_VERSION >= 1
487     ALfloat freqf;
488     data = alutLoadMemoryFromFile(samplepath.c_str(), &format, &size, &freqf );
489     freq = (ALsizei)freqf;
490     if (data == NULL) {
491         int error = alutGetError();
492         string msg = "Failed to load wav file: ";
493         msg.append(alutGetErrorString(error));
494         throw sg_io_exception(msg.c_str(), sg_location(samplepath));
495         return false;
496     }
497
498 #else
499     ALbyte *fname = (ALbyte *)samplepath.c_str();
500 # if defined (__APPLE__)
501     alutLoadWAVFile( fname, &format, &data, &size, &freq );
502 # else
503     ALboolean loop;
504     alutLoadWAVFile( fname, &format, &data, &size, &freq, &loop );
505 # endif
506     ALenum error =  alGetError();
507     if ( error != AL_NO_ERROR ) {
508         string msg = "Failed to load wav file: ";
509         msg.append(alutGetErrorString(error));
510         throw sg_io_exception(msg.c_str(), sg_location(samplepath));
511         return false;
512     }
513 #endif
514
515     *dbuf = (void *)data;
516     *fmt = (int)format;
517     *sz = (unsigned int)size;
518     *frq = (int)freq;
519
520     return true;
521 }
522
523
524 bool SGSoundMgr::testForError(void *p, string s)
525 {
526    if (p == NULL) {
527       SG_LOG( SG_GENERAL, SG_ALERT, "Error: " << s);
528       return true;
529    }
530    return false;
531 }
532
533
534 bool SGSoundMgr::testForALError(string s)
535 {
536     ALenum error = alGetError();
537     if (error != AL_NO_ERROR)  {
538        SG_LOG( SG_GENERAL, SG_ALERT, "AL Error (sound manager): "
539                                       << alGetString(error) << " at " << s);
540        return true;
541     }
542     return false;
543 }
544
545 bool SGSoundMgr::testForALCError(string s)
546 {
547     ALCenum error;
548     error = alcGetError(_device);
549     if (error != ALC_NO_ERROR) {
550         SG_LOG( SG_GENERAL, SG_ALERT, "ALC Error (sound manager): "
551                                        << alcGetString(_device, error) << " at "
552                                        << s);
553         return true;
554     }
555     return false;
556 }
557
558 bool SGSoundMgr::testForALUTError(string s)
559 {
560 #if defined(ALUT_API_MAJOR_VERSION) && ALUT_API_MAJOR_VERSION >= 1
561     ALenum error;
562     error =  alutGetError ();
563     if (error != ALUT_ERROR_NO_ERROR) {
564         SG_LOG( SG_GENERAL, SG_ALERT, "ALUT Error (sound manager): "
565                                        << alutGetErrorString(error) << " at "
566                                        << s);
567         return true;
568     }
569 #endif
570     return false;
571 }