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