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