]> git.mxchange.org Git - simgear.git/blob - simgear/sound/sample_openal.cxx
7d112b244cf23351cb5075d8e197a71883b6b183
[simgear.git] / simgear / sound / sample_openal.cxx
1 // sample.cxx -- Sound sample encapsulation class
2 // 
3 // Written by Curtis Olson, started April 2004.
4 //
5 // Copyright (C) 2004  Curtis L. Olson - http://www.flightgear.org/~curt
6 //
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.
11 //
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.
16 //
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.
20 //
21 // $Id$
22
23 #ifdef HAVE_CONFIG_H
24 #  include <simgear_config.h>
25 #endif
26
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>
32 #else
33 # include <AL/al.h>
34 # include <AL/alut.h>
35 #endif
36
37 #include <simgear/debug/logstream.hxx>
38 #include <simgear/misc/sg_path.hxx>
39 #include <simgear/structure/exception.hxx>
40
41 #include "sample_openal.hxx"
42
43
44 //
45 // SGSoundSample
46 //
47
48
49 static bool print_openal_error(const string &s = "unknown") {
50     ALuint error = alGetError();
51     if ( error == AL_NO_ERROR ) {
52        return false;
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 );
63     } else {
64         SG_LOG( SG_GENERAL, SG_ALERT, "Unhandled error code = " << error );
65     }
66     return error;
67 }
68
69 // empry constructor
70 SGSoundSample::SGSoundSample() :
71     buffer(0),
72     source(0),
73     pitch(1.0),
74     volume(1.0),
75     reference_dist(500.0),
76     max_dist(3000.),
77     loop(AL_FALSE),
78 #ifdef USE_SOFTWARE_DOPPLER
79     doppler_pitch_factor(1),
80     doppler_volume_factor(1),
81 #endif
82     playing(false),
83     no_Doppler_effect(true)
84 {
85 }
86
87 // constructor
88 SGSoundSample::SGSoundSample( const char *path, const char *file , bool _no_Doppler_effect ) :
89     buffer(0),
90     source(0),
91     pitch(1.0),
92     volume(1.0),
93     reference_dist(500.0),
94     max_dist(3000.),
95     loop(AL_FALSE),
96 #ifdef USE_SOFTWARE_DOPPLER
97     doppler_pitch_factor(1),
98     doppler_volume_factor(1),
99 #endif
100     playing(false),
101     no_Doppler_effect(_no_Doppler_effect)
102     {
103     SGPath samplepath( path );
104     if ( strlen(file) ) {
105         samplepath.append( file );
106     }
107     sample_name = samplepath.str();
108
109     SG_LOG( SG_GENERAL, SG_DEBUG, "From file sounds sample = "
110             << samplepath.str() );
111
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;
117
118     // clear errors from elsewhere?
119     alGetError();
120
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.");
125     }
126
127     // Load the sample file
128 #if defined(ALUT_API_MAJOR_VERSION) && ALUT_API_MAJOR_VERSION >= 1
129
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))));
136   }
137
138 #else
139         //
140         // pre 1.0 alut version
141         //
142     ALvoid* data = load_file(path, file);
143
144     // Copy data to the internal OpenAL buffer
145     alBufferData( buffer, format, data, size, freq );
146
147     if ( print_openal_error("constructor (alBufferData)") ) {
148         throw sg_exception("Failed to buffer data.");
149     }
150
151     alutUnloadWAV( format, data, size, freq );
152 #endif
153
154     print_openal_error("constructor return");
155 }
156
157 // constructor
158 SGSoundSample::SGSoundSample( unsigned char *_data, int len, int _freq , bool _no_Doppler_effect ) :
159     buffer(0),
160     source(0),
161     pitch(1.0),
162     volume(1.0),
163     reference_dist(500.0),
164     max_dist(3000.),
165     loop(AL_FALSE),
166 #ifdef USE_SOFTWARE_DOPPLER
167     doppler_pitch_factor(1),
168     doppler_volume_factor(1),
169 #endif
170     playing(false),
171     no_Doppler_effect(_no_Doppler_effect)
172 {
173     SG_LOG( SG_GENERAL, SG_DEBUG, "In memory sounds sample" );
174
175     sample_name = "unknown, generated from data";
176
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;
182
183     // clear errors from elsewhere?
184     alGetError();
185
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." );
190     }
191
192     format = AL_FORMAT_MONO8;
193     size = len;
194     freq = _freq;
195
196     alBufferData( buffer, format, _data, size, freq );
197     if ( print_openal_error("constructor (alBufferData)") ) {
198         throw sg_exception("Failed to buffer data.");
199     }
200
201     print_openal_error("constructor return");
202 }
203
204
205 // destructor
206 SGSoundSample::~SGSoundSample() {
207     SG_LOG( SG_GENERAL, SG_INFO, "Deleting a sample" );
208     if (buffer)
209         alDeleteBuffers(1, &buffer);
210 }
211
212
213 // play the sample
214 void SGSoundSample::play( bool _loop ) {
215
216     if ( source ) {
217         alSourceStop( source );
218     }
219
220     playing = bind_source();
221     if ( playing ) {
222         loop = _loop;
223     
224         alSourcei( source, AL_LOOPING, loop );
225         alSourcePlay( source );
226
227         print_openal_error("play (alSourcePlay)");
228     }
229 }
230
231
232 // stop playing the sample
233 void SGSoundSample::stop() {
234     if (playing) {
235         alSourceStop( source );
236         alDeleteSources(1, &source);
237         source = 0;
238         print_openal_error("stop (alDeleteSources)");
239     }
240     playing = false;
241 }
242
243 // Generate sound source
244 bool
245 SGSoundSample::bind_source() {
246
247     if ( playing ) {
248         return true;
249     }
250     if ( buffer == 0 ) {
251         return false;
252     }
253
254     // Bind buffer with a source.
255     alGetError();
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.");
261         return false;
262     }
263
264     alSourcei( source, AL_BUFFER, buffer );
265 #ifndef USE_SOFTWARE_DOPPLER
266     alSourcef( source, AL_PITCH, pitch );
267     alSourcef( source, AL_GAIN, volume );
268 #else
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 );
273 #endif
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 );
281 #endif
282     alSourcei( source, AL_LOOPING, loop );
283
284     alSourcei( source, AL_SOURCE_RELATIVE, AL_TRUE );
285     alSourcef( source, AL_REFERENCE_DISTANCE, reference_dist );
286     alSourcef( source, AL_MAX_DISTANCE, max_dist );
287
288     print_openal_error("bind_sources return");
289
290     return true;
291 }
292
293 void
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; }
298     pitch = p;
299     if (playing) {
300 #ifndef USE_SOFTWARE_DOPPLER
301         alSourcef( source, AL_PITCH, pitch );
302         print_openal_error("set_pitch");
303 #else
304         alSourcef( source, AL_PITCH, pitch * doppler_pitch_factor );
305         alGetError(); //ignore if the pitch is clamped by the driver
306 #endif
307     }
308 }
309
310 void
311 SGSoundSample::set_volume( double v ) {
312     volume = v;
313     if (playing) {
314 #ifndef USE_SOFTWARE_DOPPLER
315         alSourcef( source, AL_GAIN, volume );
316 #else
317         alSourcef( source, AL_GAIN, volume * doppler_volume_factor );
318 #endif
319         print_openal_error("set_volume");
320     }
321 }
322
323
324 bool
325 SGSoundSample::is_playing( ) {
326     if (playing) {
327         ALint result;
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 );
332         }
333         return (result == AL_PLAYING) ;
334     } else
335         return false;
336 }
337
338 void
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];
343
344     if (playing) {
345         sgVec3 final_pos;
346         sgAddVec3( final_pos, source_pos, offset_pos );
347
348         alSourcefv( source, AL_POSITION, final_pos );
349         print_openal_error("set_source_pos");
350     }
351 }
352
353 void
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];
358
359     if (playing) {
360         sgVec3 final_pos;
361         sgAddVec3( final_pos, source_pos, offset_pos );
362
363         alSourcefv( source, AL_POSITION, final_pos );
364         print_openal_error("set_offset_pos");
365     }
366 }
367
368 void
369 SGSoundSample::set_orientation( ALfloat *dir, ALfloat inner_angle,
370                                            ALfloat outer_angle,
371                                            ALfloat outer_gain)
372 {
373     inner = inner_angle;
374     outer = outer_angle;
375     outergain = outer_gain;
376     direction[0] = dir[0];
377     direction[1] = dir[1];
378     direction[2] = dir[2];
379     if (playing) {
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 );
384     }
385 }
386
387 void
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];
393     } else {
394         source_vel[0] = vel[0];
395         source_vel[1] = vel[1];
396         source_vel[2] = vel[2];
397     }
398 #ifdef USE_OPEN_AL_DOPPLER
399     if (playing) {
400         alSourcefv( source, AL_VELOCITY, source_vel );
401     }
402 #elif defined (USE_OPEN_AL_DOPPLER_WITH_FIXED_LISTENER)
403     if (playing) {
404         sgVec3 relative_vel;
405         sgSubVec3( relative_vel, source_vel, listener_vel );
406         alSourcefv( source, AL_VELOCITY, relative_vel );
407     }
408 #else
409     if (no_Doppler_effect) {
410         doppler_pitch_factor = 1;
411         doppler_volume_factor = 1;
412         return;
413     }
414     double doppler, mfp;
415     sgVec3 final_pos;
416     sgAddVec3( final_pos, source_pos, offset_pos );
417     mfp = sgLengthVec3(final_pos);
418     if (mfp > 1e-6) {
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)
422         {
423             doppler = (340 - vls) / (340 - vss);
424             doppler = ( doppler > 0) ? ( ( doppler < 10) ? doppler : 10 ) : 0;
425         }
426         else
427             doppler = 0;
428     }
429     else
430         doppler = 1;
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)
441     Dopper Calculation:
442     vss = min(vss, SS/DF)
443     vls = min(vls, SS/DF)
444     f' = f * (SS - DF*vls) / (SS - DF*vss)
445     */
446     if (doppler > 0.1) {
447         if (doppler < 10) {
448             doppler_pitch_factor = doppler;
449             doppler_volume_factor = 1;
450         }
451         else {
452             doppler_pitch_factor = (doppler < 11) ? doppler : 11;
453             doppler_volume_factor = (doppler < 11) ? 11-doppler : 0;
454         }
455     }
456     else {
457         doppler_pitch_factor = 0.1;
458         doppler_volume_factor = (doppler > 0) ? doppler * 10 : 0;
459     }
460     if (playing) {
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
465     }
466 #endif
467 }
468
469 void
470 SGSoundSample::set_reference_dist( ALfloat dist ) {
471     reference_dist = dist;
472     if (playing) {
473         alSourcef( source, AL_REFERENCE_DISTANCE, reference_dist );
474     }
475 }
476
477
478 void
479 SGSoundSample::set_max_dist( ALfloat dist ) {
480     max_dist = dist;
481     if (playing) {
482         alSourcef( source, AL_MAX_DISTANCE, max_dist );
483     }
484 }
485
486 ALvoid *
487 SGSoundSample::load_file(const char *path, const char *file)
488 {
489     ALvoid* data = 0;
490
491     SGPath samplepath( path );
492     if ( strlen(file) ) {
493         samplepath.append( file );
494     }
495
496 #if defined(ALUT_API_MAJOR_VERSION) && ALUT_API_MAJOR_VERSION >= 1
497     ALfloat freqf;
498     data = alutLoadMemoryFromFile(samplepath.c_str(), &format, &size, &freqf );
499     if (data == NULL) {
500         throw sg_io_exception("Failed to load wav file.",
501                                         sg_location(samplepath.str()));
502     }
503     freq = (ALsizei)freqf;
504 #else
505 # if defined (__APPLE__)
506     alutLoadWAVFile( (ALbyte *)samplepath.c_str(),
507                      &format, &data, &size, &freq );
508 # else
509     alutLoadWAVFile( (ALbyte *)samplepath.c_str(),
510                      &format, &data, &size, &freq, &loop );
511 # endif
512     if ( print_openal_error("constructor (alutLoadWAVFile)") ) {
513         throw sg_io_exception("Failed to load wav file.",
514                                         sg_location(samplepath.str()));
515     }
516 #endif
517
518     return data;
519 }
520