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