]> git.mxchange.org Git - simgear.git/blob - simgear/sound/sample_openal.cxx
Let the application free the buffer data.
[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     buffer(0),
146     source(0),
147     pitch(1.0),
148     volume(1.0),
149     reference_dist(500.0),
150     max_dist(3000.),
151     loop(AL_FALSE),
152     playing(false)
153 {
154     SG_LOG( SG_GENERAL, SG_DEBUG, "In memory sounds sample" );
155
156     sample_name = "unknown, generated from data";
157
158     source_pos[0] = 0.0; source_pos[1] = 0.0; source_pos[2] = 0.0;
159     offset_pos[0] = 0.0; offset_pos[1] = 0.0; offset_pos[2] = 0.0;
160     source_vel[0] = 0.0; source_vel[1] = 0.0; source_vel[2] = 0.0;
161     direction[0] = 0.0; direction[1] = 0.0; direction[2] = 0.0;
162     inner = outer = 360.0; outergain = 0.0;
163
164     // clear errors from elsewhere?
165     alGetError();
166
167     // Load wav data into a buffer.
168     alGenBuffers(1, &buffer);
169     if ( print_openal_error("constructor (alGenBuffers)") ) {
170         throw sg_exception("Failed to gen buffer." );
171     }
172
173     format = AL_FORMAT_MONO8;
174     size = len;
175     freq = _freq;
176
177     alBufferData( buffer, format, _data, size, freq );
178     if ( print_openal_error("constructor (alBufferData)") ) {
179         throw sg_exception("Failed to buffer data.");
180     }
181
182     print_openal_error("constructor return");
183 }
184
185
186 // destructor
187 SGSoundSample::~SGSoundSample() {
188     SG_LOG( SG_GENERAL, SG_INFO, "Deleting a sample" );
189     if (buffer)
190         alDeleteBuffers(1, &buffer);
191 }
192
193
194 // play the sample
195 void SGSoundSample::play( bool _loop ) {
196
197     if ( source ) {
198         alSourceStop( source );
199     }
200
201     playing = bind_source();
202     if ( playing ) {
203         loop = _loop;
204     
205         alSourcei( source, AL_LOOPING, loop );
206         alSourcePlay( source );
207
208         print_openal_error("play (alSourcePlay)");
209     }
210 }
211
212
213 // stop playing the sample
214 void SGSoundSample::stop() {
215     if (playing) {
216         alSourceStop( source );
217         alDeleteSources(1, &source);
218         source = 0;
219         print_openal_error("stop (alDeleteSources)");
220     }
221     playing = false;
222 }
223
224 // Generate sound source
225 bool
226 SGSoundSample::bind_source() {
227
228     if ( playing ) {
229         return true;
230     }
231     if ( buffer == 0 ) {
232         return false;
233     }
234
235     // Bind buffer with a source.
236     alGetError();
237     alGenSources(1, &source);
238     if ( print_openal_error("bind_source (alGenSources)") ) {
239         // No biggy, better luck next time.
240         SG_LOG( SG_GENERAL, SG_ALERT, "Failed to generate audio source.");
241         // SG_LOG( SG_GENERAL, SG_ALERT, "Please update your sound driver and try again.");
242         return false;
243     }
244
245     alSourcei( source, AL_BUFFER, buffer );
246     alSourcef( source, AL_PITCH, pitch );
247     alSourcef( source, AL_GAIN, volume );
248     alSourcefv( source, AL_POSITION, source_pos );
249     alSourcefv( source, AL_DIRECTION, direction );
250     alSourcef( source, AL_CONE_INNER_ANGLE, inner );
251     alSourcef( source, AL_CONE_OUTER_ANGLE, outer );
252     alSourcef( source, AL_CONE_OUTER_GAIN, outergain);
253     alSourcefv( source, AL_VELOCITY, source_vel );
254     alSourcei( source, AL_LOOPING, loop );
255
256     alSourcei( source, AL_SOURCE_RELATIVE, AL_TRUE );
257     alSourcef( source, AL_REFERENCE_DISTANCE, reference_dist );
258     alSourcef( source, AL_MAX_DISTANCE, max_dist );
259
260     print_openal_error("bind_sources return");
261
262     return true;
263 }
264
265 void
266 SGSoundSample::set_pitch( double p ) {
267     // clamp in the range of 0.01 to 2.0
268     if ( p < 0.01 ) { p = 0.01; }
269     if ( p > 2.0 ) { p = 2.0; }
270     pitch = p;
271     if (playing) {
272         alSourcef( source, AL_PITCH, pitch );
273         print_openal_error("set_pitch");
274     }
275 }
276
277 void
278 SGSoundSample::set_volume( double v ) {
279     volume = v;
280     if (playing) {
281         alSourcef( source, AL_GAIN, volume );
282         print_openal_error("set_volume");
283     }
284 }
285
286
287 bool
288 SGSoundSample::is_playing( ) {
289     if (playing) {
290         ALint result;
291         alGetSourcei( source, AL_SOURCE_STATE, &result );
292         if ( alGetError() != AL_NO_ERROR) {
293             SG_LOG( SG_GENERAL, SG_ALERT,
294                 "Oops AL error in sample is_playing(): " << sample_name );
295         }
296         return (result == AL_PLAYING) ;
297     } else
298         return false;
299 }
300
301 void
302 SGSoundSample::set_source_pos( ALfloat *pos ) {
303     source_pos[0] = pos[0];
304     source_pos[1] = pos[1];
305     source_pos[2] = pos[2];
306
307     if (playing) {
308         sgVec3 final_pos;
309         sgAddVec3( final_pos, source_pos, offset_pos );
310
311         alSourcefv( source, AL_POSITION, final_pos );
312     }
313 }
314
315 void
316 SGSoundSample::set_offset_pos( ALfloat *pos ) {
317     offset_pos[0] = pos[0];
318     offset_pos[1] = pos[1];
319     offset_pos[2] = pos[2];
320
321     if (playing) {
322         sgVec3 final_pos;
323         sgAddVec3( final_pos, source_pos, offset_pos );
324
325         alSourcefv( source, AL_POSITION, final_pos );
326     }
327 }
328
329 void
330 SGSoundSample::set_orientation( ALfloat *dir, ALfloat inner_angle,
331                                            ALfloat outer_angle,
332                                            ALfloat outer_gain)
333 {
334     inner = inner_angle;
335     outer = outer_angle;
336     outergain = outer_gain;
337     if (playing) {
338         alSourcefv( source, AL_DIRECTION, dir);
339         alSourcef( source, AL_CONE_INNER_ANGLE, inner );
340         alSourcef( source, AL_CONE_OUTER_ANGLE, outer );
341         alSourcef( source, AL_CONE_OUTER_GAIN, outergain );
342     }
343 }
344
345 void
346 SGSoundSample::set_source_vel( ALfloat *vel ) {
347     source_vel[0] = vel[0];
348     source_vel[1] = vel[1];
349     source_vel[2] = vel[2];
350     if (playing) {
351         alSourcefv( source, AL_VELOCITY, source_vel );
352     }
353 }
354
355 void
356 SGSoundSample::set_reference_dist( ALfloat dist ) {
357     reference_dist = dist;
358     if (playing) {
359         alSourcef( source, AL_REFERENCE_DISTANCE, reference_dist );
360     }
361 }
362
363
364 void
365 SGSoundSample::set_max_dist( ALfloat dist ) {
366     max_dist = dist;
367     if (playing) {
368         alSourcef( source, AL_MAX_DISTANCE, max_dist );
369     }
370 }
371
372 ALvoid *
373 SGSoundSample::load_file(const char *path, const char *file)
374 {
375     ALvoid* data = 0;
376
377     SGPath samplepath( path );
378     if ( strlen(file) ) {
379         samplepath.append( file );
380     }
381
382 #if defined(ALUT_API_MAJOR_VERSION) && ALUT_API_MAJOR_VERSION >= 1
383     ALfloat freqf;
384     data = alutLoadMemoryFromFile(samplepath.c_str(), &format, &size, &freqf );
385     if (data == NULL) {
386         throw sg_exception("Failed to load wav file.");
387     }
388     freq = (ALsizei)freqf;
389 #else
390 # if defined (__APPLE__)
391     alutLoadWAVFile( (ALbyte *)samplepath.c_str(),
392                      &format, &data, &size, &freq );
393 # else
394     alutLoadWAVFile( (ALbyte *)samplepath.c_str(),
395                      &format, &data, &size, &freq, &loop );
396 # endif
397     if ( print_openal_error("constructor (alutLoadWAVFile)") ) {
398         throw sg_exception("Failed to load wav file.");
399     }
400 #endif
401
402     return data;
403 }
404