2 Copyright (C) 2003, 2010 - Wolfire Games
4 This file is part of Lugaru.
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.
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.
15 See the GNU General Public License for more details.
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.
28 #include "openal_wrapper.h"
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.
34 #define DYNAMIC_LOAD_OPENAL 0
36 #if DYNAMIC_LOAD_OPENAL
40 #define AL_FUNC(t,ret,fn,params,call,rt) \
42 static ret ALAPIENTRY (*p##fn) params = NULL; \
43 ret ALAPIENTRY fn params { rt p##fn call; } \
48 static void *aldlhandle = NULL;
50 static bool lookup_alsym(const char *funcname, void **func, const char *libname)
55 *func = dlsym(aldlhandle, funcname);
58 fprintf(stderr, "Failed to find OpenAL symbol \"%s\" in \"%s\"\n",
65 static void unload_alsyms(void)
67 #define AL_FUNC(t,ret,fn,params,call,rt) p##fn = NULL;
77 static bool lookup_all_alsyms(const char *libname)
81 if ( (aldlhandle = dlopen(libname, RTLD_GLOBAL | RTLD_NOW)) == NULL )
86 #define AL_FUNC(t,ret,fn,params,call,rt) \
87 if (!lookup_alsym(#fn, (void **) &p##fn, libname)) retval = false;
97 #define lookup_all_alsyms(x) (true)
98 #define unload_alsyms()
104 OPENAL_SAMPLE *sample;
109 typedef struct OPENAL_SAMPLE
112 ALuint bid; // buffer id.
118 typedef struct OPENAL_STREAM
121 ALuint bid; // buffer id.
126 static size_t num_channels = 0;
127 static OPENAL_Channels *channels = NULL;
128 static bool initialized = false;
129 static float listener_position[3];
131 static inline bool source_too_close(const int channel)
133 const OPENAL_Channels *chan = &channels[channel];
134 const float *pos = chan->position;
135 const float distance = sqrtf(powf((pos[0] - listener_position[0]), 2.0f) +
136 powf((pos[1] - listener_position[1]), 2.0f) +
137 powf((pos[2] - listener_position[2]), 2.0f));
138 return (distance <= chan->sample->min_distance);
142 static void set_channel_position(const int channel, const float x,
143 const float y, const float z)
145 OPENAL_Channels *chan = &channels[channel];
147 chan->position[0] = x;
148 chan->position[1] = y;
149 chan->position[2] = z;
151 OPENAL_SAMPLE *sptr = chan->sample;
155 const ALuint sid = chan->sid;
156 const bool no_attenuate = ((sptr->is2d) || (source_too_close(channel)));
160 alSourcei(sid, AL_SOURCE_RELATIVE, AL_TRUE);
161 alSource3f(sid, AL_POSITION, 0.0f, 0.0f, 0.0f);
165 alSourcei(sid, AL_SOURCE_RELATIVE, AL_FALSE);
166 alSource3f(sid, AL_POSITION, x, y, z);
171 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)
173 if (!initialized) return;
176 alListener3f(AL_POSITION, pos[0], pos[1], -pos[2]);
177 listener_position[0] = pos[0];
178 listener_position[1] = pos[1];
179 listener_position[2] = -pos[2];
182 ALfloat vec[6] = { fx, fy, -fz, tz, ty, -tz };
183 alListenerfv(AL_ORIENTATION, vec);
185 // we ignore velocity, since doppler's broken in the Linux AL at the moment...
187 // adjust existing positions...
188 for (int i = 0; i < num_channels; i++)
190 const float *p = channels[i].position;
191 set_channel_position(i, p[0], p[1], p[2]);
195 AL_API signed char OPENAL_3D_SetAttributes(int channel, const float *pos, const float *vel)
197 if (!initialized) return false;
198 if ((channel < 0) || (channel >= num_channels)) return false;
201 set_channel_position(channel, pos[0], pos[1], -pos[2]);
203 // we ignore velocity, since doppler's broken in the Linux AL at the moment...
208 AL_API void OPENAL_3D_SetDopplerFactor(float scale)
210 if (!initialized) return;
211 // unimplemented...looks like init routines just call this with scale == 0.0f anyhow.
214 AL_API signed char OPENAL_Init(int mixrate, int maxsoftwarechannels, unsigned int flags)
216 if (initialized) return false;
217 if (maxsoftwarechannels == 0) return false;
219 if (flags != 0) // unsupported.
222 if (!lookup_all_alsyms("./openal.so")) // !!! FIXME: linux specific lib name
224 if (!lookup_all_alsyms("openal.so.1")) // !!! FIXME: linux specific lib name
226 if (!lookup_all_alsyms("openal.so")) // !!! FIXME: linux specific lib name
231 ALCdevice *dev = alcOpenDevice(NULL);
235 ALint caps[] = { ALC_FREQUENCY, mixrate, 0 };
236 ALCcontext *ctx = alcCreateContext(dev, caps);
243 alcMakeContextCurrent(ctx);
244 alcProcessContext(ctx);
246 bool cmdline(const char *cmd);
247 if (cmdline("openalinfo"))
249 printf("AL_VENDOR: %s\n", (char *) alGetString(AL_VENDOR));
250 printf("AL_RENDERER: %s\n", (char *) alGetString(AL_RENDERER));
251 printf("AL_VERSION: %s\n", (char *) alGetString(AL_VERSION));
252 printf("AL_EXTENSIONS: %s\n", (char *) alGetString(AL_EXTENSIONS));
255 num_channels = maxsoftwarechannels;
256 channels = new OPENAL_Channels[maxsoftwarechannels];
257 memset(channels, '\0', sizeof (OPENAL_Channels) * num_channels);
258 for (int i = 0; i < num_channels; i++)
259 alGenSources(1, &channels[i].sid); // !!! FIXME: verify this didn't fail!
265 AL_API void OPENAL_Close()
267 if (!initialized) return;
269 ALCcontext *ctx = alcGetCurrentContext();
272 for (int i = 0; i < num_channels; i++)
274 alSourceStop(channels[i].sid);
275 alSourcei(channels[i].sid, AL_BUFFER, 0);
276 alDeleteSources(1, &channels[i].sid);
278 ALCdevice *dev = alcGetContextsDevice(ctx);
279 alcMakeContextCurrent(NULL);
280 alcSuspendContext(ctx);
281 alcDestroyContext(ctx);
293 AL_API OPENAL_SAMPLE *OPENAL_GetCurrentSample(int channel)
295 if (!initialized) return NULL;
296 if ((channel < 0) || (channel >= num_channels)) return NULL;
297 return channels[channel].sample;
300 AL_API signed char OPENAL_GetPaused(int channel)
302 if (!initialized) return false;
303 if ((channel < 0) || (channel >= num_channels)) return false;
304 if (channels[channel].startpaused)
308 alGetSourceiv(channels[channel].sid, AL_SOURCE_STATE, &state);
309 return((state == AL_PAUSED) ? true : false);
312 AL_API unsigned int OPENAL_GetLoopMode(int channel)
314 if (!initialized) return 0;
315 if ((channel < 0) || (channel >= num_channels)) return 0;
317 alGetSourceiv(channels[channel].sid, AL_LOOPING, &loop);
319 return(OPENAL_LOOP_NORMAL);
320 return OPENAL_LOOP_OFF;
323 AL_API signed char OPENAL_IsPlaying(int channel)
325 if (!initialized) return false;
326 if ((channel < 0) || (channel >= num_channels)) return false;
328 alGetSourceiv(channels[channel].sid, AL_SOURCE_STATE, &state);
329 return((state == AL_PLAYING) ? true : false);
332 AL_API int OPENAL_PlaySoundEx(int channel, OPENAL_SAMPLE *sptr, OPENAL_DSPUNIT *dsp, signed char startpaused)
334 if (!initialized) return -1;
335 if (sptr == NULL) return -1;
336 if (dsp != NULL) return -1;
337 if (channel == OPENAL_FREE)
339 for (int i = 0; i < num_channels; i++)
342 alGetSourceiv(channels[i].sid, AL_SOURCE_STATE, &state);
343 if ((state != AL_PLAYING) && (state != AL_PAUSED))
351 if ((channel < 0) || (channel >= num_channels)) return -1;
352 alSourceStop(channels[channel].sid);
353 channels[channel].sample = sptr;
354 alSourcei(channels[channel].sid, AL_BUFFER, sptr->bid);
355 alSourcei(channels[channel].sid, AL_LOOPING, (sptr->mode == OPENAL_LOOP_OFF) ? AL_FALSE : AL_TRUE);
356 set_channel_position(channel, 0.0f, 0.0f, 0.0f);
358 channels[channel].startpaused = ((startpaused) ? true : false);
360 alSourcePlay(channels[channel].sid);
365 static void *decode_to_pcm(const char *_fname, ALenum &format, ALsizei &size, ALuint &freq)
368 const int bigendian = 1;
370 const int bigendian = 0;
373 // !!! FIXME: if it's not Ogg, we don't have a decoder. I'm lazy. :/
374 char *fname = (char *) alloca(strlen(_fname) + 16);
375 strcpy(fname, _fname);
376 char *ptr = strchr(fname, '.');
377 if (ptr) *ptr = NULL;
378 strcat(fname, ".ogg");
382 FILE *io = fopen(fname, "rb");
386 ALubyte *retval = NULL;
388 #if 0 // untested, so disable this!
389 // Can we just feed it to the AL compressed?
390 if (alIsExtensionPresent((const ALubyte *) "AL_EXT_vorbis"))
392 format = alGetEnumValue((const ALubyte *) "AL_FORMAT_VORBIS_EXT");
394 fseek(io, 0, SEEK_END);
396 fseek(io, 0, SEEK_SET);
397 retval = (ALubyte *) malloc(size);
398 size_t rc = fread(retval, size, 1, io);
409 // Uncompress and feed to the AL.
411 memset(&vf, '\0', sizeof (vf));
412 if (ov_open(io, &vf, NULL, 0) == 0)
415 vorbis_info *info = ov_info(&vf, -1);
417 format = (info->channels == 1) ? AL_FORMAT_MONO16 : AL_FORMAT_STEREO16;
420 if ((info->channels != 1) && (info->channels != 2))
428 size_t allocated = 64 * 1024;
429 retval = (ALubyte *) malloc(allocated);
430 while ( (rc = ov_read(&vf, buf, sizeof (buf), bigendian, 2, 1, &bitstream)) != 0 )
435 if (size >= allocated)
438 ALubyte *tmp = (ALubyte *) realloc(retval, allocated);
447 memcpy(retval + (size - rc), buf, rc);
459 AL_API OPENAL_SAMPLE *OPENAL_Sample_Load(int index, const char *name_or_data, unsigned int mode, int offset, int length)
461 if (!initialized) return NULL;
462 if (index != OPENAL_FREE) return NULL; // this is all the game does...
463 if (offset != 0) return NULL; // this is all the game does...
464 if (length != 0) return NULL; // this is all the game does...
465 if ((mode != OPENAL_HW3D) && (mode != OPENAL_2D)) return NULL; // this is all the game does...
467 OPENAL_SAMPLE *retval = NULL;
468 ALuint bufferName = 0;
469 ALenum format = AL_NONE;
471 ALuint frequency = 0;
472 void *data = decode_to_pcm(name_or_data, format, size, frequency);
478 alGenBuffers(1, &bid);
479 if (alGetError() == AL_NO_ERROR)
481 alBufferData(bid, format, data, size, frequency);
482 retval = new OPENAL_SAMPLE;
484 retval->mode = OPENAL_LOOP_OFF;
485 retval->is2d = (mode == OPENAL_2D);
486 retval->name = new char[strlen(name_or_data) + 1];
488 strcpy(retval->name, name_or_data);
495 AL_API void OPENAL_Sample_Free(OPENAL_SAMPLE *sptr)
497 if (!initialized) return;
500 for (int i = 0; i < num_channels; i++)
502 if (channels[i].sample == sptr)
504 alSourceStop(channels[i].sid);
505 alSourcei(channels[i].sid, AL_BUFFER, 0);
506 channels[i].sample = NULL;
509 alDeleteBuffers(1, &sptr->bid);
515 AL_API signed char OPENAL_Sample_SetMode(OPENAL_SAMPLE *sptr, unsigned int mode)
517 if (!initialized) return false;
518 if ((mode != OPENAL_LOOP_NORMAL) && (mode != OPENAL_LOOP_OFF)) return false;
519 if (!sptr) return false;
524 AL_API signed char OPENAL_Sample_SetMinMaxDistance(OPENAL_SAMPLE *sptr, float mindist, float maxdist)
526 if (!initialized) return false;
527 if (sptr == NULL) return false;
528 sptr->min_distance = mindist;
529 // we ignore maxdist. It's not really important to this game, and the
530 // FMOD docs suggest that it's worthless anyhow.
532 // recalc sources to see if we need to adjust attenuation.
533 for (int i = 0; i < num_channels; i++)
535 if (channels[i].sample == sptr)
537 const float *p = channels[i].position;
538 set_channel_position(i, p[0], p[1], p[2]);
545 AL_API signed char OPENAL_SetFrequency(int channel, int freq)
547 if (!initialized) return false;
548 if (channel == OPENAL_ALL)
550 for (int i = 0; i < num_channels; i++)
551 OPENAL_SetFrequency(i, freq);
555 if ((channel < 0) || (channel >= num_channels)) return false;
556 if (freq == 8012) // hack
557 alSourcef(channels[channel].sid, AL_PITCH, 8012.0f / 44100.0f);
559 alSourcef(channels[channel].sid, AL_PITCH, 1.0f);
563 AL_API signed char OPENAL_SetVolume(int channel, int vol)
565 if (!initialized) return false;
567 if (channel == OPENAL_ALL)
569 for (int i = 0; i < num_channels; i++)
570 OPENAL_SetVolume(i, vol);
574 if ((channel < 0) || (channel >= num_channels)) return false;
576 if (vol < 0) vol = 0;
577 else if (vol > 255) vol = 255;
578 ALfloat gain = ((ALfloat) vol) / 255.0f;
579 alSourcef(channels[channel].sid, AL_GAIN, gain);
583 AL_API signed char OPENAL_SetPaused(int channel, signed char paused)
585 if (!initialized) return false;
587 if (channel == OPENAL_ALL)
589 for (int i = 0; i < num_channels; i++)
590 OPENAL_SetPaused(i, paused);
594 if ((channel < 0) || (channel >= num_channels)) return false;
597 if (channels[channel].startpaused)
600 alGetSourceiv(channels[channel].sid, AL_SOURCE_STATE, &state);
602 if ((paused) && (state == AL_PLAYING))
603 alSourcePause(channels[channel].sid);
604 else if ((!paused) && (state == AL_PAUSED))
606 alSourcePlay(channels[channel].sid);
607 channels[channel].startpaused = false;
612 AL_API void OPENAL_SetSFXMasterVolume(int volume)
614 if (!initialized) return;
615 ALfloat gain = ((ALfloat) volume) / 255.0f;
616 alListenerf(AL_GAIN, gain);
619 AL_API signed char OPENAL_StopSound(int channel)
621 if (!initialized) return false;
623 if (channel == OPENAL_ALL)
625 for (int i = 0; i < num_channels; i++)
630 if ((channel < 0) || (channel >= num_channels)) return false;
631 alSourceStop(channels[channel].sid);
632 channels[channel].startpaused = false;
636 AL_API OPENAL_STREAM *OPENAL_Stream_Open(const char *name_or_data, unsigned int mode, int offset, int length)
638 return (OPENAL_STREAM *) OPENAL_Sample_Load(OPENAL_FREE, name_or_data, mode, offset, length);
641 AL_API signed char OPENAL_Stream_Close(OPENAL_STREAM *stream)
643 OPENAL_Sample_Free((OPENAL_SAMPLE *) stream);
646 AL_API OPENAL_SAMPLE *OPENAL_Stream_GetSample(OPENAL_STREAM *stream)
648 if (!initialized) return NULL;
649 return (OPENAL_SAMPLE *) stream;
652 AL_API int OPENAL_Stream_PlayEx(int channel, OPENAL_STREAM *stream, OPENAL_DSPUNIT *dsp, signed char startpaused)
654 return OPENAL_PlaySoundEx(channel, (OPENAL_SAMPLE *) stream, dsp, startpaused);
657 AL_API signed char OPENAL_Stream_Stop(OPENAL_STREAM *stream)
659 if (!initialized) return false;
660 for (int i = 0; i < num_channels; i++)
662 if (channels[i].sample == (OPENAL_SAMPLE *) stream)
664 alSourceStop(channels[i].sid);
665 channels[i].startpaused = false;
671 AL_API signed char OPENAL_Stream_SetMode(OPENAL_STREAM *stream, unsigned int mode)
673 return OPENAL_Sample_SetMode((OPENAL_SAMPLE *) stream, mode);
676 AL_API void OPENAL_Update()
678 if (!initialized) return;
679 alcProcessContext(alcGetCurrentContext());
682 AL_API signed char OPENAL_SetOutput(int outputtype)