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