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