]> git.mxchange.org Git - simgear.git/blob - simgear/sound/soundmgr_openal.cxx
Fix a pause situation where more code was executed than expected. Unbind an OpenAL...
[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
159 void SGSoundMgr::activate() {
160     if ( _working ) {
161         _active = true;
162         sample_group_map_iterator sample_grp_current = _sample_groups.begin();
163         sample_group_map_iterator sample_grp_end = _sample_groups.end();
164         for ( ; sample_grp_current != sample_grp_end; ++sample_grp_current ) {
165             SGSampleGroup *sgrp = sample_grp_current->second;
166             sgrp->activate();
167         }
168     }
169 }
170
171 // stop the sound manager
172 void SGSoundMgr::stop() {
173     if (_working) {
174         _working = false;
175         _active = false;
176
177         // clear any OpenAL buffers before shutting down
178         buffer_map_iterator buffers_current = _buffers.begin();
179         buffer_map_iterator buffers_end = _buffers.end();
180         for ( ; buffers_current != buffers_end; ++buffers_current ) {
181             refUint ref = buffers_current->second;
182             ALuint buffer = ref.id;
183             alDeleteBuffers(1, &buffer);
184         }
185         _buffers.clear();
186
187         _context = alcGetCurrentContext();
188         _device = alcGetContextsDevice(_context);
189         alcDestroyContext(_context);
190         alcCloseDevice(_device);
191     }
192 }
193
194 void SGSoundMgr::suspend() {
195     if (_working) {
196         sample_group_map_iterator sample_grp_current = _sample_groups.begin();
197         sample_group_map_iterator sample_grp_end = _sample_groups.end();
198         for ( ; sample_grp_current != sample_grp_end; ++sample_grp_current ) {
199             SGSampleGroup *sgrp = sample_grp_current->second;
200             sgrp->suspend();
201         }
202         _active = false;
203     }
204 }
205
206 void SGSoundMgr::resume() {
207     if (_working) {
208         sample_group_map_iterator sample_grp_current = _sample_groups.begin();
209         sample_group_map_iterator sample_grp_end = _sample_groups.end();
210         for ( ; sample_grp_current != sample_grp_end; ++sample_grp_current ) {
211             SGSampleGroup *sgrp = sample_grp_current->second;
212             sgrp->resume();
213         }
214         _active = true;
215     }
216 }
217
218 void SGSoundMgr::bind ()
219 {
220     _free_sources.clear();
221     _free_sources.reserve( MAX_SOURCES );
222     _sources_in_use.clear();
223     _sources_in_use.reserve( MAX_SOURCES );
224 }
225
226
227 void SGSoundMgr::unbind ()
228 {
229     _sample_groups.clear();
230
231     // delete free sources
232     for (unsigned int i=0; i<_free_sources.size(); i++) {
233         ALuint source = _free_sources[i];
234         alDeleteSources( 1 , &source );
235     }
236
237     _free_sources.clear();
238     _sources_in_use.clear();
239 }
240
241 // run the audio scheduler
242 void SGSoundMgr::update_late( double dt ) {
243     if (_active) {
244         sample_group_map_iterator sample_grp_current = _sample_groups.begin();
245         sample_group_map_iterator sample_grp_end = _sample_groups.end();
246         for ( ; sample_grp_current != sample_grp_end; ++sample_grp_current ) {
247             SGSampleGroup *sgrp = sample_grp_current->second;
248             sgrp->update(dt);
249         }
250
251         if (_changed) {
252             alListenerf( AL_GAIN, _volume );
253             alListenerfv( AL_ORIENTATION, _at_up_vec );
254             alListenerfv( AL_POSITION, toVec3f(_position).data() );
255             alListenerfv( AL_VELOCITY, toVec3f(_velocity).data() );
256             // alDopplerVelocity(340.3);        // TODO: altitude dependent
257             testForALError("update");
258             _changed = false;
259         }
260     }
261 }
262
263 // add a sample 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 (_active) 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( sample_grp_it );
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         alSourcei( source, AL_BUFFER, 0 );
395         _free_sources.push_back( source );
396         _sources_in_use.erase( it );
397     }
398 }
399
400 unsigned int SGSoundMgr::request_buffer(SGSoundSample *sample)
401 {
402     ALuint buffer = NO_BUFFER;
403
404     if ( !sample->is_valid_buffer() ) {
405         // sample was not yet loaded or removed again
406         string sample_name = sample->get_sample_name();
407
408         // see if the sample name is already cached
409         buffer_map_iterator buffer_it = _buffers.find( sample_name );
410         if ( buffer_it != _buffers.end() ) {
411             buffer_it->second.refctr++;
412             buffer = buffer_it->second.id;
413             sample->set_buffer( buffer );
414             return buffer;
415         }
416
417         // sample name was not found in the buffer cache.
418         if ( sample->is_file() ) {
419             size_t size;
420             int freq, format;
421             void *data;
422
423             load(sample_name, &data, &format, &size, &freq);
424             std::auto_ptr<unsigned char> ptr;
425             ptr.reset((unsigned char *)data);
426
427             sample->set_data( ptr );
428             sample->set_frequency( freq );
429             sample->set_format( format );
430             sample->set_size( size );
431         }
432
433         // create an OpenAL buffer handle
434         alGenBuffers(1, &buffer);
435         if ( !testForALError("generate buffer") ) {
436             // Copy data to the internal OpenAL buffer
437
438             const ALvoid *data = sample->get_data();
439             ALenum format = sample->get_format();
440             ALsizei size = sample->get_size();
441             ALsizei freq = sample->get_frequency();
442             alBufferData( buffer, format, data, size, freq );
443
444             // If this sample was read from a file we have all the information
445             // needed to read it again. For data buffers provided by the
446             // program we don't; so don't delete it's data.
447             if ( sample->is_file() ) sample->free_data();
448
449             if ( !testForALError("buffer add data") ) {
450                 sample->set_buffer(buffer);
451                 _buffers[sample_name] = refUint(buffer);
452             }
453         }
454     }
455     else
456         buffer = sample->get_buffer();
457
458     return buffer;
459 }
460
461 void SGSoundMgr::release_buffer(SGSoundSample *sample)
462 {
463     string sample_name = sample->get_sample_name();
464     buffer_map_iterator buffer_it = _buffers.find( sample_name );
465     if ( buffer_it == _buffers.end() ) {
466         // buffer was not found
467         return;
468     }
469
470     sample->no_valid_buffer();
471     buffer_it->second.refctr--;
472     if (buffer_it->second.refctr == 0) {
473         ALuint buffer = buffer_it->second.id;
474         alDeleteBuffers(1, &buffer);
475         _buffers.erase( buffer_it );
476         testForALError("release buffer");
477     }
478 }
479
480 bool SGSoundMgr::load(string &samplepath, void **dbuf, int *fmt,
481                                           size_t *sz, int *frq )
482 {
483     if ( !_working ) return false;
484
485     ALenum format;
486     ALsizei size;
487     ALsizei freq;
488     ALvoid *data;
489
490 #if defined(ALUT_API_MAJOR_VERSION) && ALUT_API_MAJOR_VERSION >= 1
491     ALfloat freqf;
492     data = alutLoadMemoryFromFile(samplepath.c_str(), &format, &size, &freqf );
493     freq = (ALsizei)freqf;
494     if (data == NULL) {
495         int error = alutGetError();
496         string msg = "Failed to load wav file: ";
497         msg.append(alutGetErrorString(error));
498         throw sg_io_exception(msg.c_str(), sg_location(samplepath));
499         return false;
500     }
501
502 #else
503     ALbyte *fname = (ALbyte *)samplepath.c_str();
504 # if defined (__APPLE__)
505     alutLoadWAVFile( fname, &format, &data, &size, &freq );
506 # else
507     ALboolean loop;
508     alutLoadWAVFile( fname, &format, &data, &size, &freq, &loop );
509 # endif
510     ALenum error =  alGetError();
511     if ( error != AL_NO_ERROR ) {
512         string msg = "Failed to load wav file: ";
513         msg.append(alGetString(error));
514         throw sg_io_exception(msg.c_str(), sg_location(samplepath));
515         return false;
516     }
517 #endif
518
519     *dbuf = (void *)data;
520     *fmt = (int)format;
521     *sz = (size_t)size;
522     *frq = (int)freq;
523
524     return true;
525 }
526
527
528 bool SGSoundMgr::testForError(void *p, string s)
529 {
530    if (p == NULL) {
531       SG_LOG( SG_GENERAL, SG_ALERT, "Error: " << s);
532       return true;
533    }
534    return false;
535 }
536
537
538 bool SGSoundMgr::testForALError(string s)
539 {
540     ALenum error = alGetError();
541     if (error != AL_NO_ERROR)  {
542        SG_LOG( SG_GENERAL, SG_ALERT, "AL Error (sound manager): "
543                                       << alGetString(error) << " at " << s);
544        return true;
545     }
546     return false;
547 }
548
549 bool SGSoundMgr::testForALCError(string s)
550 {
551     ALCenum error;
552     error = alcGetError(_device);
553     if (error != ALC_NO_ERROR) {
554         SG_LOG( SG_GENERAL, SG_ALERT, "ALC Error (sound manager): "
555                                        << alcGetString(_device, error) << " at "
556                                        << s);
557         return true;
558     }
559     return false;
560 }
561
562 bool SGSoundMgr::testForALUTError(string s)
563 {
564 #if defined(ALUT_API_MAJOR_VERSION) && ALUT_API_MAJOR_VERSION >= 1
565     ALenum error;
566     error =  alutGetError ();
567     if (error != ALUT_ERROR_NO_ERROR) {
568         SG_LOG( SG_GENERAL, SG_ALERT, "ALUT Error (sound manager): "
569                                        << alutGetErrorString(error) << " at "
570                                        << s);
571         return true;
572     }
573 #endif
574     return false;
575 }