]> git.jsancho.org Git - lugaru.git/blob - Source/openal_wrapper.cpp
9abf8ad4fd2af95b288f061e909ebba70a7bc69c
[lugaru.git] / Source / openal_wrapper.cpp
1 /*
2 Copyright (C) 2003, 2010 - Wolfire Games
3
4 This file is part of Lugaru.
5
6 Lugaru is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2 of the License, or
9 (at your option) any later version.
10
11 Lugaru is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 GNU General Public License for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with Lugaru.  If not, see <http://www.gnu.org/licenses/>.
18 */
19
20 #include <stdio.h>
21 #include <stdlib.h>
22 #include <string.h>
23
24 #include "Quaternions.h"
25 #include "openal_wrapper.h"
26 #include "Sounds.h"
27
28 // NOTE:
29 // FMOD uses a Left Handed Coordinate system, OpenAL uses a Right Handed
30 //  one...so we just need to flip the sign on the Z axis when appropriate.
31
32 #define DYNAMIC_LOAD_OPENAL 0
33
34 #if DYNAMIC_LOAD_OPENAL
35
36 #include <dlfcn.h>
37
38 #define AL_FUNC(t,ret,fn,params,call,rt) \
39     extern "C" { \
40         static ret ALAPIENTRY (*p##fn) params = NULL; \
41         ret ALAPIENTRY fn params { rt p##fn call; } \
42     }
43 #include "alstubs.h"
44 #undef AL_FUNC
45
46 static void *aldlhandle = NULL;
47
48 static bool lookup_alsym(const char *funcname, void **func, const char *libname)
49 {
50     if (!aldlhandle)
51         return false;
52
53     *func = dlsym(aldlhandle, funcname);
54     if (*func == NULL) {
55         fprintf(stderr, "Failed to find OpenAL symbol \"%s\" in \"%s\"\n",
56                 funcname, libname);
57         return false;
58     }
59     return true;
60 }
61
62 static void unload_alsyms(void)
63 {
64 #define AL_FUNC(t,ret,fn,params,call,rt) p##fn = NULL;
65 #include "alstubs.h"
66 #undef AL_FUNC
67     if (aldlhandle) {
68         dlclose(aldlhandle);
69         aldlhandle = NULL;
70     }
71 }
72
73 static bool lookup_all_alsyms(const char *libname)
74 {
75     if (!aldlhandle) {
76         if ( (aldlhandle = dlopen(libname, RTLD_GLOBAL | RTLD_NOW)) == NULL )
77             return false;
78     }
79
80     bool retval = true;
81 #define AL_FUNC(t,ret,fn,params,call,rt) \
82         if (!lookup_alsym(#fn, (void **) &p##fn, libname)) retval = false;
83 #include "alstubs.h"
84 #undef AL_FUNC
85
86     if (!retval)
87         unload_alsyms();
88
89     return retval;
90 }
91 #else
92 #define lookup_all_alsyms(x) (true)
93 #define unload_alsyms()
94 #endif
95
96 typedef struct {
97     ALuint sid;
98     OPENAL_SAMPLE *sample;
99     bool startpaused;
100     float position[3];
101 } OPENAL_Channels;
102
103 typedef struct OPENAL_SAMPLE {
104     char *name;
105     ALuint bid;  // buffer id.
106     int mode;
107     int is2d;
108 } OPENAL_SAMPLE;
109
110 static size_t num_channels = 0;
111 static OPENAL_Channels *impl_channels = NULL;
112 static bool initialized = false;
113 static float listener_position[3];
114
115 static void set_channel_position(const int channel, const float x,
116                                  const float y, const float z)
117 {
118     OPENAL_Channels *chan = &impl_channels[channel];
119
120     chan->position[0] = x;
121     chan->position[1] = y;
122     chan->position[2] = z;
123
124     OPENAL_SAMPLE *sptr = chan->sample;
125     if (sptr == NULL)
126         return;
127
128     const ALuint sid = chan->sid;
129     const bool no_attenuate = sptr->is2d;
130
131     if (no_attenuate) {
132         alSourcei(sid, AL_SOURCE_RELATIVE, AL_TRUE);
133         alSource3f(sid, AL_POSITION, 0.0f, 0.0f, 0.0f);
134     } else {
135         alSourcei(sid, AL_SOURCE_RELATIVE, AL_FALSE);
136         alSource3f(sid, AL_POSITION, x, y, z);
137     }
138 }
139
140
141 AL_API void OPENAL_3D_Listener_SetAttributes(const float *pos, const float *vel, float fx, float fy, float fz, float tx, float ty, float tz)
142 {
143     if (!initialized)
144         return;
145     if (pos != NULL) {
146         alListener3f(AL_POSITION, pos[0], pos[1], -pos[2]);
147         listener_position[0] = pos[0];
148         listener_position[1] = pos[1];
149         listener_position[2] = -pos[2];
150     }
151
152     ALfloat vec[6] = { fx, fy, -fz, tz, ty, -tz };
153     alListenerfv(AL_ORIENTATION, vec);
154
155     // we ignore velocity, since doppler's broken in the Linux AL at the moment...
156
157     // adjust existing positions...
158     for (int i = 0; i < num_channels; i++) {
159         const float *p = impl_channels[i].position;
160         set_channel_position(i, p[0], p[1], p[2]);
161     }
162 }
163
164 AL_API signed char OPENAL_3D_SetAttributes(int channel, const float *pos, const float *vel)
165 {
166     if (!initialized)
167         return false;
168     if ((channel < 0) || (channel >= num_channels))
169         return false;
170
171     if (pos != NULL)
172         set_channel_position(channel, pos[0], pos[1], -pos[2]);
173
174     // we ignore velocity, since doppler's broken in the Linux AL at the moment...
175
176     return true;
177 }
178
179 AL_API signed char OPENAL_3D_SetAttributes_(int channel, const XYZ &pos, const float *vel)
180 {
181     if (!initialized)
182         return false;
183     if ((channel < 0) || (channel >= num_channels))
184         return false;
185
186     set_channel_position(channel, pos.x, pos.y, -pos.z);
187
188     return true;
189 }
190
191 AL_API signed char OPENAL_Init(int mixrate, int maxsoftwarechannels, unsigned int flags)
192 {
193     if (initialized)
194         return false;
195     if (maxsoftwarechannels == 0)
196         return false;
197
198     if (flags != 0)  // unsupported.
199         return false;
200
201     if (!lookup_all_alsyms("./openal.so")) { // !!! FIXME: linux specific lib name
202         if (!lookup_all_alsyms("openal.so.1")) { // !!! FIXME: linux specific lib name
203             if (!lookup_all_alsyms("openal.so"))  // !!! FIXME: linux specific lib name
204                 return false;
205         }
206     }
207
208     ALCdevice *dev = alcOpenDevice(NULL);
209     if (!dev)
210         return false;
211
212     ALint caps[] = { ALC_FREQUENCY, mixrate, 0 };
213     ALCcontext *ctx = alcCreateContext(dev, caps);
214     if (!ctx) {
215         alcCloseDevice(dev);
216         return false;
217     }
218
219     alcMakeContextCurrent(ctx);
220     alcProcessContext(ctx);
221
222     bool cmdline(const char * cmd);
223     if (cmdline("openalinfo")) {
224         printf("AL_VENDOR: %s\n", (char *) alGetString(AL_VENDOR));
225         printf("AL_RENDERER: %s\n", (char *) alGetString(AL_RENDERER));
226         printf("AL_VERSION: %s\n", (char *) alGetString(AL_VERSION));
227         printf("AL_EXTENSIONS: %s\n", (char *) alGetString(AL_EXTENSIONS));
228     }
229
230     num_channels = maxsoftwarechannels;
231     impl_channels = new OPENAL_Channels[maxsoftwarechannels];
232     memset(impl_channels, '\0', sizeof (OPENAL_Channels) * num_channels);
233     for (int i = 0; i < num_channels; i++)
234         alGenSources(1, &impl_channels[i].sid);  // !!! FIXME: verify this didn't fail!
235
236     initialized = true;
237     return true;
238 }
239
240 AL_API void OPENAL_Close()
241 {
242     if (!initialized)
243         return;
244
245     ALCcontext *ctx = alcGetCurrentContext();
246     if (ctx) {
247         for (int i = 0; i < num_channels; i++) {
248             alSourceStop(impl_channels[i].sid);
249             alSourcei(impl_channels[i].sid, AL_BUFFER, 0);
250             alDeleteSources(1, &impl_channels[i].sid);
251         }
252         ALCdevice *dev = alcGetContextsDevice(ctx);
253         alcMakeContextCurrent(NULL);
254         alcSuspendContext(ctx);
255         alcDestroyContext(ctx);
256         alcCloseDevice(dev);
257     }
258
259     num_channels = 0;
260     delete[] impl_channels;
261     impl_channels = NULL;
262
263     unload_alsyms();
264     initialized = false;
265 }
266
267 static OPENAL_SAMPLE *OPENAL_GetCurrentSample(int channel)
268 {
269     if (!initialized)
270         return NULL;
271     if ((channel < 0) || (channel >= num_channels))
272         return NULL;
273     return impl_channels[channel].sample;
274 }
275
276 static signed char OPENAL_GetPaused(int channel)
277 {
278     if (!initialized)
279         return false;
280     if ((channel < 0) || (channel >= num_channels))
281         return false;
282     if (impl_channels[channel].startpaused)
283         return(true);
284
285     ALint state = 0;
286     alGetSourceiv(impl_channels[channel].sid, AL_SOURCE_STATE, &state);
287     return((state == AL_PAUSED) ? true : false);
288 }
289
290 static unsigned int OPENAL_GetLoopMode(int channel)
291 {
292     if (!initialized)
293         return 0;
294     if ((channel < 0) || (channel >= num_channels))
295         return 0;
296     ALint loop = 0;
297     alGetSourceiv(impl_channels[channel].sid, AL_LOOPING, &loop);
298     if (loop)
299         return(OPENAL_LOOP_NORMAL);
300     return OPENAL_LOOP_OFF;
301 }
302
303 static signed char OPENAL_IsPlaying(int channel)
304 {
305     if (!initialized)
306         return false;
307     if ((channel < 0) || (channel >= num_channels))
308         return false;
309     ALint state = 0;
310     alGetSourceiv(impl_channels[channel].sid, AL_SOURCE_STATE, &state);
311     return((state == AL_PLAYING) ? true : false);
312 }
313
314 static int OPENAL_PlaySoundEx(int channel, OPENAL_SAMPLE *sptr, OPENAL_DSPUNIT *dsp, signed char startpaused)
315 {
316     if (!initialized)
317         return -1;
318     if (sptr == NULL)
319         return -1;
320     if (dsp != NULL)
321         return -1;
322     if (channel == OPENAL_FREE) {
323         for (int i = 0; i < num_channels; i++) {
324             ALint state = 0;
325             alGetSourceiv(impl_channels[i].sid, AL_SOURCE_STATE, &state);
326             if ((state != AL_PLAYING) && (state != AL_PAUSED)) {
327                 channel = i;
328                 break;
329             }
330         }
331     }
332
333     if ((channel < 0) || (channel >= num_channels))
334         return -1;
335     alSourceStop(impl_channels[channel].sid);
336     impl_channels[channel].sample = sptr;
337     alSourcei(impl_channels[channel].sid, AL_BUFFER, sptr->bid);
338     alSourcei(impl_channels[channel].sid, AL_LOOPING, (sptr->mode == OPENAL_LOOP_OFF) ? AL_FALSE : AL_TRUE);
339     set_channel_position(channel, 0.0f, 0.0f, 0.0f);
340
341     impl_channels[channel].startpaused = ((startpaused) ? true : false);
342     if (!startpaused)
343         alSourcePlay(impl_channels[channel].sid);
344     return channel;
345 }
346
347
348 static void *decode_to_pcm(const char *_fname, ALenum &format, ALsizei &size, ALuint &freq)
349 {
350 #ifdef __POWERPC__
351     const int bigendian = 1;
352 #else
353     const int bigendian = 0;
354 #endif
355
356     // !!! FIXME: if it's not Ogg, we don't have a decoder. I'm lazy.  :/
357     char *fname = (char *) alloca(strlen(_fname) + 16);
358     strcpy(fname, _fname);
359     char *ptr = strchr(fname, '.');
360     if (ptr)
361         *ptr = '\0';
362     strcat(fname, ".ogg");
363
364     // just in case...
365 #undef fopen
366     FILE *io = fopen(fname, "rb");
367     if (io == NULL)
368         return NULL;
369
370     ALubyte *retval = NULL;
371
372 #if 0  // untested, so disable this!
373     // Can we just feed it to the AL compressed?
374     if (alIsExtensionPresent((const ALubyte *) "AL_EXT_vorbis")) {
375         format = alGetEnumValue((const ALubyte *) "AL_FORMAT_VORBIS_EXT");
376         freq = 44100;
377         fseek(io, 0, SEEK_END);
378         size = ftell(io);
379         fseek(io, 0, SEEK_SET);
380         retval = (ALubyte *) malloc(size);
381         size_t rc = fread(retval, size, 1, io);
382         fclose(io);
383         if (rc != 1) {
384             free(retval);
385             return NULL;
386         }
387         return retval;
388     }
389 #endif
390
391     // Uncompress and feed to the AL.
392     OggVorbis_File vf;
393     memset(&vf, '\0', sizeof (vf));
394     if (ov_open(io, &vf, NULL, 0) == 0) {
395         int bitstream = 0;
396         vorbis_info *info = ov_info(&vf, -1);
397         size = 0;
398         format = (info->channels == 1) ? AL_FORMAT_MONO16 : AL_FORMAT_STEREO16;
399         freq = info->rate;
400
401         if ((info->channels != 1) && (info->channels != 2)) {
402             ov_clear(&vf);
403             return NULL;
404         }
405
406         char buf[1024 * 16];
407         long rc = 0;
408         size_t allocated = 64 * 1024;
409         retval = (ALubyte *) malloc(allocated);
410         while ( (rc = ov_read(&vf, buf, sizeof (buf), bigendian, 2, 1, &bitstream)) != 0 ) {
411             if (rc > 0) {
412                 size += rc;
413                 if (size >= allocated) {
414                     allocated *= 2;
415                     ALubyte *tmp = (ALubyte *) realloc(retval, allocated);
416                     if (tmp == NULL) {
417                         free(retval);
418                         retval = NULL;
419                         break;
420                     }
421                     retval = tmp;
422                 }
423                 memcpy(retval + (size - rc), buf, rc);
424             }
425         }
426         ov_clear(&vf);
427         return retval;
428     }
429
430     fclose(io);
431     return NULL;
432 }
433
434
435 AL_API OPENAL_SAMPLE *OPENAL_Sample_Load(int index, const char *name_or_data, unsigned int mode, int offset, int length)
436 {
437     if (!initialized)
438         return NULL;
439     if (index != OPENAL_FREE)
440         return NULL;  // this is all the game does...
441     if (offset != 0)
442         return NULL;  // this is all the game does...
443     if (length != 0)
444         return NULL;  // this is all the game does...
445     if ((mode != OPENAL_HW3D) && (mode != OPENAL_2D))
446         return NULL;  // this is all the game does...
447
448     OPENAL_SAMPLE *retval = NULL;
449     ALuint bufferName = 0;
450     ALenum format = AL_NONE;
451     ALsizei size = 0;
452     ALuint frequency = 0;
453     void *data = decode_to_pcm(name_or_data, format, size, frequency);
454     if (data == NULL)
455         return NULL;
456
457     ALuint bid = 0;
458     alGetError();
459     alGenBuffers(1, &bid);
460     if (alGetError() == AL_NO_ERROR) {
461         alBufferData(bid, format, data, size, frequency);
462         retval = new OPENAL_SAMPLE;
463         retval->bid = bid;
464         retval->mode = OPENAL_LOOP_OFF;
465         retval->is2d = (mode == OPENAL_2D);
466         retval->name = new char[strlen(name_or_data) + 1];
467         if (retval->name)
468             strcpy(retval->name, name_or_data);
469     }
470
471     free(data);
472     return(retval);
473 }
474
475 AL_API void OPENAL_Sample_Free(OPENAL_SAMPLE *sptr)
476 {
477     if (!initialized)
478         return;
479     if (sptr) {
480         for (int i = 0; i < num_channels; i++) {
481             if (impl_channels[i].sample == sptr) {
482                 alSourceStop(impl_channels[i].sid);
483                 alSourcei(impl_channels[i].sid, AL_BUFFER, 0);
484                 impl_channels[i].sample = NULL;
485             }
486         }
487         alDeleteBuffers(1, &sptr->bid);
488         delete[] sptr->name;
489         delete sptr;
490     }
491 }
492
493 static signed char OPENAL_Sample_SetMode(OPENAL_SAMPLE *sptr, unsigned int mode)
494 {
495     if (!initialized)
496         return false;
497     if ((mode != OPENAL_LOOP_NORMAL) && (mode != OPENAL_LOOP_OFF))
498         return false;
499     if (!sptr)
500         return false;
501     sptr->mode = mode;
502     return true;
503 }
504
505 AL_API signed char OPENAL_SetFrequency(int channel, int freq)
506 {
507     if (!initialized)
508         return false;
509     if (channel == OPENAL_ALL) {
510         for (int i = 0; i < num_channels; i++)
511             OPENAL_SetFrequency(i, freq);
512         return true;
513     }
514
515     if ((channel < 0) || (channel >= num_channels))
516         return false;
517     if (freq == 8012)
518         // hack
519         alSourcef(impl_channels[channel].sid, AL_PITCH, 8012.0f / 44100.0f);
520     else
521         alSourcef(impl_channels[channel].sid, AL_PITCH, 1.0f);
522     return true;
523 }
524
525 AL_API signed char OPENAL_SetVolume(int channel, int vol)
526 {
527     if (!initialized)
528         return false;
529
530     if (channel == OPENAL_ALL) {
531         for (int i = 0; i < num_channels; i++)
532             OPENAL_SetVolume(i, vol);
533         return true;
534     }
535
536     if ((channel < 0) || (channel >= num_channels))
537         return false;
538
539     if (vol < 0)
540         vol = 0;
541     else if (vol > 255)
542         vol = 255;
543     ALfloat gain = ((ALfloat) vol) / 255.0f;
544     alSourcef(impl_channels[channel].sid, AL_GAIN, gain);
545     return true;
546 }
547
548 AL_API signed char OPENAL_SetPaused(int channel, signed char paused)
549 {
550     if (!initialized)
551         return false;
552
553     if (channel == OPENAL_ALL) {
554         for (int i = 0; i < num_channels; i++)
555             OPENAL_SetPaused(i, paused);
556         return true;
557     }
558
559     if ((channel < 0) || (channel >= num_channels))
560         return false;
561
562     ALint state = 0;
563     if (impl_channels[channel].startpaused)
564         state = AL_PAUSED;
565     else
566         alGetSourceiv(impl_channels[channel].sid, AL_SOURCE_STATE, &state);
567
568     if ((paused) && (state == AL_PLAYING))
569         alSourcePause(impl_channels[channel].sid);
570     else if ((!paused) && (state == AL_PAUSED)) {
571         alSourcePlay(impl_channels[channel].sid);
572         impl_channels[channel].startpaused = false;
573     }
574     return true;
575 }
576
577 AL_API void OPENAL_SetSFXMasterVolume(int volume)
578 {
579     if (!initialized)
580         return;
581     ALfloat gain = ((ALfloat) volume) / 255.0f;
582     alListenerf(AL_GAIN, gain);
583 }
584
585 AL_API signed char OPENAL_StopSound(int channel)
586 {
587     if (!initialized)
588         return false;
589
590     if (channel == OPENAL_ALL) {
591         for (int i = 0; i < num_channels; i++)
592             OPENAL_StopSound(i);
593         return true;
594     }
595
596     if ((channel < 0) || (channel >= num_channels))
597         return false;
598     alSourceStop(impl_channels[channel].sid);
599     impl_channels[channel].startpaused = false;
600     return true;
601 }
602
603 AL_API void OPENAL_Stream_Close(OPENAL_STREAM *stream)
604 {
605     OPENAL_Sample_Free((OPENAL_SAMPLE *) stream);
606 }
607
608 static OPENAL_SAMPLE *OPENAL_Stream_GetSample(OPENAL_STREAM *stream)
609 {
610     if (!initialized)
611         return NULL;
612     return (OPENAL_SAMPLE *) stream;
613 }
614
615 static int OPENAL_Stream_PlayEx(int channel, OPENAL_STREAM *stream, OPENAL_DSPUNIT *dsp, signed char startpaused)
616 {
617     return OPENAL_PlaySoundEx(channel, (OPENAL_SAMPLE *) stream, dsp, startpaused);
618 }
619
620 static signed char OPENAL_Stream_Stop(OPENAL_STREAM *stream)
621 {
622     if (!initialized)
623         return false;
624     for (int i = 0; i < num_channels; i++) {
625         if (impl_channels[i].sample == (OPENAL_SAMPLE *) stream) {
626             alSourceStop(impl_channels[i].sid);
627             impl_channels[i].startpaused = false;
628         }
629     }
630     return true;
631 }
632
633 AL_API signed char OPENAL_Stream_SetMode(OPENAL_STREAM *stream, unsigned int mode)
634 {
635     return OPENAL_Sample_SetMode((OPENAL_SAMPLE *) stream, mode);
636 }
637
638 AL_API void OPENAL_Update()
639 {
640     if (!initialized)
641         return;
642     alcProcessContext(alcGetCurrentContext());
643 }
644
645 AL_API signed char OPENAL_SetOutput(int outputtype)
646 {
647     return true;
648 }
649
650 extern int channels[];
651
652 extern "C" void PlaySoundEx(int chan, OPENAL_SAMPLE *sptr, OPENAL_DSPUNIT *dsp, signed char startpaused)
653 {
654     const OPENAL_SAMPLE * currSample = OPENAL_GetCurrentSample(channels[chan]);
655     if (currSample && currSample == samp[chan]) {
656         if (OPENAL_GetPaused(channels[chan])) {
657             OPENAL_StopSound(channels[chan]);
658             channels[chan] = OPENAL_FREE;
659         } else if (OPENAL_IsPlaying(channels[chan])) {
660             int loop_mode = OPENAL_GetLoopMode(channels[chan]);
661             if (loop_mode & OPENAL_LOOP_OFF) {
662                 channels[chan] = OPENAL_FREE;
663             }
664         }
665     } else {
666         channels[chan] = OPENAL_FREE;
667     }
668
669     channels[chan] = OPENAL_PlaySoundEx(channels[chan], sptr, dsp, startpaused);
670     if (channels[chan] < 0) {
671         channels[chan] = OPENAL_PlaySoundEx(OPENAL_FREE, sptr, dsp, startpaused);
672     }
673 }
674
675 extern "C" void PlayStreamEx(int chan, OPENAL_STREAM *sptr, OPENAL_DSPUNIT *dsp, signed char startpaused)
676 {
677     const OPENAL_SAMPLE * currSample = OPENAL_GetCurrentSample(channels[chan]);
678     if (currSample && currSample == OPENAL_Stream_GetSample(sptr)) {
679         OPENAL_StopSound(channels[chan]);
680         OPENAL_Stream_Stop(sptr);
681     } else {
682         OPENAL_Stream_Stop(sptr);
683         channels[chan] = OPENAL_FREE;
684     }
685
686     channels[chan] = OPENAL_Stream_PlayEx(channels[chan], sptr, dsp, startpaused);
687     if (channels[chan] < 0) {
688         channels[chan] = OPENAL_Stream_PlayEx(OPENAL_FREE, sptr, dsp, startpaused);
689     }
690 }