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