]> git.jsancho.org Git - lugaru.git/blob - Source/openal_wrapper.cpp
Disable AL_EXT_vorbis, as untested.
[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 } OPENAL_Channels;
96
97 typedef struct FSOUND_SAMPLE
98 {
99     char *name;
100     ALuint bid;  // buffer id.
101     int mode;
102     int is2d;
103 } FSOUND_SAMPLE;
104
105 typedef struct FSOUND_STREAM
106 {
107     char *name;
108     ALuint bid;  // buffer id.
109     int mode;
110     int is2d;
111 } FSOUND_STREAM;
112
113 static size_t num_channels = 0;
114 static OPENAL_Channels *channels = NULL;
115 static bool initialized = false;
116
117
118 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)
119 {
120     if (!initialized) return;
121     if (pos != NULL)
122         alListener3f(AL_POSITION, pos[0], pos[1], -pos[2]);
123     ALfloat vec[6] = { fx, fy, -fz, tz, ty, -tz };
124     alListenerfv(AL_ORIENTATION, vec);
125
126     // we ignore velocity, since doppler's broken in the Linux AL at the moment...
127 }
128
129 signed char F_API OPENAL_3D_SetAttributes(int channel, const float *pos, const float *vel)
130 {
131     if (!initialized) return FALSE;
132     if ((channel < 0) || (channel >= num_channels)) return FALSE;
133
134     if ((pos != NULL) && (!channels[channel].sample->is2d))
135         alSource3f(channels[channel].sid, AL_POSITION, pos[0], pos[1], -pos[2]);
136
137     // we ignore velocity, since doppler's broken in the Linux AL at the moment...
138     return TRUE;
139 }
140
141 void F_API OPENAL_3D_SetDopplerFactor(float scale)
142 {
143     if (!initialized) return;
144     // unimplemented...looks like init routines just call this with scale == 0.0f anyhow.
145 }
146
147 signed char F_API OPENAL_Init(int mixrate, int maxsoftwarechannels, unsigned int flags)
148 {
149     if (initialized) return FALSE;
150     if (maxsoftwarechannels == 0) return FALSE;
151
152     if (flags != 0)  // unsupported.
153         return FALSE;
154
155     if (!lookup_all_alsyms("./openal.so"))  // !!! FIXME: linux specific lib name
156     {
157         if (!lookup_all_alsyms("openal.so.1"))  // !!! FIXME: linux specific lib name
158         {
159             if (!lookup_all_alsyms("openal.so"))  // !!! FIXME: linux specific lib name
160                 return FALSE;
161         }
162     }
163
164     ALCdevice *dev = alcOpenDevice(NULL);
165     if (!dev)
166         return FALSE;
167
168     ALint caps[] = { ALC_FREQUENCY, mixrate, 0 };
169     ALCcontext *ctx = alcCreateContext(dev, caps);
170     if (!ctx)
171     {
172         alcCloseDevice(dev);
173         return FALSE;
174     }
175
176     alcMakeContextCurrent(ctx);
177     alcProcessContext(ctx);
178
179     bool cmdline(const char *cmd);
180     if (cmdline("openalinfo"))
181     {
182         printf("AL_VENDOR: %s\n", (char *) alGetString(AL_VENDOR));
183         printf("AL_RENDERER: %s\n", (char *) alGetString(AL_RENDERER));
184         printf("AL_VERSION: %s\n", (char *) alGetString(AL_VERSION));
185         printf("AL_EXTENSIONS: %s\n", (char *) alGetString(AL_EXTENSIONS));
186     }
187
188     num_channels = maxsoftwarechannels;
189     channels = new OPENAL_Channels[maxsoftwarechannels];
190     memset(channels, '\0', sizeof (OPENAL_Channels) * num_channels);
191     for (int i = 0; i < num_channels; i++)
192         alGenSources(1, &channels[i].sid);  // !!! FIXME: verify this didn't fail!
193
194     initialized = true;
195     return TRUE;
196 }
197
198 void F_API OPENAL_Close()
199 {
200     if (!initialized) return;
201
202     ALCcontext *ctx = alcGetCurrentContext();
203     if (ctx)
204     {
205         for (int i = 0; i < num_channels; i++)
206         {
207             alSourceStop(channels[i].sid);
208             alSourcei(channels[i].sid, AL_BUFFER, 0);
209             alDeleteSources(1, &channels[i].sid);
210         }
211         ALCdevice *dev = alcGetContextsDevice(ctx);
212         alcMakeContextCurrent(NULL);
213         alcSuspendContext(ctx);
214         alcDestroyContext(ctx);
215         alcCloseDevice(dev);
216     }
217
218     num_channels = 0;
219     delete[] channels;
220     channels = NULL;
221
222     unload_alsyms();
223     initialized = false;
224 }
225
226 FSOUND_SAMPLE *F_API OPENAL_GetCurrentSample(int channel)
227 {
228     if (!initialized) return NULL;
229     if ((channel < 0) || (channel >= num_channels)) return NULL;
230     return channels[channel].sample;
231 }
232
233 signed char F_API OPENAL_GetPaused(int channel)
234 {
235     if (!initialized) return FALSE;
236     if ((channel < 0) || (channel >= num_channels)) return FALSE;
237     if (channels[channel].startpaused)
238         return(TRUE);
239
240     ALint state = 0;
241     alGetSourceiv(channels[channel].sid, AL_SOURCE_STATE, &state);
242     return((state == AL_PAUSED) ? TRUE : FALSE);
243 }
244
245 unsigned int F_API OPENAL_GetLoopMode(int channel)
246 {
247     if (!initialized) return 0;
248     if ((channel < 0) || (channel >= num_channels)) return 0;
249     ALint loop = 0;
250     alGetSourceiv(channels[channel].sid, AL_LOOPING, &loop);
251     if (loop)
252         return(FSOUND_LOOP_NORMAL);
253     return FSOUND_LOOP_OFF;
254 }
255
256 signed char F_API OPENAL_IsPlaying(int channel)
257 {
258     if (!initialized) return FALSE;
259     if ((channel < 0) || (channel >= num_channels)) return FALSE;
260     ALint state = 0;
261     alGetSourceiv(channels[channel].sid, AL_SOURCE_STATE, &state);
262     return((state == AL_PLAYING) ? TRUE : FALSE);
263 }
264
265 int F_API OPENAL_PlaySoundEx(int channel, FSOUND_SAMPLE *sptr, FSOUND_DSPUNIT *dsp, signed char startpaused)
266 {
267     if (!initialized) return -1;
268     if (sptr == NULL) return -1;
269     if (dsp != NULL) return -1;
270     if (channel == FSOUND_FREE)
271     {
272         for (int i = 0; i < num_channels; i++)
273         {
274             ALint state = 0;
275             alGetSourceiv(channels[i].sid, AL_SOURCE_STATE, &state);
276             if ((state != AL_PLAYING) && (state != AL_PAUSED))
277             {
278                 channel = i;
279                 break;
280             }
281         }
282     }
283
284     if ((channel < 0) || (channel >= num_channels)) return -1;
285     alSourceStop(channels[channel].sid);
286     channels[channel].sample = sptr;
287     alSourcei(channels[channel].sid, AL_BUFFER, sptr->bid);
288     alSourcei(channels[channel].sid, AL_LOOPING, (sptr->mode == FSOUND_LOOP_OFF) ? AL_FALSE : AL_TRUE);
289     alSourcei(channels[channel].sid, AL_SOURCE_RELATIVE, (sptr->is2d) ? AL_TRUE : AL_FALSE);
290     alSource3f(channels[channel].sid, AL_POSITION, 0.0f, 0.0f, 0.0f);
291
292     channels[channel].startpaused = ((startpaused) ? true : false);
293     if (!startpaused)
294         alSourcePlay(channels[channel].sid);
295     return channel;
296 }
297
298
299 static void *decode_to_pcm(const char *_fname, ALenum &format, ALsizei &size, ALuint &freq)
300 {
301     // !!! FIXME: if it's not Ogg, we don't have a decoder. I'm lazy.  :/
302     char *fname = (char *) alloca(strlen(_fname) + 16);
303     strcpy(fname, _fname);
304     char *ptr = strchr(fname, '.');
305     if (ptr) *ptr = NULL;
306     strcat(fname, ".ogg");
307
308     // just in case...
309     #undef fopen
310     FILE *io = fopen(fname, "rb");
311     if (io == NULL)
312         return NULL;
313
314     ALubyte *retval = NULL;
315
316     #if 0  // untested, so disable this!
317     // Can we just feed it to the AL compressed?
318     if (alIsExtensionPresent((const ALubyte *) "AL_EXT_vorbis"))
319     {
320         format = alGetEnumValue((const ALubyte *) "AL_FORMAT_VORBIS_EXT");
321         freq = 44100;
322         fseek(io, 0, SEEK_END);
323         size = ftell(io);
324         fseek(io, 0, SEEK_SET);
325         retval = (ALubyte *) malloc(size);
326         size_t rc = fread(retval, size, 1, io);
327         fclose(io);
328         if (rc != 1)
329         {
330             free(retval);
331             return NULL;
332         }
333         return retval;
334     }
335     #endif
336
337     // Uncompress and feed to the AL.
338     OggVorbis_File vf;
339     memset(&vf, '\0', sizeof (vf));
340     if (ov_open(io, &vf, NULL, 0) == 0)
341     {
342         int bitstream = 0;
343         vorbis_info *info = ov_info(&vf, -1);
344         size = 0;
345         format = (info->channels == 1) ? AL_FORMAT_MONO16 : AL_FORMAT_STEREO16;
346         freq = info->rate;
347
348         if ((info->channels != 1) && (info->channels != 2))
349         {
350             ov_clear(&vf);
351             return NULL;
352         }
353
354         char buf[1024 * 16];
355         long rc = 0;
356         size_t allocated = 64 * 1024;
357         retval = (ALubyte *) malloc(allocated);
358         while ( (rc = ov_read(&vf, buf, sizeof (buf), 0, 2, 1, &bitstream)) != 0 )
359         {
360             if (rc > 0)
361             {
362                 size += rc;
363                 if (size >= allocated)
364                 {
365                     allocated *= 2;
366                     ALubyte *tmp = (ALubyte *) realloc(retval, allocated);
367                     if (tmp == NULL)
368                     {
369                         free(retval);
370                         retval = NULL;
371                         break;
372                     }
373                     retval = tmp;
374                 }
375                 memcpy(retval + (size - rc), buf, rc);
376             }
377         }
378         ov_clear(&vf);
379         return retval;
380     }
381
382     fclose(io);
383     return NULL;
384 }
385
386
387 FSOUND_SAMPLE * F_API OPENAL_Sample_Load(int index, const char *name_or_data, unsigned int mode, int offset, int length)
388 {
389     if (!initialized) return NULL;
390     if (index != FSOUND_FREE) return NULL;  // this is all the game does...
391     if (offset != 0) return NULL;  // this is all the game does...
392     if (length != 0) return NULL;  // this is all the game does...
393     if ((mode != FSOUND_HW3D) && (mode != FSOUND_2D)) return NULL;  // this is all the game does...
394
395     FSOUND_SAMPLE *retval = NULL;
396     ALuint bufferName = 0;
397     ALenum format = AL_NONE;
398     ALsizei size = 0;
399     ALuint frequency = 0;
400     void *data = decode_to_pcm(name_or_data, format, size, frequency);
401     if (data == NULL)
402         return NULL;
403
404     ALuint bid = 0;
405     alGetError();
406     alGenBuffers(1, &bid);
407     if (alGetError() == AL_NO_ERROR)
408     {
409         alBufferData(bid, format, data, size, frequency);
410         retval = new FSOUND_SAMPLE;
411         retval->bid = bid;
412         retval->mode = FSOUND_LOOP_OFF;
413         retval->is2d = (mode == FSOUND_2D);
414         retval->name = new char[strlen(name_or_data) + 1];
415         if (retval->name)
416             strcpy(retval->name, name_or_data);
417     }
418
419     free(data);
420     return(retval);
421 }
422
423 void F_API OPENAL_Sample_Free(FSOUND_SAMPLE *sptr)
424 {
425     if (!initialized) return;
426     if (sptr)
427     {
428         for (int i = 0; i < num_channels; i++)
429         {
430             if (channels[i].sample == sptr)
431             {
432                 alSourceStop(channels[i].sid);
433                 alSourcei(channels[i].sid, AL_BUFFER, 0);
434                 channels[i].sample = NULL;
435             }
436         }
437         alDeleteBuffers(1, &sptr->bid);
438         delete[] sptr->name;
439         delete sptr;
440     }
441 }
442
443 signed char F_API OPENAL_Sample_SetMode(FSOUND_SAMPLE *sptr, unsigned int mode)
444 {
445     if (!initialized) return FALSE;
446     if ((mode != FSOUND_LOOP_NORMAL) && (mode != FSOUND_LOOP_OFF)) return FALSE;
447     if (!sptr) return FALSE;
448     sptr->mode = mode;
449     return TRUE;
450 }
451
452 signed char F_API OPENAL_Sample_SetMinMaxDistance(FSOUND_SAMPLE *sptr, float min, float max)
453 {
454     if (!initialized) return FALSE;
455     if (sptr == NULL) return FALSE;
456     // !!! FIXME: write me
457     return 0;
458 }
459
460 signed char F_API OPENAL_SetFrequency(int channel, int freq)
461 {
462     if (!initialized) return FALSE;
463     if (channel == FSOUND_ALL)
464     {
465         for (int i = 0; i < num_channels; i++)
466             OPENAL_SetFrequency(i, freq);
467         return TRUE;
468     }
469
470     if ((channel < 0) || (channel >= num_channels)) return FALSE;
471     if (freq == 8012)  // hack
472         alSourcef(channels[channel].sid, AL_PITCH, 8012.0f / 44100.0f);
473     else
474         alSourcef(channels[channel].sid, AL_PITCH, 1.0f);
475     return TRUE;
476 }
477
478 signed char F_API OPENAL_SetVolume(int channel, int vol)
479 {
480     if (!initialized) return FALSE;
481
482     if (channel == FSOUND_ALL)
483     {
484         for (int i = 0; i < num_channels; i++)
485             OPENAL_SetVolume(i, vol);
486         return TRUE;
487     }
488
489     if ((channel < 0) || (channel >= num_channels)) return FALSE;
490
491     if (vol < 0) vol = 0;
492     else if (vol > 255) vol = 255;
493     ALfloat gain = ((ALfloat) vol) / 255.0f;
494     alSourcef(channels[channel].sid, AL_GAIN, gain);
495     return TRUE;
496 }
497
498 signed char F_API OPENAL_SetPaused(int channel, signed char paused)
499 {
500     if (!initialized) return FALSE;
501
502     if (channel == FSOUND_ALL)
503     {
504         for (int i = 0; i < num_channels; i++)
505             OPENAL_SetPaused(i, paused);
506         return TRUE;
507     }
508
509     if ((channel < 0) || (channel >= num_channels)) return FALSE;
510
511     ALint state = 0;
512     if (channels[channel].startpaused)
513         state = AL_PAUSED;
514     else
515         alGetSourceiv(channels[channel].sid, AL_SOURCE_STATE, &state);
516
517     if ((paused) && (state == AL_PLAYING))
518         alSourcePause(channels[channel].sid);
519     else if ((!paused) && (state == AL_PAUSED))
520     {
521         alSourcePlay(channels[channel].sid);
522         channels[channel].startpaused = false;
523     }
524     return TRUE;
525 }
526
527 void F_API OPENAL_SetSFXMasterVolume(int volume)
528 {
529     if (!initialized) return;
530     ALfloat gain = ((ALfloat) volume) / 255.0f;
531     alListenerf(AL_GAIN, gain);
532 }
533
534 signed char F_API OPENAL_StopSound(int channel)
535 {
536     if (!initialized) return FALSE;
537
538     if (channel == FSOUND_ALL)
539     {
540         for (int i = 0; i < num_channels; i++)
541             OPENAL_StopSound(i);
542         return TRUE;
543     }
544
545     if ((channel < 0) || (channel >= num_channels)) return FALSE;
546     alSourceStop(channels[channel].sid);
547     channels[channel].startpaused = false;
548     return TRUE;
549 }
550
551 FSOUND_STREAM * F_API OPENAL_Stream_Open(const char *name_or_data, unsigned int mode, int offset, int length)
552 {
553     return (FSOUND_STREAM *) OPENAL_Sample_Load(FSOUND_FREE, name_or_data, mode, offset, length);
554 }
555
556 signed char F_API OPENAL_Stream_Close(FSOUND_STREAM *stream)
557 {
558     OPENAL_Sample_Free((FSOUND_SAMPLE *) stream);
559 }
560
561 FSOUND_SAMPLE * F_API OPENAL_Stream_GetSample(FSOUND_STREAM *stream)
562 {
563     if (!initialized) return NULL;
564     return (FSOUND_SAMPLE *) stream;
565 }
566
567 int F_API OPENAL_Stream_PlayEx(int channel, FSOUND_STREAM *stream, FSOUND_DSPUNIT *dsp, signed char startpaused)
568 {
569     return OPENAL_PlaySoundEx(channel, (FSOUND_SAMPLE *) stream, dsp, startpaused);
570 }
571
572 signed char F_API OPENAL_Stream_Stop(FSOUND_STREAM *stream)
573 {
574     if (!initialized) return FALSE;
575     for (int i = 0; i < num_channels; i++)
576     {
577         if (channels[i].sample == (FSOUND_SAMPLE *) stream)
578         {
579             alSourceStop(channels[i].sid);
580             channels[i].startpaused = false;
581         }
582     }
583     return TRUE;
584 }
585
586 signed char F_API OPENAL_Stream_SetMode(FSOUND_STREAM *stream, unsigned int mode)
587 {
588     return OPENAL_Sample_SetMode((FSOUND_SAMPLE *) stream, mode);
589 }
590
591 void F_API OPENAL_Update()
592 {
593     if (!initialized) return;
594     alcProcessContext(alcGetCurrentContext());
595 }
596
597 signed char F_API OPENAL_SetOutput(int outputtype)
598 {
599     return TRUE;
600 }
601
602 #endif
603