]> git.mxchange.org Git - simgear.git/blob - simgear/sound/soundmgr_openal.cxx
give the sample class as much info as possible to properly position and orientate...
[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         return;
105     }
106
107     if ( !alcMakeContextCurrent(context) ) {
108         testForALCError("context initialization");
109         return;
110     }
111
112     _context = context;
113     _working = true;
114
115     _at_up_vec[0] = 0.0; _at_up_vec[1] = 0.0; _at_up_vec[2] = -1.0;
116     _at_up_vec[3] = 0.0; _at_up_vec[4] = 1.0; _at_up_vec[5] = 0.0;
117
118     alListenerf( AL_GAIN, 0.2f );
119     alListenerfv( AL_POSITION, SGVec3f::zeros().data() );
120     alListenerfv( AL_ORIENTATION, _at_up_vec );
121     alListenerfv( AL_VELOCITY, toVec3f(_velocity).data() );
122
123     alDopplerFactor(0.5);
124     alDopplerVelocity(340.3);   // speed of sound in meters per second.
125
126     if ( alIsExtensionPresent((const ALchar*)"EXT_exponent_distance") ) {
127         alDistanceModel(AL_EXPONENT_DISTANCE);
128     } else {
129         alDistanceModel(AL_INVERSE_DISTANCE);
130     }
131
132     testForALError("listener initialization");
133
134     alGetError(); // clear any undetetced error, just to be sure
135
136     // get a free source one at a time
137     // if an error is returned no more (hardware) sources are available
138     for (unsigned int i=0; i<MAX_SOURCES; i++) {
139         ALuint source;
140         ALenum error;
141
142         alGetError();
143         alGenSources(1, &source);
144         error = alGetError();
145         if ( error == AL_NO_ERROR ) {
146             _free_sources.push_back( source );
147         }
148         else break;
149     }
150 }
151
152 // suspend the sound manager
153 void SGSoundMgr::stop() {
154     if (_working) {
155         _working = false;
156
157         // clear any OpenAL buffers before shutting down
158         buffer_map_iterator buffers_current;
159         while(_buffers.size()){
160             buffers_current = _buffers.begin();
161             refUint ref = buffers_current->second;
162             ALuint buffer = ref.id;
163             alDeleteBuffers(1, &buffer);
164             _buffers.erase( buffers_current );
165         }
166
167         _context = alcGetCurrentContext();
168         _device = alcGetContextsDevice(_context);
169         alcMakeContextCurrent(NULL);
170         alcDestroyContext(_context);
171         alcCloseDevice(_device);
172     }
173 }
174
175 void SGSoundMgr::suspend() {
176     if (_working) {
177         sample_group_map_iterator sample_grp_current = _sample_groups.begin();
178         sample_group_map_iterator sample_grp_end = _sample_groups.end();
179         for ( ; sample_grp_current != sample_grp_end; ++sample_grp_current ) {
180             SGSampleGroup *sgrp = sample_grp_current->second;
181             sgrp->suspend();
182         }
183     }
184 }
185
186
187 void SGSoundMgr::bind ()
188 {
189     _free_sources.clear();
190     _free_sources.reserve( MAX_SOURCES );
191     _sources_in_use.clear();
192     _sources_in_use.reserve( MAX_SOURCES );
193 }
194
195
196 void SGSoundMgr::unbind ()
197 {
198     _sample_groups.clear();
199
200     // delete free sources
201     for (unsigned int i=0; i<_free_sources.size(); i++) {
202         ALuint source = _free_sources.at( i );
203         alDeleteSources( 1 , &source );
204     }
205
206     _free_sources.clear();
207     _sources_in_use.clear();
208 }
209
210 void SGSoundMgr::update( double dt )
211 {
212     // nothing to do in the regular update, everything is done on the following
213     // function
214 }
215
216
217 // run the audio scheduler
218 void SGSoundMgr::update_late( double dt ) {
219     if (_working) {
220         alcSuspendContext(_context);
221
222         sample_group_map_iterator sample_grp_current = _sample_groups.begin();
223         sample_group_map_iterator sample_grp_end = _sample_groups.end();
224         for ( ; sample_grp_current != sample_grp_end; ++sample_grp_current ) {
225             SGSampleGroup *sgrp = sample_grp_current->second;
226             sgrp->update(dt);
227         }
228
229         if (_changed) {
230             alListenerf( AL_GAIN, _volume );
231             alListenerfv( AL_ORIENTATION, _at_up_vec );
232             alListenerfv( AL_POSITION, toVec3f(_position).data() );
233             alListenerfv( AL_VELOCITY, toVec3f(_velocity).data() );
234             // alDopplerVelocity(340.3);        // TODO: altitude dependent
235             testForALError("update");
236             _changed = false;
237         }
238         alcProcessContext(_context);
239     }
240 }
241
242
243 void
244 SGSoundMgr::resume ()
245 {
246     if (_working) {
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->resume();
252         }
253     }
254 }
255
256
257 // add a sampel group, return true if successful
258 bool SGSoundMgr::add( SGSampleGroup *sgrp, const string& refname )
259 {
260     sample_group_map_iterator sample_grp_it = _sample_groups.find( refname );
261     if ( sample_grp_it != _sample_groups.end() ) {
262         // sample group already exists
263         return false;
264     }
265
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             unsigned int 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             sample->free_data();
433
434             if ( !testForALError("buffer add data") ) {
435                 sample->set_buffer(buffer);
436                 _buffers[sample_name] = refUint(buffer);
437             }
438         }
439     }
440     else
441         buffer = sample->get_buffer();
442
443     return buffer;
444 }
445
446 void SGSoundMgr::release_buffer(SGSoundSample *sample)
447 {
448     string sample_name = sample->get_sample_name();
449
450     buffer_map_iterator buffer_it = _buffers.find( sample_name );
451     if ( buffer_it == _buffers.end() ) {
452         // buffer was not found
453         return;
454     }
455
456     sample->no_valid_buffer();
457     buffer_it->second.refctr--;
458     if (buffer_it->second.refctr == 0) {
459         ALuint buffer = buffer_it->second.id;
460         _buffers.erase( buffer_it );
461         alDeleteBuffers(1, &buffer);
462         testForALError("release buffer");
463     }
464 }
465
466 bool SGSoundMgr::load(string &samplepath, void **dbuf, int *fmt,
467                                           unsigned int *sz, int *frq )
468 {
469     ALenum format = (ALenum)*fmt;
470     ALsizei size = (ALsizei)*sz;
471     ALsizei freq = (ALsizei)*frq;
472     ALvoid *data;
473
474 #if defined(ALUT_API_MAJOR_VERSION) && ALUT_API_MAJOR_VERSION >= 1
475     ALfloat freqf;
476     data = alutLoadMemoryFromFile(samplepath.c_str(), &format, &size, &freqf );
477     freq = (ALsizei)freqf;
478     if (data == NULL) {
479         int error = alutGetError();
480         string msg = "Failed to load wav file: ";
481         msg.append(alutGetErrorString(error));
482         throw sg_io_exception(msg.c_str(), sg_location(samplepath));
483         return false;
484     }
485
486 #else
487     ALbyte *fname = (ALbyte *)samplepath.c_str();
488 # if defined (__APPLE__)
489     alutLoadWAVFile( fname, &format, &data, &size, &freq );
490 # else
491     ALboolean loop;
492     alutLoadWAVFile( fname, &format, &data, &size, &freq, &loop );
493 # endif
494     ALenum error =  alutGetError();
495     if ( error != ALUT_ERROR_NO_ERROR ) {
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 #endif
502
503     *dbuf = (void *)data;
504     *fmt = (int)format;
505     *sz = (unsigned int)size;
506     *frq = (int)freq;
507
508     return true;
509 }
510
511
512 bool SGSoundMgr::testForError(void *p, string s)
513 {
514    if (p == NULL) {
515       SG_LOG( SG_GENERAL, SG_ALERT, "Error: " << s);
516       return true;
517    }
518    return false;
519 }
520
521
522 bool SGSoundMgr::testForALError(string s)
523 {
524     ALenum error = alGetError();
525     if (error != AL_NO_ERROR)  {
526        SG_LOG( SG_GENERAL, SG_ALERT, "AL Error (sound manager): "
527                                       << alGetString(error) << " at " << s);
528        return true;
529     }
530     return false;
531 }
532
533 bool SGSoundMgr::testForALCError(string s)
534 {
535     ALCenum error;
536     error = alcGetError(_device);
537     if (error != ALC_NO_ERROR) {
538         SG_LOG( SG_GENERAL, SG_ALERT, "ALC Error (sound manager): "
539                                        << alcGetString(_device, error) << " at "
540                                        << s);
541         return true;
542     }
543     return false;
544 }
545
546 bool SGSoundMgr::testForALUTError(string s)
547 {
548 #if defined(ALUT_API_MAJOR_VERSION) && ALUT_API_MAJOR_VERSION >= 1
549     ALenum error;
550     error =  alutGetError ();
551     if (error != ALUT_ERROR_NO_ERROR) {
552         SG_LOG( SG_GENERAL, SG_ALERT, "ALUT Error (sound manager): "
553                                        << alutGetErrorString(error) << " at "
554                                        << s);
555         return true;
556     }
557 #endif
558     return false;
559 }