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