]> git.jsancho.org Git - lugaru.git/blob - Source/openal_wrapper.cpp
Drop Open_Stream
[lugaru.git] / Source / openal_wrapper.cpp
1 /*
2 Copyright (C) 2003, 2010 - Wolfire Games
3
4 This file is part of Lugaru.
5
6 Lugaru is free software; you can redistribute it and/or
7 modify it under the terms of the GNU General Public License
8 as published by the Free Software Foundation; either version 2
9 of the License, or (at your option) any later version.
10
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  
14
15 See the GNU 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., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
20 */
21
22 #if USE_OPENAL
23
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <string.h>
27
28 #include "openal_wrapper.h"
29
30 // NOTE:
31 // FMOD uses a Left Handed Coordinate system, OpenAL uses a Right Handed
32 //  one...so we just need to flip the sign on the Z axis when appropriate.
33
34 #define DYNAMIC_LOAD_OPENAL 0
35
36 #if DYNAMIC_LOAD_OPENAL
37
38 #include <dlfcn.h>
39
40 #define AL_FUNC(t,ret,fn,params,call,rt) \
41     extern "C" { \
42         static ret ALAPIENTRY (*p##fn) params = NULL; \
43         ret ALAPIENTRY fn params { rt p##fn call; } \
44     }
45 #include "alstubs.h"
46 #undef AL_FUNC
47
48 static void *aldlhandle = NULL;
49
50 static bool lookup_alsym(const char *funcname, void **func, const char *libname)
51 {
52     if (!aldlhandle)
53         return false;
54
55     *func = dlsym(aldlhandle, funcname);
56     if (*func == NULL)
57     {
58         fprintf(stderr, "Failed to find OpenAL symbol \"%s\" in \"%s\"\n",
59                  funcname, libname);
60         return false;
61     }
62     return true;
63 }
64
65 static void unload_alsyms(void)
66 {
67     #define AL_FUNC(t,ret,fn,params,call,rt) p##fn = NULL;
68     #include "alstubs.h"
69     #undef AL_FUNC
70     if (aldlhandle)
71     {
72         dlclose(aldlhandle);
73         aldlhandle = NULL;
74     }
75 }
76
77 static bool lookup_all_alsyms(const char *libname)
78 {
79     if (!aldlhandle)
80     {
81         if ( (aldlhandle = dlopen(libname, RTLD_GLOBAL | RTLD_NOW)) == NULL )
82             return false;
83     }
84
85     bool retval = true;
86     #define AL_FUNC(t,ret,fn,params,call,rt) \
87         if (!lookup_alsym(#fn, (void **) &p##fn, libname)) retval = false;
88     #include "alstubs.h"
89     #undef AL_FUNC
90
91     if (!retval)
92         unload_alsyms();
93
94     return retval;
95 }
96 #else
97 #define lookup_all_alsyms(x) (true)
98 #define unload_alsyms()
99 #endif
100
101 typedef struct
102 {
103     ALuint sid;
104     OPENAL_SAMPLE *sample;
105     bool startpaused;
106     float position[3];
107 } OPENAL_Channels;
108
109 typedef struct OPENAL_SAMPLE
110 {
111     char *name;
112     ALuint bid;  // buffer id.
113     int mode;
114     int is2d;
115 } OPENAL_SAMPLE;
116
117 static size_t num_channels = 0;
118 static OPENAL_Channels *channels = NULL;
119 static bool initialized = false;
120 static float listener_position[3];
121
122 static void set_channel_position(const int channel, const float x,
123                                  const float y, const float z)
124 {
125     OPENAL_Channels *chan = &channels[channel];
126
127     chan->position[0] = x;
128     chan->position[1] = y;
129     chan->position[2] = z;
130
131     OPENAL_SAMPLE *sptr = chan->sample;
132     if (sptr == NULL)
133         return;
134
135     const ALuint sid = chan->sid;
136     const bool no_attenuate = sptr->is2d;
137
138     if (no_attenuate)
139     {
140         alSourcei(sid, AL_SOURCE_RELATIVE, AL_TRUE);
141         alSource3f(sid, AL_POSITION, 0.0f, 0.0f, 0.0f);
142     }
143     else
144     {
145         alSourcei(sid, AL_SOURCE_RELATIVE, AL_FALSE);
146         alSource3f(sid, AL_POSITION, x, y, z);
147     }
148 }
149
150
151 AL_API void OPENAL_3D_Listener_SetAttributes(const float *pos, const float *vel, float fx, float fy, float fz, float tx, float ty, float tz)
152 {
153     if (!initialized) return;
154     if (pos != NULL)
155     {
156         alListener3f(AL_POSITION, pos[0], pos[1], -pos[2]);
157         listener_position[0] = pos[0];
158         listener_position[1] = pos[1];
159         listener_position[2] = -pos[2];
160     }
161
162     ALfloat vec[6] = { fx, fy, -fz, tz, ty, -tz };
163     alListenerfv(AL_ORIENTATION, vec);
164
165     // we ignore velocity, since doppler's broken in the Linux AL at the moment...
166
167     // adjust existing positions...
168     for (int i = 0; i < num_channels; i++)
169     {
170         const float *p = channels[i].position;
171         set_channel_position(i, p[0], p[1], p[2]);
172     }
173 }
174
175 AL_API signed char OPENAL_3D_SetAttributes(int channel, const float *pos, const float *vel)
176 {
177     if (!initialized) return false;
178     if ((channel < 0) || (channel >= num_channels)) return false;
179
180     if (pos != NULL)
181         set_channel_position(channel, pos[0], pos[1], -pos[2]);
182
183     // we ignore velocity, since doppler's broken in the Linux AL at the moment...
184
185     return true;
186 }
187
188 AL_API void OPENAL_3D_SetDopplerFactor(float scale)
189 {
190     if (!initialized) return;
191     // unimplemented...looks like init routines just call this with scale == 0.0f anyhow.
192 }
193
194 AL_API signed char OPENAL_Init(int mixrate, int maxsoftwarechannels, unsigned int flags)
195 {
196     if (initialized) return false;
197     if (maxsoftwarechannels == 0) return false;
198
199     if (flags != 0)  // unsupported.
200         return false;
201
202     if (!lookup_all_alsyms("./openal.so"))  // !!! FIXME: linux specific lib name
203     {
204         if (!lookup_all_alsyms("openal.so.1"))  // !!! FIXME: linux specific lib name
205         {
206             if (!lookup_all_alsyms("openal.so"))  // !!! FIXME: linux specific lib name
207                 return false;
208         }
209     }
210
211     ALCdevice *dev = alcOpenDevice(NULL);
212     if (!dev)
213         return false;
214
215     ALint caps[] = { ALC_FREQUENCY, mixrate, 0 };
216     ALCcontext *ctx = alcCreateContext(dev, caps);
217     if (!ctx)
218     {
219         alcCloseDevice(dev);
220         return false;
221     }
222
223     alcMakeContextCurrent(ctx);
224     alcProcessContext(ctx);
225
226     bool cmdline(const char *cmd);
227     if (cmdline("openalinfo"))
228     {
229         printf("AL_VENDOR: %s\n", (char *) alGetString(AL_VENDOR));
230         printf("AL_RENDERER: %s\n", (char *) alGetString(AL_RENDERER));
231         printf("AL_VERSION: %s\n", (char *) alGetString(AL_VERSION));
232         printf("AL_EXTENSIONS: %s\n", (char *) alGetString(AL_EXTENSIONS));
233     }
234
235     num_channels = maxsoftwarechannels;
236     channels = new OPENAL_Channels[maxsoftwarechannels];
237     memset(channels, '\0', sizeof (OPENAL_Channels) * num_channels);
238     for (int i = 0; i < num_channels; i++)
239         alGenSources(1, &channels[i].sid);  // !!! FIXME: verify this didn't fail!
240
241     initialized = true;
242     return true;
243 }
244
245 AL_API void OPENAL_Close()
246 {
247     if (!initialized) return;
248
249     ALCcontext *ctx = alcGetCurrentContext();
250     if (ctx)
251     {
252         for (int i = 0; i < num_channels; i++)
253         {
254             alSourceStop(channels[i].sid);
255             alSourcei(channels[i].sid, AL_BUFFER, 0);
256             alDeleteSources(1, &channels[i].sid);
257         }
258         ALCdevice *dev = alcGetContextsDevice(ctx);
259         alcMakeContextCurrent(NULL);
260         alcSuspendContext(ctx);
261         alcDestroyContext(ctx);
262         alcCloseDevice(dev);
263     }
264
265     num_channels = 0;
266     delete[] channels;
267     channels = NULL;
268
269     unload_alsyms();
270     initialized = false;
271 }
272
273 AL_API OPENAL_SAMPLE *OPENAL_GetCurrentSample(int channel)
274 {
275     if (!initialized) return NULL;
276     if ((channel < 0) || (channel >= num_channels)) return NULL;
277     return channels[channel].sample;
278 }
279
280 AL_API signed char OPENAL_GetPaused(int channel)
281 {
282     if (!initialized) return false;
283     if ((channel < 0) || (channel >= num_channels)) return false;
284     if (channels[channel].startpaused)
285         return(true);
286
287     ALint state = 0;
288     alGetSourceiv(channels[channel].sid, AL_SOURCE_STATE, &state);
289     return((state == AL_PAUSED) ? true : false);
290 }
291
292 AL_API unsigned int OPENAL_GetLoopMode(int channel)
293 {
294     if (!initialized) return 0;
295     if ((channel < 0) || (channel >= num_channels)) return 0;
296     ALint loop = 0;
297     alGetSourceiv(channels[channel].sid, AL_LOOPING, &loop);
298     if (loop)
299         return(OPENAL_LOOP_NORMAL);
300     return OPENAL_LOOP_OFF;
301 }
302
303 AL_API signed char OPENAL_IsPlaying(int channel)
304 {
305     if (!initialized) return false;
306     if ((channel < 0) || (channel >= num_channels)) return false;
307     ALint state = 0;
308     alGetSourceiv(channels[channel].sid, AL_SOURCE_STATE, &state);
309     return((state == AL_PLAYING) ? true : false);
310 }
311
312 AL_API int OPENAL_PlaySoundEx(int channel, OPENAL_SAMPLE *sptr, OPENAL_DSPUNIT *dsp, signed char startpaused)
313 {
314     if (!initialized) return -1;
315     if (sptr == NULL) return -1;
316     if (dsp != NULL) return -1;
317     if (channel == OPENAL_FREE)
318     {
319         for (int i = 0; i < num_channels; i++)
320         {
321             ALint state = 0;
322             alGetSourceiv(channels[i].sid, AL_SOURCE_STATE, &state);
323             if ((state != AL_PLAYING) && (state != AL_PAUSED))
324             {
325                 channel = i;
326                 break;
327             }
328         }
329     }
330
331     if ((channel < 0) || (channel >= num_channels)) return -1;
332     alSourceStop(channels[channel].sid);
333     channels[channel].sample = sptr;
334     alSourcei(channels[channel].sid, AL_BUFFER, sptr->bid);
335     alSourcei(channels[channel].sid, AL_LOOPING, (sptr->mode == OPENAL_LOOP_OFF) ? AL_FALSE : AL_TRUE);
336     set_channel_position(channel, 0.0f, 0.0f, 0.0f);
337
338     channels[channel].startpaused = ((startpaused) ? true : false);
339     if (!startpaused)
340         alSourcePlay(channels[channel].sid);
341     return channel;
342 }
343
344
345 static void *decode_to_pcm(const char *_fname, ALenum &format, ALsizei &size, ALuint &freq)
346 {
347 #ifdef __POWERPC__
348     const int bigendian = 1;
349 #else
350     const int bigendian = 0;
351 #endif
352
353     // !!! FIXME: if it's not Ogg, we don't have a decoder. I'm lazy.  :/
354     char *fname = (char *) alloca(strlen(_fname) + 16);
355     strcpy(fname, _fname);
356     char *ptr = strchr(fname, '.');
357     if (ptr) *ptr = '\0';
358     strcat(fname, ".ogg");
359
360     // just in case...
361     #undef fopen
362     FILE *io = fopen(fname, "rb");
363     if (io == NULL)
364         return NULL;
365
366     ALubyte *retval = NULL;
367
368     #if 0  // untested, so disable this!
369     // Can we just feed it to the AL compressed?
370     if (alIsExtensionPresent((const ALubyte *) "AL_EXT_vorbis"))
371     {
372         format = alGetEnumValue((const ALubyte *) "AL_FORMAT_VORBIS_EXT");
373         freq = 44100;
374         fseek(io, 0, SEEK_END);
375         size = ftell(io);
376         fseek(io, 0, SEEK_SET);
377         retval = (ALubyte *) malloc(size);
378         size_t rc = fread(retval, size, 1, io);
379         fclose(io);
380         if (rc != 1)
381         {
382             free(retval);
383             return NULL;
384         }
385         return retval;
386     }
387     #endif
388
389     // Uncompress and feed to the AL.
390     OggVorbis_File vf;
391     memset(&vf, '\0', sizeof (vf));
392     if (ov_open(io, &vf, NULL, 0) == 0)
393     {
394         int bitstream = 0;
395         vorbis_info *info = ov_info(&vf, -1);
396         size = 0;
397         format = (info->channels == 1) ? AL_FORMAT_MONO16 : AL_FORMAT_STEREO16;
398         freq = info->rate;
399
400         if ((info->channels != 1) && (info->channels != 2))
401         {
402             ov_clear(&vf);
403             return NULL;
404         }
405
406         char buf[1024 * 16];
407         long rc = 0;
408         size_t allocated = 64 * 1024;
409         retval = (ALubyte *) malloc(allocated);
410         while ( (rc = ov_read(&vf, buf, sizeof (buf), bigendian, 2, 1, &bitstream)) != 0 )
411         {
412             if (rc > 0)
413             {
414                 size += rc;
415                 if (size >= allocated)
416                 {
417                     allocated *= 2;
418                     ALubyte *tmp = (ALubyte *) realloc(retval, allocated);
419                     if (tmp == NULL)
420                     {
421                         free(retval);
422                         retval = NULL;
423                         break;
424                     }
425                     retval = tmp;
426                 }
427                 memcpy(retval + (size - rc), buf, rc);
428             }
429         }
430         ov_clear(&vf);
431         return retval;
432     }
433
434     fclose(io);
435     return NULL;
436 }
437
438
439 AL_API OPENAL_SAMPLE *OPENAL_Sample_Load(int index, const char *name_or_data, unsigned int mode, int offset, int length)
440 {
441     if (!initialized) return NULL;
442     if (index != OPENAL_FREE) return NULL;  // this is all the game does...
443     if (offset != 0) return NULL;  // this is all the game does...
444     if (length != 0) return NULL;  // this is all the game does...
445     if ((mode != OPENAL_HW3D) && (mode != OPENAL_2D)) return NULL;  // this is all the game does...
446
447     OPENAL_SAMPLE *retval = NULL;
448     ALuint bufferName = 0;
449     ALenum format = AL_NONE;
450     ALsizei size = 0;
451     ALuint frequency = 0;
452     void *data = decode_to_pcm(name_or_data, format, size, frequency);
453     if (data == NULL)
454         return NULL;
455
456     ALuint bid = 0;
457     alGetError();
458     alGenBuffers(1, &bid);
459     if (alGetError() == AL_NO_ERROR)
460     {
461         alBufferData(bid, format, data, size, frequency);
462         retval = new OPENAL_SAMPLE;
463         retval->bid = bid;
464         retval->mode = OPENAL_LOOP_OFF;
465         retval->is2d = (mode == OPENAL_2D);
466         retval->name = new char[strlen(name_or_data) + 1];
467         if (retval->name)
468             strcpy(retval->name, name_or_data);
469     }
470
471     free(data);
472     return(retval);
473 }
474
475 AL_API void OPENAL_Sample_Free(OPENAL_SAMPLE *sptr)
476 {
477     if (!initialized) return;
478     if (sptr)
479     {
480         for (int i = 0; i < num_channels; i++)
481         {
482             if (channels[i].sample == sptr)
483             {
484                 alSourceStop(channels[i].sid);
485                 alSourcei(channels[i].sid, AL_BUFFER, 0);
486                 channels[i].sample = NULL;
487             }
488         }
489         alDeleteBuffers(1, &sptr->bid);
490         delete[] sptr->name;
491         delete sptr;
492     }
493 }
494
495 AL_API signed char OPENAL_Sample_SetMode(OPENAL_SAMPLE *sptr, unsigned int mode)
496 {
497     if (!initialized) return false;
498     if ((mode != OPENAL_LOOP_NORMAL) && (mode != OPENAL_LOOP_OFF)) return false;
499     if (!sptr) return false;
500     sptr->mode = mode;
501     return true;
502 }
503
504 AL_API signed char OPENAL_SetFrequency(int channel, int freq)
505 {
506     if (!initialized) return false;
507     if (channel == OPENAL_ALL)
508     {
509         for (int i = 0; i < num_channels; i++)
510             OPENAL_SetFrequency(i, freq);
511         return true;
512     }
513
514     if ((channel < 0) || (channel >= num_channels)) return false;
515     if (freq == 8012)  // hack
516         alSourcef(channels[channel].sid, AL_PITCH, 8012.0f / 44100.0f);
517     else
518         alSourcef(channels[channel].sid, AL_PITCH, 1.0f);
519     return true;
520 }
521
522 AL_API signed char OPENAL_SetVolume(int channel, int vol)
523 {
524     if (!initialized) return false;
525
526     if (channel == OPENAL_ALL)
527     {
528         for (int i = 0; i < num_channels; i++)
529             OPENAL_SetVolume(i, vol);
530         return true;
531     }
532
533     if ((channel < 0) || (channel >= num_channels)) return false;
534
535     if (vol < 0) vol = 0;
536     else if (vol > 255) vol = 255;
537     ALfloat gain = ((ALfloat) vol) / 255.0f;
538     alSourcef(channels[channel].sid, AL_GAIN, gain);
539     return true;
540 }
541
542 AL_API signed char OPENAL_SetPaused(int channel, signed char paused)
543 {
544     if (!initialized) return false;
545
546     if (channel == OPENAL_ALL)
547     {
548         for (int i = 0; i < num_channels; i++)
549             OPENAL_SetPaused(i, paused);
550         return true;
551     }
552
553     if ((channel < 0) || (channel >= num_channels)) return false;
554
555     ALint state = 0;
556     if (channels[channel].startpaused)
557         state = AL_PAUSED;
558     else
559         alGetSourceiv(channels[channel].sid, AL_SOURCE_STATE, &state);
560
561     if ((paused) && (state == AL_PLAYING))
562         alSourcePause(channels[channel].sid);
563     else if ((!paused) && (state == AL_PAUSED))
564     {
565         alSourcePlay(channels[channel].sid);
566         channels[channel].startpaused = false;
567     }
568     return true;
569 }
570
571 AL_API void OPENAL_SetSFXMasterVolume(int volume)
572 {
573     if (!initialized) return;
574     ALfloat gain = ((ALfloat) volume) / 255.0f;
575     alListenerf(AL_GAIN, gain);
576 }
577
578 AL_API signed char OPENAL_StopSound(int channel)
579 {
580     if (!initialized) return false;
581
582     if (channel == OPENAL_ALL)
583     {
584         for (int i = 0; i < num_channels; i++)
585             OPENAL_StopSound(i);
586         return true;
587     }
588
589     if ((channel < 0) || (channel >= num_channels)) return false;
590     alSourceStop(channels[channel].sid);
591     channels[channel].startpaused = false;
592     return true;
593 }
594
595 AL_API void OPENAL_Stream_Close(OPENAL_STREAM *stream)
596 {
597     OPENAL_Sample_Free((OPENAL_SAMPLE *) stream);
598 }
599
600 AL_API OPENAL_SAMPLE *OPENAL_Stream_GetSample(OPENAL_STREAM *stream)
601 {
602     if (!initialized) return NULL;
603     return (OPENAL_SAMPLE *) stream;
604 }
605
606 AL_API int OPENAL_Stream_PlayEx(int channel, OPENAL_STREAM *stream, OPENAL_DSPUNIT *dsp, signed char startpaused)
607 {
608     return OPENAL_PlaySoundEx(channel, (OPENAL_SAMPLE *) stream, dsp, startpaused);
609 }
610
611 AL_API signed char OPENAL_Stream_Stop(OPENAL_STREAM *stream)
612 {
613     if (!initialized) return false;
614     for (int i = 0; i < num_channels; i++)
615     {
616         if (channels[i].sample == (OPENAL_SAMPLE *) stream)
617         {
618             alSourceStop(channels[i].sid);
619             channels[i].startpaused = false;
620         }
621     }
622     return true;
623 }
624
625 AL_API signed char OPENAL_Stream_SetMode(OPENAL_STREAM *stream, unsigned int mode)
626 {
627     return OPENAL_Sample_SetMode((OPENAL_SAMPLE *) stream, mode);
628 }
629
630 AL_API void OPENAL_Update()
631 {
632     if (!initialized) return;
633     alcProcessContext(alcGetCurrentContext());
634 }
635
636 AL_API signed char OPENAL_SetOutput(int outputtype)
637 {
638     return true;
639 }
640
641 #endif
642