1 // sample.cxx -- Sound sample encapsulation class
3 // Written by Curtis Olson, started April 2004.
5 // Copyright (C) 2004 Curtis L. Olson - http://www.flightgear.org/~curt
7 // This program is free software; you can redistribute it and/or
8 // modify it under the terms of the GNU General Public License as
9 // published by the Free Software Foundation; either version 2 of the
10 // License, or (at your option) any later version.
12 // This program is distributed in the hope that it will be useful, but
13 // WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 // General Public License for more details.
17 // You should have received a copy of the GNU General Public License
18 // along with this program; if not, write to the Free Software
19 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
24 # include <simgear_config.h>
27 #if defined( __APPLE__ )
28 # define AL_ILLEGAL_ENUM AL_INVALID_ENUM
29 # define AL_ILLEGAL_COMMAND AL_INVALID_OPERATION
30 # include <OpenAL/al.h>
31 # include <OpenAL/alut.h>
37 #include <simgear/debug/logstream.hxx>
38 #include <simgear/misc/sg_path.hxx>
39 #include <simgear/structure/exception.hxx>
41 #include "sample_openal.hxx"
49 static bool print_openal_error(const string &s = "unknown") {
50 ALuint error = alGetError();
51 if ( error == AL_NO_ERROR ) {
53 } else if ( error == AL_INVALID_NAME ) {
54 SG_LOG( SG_GENERAL, SG_ALERT, "OpenAL error (AL_INVALID_NAME): " << s );
55 } else if ( error == AL_ILLEGAL_ENUM ) {
56 SG_LOG( SG_GENERAL, SG_ALERT, "OpenAL error (AL_ILLEGAL_ENUM): " << s );
57 } else if ( error == AL_INVALID_VALUE ) {
58 SG_LOG( SG_GENERAL, SG_ALERT, "OpenAL error (AL_INVALID_VALUE): " << s );
59 } else if ( error == AL_ILLEGAL_COMMAND ) {
60 SG_LOG( SG_GENERAL, SG_ALERT, "OpenAL error (AL_ILLEGAL_COMMAND): " << s );
61 } else if ( error == AL_OUT_OF_MEMORY ) {
62 SG_LOG( SG_GENERAL, SG_ALERT, "OpenAL error (AL_OUT_OF_MEMORY): " << s );
64 SG_LOG( SG_GENERAL, SG_ALERT, "Unhandled error code = " << error );
70 SGSoundSample::SGSoundSample() :
75 reference_dist(500.0),
78 #ifdef USE_SOFTWARE_DOPPLER
79 doppler_pitch_factor(1),
80 doppler_volume_factor(1),
83 no_Doppler_effect(true)
88 SGSoundSample::SGSoundSample( const char *path, const char *file, bool _no_Doppler_effect ) :
93 reference_dist(500.0),
96 #ifdef USE_SOFTWARE_DOPPLER
97 doppler_pitch_factor(1),
98 doppler_volume_factor(1),
101 no_Doppler_effect(_no_Doppler_effect)
103 SGPath samplepath( path );
104 if ( strlen(file) ) {
105 samplepath.append( file );
107 sample_name = samplepath.str();
109 SG_LOG( SG_GENERAL, SG_DEBUG, "From file sounds sample = "
110 << samplepath.str() );
112 source_pos[0] = 0.0; source_pos[1] = 0.0; source_pos[2] = 0.0;
113 offset_pos[0] = 0.0; offset_pos[1] = 0.0; offset_pos[2] = 0.0;
114 source_vel[0] = 0.0; source_vel[1] = 0.0; source_vel[2] = 0.0;
115 direction[0] = 0.0; direction[1] = 0.0; direction[2] = 0.0;
116 inner = outer = 360.0; outergain = 0.0;
118 // clear errors from elsewhere?
121 // create an OpenAL buffer handle
122 alGenBuffers(1, &buffer);
123 if ( print_openal_error("constructor (alGenBuffers)") ) {
124 throw sg_exception("Failed to gen OpenAL buffer.");
127 // Load the sample file
128 #if defined(ALUT_API_MAJOR_VERSION) && ALUT_API_MAJOR_VERSION >= 1
130 buffer = alutCreateBufferFromFile(samplepath.c_str());
131 if (buffer == AL_NONE) {
132 ALenum error = alutGetError ();
133 print_openal_error("constructor (alutCreateBufferFromFile)");
134 throw sg_io_exception("Failed to load wav file: ",
135 sg_location(string(alutGetErrorString (error))));
140 // pre 1.0 alut version
142 ALvoid* data = load_file(path, file);
144 // Copy data to the internal OpenAL buffer
145 alBufferData( buffer, format, data, size, freq );
147 if ( print_openal_error("constructor (alBufferData)") ) {
148 throw sg_exception("Failed to buffer data.");
151 alutUnloadWAV( format, data, size, freq );
154 print_openal_error("constructor return");
158 SGSoundSample::SGSoundSample( unsigned char *_data, int len, int _freq, bool _no_Doppler_effect ) :
163 reference_dist(500.0),
166 #ifdef USE_SOFTWARE_DOPPLER
167 doppler_pitch_factor(1),
168 doppler_volume_factor(1),
171 no_Doppler_effect(_no_Doppler_effect)
173 SG_LOG( SG_GENERAL, SG_DEBUG, "In memory sounds sample" );
175 sample_name = "unknown, generated from data";
177 source_pos[0] = 0.0; source_pos[1] = 0.0; source_pos[2] = 0.0;
178 offset_pos[0] = 0.0; offset_pos[1] = 0.0; offset_pos[2] = 0.0;
179 source_vel[0] = 0.0; source_vel[1] = 0.0; source_vel[2] = 0.0;
180 direction[0] = 0.0; direction[1] = 0.0; direction[2] = 0.0;
181 inner = outer = 360.0; outergain = 0.0;
183 // clear errors from elsewhere?
186 // Load wav data into a buffer.
187 alGenBuffers(1, &buffer);
188 if ( print_openal_error("constructor (alGenBuffers)") ) {
189 throw sg_exception("Failed to gen buffer." );
192 format = AL_FORMAT_MONO8;
196 alBufferData( buffer, format, _data, size, freq );
197 if ( print_openal_error("constructor (alBufferData)") ) {
198 throw sg_exception("Failed to buffer data.");
201 print_openal_error("constructor return");
206 SGSoundSample::~SGSoundSample() {
207 SG_LOG( SG_GENERAL, SG_INFO, "Deleting a sample" );
209 alDeleteBuffers(1, &buffer);
214 void SGSoundSample::play( bool _loop ) {
217 alSourceStop( source );
220 playing = bind_source();
224 alSourcei( source, AL_LOOPING, loop );
225 alSourcePlay( source );
227 print_openal_error("play (alSourcePlay)");
232 // stop playing the sample
233 void SGSoundSample::stop() {
235 alSourceStop( source );
236 alDeleteSources(1, &source);
238 print_openal_error("stop (alDeleteSources)");
243 // Generate sound source
245 SGSoundSample::bind_source() {
254 // Bind buffer with a source.
256 alGenSources(1, &source);
257 if ( print_openal_error("bind_source (alGenSources)") ) {
258 // No biggy, better luck next time.
259 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to generate audio source.");
260 // SG_LOG( SG_GENERAL, SG_ALERT, "Please update your sound driver and try again.");
264 alSourcei( source, AL_BUFFER, buffer );
265 #ifndef USE_SOFTWARE_DOPPLER
266 alSourcef( source, AL_PITCH, pitch );
267 alSourcef( source, AL_GAIN, volume );
269 print_openal_error("bind_sources return");
270 alSourcef( source, AL_PITCH, pitch * doppler_pitch_factor );
271 alGetError(); // ignore if the pitch is clamped by the driver
272 alSourcef( source, AL_GAIN, volume * doppler_volume_factor );
274 alSourcefv( source, AL_POSITION, source_pos );
275 alSourcefv( source, AL_DIRECTION, direction );
276 alSourcef( source, AL_CONE_INNER_ANGLE, inner );
277 alSourcef( source, AL_CONE_OUTER_ANGLE, outer );
278 alSourcef( source, AL_CONE_OUTER_GAIN, outergain);
279 #ifdef USE_OPEN_AL_DOPPLER
280 alSourcefv( source, AL_VELOCITY, source_vel );
282 alSourcei( source, AL_LOOPING, loop );
284 alSourcei( source, AL_SOURCE_RELATIVE, AL_TRUE );
285 alSourcef( source, AL_REFERENCE_DISTANCE, reference_dist );
286 alSourcef( source, AL_MAX_DISTANCE, max_dist );
288 print_openal_error("bind_sources return");
294 SGSoundSample::set_pitch( double p ) {
295 // clamp in the range of 0.01 to 2.0
296 if ( p < 0.01 ) { p = 0.01; }
297 if ( p > 2.0 ) { p = 2.0; }
300 #ifndef USE_SOFTWARE_DOPPLER
301 alSourcef( source, AL_PITCH, pitch );
302 print_openal_error("set_pitch");
304 alSourcef( source, AL_PITCH, pitch * doppler_pitch_factor );
305 alGetError(); // ignore if the pitch is clamped by the driver
311 SGSoundSample::set_volume( double v ) {
314 #ifndef USE_SOFTWARE_DOPPLER
315 alSourcef( source, AL_GAIN, volume );
317 alSourcef( source, AL_GAIN, volume * doppler_volume_factor );
319 print_openal_error("set_volume");
325 SGSoundSample::is_playing( ) {
328 alGetSourcei( source, AL_SOURCE_STATE, &result );
329 if ( alGetError() != AL_NO_ERROR) {
330 SG_LOG( SG_GENERAL, SG_ALERT,
331 "Oops AL error in sample is_playing(): " << sample_name );
333 return (result == AL_PLAYING) ;
339 SGSoundSample::set_source_pos( ALfloat *pos ) {
340 source_pos[0] = pos[0];
341 source_pos[1] = pos[1];
342 source_pos[2] = pos[2];
346 sgAddVec3( final_pos, source_pos, offset_pos );
348 alSourcefv( source, AL_POSITION, final_pos );
349 print_openal_error("set_source_pos");
354 SGSoundSample::set_offset_pos( ALfloat *pos ) {
355 offset_pos[0] = pos[0];
356 offset_pos[1] = pos[1];
357 offset_pos[2] = pos[2];
361 sgAddVec3( final_pos, source_pos, offset_pos );
363 alSourcefv( source, AL_POSITION, final_pos );
364 print_openal_error("set_offset_pos");
369 SGSoundSample::set_orientation( ALfloat *dir, ALfloat inner_angle,
375 outergain = outer_gain;
376 direction[0] = dir[0];
377 direction[1] = dir[1];
378 direction[2] = dir[2];
380 alSourcefv( source, AL_DIRECTION, dir);
381 alSourcef( source, AL_CONE_INNER_ANGLE, inner );
382 alSourcef( source, AL_CONE_OUTER_ANGLE, outer );
383 alSourcef( source, AL_CONE_OUTER_GAIN, outergain );
388 SGSoundSample::set_source_vel( ALfloat *vel, ALfloat *listener_vel ) {
389 if (no_Doppler_effect) {
390 source_vel[0] = listener_vel[0];
391 source_vel[1] = listener_vel[1];
392 source_vel[2] = listener_vel[2];
394 source_vel[0] = vel[0];
395 source_vel[1] = vel[1];
396 source_vel[2] = vel[2];
398 #ifdef USE_OPEN_AL_DOPPLER
400 alSourcefv( source, AL_VELOCITY, source_vel );
402 #elif defined (USE_OPEN_AL_DOPPLER_WITH_FIXED_LISTENER)
405 sgSubVec3( relative_vel, source_vel, listener_vel );
406 alSourcefv( source, AL_VELOCITY, relative_vel );
409 if (no_Doppler_effect) {
410 doppler_pitch_factor = 1;
411 doppler_volume_factor = 1;
416 sgAddVec3( final_pos, source_pos, offset_pos );
417 mfp = sgLengthVec3(final_pos);
419 double vls = -sgScalarProductVec3( listener_vel, final_pos ) / mfp;
420 double vss = -sgScalarProductVec3( source_vel, final_pos ) / mfp;
421 if (fabs(340 - vss) > 1e-6)
423 doppler = (340 - vls) / (340 - vss);
424 doppler = ( doppler > 0) ? ( ( doppler < 10) ? doppler : 10 ) : 0;
431 /* the OpenAL documentation of the Doppler calculation
432 SS: AL_SPEED_OF_SOUND = speed of sound (default value 343.3)
433 DF: AL_DOPPLER_FACTOR = Doppler factor (default 1.0)
434 vls: Listener velocity scalar (scalar, projected on source-to-listener vector)
435 vss: Source velocity scalar (scalar, projected on source-to-listener vector)
436 SL = source to listener vector
437 SV = Source Velocity vector
438 LV = Listener Velocity vector
439 vls = DotProduct(SL, LV) / Mag(SL)
440 vss = DotProduct(SL, SV) / Mag(SL)
442 vss = min(vss, SS/DF)
443 vls = min(vls, SS/DF)
444 f' = f * (SS - DF*vls) / (SS - DF*vss)
448 doppler_pitch_factor = doppler;
449 doppler_volume_factor = 1;
452 doppler_pitch_factor = (doppler < 11) ? doppler : 11;
453 doppler_volume_factor = (doppler < 11) ? 11-doppler : 0;
457 doppler_pitch_factor = 0.1;
458 doppler_volume_factor = (doppler > 0) ? doppler * 10 : 0;
461 alSourcef( source, AL_GAIN, volume * doppler_volume_factor );
462 print_openal_error("set_source_vel: volume");
463 alSourcef( source, AL_PITCH, pitch * doppler_pitch_factor );
464 alGetError(); //ignore if the pitch is clamped
470 SGSoundSample::set_reference_dist( ALfloat dist ) {
471 reference_dist = dist;
473 alSourcef( source, AL_REFERENCE_DISTANCE, reference_dist );
479 SGSoundSample::set_max_dist( ALfloat dist ) {
482 alSourcef( source, AL_MAX_DISTANCE, max_dist );
487 SGSoundSample::load_file(const char *path, const char *file)
491 SGPath samplepath( path );
492 if ( strlen(file) ) {
493 samplepath.append( file );
496 #if defined(ALUT_API_MAJOR_VERSION) && ALUT_API_MAJOR_VERSION >= 1
498 data = alutLoadMemoryFromFile(samplepath.c_str(), &format, &size, &freqf );
500 throw sg_io_exception("Failed to load wav file.",
501 sg_location(samplepath.str()));
503 freq = (ALsizei)freqf;
505 # if defined (__APPLE__)
506 alutLoadWAVFile( (ALbyte *)samplepath.c_str(),
507 &format, &data, &size, &freq );
509 alutLoadWAVFile( (ALbyte *)samplepath.c_str(),
510 &format, &data, &size, &freq, &loop );
512 if ( print_openal_error("constructor (alutLoadWAVFile)") ) {
513 throw sg_io_exception("Failed to load wav file.",
514 sg_location(samplepath.str()));