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