]> git.jsancho.org Git - lugaru.git/blob - Source/Audio/openal_wrapper.cpp
Sorted all source files in folders
[lugaru.git] / Source / Audio / 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 "Math/Quaternions.h"
26 #include "Audio/openal_wrapper.h"
27 #include "Audio/Sounds.h"
28 #include "Game.h"
29
30 extern float slomofreq;
31
32 // NOTE:
33 // FMOD uses a Left Handed Coordinate system, OpenAL uses a Right Handed
34 //  one...so we just need to flip the sign on the Z axis when appropriate.
35
36 typedef struct {
37     ALuint sid;
38     OPENAL_SAMPLE *sample;
39     bool startpaused;
40     float position[3];
41 } OPENAL_Channels;
42
43 typedef struct OPENAL_SAMPLE {
44     char *name;
45     ALuint bid;  // buffer id.
46     int mode;
47     int is2d;
48 } OPENAL_SAMPLE;
49
50 static size_t num_channels = 0;
51 static OPENAL_Channels *impl_channels = NULL;
52 static bool initialized = false;
53 static float listener_position[3];
54
55 static void set_channel_position(const int channel, const float x,
56                                  const float y, const float z)
57 {
58     OPENAL_Channels *chan = &impl_channels[channel];
59
60     chan->position[0] = x;
61     chan->position[1] = y;
62     chan->position[2] = z;
63
64     OPENAL_SAMPLE *sptr = chan->sample;
65     if (sptr == NULL)
66         return;
67
68     const ALuint sid = chan->sid;
69     const bool no_attenuate = sptr->is2d;
70
71     if (no_attenuate) {
72         alSourcei(sid, AL_SOURCE_RELATIVE, AL_TRUE);
73         alSource3f(sid, AL_POSITION, 0.0f, 0.0f, 0.0f);
74     } else {
75         alSourcei(sid, AL_SOURCE_RELATIVE, AL_FALSE);
76         alSource3f(sid, AL_POSITION, x, y, z);
77     }
78 }
79
80
81 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)
82 {
83     if (!initialized)
84         return;
85     if (pos != NULL) {
86         alListener3f(AL_POSITION, pos[0], pos[1], -pos[2]);
87         listener_position[0] = pos[0];
88         listener_position[1] = pos[1];
89         listener_position[2] = -pos[2];
90     }
91
92     ALfloat vec[6] = { fx, fy, -fz, tz, ty, -tz };
93     alListenerfv(AL_ORIENTATION, vec);
94
95     // we ignore velocity, since doppler's broken in the Linux AL at the moment...
96
97     // adjust existing positions...
98     for (int i = 0; i < num_channels; i++) {
99         const float *p = impl_channels[i].position;
100         set_channel_position(i, p[0], p[1], p[2]);
101     }
102 }
103
104 AL_API signed char OPENAL_3D_SetAttributes(int channel, const float *pos, const float *vel)
105 {
106     if (!initialized)
107         return false;
108     if ((channel < 0) || (channel >= num_channels))
109         return false;
110
111     if (pos != NULL)
112         set_channel_position(channel, pos[0], pos[1], -pos[2]);
113
114     // we ignore velocity, since doppler's broken in the Linux AL at the moment...
115
116     return true;
117 }
118
119 AL_API signed char OPENAL_3D_SetAttributes_(int channel, const XYZ &pos, const float *vel)
120 {
121     if (!initialized)
122         return false;
123     if ((channel < 0) || (channel >= num_channels))
124         return false;
125
126     set_channel_position(channel, pos.x, pos.y, -pos.z);
127
128     return true;
129 }
130
131 AL_API signed char OPENAL_Init(int mixrate, int maxsoftwarechannels, unsigned int flags)
132 {
133     if (initialized)
134         return false;
135     if (maxsoftwarechannels == 0)
136         return false;
137
138     if (flags != 0)  // unsupported.
139         return false;
140
141     ALCdevice *dev = alcOpenDevice(NULL);
142     if (!dev)
143         return false;
144
145     ALint caps[] = { ALC_FREQUENCY, mixrate, 0 };
146     ALCcontext *ctx = alcCreateContext(dev, caps);
147     if (!ctx) {
148         alcCloseDevice(dev);
149         return false;
150     }
151
152     alcMakeContextCurrent(ctx);
153     alcProcessContext(ctx);
154
155     if (commandLineOptions[OPENALINFO]) {
156         printf("AL_VENDOR: %s\n", (char *) alGetString(AL_VENDOR));
157         printf("AL_RENDERER: %s\n", (char *) alGetString(AL_RENDERER));
158         printf("AL_VERSION: %s\n", (char *) alGetString(AL_VERSION));
159         printf("AL_EXTENSIONS: %s\n", (char *) alGetString(AL_EXTENSIONS));
160     }
161
162     num_channels = maxsoftwarechannels;
163     impl_channels = new OPENAL_Channels[maxsoftwarechannels];
164     memset(impl_channels, '\0', sizeof (OPENAL_Channels) * num_channels);
165     for (int i = 0; i < num_channels; i++)
166         alGenSources(1, &impl_channels[i].sid);  // !!! FIXME: verify this didn't fail!
167
168     initialized = true;
169     return true;
170 }
171
172 AL_API void OPENAL_Close()
173 {
174     if (!initialized)
175         return;
176
177     ALCcontext *ctx = alcGetCurrentContext();
178     if (ctx) {
179         for (int i = 0; i < num_channels; i++) {
180             alSourceStop(impl_channels[i].sid);
181             alSourcei(impl_channels[i].sid, AL_BUFFER, 0);
182             alDeleteSources(1, &impl_channels[i].sid);
183         }
184         ALCdevice *dev = alcGetContextsDevice(ctx);
185         alcMakeContextCurrent(NULL);
186         alcSuspendContext(ctx);
187         alcDestroyContext(ctx);
188         alcCloseDevice(dev);
189     }
190
191     num_channels = 0;
192     delete[] impl_channels;
193     impl_channels = NULL;
194
195     initialized = false;
196 }
197
198 static OPENAL_SAMPLE *OPENAL_GetCurrentSample(int channel)
199 {
200     if (!initialized)
201         return NULL;
202     if ((channel < 0) || (channel >= num_channels))
203         return NULL;
204     return impl_channels[channel].sample;
205 }
206
207 static signed char OPENAL_GetPaused(int channel)
208 {
209     if (!initialized)
210         return false;
211     if ((channel < 0) || (channel >= num_channels))
212         return false;
213     if (impl_channels[channel].startpaused)
214         return(true);
215
216     ALint state = 0;
217     alGetSourceiv(impl_channels[channel].sid, AL_SOURCE_STATE, &state);
218     return((state == AL_PAUSED) ? true : false);
219 }
220
221 static unsigned int OPENAL_GetLoopMode(int channel)
222 {
223     if (!initialized)
224         return 0;
225     if ((channel < 0) || (channel >= num_channels))
226         return 0;
227     ALint loop = 0;
228     alGetSourceiv(impl_channels[channel].sid, AL_LOOPING, &loop);
229     if (loop)
230         return(OPENAL_LOOP_NORMAL);
231     return OPENAL_LOOP_OFF;
232 }
233
234 static signed char OPENAL_IsPlaying(int channel)
235 {
236     if (!initialized)
237         return false;
238     if ((channel < 0) || (channel >= num_channels))
239         return false;
240     ALint state = 0;
241     alGetSourceiv(impl_channels[channel].sid, AL_SOURCE_STATE, &state);
242     return((state == AL_PLAYING) ? true : false);
243 }
244
245 static int OPENAL_PlaySoundEx(int channel, OPENAL_SAMPLE *sptr, OPENAL_DSPUNIT *dsp, signed char startpaused)
246 {
247     if (!initialized)
248         return -1;
249     if (sptr == NULL)
250         return -1;
251     if (dsp != NULL)
252         return -1;
253     if (channel == OPENAL_FREE) {
254         for (int i = 0; i < num_channels; i++) {
255             ALint state = 0;
256             alGetSourceiv(impl_channels[i].sid, AL_SOURCE_STATE, &state);
257             if ((state != AL_PLAYING) && (state != AL_PAUSED)) {
258                 channel = i;
259                 break;
260             }
261         }
262     }
263
264     if ((channel < 0) || (channel >= num_channels))
265         return -1;
266     alSourceStop(impl_channels[channel].sid);
267     impl_channels[channel].sample = sptr;
268     alSourcei(impl_channels[channel].sid, AL_BUFFER, sptr->bid);
269     alSourcei(impl_channels[channel].sid, AL_LOOPING, (sptr->mode == OPENAL_LOOP_OFF) ? AL_FALSE : AL_TRUE);
270     set_channel_position(channel, 0.0f, 0.0f, 0.0f);
271
272     impl_channels[channel].startpaused = ((startpaused) ? true : false);
273     if (!startpaused)
274         alSourcePlay(impl_channels[channel].sid);
275     return channel;
276 }
277
278
279 static void *decode_to_pcm(const char *_fname, ALenum &format, ALsizei &size, ALuint &freq)
280 {
281 #ifdef __POWERPC__
282     const int bigendian = 1;
283 #else
284     const int bigendian = 0;
285 #endif
286
287     // !!! FIXME: if it's not Ogg, we don't have a decoder. I'm lazy.  :/
288     char *fname = (char *) alloca(strlen(_fname) + 16);
289     strcpy(fname, _fname);
290     char *ptr = strchr(fname, '.');
291     if (ptr)
292         *ptr = '\0';
293     strcat(fname, ".ogg");
294
295     // just in case...
296     FILE *io = fopen(fname, "rb");
297     if (io == NULL)
298         return NULL;
299
300     ALubyte *retval = NULL;
301
302 #if 0  // untested, so disable this!
303     // Can we just feed it to the AL compressed?
304     if (alIsExtensionPresent((const ALubyte *) "AL_EXT_vorbis")) {
305         format = alGetEnumValue((const ALubyte *) "AL_FORMAT_VORBIS_EXT");
306         freq = 44100;
307         fseek(io, 0, SEEK_END);
308         size = ftell(io);
309         fseek(io, 0, SEEK_SET);
310         retval = (ALubyte *) malloc(size);
311         size_t rc = fread(retval, size, 1, io);
312         fclose(io);
313         if (rc != 1) {
314             free(retval);
315             return NULL;
316         }
317         return retval;
318     }
319 #endif
320
321     // Uncompress and feed to the AL.
322     OggVorbis_File vf;
323     memset(&vf, '\0', sizeof (vf));
324     if (ov_open(io, &vf, NULL, 0) == 0) {
325         int bitstream = 0;
326         vorbis_info *info = ov_info(&vf, -1);
327         size = 0;
328         format = (info->channels == 1) ? AL_FORMAT_MONO16 : AL_FORMAT_STEREO16;
329         freq = info->rate;
330
331         if ((info->channels != 1) && (info->channels != 2)) {
332             ov_clear(&vf);
333             return NULL;
334         }
335
336         char buf[1024 * 16];
337         long rc = 0;
338         size_t allocated = 64 * 1024;
339         retval = (ALubyte *) malloc(allocated);
340         while ( (rc = ov_read(&vf, buf, sizeof (buf), bigendian, 2, 1, &bitstream)) != 0 ) {
341             if (rc > 0) {
342                 size += rc;
343                 if (size >= allocated) {
344                     allocated *= 2;
345                     ALubyte *tmp = (ALubyte *) realloc(retval, allocated);
346                     if (tmp == NULL) {
347                         free(retval);
348                         retval = NULL;
349                         break;
350                     }
351                     retval = tmp;
352                 }
353                 memcpy(retval + (size - rc), buf, rc);
354             }
355         }
356         ov_clear(&vf);
357         return retval;
358     }
359
360     fclose(io);
361     return NULL;
362 }
363
364
365 AL_API OPENAL_SAMPLE *OPENAL_Sample_Load(int index, const char *name_or_data, unsigned int mode, int offset, int length)
366 {
367     if (!initialized)
368         return NULL;
369     if (index != OPENAL_FREE)
370         return NULL;  // this is all the game does...
371     if (offset != 0)
372         return NULL;  // this is all the game does...
373     if (length != 0)
374         return NULL;  // this is all the game does...
375     if ((mode != OPENAL_HW3D) && (mode != OPENAL_2D))
376         return NULL;  // this is all the game does...
377
378     OPENAL_SAMPLE *retval = NULL;
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, bool slomo)
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, slomo);
441         return true;
442     }
443
444     if ((channel < 0) || (channel >= num_channels))
445         return false;
446     if (slomo)
447         alSourcef(impl_channels[channel].sid, AL_PITCH, ((ALfloat) slomofreq) / 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 }