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