]> git.jsancho.org Git - lugaru.git/blob - Source/openal_wrapper.cpp
BEAUTIFIED ALL SOURCE CODE
[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) return;
148     if (pos != NULL) {
149         alListener3f(AL_POSITION, pos[0], pos[1], -pos[2]);
150         listener_position[0] = pos[0];
151         listener_position[1] = pos[1];
152         listener_position[2] = -pos[2];
153     }
154
155     ALfloat vec[6] = { fx, fy, -fz, tz, ty, -tz };
156     alListenerfv(AL_ORIENTATION, vec);
157
158     // we ignore velocity, since doppler's broken in the Linux AL at the moment...
159
160     // adjust existing positions...
161     for (int i = 0; i < num_channels; i++) {
162         const float *p = impl_channels[i].position;
163         set_channel_position(i, p[0], p[1], p[2]);
164     }
165 }
166
167 AL_API signed char OPENAL_3D_SetAttributes(int channel, const float *pos, const float *vel)
168 {
169     if (!initialized) return false;
170     if ((channel < 0) || (channel >= num_channels)) return false;
171
172     if (pos != NULL)
173         set_channel_position(channel, pos[0], pos[1], -pos[2]);
174
175     // we ignore velocity, since doppler's broken in the Linux AL at the moment...
176
177     return true;
178 }
179
180 AL_API signed char OPENAL_3D_SetAttributes_(int channel, const XYZ &pos, const float *vel)
181 {
182     if (!initialized) return false;
183     if ((channel < 0) || (channel >= num_channels)) return false;
184
185     set_channel_position(channel, pos.x, pos.y, -pos.z);
186
187     return true;
188 }
189
190 AL_API signed char OPENAL_Init(int mixrate, int maxsoftwarechannels, unsigned int flags)
191 {
192     if (initialized) return false;
193     if (maxsoftwarechannels == 0) return false;
194
195     if (flags != 0)  // unsupported.
196         return false;
197
198     if (!lookup_all_alsyms("./openal.so")) { // !!! FIXME: linux specific lib name
199         if (!lookup_all_alsyms("openal.so.1")) { // !!! FIXME: linux specific lib name
200             if (!lookup_all_alsyms("openal.so"))  // !!! FIXME: linux specific lib name
201                 return false;
202         }
203     }
204
205     ALCdevice *dev = alcOpenDevice(NULL);
206     if (!dev)
207         return false;
208
209     ALint caps[] = { ALC_FREQUENCY, mixrate, 0 };
210     ALCcontext *ctx = alcCreateContext(dev, caps);
211     if (!ctx) {
212         alcCloseDevice(dev);
213         return false;
214     }
215
216     alcMakeContextCurrent(ctx);
217     alcProcessContext(ctx);
218
219     bool cmdline(const char * cmd);
220     if (cmdline("openalinfo")) {
221         printf("AL_VENDOR: %s\n", (char *) alGetString(AL_VENDOR));
222         printf("AL_RENDERER: %s\n", (char *) alGetString(AL_RENDERER));
223         printf("AL_VERSION: %s\n", (char *) alGetString(AL_VERSION));
224         printf("AL_EXTENSIONS: %s\n", (char *) alGetString(AL_EXTENSIONS));
225     }
226
227     num_channels = maxsoftwarechannels;
228     impl_channels = new OPENAL_Channels[maxsoftwarechannels];
229     memset(impl_channels, '\0', sizeof (OPENAL_Channels) * num_channels);
230     for (int i = 0; i < num_channels; i++)
231         alGenSources(1, &impl_channels[i].sid);  // !!! FIXME: verify this didn't fail!
232
233     initialized = true;
234     return true;
235 }
236
237 AL_API void OPENAL_Close()
238 {
239     if (!initialized) return;
240
241     ALCcontext *ctx = alcGetCurrentContext();
242     if (ctx) {
243         for (int i = 0; i < num_channels; i++) {
244             alSourceStop(impl_channels[i].sid);
245             alSourcei(impl_channels[i].sid, AL_BUFFER, 0);
246             alDeleteSources(1, &impl_channels[i].sid);
247         }
248         ALCdevice *dev = alcGetContextsDevice(ctx);
249         alcMakeContextCurrent(NULL);
250         alcSuspendContext(ctx);
251         alcDestroyContext(ctx);
252         alcCloseDevice(dev);
253     }
254
255     num_channels = 0;
256     delete[] impl_channels;
257     impl_channels = NULL;
258
259     unload_alsyms();
260     initialized = false;
261 }
262
263 static OPENAL_SAMPLE *OPENAL_GetCurrentSample(int channel)
264 {
265     if (!initialized) return NULL;
266     if ((channel < 0) || (channel >= num_channels)) return NULL;
267     return impl_channels[channel].sample;
268 }
269
270 static signed char OPENAL_GetPaused(int channel)
271 {
272     if (!initialized) return false;
273     if ((channel < 0) || (channel >= num_channels)) return false;
274     if (impl_channels[channel].startpaused)
275         return(true);
276
277     ALint state = 0;
278     alGetSourceiv(impl_channels[channel].sid, AL_SOURCE_STATE, &state);
279     return((state == AL_PAUSED) ? true : false);
280 }
281
282 static unsigned int OPENAL_GetLoopMode(int channel)
283 {
284     if (!initialized) return 0;
285     if ((channel < 0) || (channel >= num_channels)) return 0;
286     ALint loop = 0;
287     alGetSourceiv(impl_channels[channel].sid, AL_LOOPING, &loop);
288     if (loop)
289         return(OPENAL_LOOP_NORMAL);
290     return OPENAL_LOOP_OFF;
291 }
292
293 static signed char OPENAL_IsPlaying(int channel)
294 {
295     if (!initialized) return false;
296     if ((channel < 0) || (channel >= num_channels)) return false;
297     ALint state = 0;
298     alGetSourceiv(impl_channels[channel].sid, AL_SOURCE_STATE, &state);
299     return((state == AL_PLAYING) ? true : false);
300 }
301
302 static int OPENAL_PlaySoundEx(int channel, OPENAL_SAMPLE *sptr, OPENAL_DSPUNIT *dsp, signed char startpaused)
303 {
304     if (!initialized) return -1;
305     if (sptr == NULL) return -1;
306     if (dsp != NULL) return -1;
307     if (channel == OPENAL_FREE) {
308         for (int i = 0; i < num_channels; i++) {
309             ALint state = 0;
310             alGetSourceiv(impl_channels[i].sid, AL_SOURCE_STATE, &state);
311             if ((state != AL_PLAYING) && (state != AL_PAUSED)) {
312                 channel = i;
313                 break;
314             }
315         }
316     }
317
318     if ((channel < 0) || (channel >= num_channels)) return -1;
319     alSourceStop(impl_channels[channel].sid);
320     impl_channels[channel].sample = sptr;
321     alSourcei(impl_channels[channel].sid, AL_BUFFER, sptr->bid);
322     alSourcei(impl_channels[channel].sid, AL_LOOPING, (sptr->mode == OPENAL_LOOP_OFF) ? AL_FALSE : AL_TRUE);
323     set_channel_position(channel, 0.0f, 0.0f, 0.0f);
324
325     impl_channels[channel].startpaused = ((startpaused) ? true : false);
326     if (!startpaused)
327         alSourcePlay(impl_channels[channel].sid);
328     return channel;
329 }
330
331
332 static void *decode_to_pcm(const char *_fname, ALenum &format, ALsizei &size, ALuint &freq)
333 {
334 #ifdef __POWERPC__
335     const int bigendian = 1;
336 #else
337     const int bigendian = 0;
338 #endif
339
340     // !!! FIXME: if it's not Ogg, we don't have a decoder. I'm lazy.  :/
341     char *fname = (char *) alloca(strlen(_fname) + 16);
342     strcpy(fname, _fname);
343     char *ptr = strchr(fname, '.');
344     if (ptr) *ptr = '\0';
345     strcat(fname, ".ogg");
346
347     // just in case...
348 #undef fopen
349     FILE *io = fopen(fname, "rb");
350     if (io == NULL)
351         return NULL;
352
353     ALubyte *retval = NULL;
354
355 #if 0  // untested, so disable this!
356     // Can we just feed it to the AL compressed?
357     if (alIsExtensionPresent((const ALubyte *) "AL_EXT_vorbis")) {
358         format = alGetEnumValue((const ALubyte *) "AL_FORMAT_VORBIS_EXT");
359         freq = 44100;
360         fseek(io, 0, SEEK_END);
361         size = ftell(io);
362         fseek(io, 0, SEEK_SET);
363         retval = (ALubyte *) malloc(size);
364         size_t rc = fread(retval, size, 1, io);
365         fclose(io);
366         if (rc != 1) {
367             free(retval);
368             return NULL;
369         }
370         return retval;
371     }
372 #endif
373
374     // Uncompress and feed to the AL.
375     OggVorbis_File vf;
376     memset(&vf, '\0', sizeof (vf));
377     if (ov_open(io, &vf, NULL, 0) == 0) {
378         int bitstream = 0;
379         vorbis_info *info = ov_info(&vf, -1);
380         size = 0;
381         format = (info->channels == 1) ? AL_FORMAT_MONO16 : AL_FORMAT_STEREO16;
382         freq = info->rate;
383
384         if ((info->channels != 1) && (info->channels != 2)) {
385             ov_clear(&vf);
386             return NULL;
387         }
388
389         char buf[1024 * 16];
390         long rc = 0;
391         size_t allocated = 64 * 1024;
392         retval = (ALubyte *) malloc(allocated);
393         while ( (rc = ov_read(&vf, buf, sizeof (buf), bigendian, 2, 1, &bitstream)) != 0 ) {
394             if (rc > 0) {
395                 size += rc;
396                 if (size >= allocated) {
397                     allocated *= 2;
398                     ALubyte *tmp = (ALubyte *) realloc(retval, allocated);
399                     if (tmp == NULL) {
400                         free(retval);
401                         retval = NULL;
402                         break;
403                     }
404                     retval = tmp;
405                 }
406                 memcpy(retval + (size - rc), buf, rc);
407             }
408         }
409         ov_clear(&vf);
410         return retval;
411     }
412
413     fclose(io);
414     return NULL;
415 }
416
417
418 AL_API OPENAL_SAMPLE *OPENAL_Sample_Load(int index, const char *name_or_data, unsigned int mode, int offset, int length)
419 {
420     if (!initialized) return NULL;
421     if (index != OPENAL_FREE) return NULL;  // this is all the game does...
422     if (offset != 0) return NULL;  // this is all the game does...
423     if (length != 0) return NULL;  // this is all the game does...
424     if ((mode != OPENAL_HW3D) && (mode != OPENAL_2D)) return NULL;  // this is all the game does...
425
426     OPENAL_SAMPLE *retval = NULL;
427     ALuint bufferName = 0;
428     ALenum format = AL_NONE;
429     ALsizei size = 0;
430     ALuint frequency = 0;
431     void *data = decode_to_pcm(name_or_data, format, size, frequency);
432     if (data == NULL)
433         return NULL;
434
435     ALuint bid = 0;
436     alGetError();
437     alGenBuffers(1, &bid);
438     if (alGetError() == AL_NO_ERROR) {
439         alBufferData(bid, format, data, size, frequency);
440         retval = new OPENAL_SAMPLE;
441         retval->bid = bid;
442         retval->mode = OPENAL_LOOP_OFF;
443         retval->is2d = (mode == OPENAL_2D);
444         retval->name = new char[strlen(name_or_data) + 1];
445         if (retval->name)
446             strcpy(retval->name, name_or_data);
447     }
448
449     free(data);
450     return(retval);
451 }
452
453 AL_API void OPENAL_Sample_Free(OPENAL_SAMPLE *sptr)
454 {
455     if (!initialized) return;
456     if (sptr) {
457         for (int i = 0; i < num_channels; i++) {
458             if (impl_channels[i].sample == sptr) {
459                 alSourceStop(impl_channels[i].sid);
460                 alSourcei(impl_channels[i].sid, AL_BUFFER, 0);
461                 impl_channels[i].sample = NULL;
462             }
463         }
464         alDeleteBuffers(1, &sptr->bid);
465         delete[] sptr->name;
466         delete sptr;
467     }
468 }
469
470 static signed char OPENAL_Sample_SetMode(OPENAL_SAMPLE *sptr, unsigned int mode)
471 {
472     if (!initialized) return false;
473     if ((mode != OPENAL_LOOP_NORMAL) && (mode != OPENAL_LOOP_OFF)) return false;
474     if (!sptr) return false;
475     sptr->mode = mode;
476     return true;
477 }
478
479 AL_API signed char OPENAL_SetFrequency(int channel, int freq)
480 {
481     if (!initialized) return false;
482     if (channel == OPENAL_ALL) {
483         for (int i = 0; i < num_channels; i++)
484             OPENAL_SetFrequency(i, freq);
485         return true;
486     }
487
488     if ((channel < 0) || (channel >= num_channels)) return false;
489     if (freq == 8012)  // hack
490         alSourcef(impl_channels[channel].sid, AL_PITCH, 8012.0f / 44100.0f);
491     else
492         alSourcef(impl_channels[channel].sid, AL_PITCH, 1.0f);
493     return true;
494 }
495
496 AL_API signed char OPENAL_SetVolume(int channel, int vol)
497 {
498     if (!initialized) return false;
499
500     if (channel == OPENAL_ALL) {
501         for (int i = 0; i < num_channels; i++)
502             OPENAL_SetVolume(i, vol);
503         return true;
504     }
505
506     if ((channel < 0) || (channel >= num_channels)) return false;
507
508     if (vol < 0) vol = 0;
509     else if (vol > 255) vol = 255;
510     ALfloat gain = ((ALfloat) vol) / 255.0f;
511     alSourcef(impl_channels[channel].sid, AL_GAIN, gain);
512     return true;
513 }
514
515 AL_API signed char OPENAL_SetPaused(int channel, signed char paused)
516 {
517     if (!initialized) return false;
518
519     if (channel == OPENAL_ALL) {
520         for (int i = 0; i < num_channels; i++)
521             OPENAL_SetPaused(i, paused);
522         return true;
523     }
524
525     if ((channel < 0) || (channel >= num_channels)) return false;
526
527     ALint state = 0;
528     if (impl_channels[channel].startpaused)
529         state = AL_PAUSED;
530     else
531         alGetSourceiv(impl_channels[channel].sid, AL_SOURCE_STATE, &state);
532
533     if ((paused) && (state == AL_PLAYING))
534         alSourcePause(impl_channels[channel].sid);
535     else if ((!paused) && (state == AL_PAUSED)) {
536         alSourcePlay(impl_channels[channel].sid);
537         impl_channels[channel].startpaused = false;
538     }
539     return true;
540 }
541
542 AL_API void OPENAL_SetSFXMasterVolume(int volume)
543 {
544     if (!initialized) return;
545     ALfloat gain = ((ALfloat) volume) / 255.0f;
546     alListenerf(AL_GAIN, gain);
547 }
548
549 AL_API signed char OPENAL_StopSound(int channel)
550 {
551     if (!initialized) return false;
552
553     if (channel == OPENAL_ALL) {
554         for (int i = 0; i < num_channels; i++)
555             OPENAL_StopSound(i);
556         return true;
557     }
558
559     if ((channel < 0) || (channel >= num_channels)) return false;
560     alSourceStop(impl_channels[channel].sid);
561     impl_channels[channel].startpaused = false;
562     return true;
563 }
564
565 AL_API void OPENAL_Stream_Close(OPENAL_STREAM *stream)
566 {
567     OPENAL_Sample_Free((OPENAL_SAMPLE *) stream);
568 }
569
570 static OPENAL_SAMPLE *OPENAL_Stream_GetSample(OPENAL_STREAM *stream)
571 {
572     if (!initialized) return NULL;
573     return (OPENAL_SAMPLE *) stream;
574 }
575
576 static int OPENAL_Stream_PlayEx(int channel, OPENAL_STREAM *stream, OPENAL_DSPUNIT *dsp, signed char startpaused)
577 {
578     return OPENAL_PlaySoundEx(channel, (OPENAL_SAMPLE *) stream, dsp, startpaused);
579 }
580
581 static signed char OPENAL_Stream_Stop(OPENAL_STREAM *stream)
582 {
583     if (!initialized) return false;
584     for (int i = 0; i < num_channels; i++) {
585         if (impl_channels[i].sample == (OPENAL_SAMPLE *) stream) {
586             alSourceStop(impl_channels[i].sid);
587             impl_channels[i].startpaused = false;
588         }
589     }
590     return true;
591 }
592
593 AL_API signed char OPENAL_Stream_SetMode(OPENAL_STREAM *stream, unsigned int mode)
594 {
595     return OPENAL_Sample_SetMode((OPENAL_SAMPLE *) stream, mode);
596 }
597
598 AL_API void OPENAL_Update()
599 {
600     if (!initialized) return;
601     alcProcessContext(alcGetCurrentContext());
602 }
603
604 AL_API signed char OPENAL_SetOutput(int outputtype)
605 {
606     return true;
607 }
608
609 extern int channels[];
610
611 extern "C" void PlaySoundEx(int chan, OPENAL_SAMPLE *sptr, OPENAL_DSPUNIT *dsp, signed char startpaused)
612 {
613     const OPENAL_SAMPLE * currSample = OPENAL_GetCurrentSample(channels[chan]);
614     if (currSample && currSample == samp[chan]) {
615         if (OPENAL_GetPaused(channels[chan])) {
616             OPENAL_StopSound(channels[chan]);
617             channels[chan] = OPENAL_FREE;
618         } else if (OPENAL_IsPlaying(channels[chan])) {
619             int loop_mode = OPENAL_GetLoopMode(channels[chan]);
620             if (loop_mode & OPENAL_LOOP_OFF) {
621                 channels[chan] = OPENAL_FREE;
622             }
623         }
624     } else {
625         channels[chan] = OPENAL_FREE;
626     }
627
628     channels[chan] = OPENAL_PlaySoundEx(channels[chan], sptr, dsp, startpaused);
629     if (channels[chan] < 0) {
630         channels[chan] = OPENAL_PlaySoundEx(OPENAL_FREE, sptr, dsp, startpaused);
631     }
632 }
633
634 extern "C" void PlayStreamEx(int chan, OPENAL_STREAM *sptr, OPENAL_DSPUNIT *dsp, signed char startpaused)
635 {
636     const OPENAL_SAMPLE * currSample = OPENAL_GetCurrentSample(channels[chan]);
637     if (currSample && currSample == OPENAL_Stream_GetSample(sptr)) {
638         OPENAL_StopSound(channels[chan]);
639         OPENAL_Stream_Stop(sptr);
640     } else {
641         OPENAL_Stream_Stop(sptr);
642         channels[chan] = OPENAL_FREE;
643     }
644
645     channels[chan] = OPENAL_Stream_PlayEx(channels[chan], sptr, dsp, startpaused);
646     if (channels[chan] < 0) {
647         channels[chan] = OPENAL_Stream_PlayEx(OPENAL_FREE, sptr, dsp, startpaused);
648     }
649 }
650
651 #endif
652