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