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