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