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