]> git.jsancho.org Git - lugaru.git/blob - Source/openal_wrapper.cpp
0a3d9cb83707022e91132db4b1287ab88050e9ef
[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     ALenum format = AL_NONE;
379     ALsizei size = 0;
380     ALuint frequency = 0;
381     void *data = decode_to_pcm(name_or_data, format, size, frequency);
382     if (data == NULL)
383         return NULL;
384
385     ALuint bid = 0;
386     alGetError();
387     alGenBuffers(1, &bid);
388     if (alGetError() == AL_NO_ERROR) {
389         alBufferData(bid, format, data, size, frequency);
390         retval = new OPENAL_SAMPLE;
391         retval->bid = bid;
392         retval->mode = OPENAL_LOOP_OFF;
393         retval->is2d = (mode == OPENAL_2D);
394         retval->name = new char[strlen(name_or_data) + 1];
395         if (retval->name)
396             strcpy(retval->name, name_or_data);
397     }
398
399     free(data);
400     return(retval);
401 }
402
403 AL_API void OPENAL_Sample_Free(OPENAL_SAMPLE *sptr)
404 {
405     if (!initialized)
406         return;
407     if (sptr) {
408         for (int i = 0; i < num_channels; i++) {
409             if (impl_channels[i].sample == sptr) {
410                 alSourceStop(impl_channels[i].sid);
411                 alSourcei(impl_channels[i].sid, AL_BUFFER, 0);
412                 impl_channels[i].sample = NULL;
413             }
414         }
415         alDeleteBuffers(1, &sptr->bid);
416         delete[] sptr->name;
417         delete sptr;
418     }
419 }
420
421 static signed char OPENAL_Sample_SetMode(OPENAL_SAMPLE *sptr, unsigned int mode)
422 {
423     if (!initialized)
424         return false;
425     if ((mode != OPENAL_LOOP_NORMAL) && (mode != OPENAL_LOOP_OFF))
426         return false;
427     if (!sptr)
428         return false;
429     sptr->mode = mode;
430     return true;
431 }
432
433 AL_API signed char OPENAL_SetFrequency(int channel, int freq)
434 {
435     if (!initialized)
436         return false;
437     if (channel == OPENAL_ALL) {
438         for (int i = 0; i < num_channels; i++)
439             OPENAL_SetFrequency(i, freq);
440         return true;
441     }
442
443     if ((channel < 0) || (channel >= num_channels))
444         return false;
445     if (freq == 8012)
446         // hack
447         alSourcef(impl_channels[channel].sid, AL_PITCH, 8012.0f / 44100.0f);
448     else
449         alSourcef(impl_channels[channel].sid, AL_PITCH, 1.0f);
450     return true;
451 }
452
453 AL_API signed char OPENAL_SetVolume(int channel, int vol)
454 {
455     if (!initialized)
456         return false;
457
458     if (channel == OPENAL_ALL) {
459         for (int i = 0; i < num_channels; i++)
460             OPENAL_SetVolume(i, vol);
461         return true;
462     }
463
464     if ((channel < 0) || (channel >= num_channels))
465         return false;
466
467     if (vol < 0)
468         vol = 0;
469     else if (vol > 255)
470         vol = 255;
471     ALfloat gain = ((ALfloat) vol) / 255.0f;
472     alSourcef(impl_channels[channel].sid, AL_GAIN, gain);
473     return true;
474 }
475
476 AL_API signed char OPENAL_SetPaused(int channel, signed char paused)
477 {
478     if (!initialized)
479         return false;
480
481     if (channel == OPENAL_ALL) {
482         for (int i = 0; i < num_channels; i++)
483             OPENAL_SetPaused(i, paused);
484         return true;
485     }
486
487     if ((channel < 0) || (channel >= num_channels))
488         return false;
489
490     ALint state = 0;
491     if (impl_channels[channel].startpaused)
492         state = AL_PAUSED;
493     else
494         alGetSourceiv(impl_channels[channel].sid, AL_SOURCE_STATE, &state);
495
496     if ((paused) && (state == AL_PLAYING))
497         alSourcePause(impl_channels[channel].sid);
498     else if ((!paused) && (state == AL_PAUSED)) {
499         alSourcePlay(impl_channels[channel].sid);
500         impl_channels[channel].startpaused = false;
501     }
502     return true;
503 }
504
505 AL_API void OPENAL_SetSFXMasterVolume(int volume)
506 {
507     if (!initialized)
508         return;
509     ALfloat gain = ((ALfloat) volume) / 255.0f;
510     alListenerf(AL_GAIN, gain);
511 }
512
513 AL_API signed char OPENAL_StopSound(int channel)
514 {
515     if (!initialized)
516         return false;
517
518     if (channel == OPENAL_ALL) {
519         for (int i = 0; i < num_channels; i++)
520             OPENAL_StopSound(i);
521         return true;
522     }
523
524     if ((channel < 0) || (channel >= num_channels))
525         return false;
526     alSourceStop(impl_channels[channel].sid);
527     impl_channels[channel].startpaused = false;
528     return true;
529 }
530
531 static OPENAL_SAMPLE *OPENAL_Stream_GetSample(OPENAL_STREAM *stream)
532 {
533     if (!initialized)
534         return NULL;
535     return (OPENAL_SAMPLE *) stream;
536 }
537
538 static int OPENAL_Stream_PlayEx(int channel, OPENAL_STREAM *stream, OPENAL_DSPUNIT *dsp, signed char startpaused)
539 {
540     return OPENAL_PlaySoundEx(channel, (OPENAL_SAMPLE *) stream, dsp, startpaused);
541 }
542
543 static signed char OPENAL_Stream_Stop(OPENAL_STREAM *stream)
544 {
545     if (!initialized)
546         return false;
547     for (int i = 0; i < num_channels; i++) {
548         if (impl_channels[i].sample == (OPENAL_SAMPLE *) stream) {
549             alSourceStop(impl_channels[i].sid);
550             impl_channels[i].startpaused = false;
551         }
552     }
553     return true;
554 }
555
556 AL_API signed char OPENAL_Stream_SetMode(OPENAL_STREAM *stream, unsigned int mode)
557 {
558     return OPENAL_Sample_SetMode((OPENAL_SAMPLE *) stream, mode);
559 }
560
561 AL_API void OPENAL_Update()
562 {
563     if (!initialized)
564         return;
565     alcProcessContext(alcGetCurrentContext());
566 }
567
568 AL_API signed char OPENAL_SetOutput(int outputtype)
569 {
570     return true;
571 }
572
573 extern int channels[];
574
575 extern "C" void PlaySoundEx(int chan, OPENAL_SAMPLE *sptr, OPENAL_DSPUNIT *dsp, signed char startpaused)
576 {
577     const OPENAL_SAMPLE * currSample = OPENAL_GetCurrentSample(channels[chan]);
578     if (currSample && currSample == samp[chan]) {
579         if (OPENAL_GetPaused(channels[chan])) {
580             OPENAL_StopSound(channels[chan]);
581             channels[chan] = OPENAL_FREE;
582         } else if (OPENAL_IsPlaying(channels[chan])) {
583             int loop_mode = OPENAL_GetLoopMode(channels[chan]);
584             if (loop_mode & OPENAL_LOOP_OFF) {
585                 channels[chan] = OPENAL_FREE;
586             }
587         }
588     } else {
589         channels[chan] = OPENAL_FREE;
590     }
591
592     channels[chan] = OPENAL_PlaySoundEx(channels[chan], sptr, dsp, startpaused);
593     if (channels[chan] < 0) {
594         channels[chan] = OPENAL_PlaySoundEx(OPENAL_FREE, sptr, dsp, startpaused);
595     }
596 }
597
598 extern "C" void PlayStreamEx(int chan, OPENAL_STREAM *sptr, OPENAL_DSPUNIT *dsp, signed char startpaused)
599 {
600     const OPENAL_SAMPLE * currSample = OPENAL_GetCurrentSample(channels[chan]);
601     if (currSample && currSample == OPENAL_Stream_GetSample(sptr)) {
602         OPENAL_StopSound(channels[chan]);
603         OPENAL_Stream_Stop(sptr);
604     } else {
605         OPENAL_Stream_Stop(sptr);
606         channels[chan] = OPENAL_FREE;
607     }
608
609     channels[chan] = OPENAL_Stream_PlayEx(channels[chan], sptr, dsp, startpaused);
610     if (channels[chan] < 0) {
611         channels[chan] = OPENAL_Stream_PlayEx(OPENAL_FREE, sptr, dsp, startpaused);
612     }
613 }