]> git.jsancho.org Git - lugaru.git/blob - Source/openal_wrapper.cpp
More AL fixes. Seems to be complete now.
[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     // Can we just feed it to the AL compressed?
317     if (alIsExtensionPresent((const ALubyte *) "AL_EXT_vorbis"))
318     {
319         format = alGetEnumValue((const ALubyte *) "AL_FORMAT_VORBIS_EXT");
320         freq = 44100;
321         fseek(io, 0, SEEK_END);
322         size = ftell(io);
323         fseek(io, 0, SEEK_SET);
324         retval = (ALubyte *) malloc(size);
325         size_t rc = fread(retval, size, 1, io);
326         fclose(io);
327         if (rc != 1)
328         {
329             free(retval);
330             return NULL;
331         }
332         return retval;
333     }
334
335     // Uncompress and feed to the AL.
336     OggVorbis_File vf;
337     memset(&vf, '\0', sizeof (vf));
338     if (ov_open(io, &vf, NULL, 0) == 0)
339     {
340         int bitstream = 0;
341         vorbis_info *info = ov_info(&vf, -1);
342         size = 0;
343         format = (info->channels == 1) ? AL_FORMAT_MONO16 : AL_FORMAT_STEREO16;
344         freq = info->rate;
345
346         if ((info->channels != 1) && (info->channels != 2))
347         {
348             ov_clear(&vf);
349             return NULL;
350         }
351
352         char buf[1024 * 16];
353         long rc = 0;
354         size_t allocated = 64 * 1024;
355         retval = (ALubyte *) malloc(allocated);
356         while ( (rc = ov_read(&vf, buf, sizeof (buf), 0, 2, 1, &bitstream)) != 0 )
357         {
358             if (rc > 0)
359             {
360                 size += rc;
361                 if (size >= allocated)
362                 {
363                     allocated *= 2;
364                     ALubyte *tmp = (ALubyte *) realloc(retval, allocated);
365                     if (tmp == NULL)
366                     {
367                         free(retval);
368                         retval = NULL;
369                         break;
370                     }
371                     retval = tmp;
372                 }
373                 memcpy(retval + (size - rc), buf, rc);
374             }
375         }
376         ov_clear(&vf);
377         return retval;
378     }
379
380     fclose(io);
381     return NULL;
382 }
383
384
385 FSOUND_SAMPLE * F_API OPENAL_Sample_Load(int index, const char *name_or_data, unsigned int mode, int offset, int length)
386 {
387     if (!initialized) return NULL;
388     if (index != FSOUND_FREE) return NULL;  // this is all the game does...
389     if (offset != 0) return NULL;  // this is all the game does...
390     if (length != 0) return NULL;  // this is all the game does...
391     if ((mode != FSOUND_HW3D) && (mode != FSOUND_2D)) return NULL;  // this is all the game does...
392
393     FSOUND_SAMPLE *retval = NULL;
394     ALuint bufferName = 0;
395     ALenum format = AL_NONE;
396     ALsizei size = 0;
397     ALuint frequency = 0;
398     void *data = decode_to_pcm(name_or_data, format, size, frequency);
399     if (data == NULL)
400         return NULL;
401
402     ALuint bid = 0;
403     alGetError();
404     alGenBuffers(1, &bid);
405     if (alGetError() == AL_NO_ERROR)
406     {
407         alBufferData(bid, format, data, size, frequency);
408         retval = new FSOUND_SAMPLE;
409         retval->bid = bid;
410         retval->mode = FSOUND_LOOP_OFF;
411         retval->is2d = (mode == FSOUND_2D);
412         retval->name = new char[strlen(name_or_data) + 1];
413         if (retval->name)
414             strcpy(retval->name, name_or_data);
415     }
416
417     free(data);
418     return(retval);
419 }
420
421 void F_API OPENAL_Sample_Free(FSOUND_SAMPLE *sptr)
422 {
423     if (!initialized) return;
424     if (sptr)
425     {
426         for (int i = 0; i < num_channels; i++)
427         {
428             if (channels[i].sample == sptr)
429             {
430                 alSourceStop(channels[i].sid);
431                 alSourcei(channels[i].sid, AL_BUFFER, 0);
432                 channels[i].sample = NULL;
433             }
434         }
435         alDeleteBuffers(1, &sptr->bid);
436         delete[] sptr->name;
437         delete sptr;
438     }
439 }
440
441 signed char F_API OPENAL_Sample_SetMode(FSOUND_SAMPLE *sptr, unsigned int mode)
442 {
443     if (!initialized) return FALSE;
444     if ((mode != FSOUND_LOOP_NORMAL) && (mode != FSOUND_LOOP_OFF)) return FALSE;
445     if (!sptr) return FALSE;
446     sptr->mode = mode;
447     return TRUE;
448 }
449
450 signed char F_API OPENAL_Sample_SetMinMaxDistance(FSOUND_SAMPLE *sptr, float min, float max)
451 {
452     if (!initialized) return FALSE;
453     if (sptr == NULL) return FALSE;
454     // !!! FIXME: write me
455     return 0;
456 }
457
458 signed char F_API OPENAL_SetFrequency(int channel, int freq)
459 {
460     if (!initialized) return FALSE;
461     if (channel == FSOUND_ALL)
462     {
463         for (int i = 0; i < num_channels; i++)
464             OPENAL_SetFrequency(i, freq);
465         return TRUE;
466     }
467
468     if ((channel < 0) || (channel >= num_channels)) return FALSE;
469     if (freq == 8012)  // hack
470         alSourcef(channels[channel].sid, AL_PITCH, 8012.0f / 44100.0f);
471     else
472         alSourcef(channels[channel].sid, AL_PITCH, 1.0f);
473     return TRUE;
474 }
475
476 signed char F_API OPENAL_SetVolume(int channel, int vol)
477 {
478     if (!initialized) return FALSE;
479
480     if (channel == FSOUND_ALL)
481     {
482         for (int i = 0; i < num_channels; i++)
483             OPENAL_SetVolume(i, vol);
484         return TRUE;
485     }
486
487     if ((channel < 0) || (channel >= num_channels)) return FALSE;
488
489     if (vol < 0) vol = 0;
490     else if (vol > 255) vol = 255;
491     ALfloat gain = ((ALfloat) vol) / 255.0f;
492     alSourcef(channels[channel].sid, AL_GAIN, gain);
493     return TRUE;
494 }
495
496 signed char F_API OPENAL_SetPaused(int channel, signed char paused)
497 {
498     if (!initialized) return FALSE;
499
500     if (channel == FSOUND_ALL)
501     {
502         for (int i = 0; i < num_channels; i++)
503             OPENAL_SetPaused(i, paused);
504         return TRUE;
505     }
506
507     if ((channel < 0) || (channel >= num_channels)) return FALSE;
508
509     ALint state = 0;
510     if (channels[channel].startpaused)
511         state = AL_PAUSED;
512     else
513         alGetSourceiv(channels[channel].sid, AL_SOURCE_STATE, &state);
514
515     if ((paused) && (state == AL_PLAYING))
516         alSourcePause(channels[channel].sid);
517     else if ((!paused) && (state == AL_PAUSED))
518     {
519         alSourcePlay(channels[channel].sid);
520         channels[channel].startpaused = false;
521     }
522     return TRUE;
523 }
524
525 void F_API OPENAL_SetSFXMasterVolume(int volume)
526 {
527     if (!initialized) return;
528     ALfloat gain = ((ALfloat) volume) / 255.0f;
529     alListenerf(AL_GAIN, gain);
530 }
531
532 signed char F_API OPENAL_StopSound(int channel)
533 {
534     if (!initialized) return FALSE;
535
536     if (channel == FSOUND_ALL)
537     {
538         for (int i = 0; i < num_channels; i++)
539             OPENAL_StopSound(i);
540         return TRUE;
541     }
542
543     if ((channel < 0) || (channel >= num_channels)) return FALSE;
544     alSourceStop(channels[channel].sid);
545     channels[channel].startpaused = false;
546     return TRUE;
547 }
548
549 FSOUND_STREAM * F_API OPENAL_Stream_Open(const char *name_or_data, unsigned int mode, int offset, int length)
550 {
551     return (FSOUND_STREAM *) OPENAL_Sample_Load(FSOUND_FREE, name_or_data, mode, offset, length);
552 }
553
554 signed char F_API OPENAL_Stream_Close(FSOUND_STREAM *stream)
555 {
556     OPENAL_Sample_Free((FSOUND_SAMPLE *) stream);
557 }
558
559 FSOUND_SAMPLE * F_API OPENAL_Stream_GetSample(FSOUND_STREAM *stream)
560 {
561     if (!initialized) return NULL;
562     return (FSOUND_SAMPLE *) stream;
563 }
564
565 int F_API OPENAL_Stream_PlayEx(int channel, FSOUND_STREAM *stream, FSOUND_DSPUNIT *dsp, signed char startpaused)
566 {
567     return OPENAL_PlaySoundEx(channel, (FSOUND_SAMPLE *) stream, dsp, startpaused);
568 }
569
570 signed char F_API OPENAL_Stream_Stop(FSOUND_STREAM *stream)
571 {
572     if (!initialized) return FALSE;
573     for (int i = 0; i < num_channels; i++)
574     {
575         if (channels[i].sample == (FSOUND_SAMPLE *) stream)
576         {
577             alSourceStop(channels[i].sid);
578             channels[i].startpaused = false;
579         }
580     }
581     return TRUE;
582 }
583
584 signed char F_API OPENAL_Stream_SetMode(FSOUND_STREAM *stream, unsigned int mode)
585 {
586     return OPENAL_Sample_SetMode((FSOUND_SAMPLE *) stream, mode);
587 }
588
589 void F_API OPENAL_Update()
590 {
591     if (!initialized) return;
592     alcProcessContext(alcGetCurrentContext());
593 }
594
595 signed char F_API OPENAL_SetOutput(int outputtype)
596 {
597     return TRUE;
598 }
599
600 #endif
601