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