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