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