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