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