]> git.mxchange.org Git - simgear.git/blob - simgear/sound/sample_openal.cxx
124ad93904d64497db156ce88877b42064d0177e
[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., 675 Mass Ave, Cambridge, MA 02139, USA.
20 //
21 // $Id$
22
23
24 #if defined( __APPLE__ )
25 # define AL_ILLEGAL_ENUM AL_INVALID_ENUM
26 # define AL_ILLEGAL_COMMAND AL_INVALID_OPERATION
27 # include <OpenAL/al.h>
28 # include <OpenAL/alut.h>
29 #else
30 # include <AL/al.h>
31 # include <AL/alut.h>
32 #endif
33
34 #include <simgear/debug/logstream.hxx>
35 #include <simgear/misc/sg_path.hxx>
36 #include <simgear/structure/exception.hxx>
37
38 #include "sample_openal.hxx"
39
40
41 //
42 // SGSoundSample
43 //
44
45
46 static bool print_openal_error(const string &s = "unknown") {
47     ALuint error = alGetError();
48     if ( error == AL_NO_ERROR ) {
49        return false;
50     } else if ( error == AL_INVALID_NAME ) {
51         SG_LOG( SG_GENERAL, SG_ALERT, "OpenAL error (AL_INVALID_NAME): " << s );
52     } else if ( error == AL_ILLEGAL_ENUM ) {
53         SG_LOG( SG_GENERAL, SG_ALERT, "OpenAL error (AL_ILLEGAL_ENUM): "  << s );
54     } else if ( error == AL_INVALID_VALUE ) {
55         SG_LOG( SG_GENERAL, SG_ALERT, "OpenAL error (AL_INVALID_VALUE): " << s );
56     } else if ( error == AL_ILLEGAL_COMMAND ) {
57         SG_LOG( SG_GENERAL, SG_ALERT, "OpenAL error (AL_ILLEGAL_COMMAND): " << s );
58     } else if ( error == AL_OUT_OF_MEMORY ) {
59         SG_LOG( SG_GENERAL, SG_ALERT, "OpenAL error (AL_OUT_OF_MEMORY): " << s );
60     } else {
61         SG_LOG( SG_GENERAL, SG_ALERT, "Unhandled error code = " << error );
62     }
63     return error;
64 }
65
66 // empry constructor
67 SGSoundSample::SGSoundSample() :
68     buffer(0),
69     source(0),
70     pitch(1.0),
71     volume(1.0),
72     reference_dist(500.0),
73     max_dist(3000.),
74     loop(AL_FALSE),
75     playing(false)
76 {
77 }
78
79 // constructor
80 SGSoundSample::SGSoundSample( const char *path, const char *file) :
81     buffer(0),
82     source(0),
83     pitch(1.0),
84     volume(1.0),
85     reference_dist(500.0),
86     max_dist(3000.),
87     loop(AL_FALSE),
88     playing(false)
89 {
90     SGPath samplepath( path );
91     if ( strlen(file) ) {
92         samplepath.append( file );
93     }
94     sample_name = samplepath.str();
95
96     SG_LOG( SG_GENERAL, SG_DEBUG, "From file sounds sample = "
97             << samplepath.str() );
98
99     source_pos[0] = 0.0; source_pos[1] = 0.0; source_pos[2] = 0.0;
100     offset_pos[0] = 0.0; offset_pos[1] = 0.0; offset_pos[2] = 0.0;
101     source_vel[0] = 0.0; source_vel[1] = 0.0; source_vel[2] = 0.0;
102     direction[0] = 0.0; direction[1] = 0.0; direction[2] = 0.0;
103     inner = outer = 360.0; outergain = 0.0;
104
105     // clear errors from elsewhere?
106     alGetError();
107
108     // create an OpenAL buffer handle
109     alGenBuffers(1, &buffer);
110     if ( print_openal_error("constructor (alGenBuffers)") ) {
111         throw sg_exception("Failed to gen OpenAL buffer.");
112     }
113
114     // Load the sample file
115 #if defined(ALUT_API_MAJOR_VERSION) && ALUT_API_MAJOR_VERSION >= 1
116
117   buffer = alutCreateBufferFromFile(samplepath.c_str());
118   if (buffer == AL_NONE) {
119      ALenum error = alutGetError ();
120      print_openal_error("constructor (alutCreateBufferFromFile)");
121      throw sg_exception("Failed to load wav file: "+string(alutGetErrorString (error)));
122   }
123
124 #else
125         //
126         // pre 1.0 alut version
127         //
128     ALvoid* data = load_file(path, file)
129
130     // Copy data to the internal OpenAL buffer
131     alBufferData( buffer, format, data, size, freq );
132
133     if ( print_openal_error("constructor (alBufferData)") ) {
134         throw sg_exception("Failed to buffer data.");
135     }
136
137     alutUnloadWAV( format, data, size, freq );
138 #endif
139
140     print_openal_error("constructor return");
141 }
142
143 // constructor
144 SGSoundSample::SGSoundSample( unsigned char *_data, int len, int _freq,
145                               bool cleanup) :
146     buffer(0),
147     source(0),
148     pitch(1.0),
149     volume(1.0),
150     reference_dist(500.0),
151     max_dist(3000.),
152     loop(AL_FALSE),
153     playing(false)
154 {
155     SG_LOG( SG_GENERAL, SG_DEBUG, "In memory sounds sample" );
156
157     sample_name = "unknown, generated from data";
158
159     source_pos[0] = 0.0; source_pos[1] = 0.0; source_pos[2] = 0.0;
160     offset_pos[0] = 0.0; offset_pos[1] = 0.0; offset_pos[2] = 0.0;
161     source_vel[0] = 0.0; source_vel[1] = 0.0; source_vel[2] = 0.0;
162     direction[0] = 0.0; direction[1] = 0.0; direction[2] = 0.0;
163     inner = outer = 360.0; outergain = 0.0;
164
165     // clear errors from elsewhere?
166     alGetError();
167
168     // Load wav data into a buffer.
169     alGenBuffers(1, &buffer);
170     if ( print_openal_error("constructor (alGenBuffers)") ) {
171         throw sg_exception("Failed to gen buffer." );
172     }
173
174     format = AL_FORMAT_MONO8;
175     size = len;
176     freq = _freq;
177
178     alBufferData( buffer, format, _data, size, freq );
179     if ( print_openal_error("constructor (alBufferData)") ) {
180         throw sg_exception("Failed to buffer data.");
181     }
182
183     if ( cleanup ) {
184         free(_data);
185     }
186
187     print_openal_error("constructor return");
188 }
189
190
191 // destructor
192 SGSoundSample::~SGSoundSample() {
193     SG_LOG( SG_GENERAL, SG_INFO, "Deleting a sample" );
194     if (buffer)
195         alDeleteBuffers(1, &buffer);
196 }
197
198
199 // play the sample
200 void SGSoundSample::play( bool _loop ) {
201
202     if ( source ) {
203         alSourceStop( source );
204     }
205
206     playing = bind_source();
207     if ( playing ) {
208         loop = _loop;
209     
210         alSourcei( source, AL_LOOPING, loop );
211         alSourcePlay( source );
212
213         print_openal_error("play (alSourcePlay)");
214     }
215 }
216
217
218 // stop playing the sample
219 void SGSoundSample::stop() {
220     if (playing) {
221         alSourceStop( source );
222         alDeleteSources(1, &source);
223         source = 0;
224         print_openal_error("stop (alDeleteSources)");
225     }
226     playing = false;
227 }
228
229 // Generate sound source
230 bool
231 SGSoundSample::bind_source() {
232
233     if ( playing ) {
234         return true;
235     }
236     if ( buffer == 0 ) {
237         return false;
238     }
239
240     // Bind buffer with a source.
241     alGetError();
242     alGenSources(1, &source);
243     if ( print_openal_error("bind_source (alGenSources)") ) {
244         // No biggy, better luck next time.
245         SG_LOG( SG_GENERAL, SG_ALERT, "Failed to generate audio source.");
246         // SG_LOG( SG_GENERAL, SG_ALERT, "Please update your sound driver and try again.");
247         return false;
248     }
249
250     alSourcei( source, AL_BUFFER, buffer );
251     alSourcef( source, AL_PITCH, pitch );
252     alSourcef( source, AL_GAIN, volume );
253     alSourcefv( source, AL_POSITION, source_pos );
254     alSourcefv( source, AL_DIRECTION, direction );
255     alSourcef( source, AL_CONE_INNER_ANGLE, inner );
256     alSourcef( source, AL_CONE_OUTER_ANGLE, outer );
257     alSourcef( source, AL_CONE_OUTER_GAIN, outergain);
258     alSourcefv( source, AL_VELOCITY, source_vel );
259     alSourcei( source, AL_LOOPING, loop );
260
261     alSourcei( source, AL_SOURCE_RELATIVE, AL_TRUE );
262     alSourcef( source, AL_REFERENCE_DISTANCE, reference_dist );
263     alSourcef( source, AL_MAX_DISTANCE, max_dist );
264
265     print_openal_error("bind_sources return");
266
267     return true;
268 }
269
270 void
271 SGSoundSample::set_pitch( double p ) {
272     // clamp in the range of 0.01 to 2.0
273     if ( p < 0.01 ) { p = 0.01; }
274     if ( p > 2.0 ) { p = 2.0; }
275     pitch = p;
276     if (playing) {
277         alSourcef( source, AL_PITCH, pitch );
278         print_openal_error("set_pitch");
279     }
280 }
281
282 void
283 SGSoundSample::set_volume( double v ) {
284     volume = v;
285     if (playing) {
286         alSourcef( source, AL_GAIN, volume );
287         print_openal_error("set_volume");
288     }
289 }
290
291
292 bool
293 SGSoundSample::is_playing( ) {
294     if (playing) {
295         ALint result;
296         alGetSourcei( source, AL_SOURCE_STATE, &result );
297         if ( alGetError() != AL_NO_ERROR) {
298             SG_LOG( SG_GENERAL, SG_ALERT,
299                 "Oops AL error in sample is_playing(): " << sample_name );
300         }
301         return (result == AL_PLAYING) ;
302     } else
303         return false;
304 }
305
306 void
307 SGSoundSample::set_source_pos( ALfloat *pos ) {
308     source_pos[0] = pos[0];
309     source_pos[1] = pos[1];
310     source_pos[2] = pos[2];
311
312     if (playing) {
313         sgVec3 final_pos;
314         sgAddVec3( final_pos, source_pos, offset_pos );
315
316         alSourcefv( source, AL_POSITION, final_pos );
317     }
318 }
319
320 void
321 SGSoundSample::set_offset_pos( ALfloat *pos ) {
322     offset_pos[0] = pos[0];
323     offset_pos[1] = pos[1];
324     offset_pos[2] = pos[2];
325
326     if (playing) {
327         sgVec3 final_pos;
328         sgAddVec3( final_pos, source_pos, offset_pos );
329
330         alSourcefv( source, AL_POSITION, final_pos );
331     }
332 }
333
334 void
335 SGSoundSample::set_orientation( ALfloat *dir, ALfloat inner_angle,
336                                            ALfloat outer_angle,
337                                            ALfloat outer_gain)
338 {
339     inner = inner_angle;
340     outer = outer_angle;
341     outergain = outer_gain;
342     if (playing) {
343         alSourcefv( source, AL_DIRECTION, dir);
344         alSourcef( source, AL_CONE_INNER_ANGLE, inner );
345         alSourcef( source, AL_CONE_OUTER_ANGLE, outer );
346         alSourcef( source, AL_CONE_OUTER_GAIN, outergain );
347     }
348 }
349
350 void
351 SGSoundSample::set_source_vel( ALfloat *vel ) {
352     source_vel[0] = vel[0];
353     source_vel[1] = vel[1];
354     source_vel[2] = vel[2];
355     if (playing) {
356         alSourcefv( source, AL_VELOCITY, source_vel );
357     }
358 }
359
360 void
361 SGSoundSample::set_reference_dist( ALfloat dist ) {
362     reference_dist = dist;
363     if (playing) {
364         alSourcef( source, AL_REFERENCE_DISTANCE, reference_dist );
365     }
366 }
367
368
369 void
370 SGSoundSample::set_max_dist( ALfloat dist ) {
371     max_dist = dist;
372     if (playing) {
373         alSourcef( source, AL_MAX_DISTANCE, max_dist );
374     }
375 }
376
377 ALvoid *
378 SGSoundSample::load_file(const char *path, const char *file)
379 {
380     ALvoid* data = 0;
381
382     SGPath samplepath( path );
383     if ( strlen(file) ) {
384         samplepath.append( file );
385     }
386
387 #if defined(ALUT_API_MAJOR_VERSION) && ALUT_API_MAJOR_VERSION >= 1
388     ALfloat freqf;
389     data = alutLoadMemoryFromFile(samplepath.c_str(), &format, &size, &freqf );
390     if (data == NULL) {
391         throw sg_exception("Failed to load wav file.");
392     }
393     freq = (ALsizei)freqf;
394 #else
395 # if defined (__APPLE__)
396     alutLoadWAVFile( (ALbyte *)samplepath.c_str(),
397                      &format, &data, &size, &freq );
398 # else
399     alutLoadWAVFile( (ALbyte *)samplepath.c_str(),
400                      &format, &data, &size, &freq, &loop );
401 # endif
402     if ( print_openal_error("constructor (alutLoadWAVFile)") ) {
403         throw sg_exception("Failed to load wav file.");
404     }
405 #endif
406
407     return data;
408 }
409