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