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