1 /*
2  * OpenAL Loopback Example
3  *
4  * Copyright (c) 2013 by Chris Robinson <chris.kcat@gmail.com>
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a copy
7  * of this software and associated documentation files (the "Software"), to deal
8  * in the Software without restriction, including without limitation the rights
9  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10  * copies of the Software, and to permit persons to whom the Software is
11  * furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included in
14  * all copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22  * THE SOFTWARE.
23  */
24 
25 /* This file contains an example for using the loopback device for custom
26  * output handling.
27  */
28 
29 #include <assert.h>
30 #include <math.h>
31 #include <stdio.h>
32 
33 #include "SDL.h"
34 #include "SDL_audio.h"
35 #include "SDL_error.h"
36 #include "SDL_stdinc.h"
37 
38 #include "AL/al.h"
39 #include "AL/alc.h"
40 #include "AL/alext.h"
41 
42 #include "common/alhelpers.h"
43 
44 #ifndef SDL_AUDIO_MASK_BITSIZE
45 #define SDL_AUDIO_MASK_BITSIZE (0xFF)
46 #endif
47 #ifndef SDL_AUDIO_BITSIZE
48 #define SDL_AUDIO_BITSIZE(x) (x & SDL_AUDIO_MASK_BITSIZE)
49 #endif
50 
51 #ifndef M_PI
52 #define M_PI    (3.14159265358979323846)
53 #endif
54 
55 typedef struct {
56     ALCdevice *Device;
57     ALCcontext *Context;
58 
59     ALCsizei FrameSize;
60 } PlaybackInfo;
61 
62 static LPALCLOOPBACKOPENDEVICESOFT alcLoopbackOpenDeviceSOFT;
63 static LPALCISRENDERFORMATSUPPORTEDSOFT alcIsRenderFormatSupportedSOFT;
64 static LPALCRENDERSAMPLESSOFT alcRenderSamplesSOFT;
65 
66 
RenderSDLSamples(void * userdata,Uint8 * stream,int len)67 void SDLCALL RenderSDLSamples(void *userdata, Uint8 *stream, int len)
68 {
69     PlaybackInfo *playback = (PlaybackInfo*)userdata;
70     alcRenderSamplesSOFT(playback->Device, stream, len/playback->FrameSize);
71 }
72 
73 
ChannelsName(ALCenum chans)74 static const char *ChannelsName(ALCenum chans)
75 {
76     switch(chans)
77     {
78     case ALC_MONO_SOFT: return "Mono";
79     case ALC_STEREO_SOFT: return "Stereo";
80     case ALC_QUAD_SOFT: return "Quadraphonic";
81     case ALC_5POINT1_SOFT: return "5.1 Surround";
82     case ALC_6POINT1_SOFT: return "6.1 Surround";
83     case ALC_7POINT1_SOFT: return "7.1 Surround";
84     }
85     return "Unknown Channels";
86 }
87 
TypeName(ALCenum type)88 static const char *TypeName(ALCenum type)
89 {
90     switch(type)
91     {
92     case ALC_BYTE_SOFT: return "S8";
93     case ALC_UNSIGNED_BYTE_SOFT: return "U8";
94     case ALC_SHORT_SOFT: return "S16";
95     case ALC_UNSIGNED_SHORT_SOFT: return "U16";
96     case ALC_INT_SOFT: return "S32";
97     case ALC_UNSIGNED_INT_SOFT: return "U32";
98     case ALC_FLOAT_SOFT: return "Float32";
99     }
100     return "Unknown Type";
101 }
102 
103 /* Creates a one second buffer containing a sine wave, and returns the new
104  * buffer ID. */
CreateSineWave(void)105 static ALuint CreateSineWave(void)
106 {
107     ALshort data[44100*4];
108     ALuint buffer;
109     ALenum err;
110     ALuint i;
111 
112     for(i = 0;i < 44100*4;i++)
113         data[i] = (ALshort)(sin(i/44100.0 * 1000.0 * 2.0*M_PI) * 32767.0);
114 
115     /* Buffer the audio data into a new buffer object. */
116     buffer = 0;
117     alGenBuffers(1, &buffer);
118     alBufferData(buffer, AL_FORMAT_MONO16, data, sizeof(data), 44100);
119 
120     /* Check if an error occured, and clean up if so. */
121     err = alGetError();
122     if(err != AL_NO_ERROR)
123     {
124         fprintf(stderr, "OpenAL Error: %s\n", alGetString(err));
125         if(alIsBuffer(buffer))
126             alDeleteBuffers(1, &buffer);
127         return 0;
128     }
129 
130     return buffer;
131 }
132 
133 
main(int argc,char * argv[])134 int main(int argc, char *argv[])
135 {
136     PlaybackInfo playback = { NULL, NULL, 0 };
137     SDL_AudioSpec desired, obtained;
138     ALuint source, buffer;
139     ALCint attrs[16];
140     ALenum state;
141     (void)argc;
142     (void)argv;
143 
144     /* Print out error if extension is missing. */
145     if(!alcIsExtensionPresent(NULL, "ALC_SOFT_loopback"))
146     {
147         fprintf(stderr, "Error: ALC_SOFT_loopback not supported!\n");
148         return 1;
149     }
150 
151     /* Define a macro to help load the function pointers. */
152 #define LOAD_PROC(T, x)  ((x) = (T)alcGetProcAddress(NULL, #x))
153     LOAD_PROC(LPALCLOOPBACKOPENDEVICESOFT, alcLoopbackOpenDeviceSOFT);
154     LOAD_PROC(LPALCISRENDERFORMATSUPPORTEDSOFT, alcIsRenderFormatSupportedSOFT);
155     LOAD_PROC(LPALCRENDERSAMPLESSOFT, alcRenderSamplesSOFT);
156 #undef LOAD_PROC
157 
158     if(SDL_Init(SDL_INIT_AUDIO) == -1)
159     {
160         fprintf(stderr, "Failed to init SDL audio: %s\n", SDL_GetError());
161         return 1;
162     }
163 
164     /* Set up SDL audio with our requested format and callback. */
165     desired.channels = 2;
166     desired.format = AUDIO_S16SYS;
167     desired.freq = 44100;
168     desired.padding = 0;
169     desired.samples = 4096;
170     desired.callback = RenderSDLSamples;
171     desired.userdata = &playback;
172     if(SDL_OpenAudio(&desired, &obtained) != 0)
173     {
174         SDL_Quit();
175         fprintf(stderr, "Failed to open SDL audio: %s\n", SDL_GetError());
176         return 1;
177     }
178 
179     /* Set up our OpenAL attributes based on what we got from SDL. */
180     attrs[0] = ALC_FORMAT_CHANNELS_SOFT;
181     if(obtained.channels == 1)
182         attrs[1] = ALC_MONO_SOFT;
183     else if(obtained.channels == 2)
184         attrs[1] = ALC_STEREO_SOFT;
185     else
186     {
187         fprintf(stderr, "Unhandled SDL channel count: %d\n", obtained.channels);
188         goto error;
189     }
190 
191     attrs[2] = ALC_FORMAT_TYPE_SOFT;
192     if(obtained.format == AUDIO_U8)
193         attrs[3] = ALC_UNSIGNED_BYTE_SOFT;
194     else if(obtained.format == AUDIO_S8)
195         attrs[3] = ALC_BYTE_SOFT;
196     else if(obtained.format == AUDIO_U16SYS)
197         attrs[3] = ALC_UNSIGNED_SHORT_SOFT;
198     else if(obtained.format == AUDIO_S16SYS)
199         attrs[3] = ALC_SHORT_SOFT;
200     else
201     {
202         fprintf(stderr, "Unhandled SDL format: 0x%04x\n", obtained.format);
203         goto error;
204     }
205 
206     attrs[4] = ALC_FREQUENCY;
207     attrs[5] = obtained.freq;
208 
209     attrs[6] = 0; /* end of list */
210 
211     playback.FrameSize = obtained.channels * SDL_AUDIO_BITSIZE(obtained.format) / 8;
212 
213     /* Initialize OpenAL loopback device, using our format attributes. */
214     playback.Device = alcLoopbackOpenDeviceSOFT(NULL);
215     if(!playback.Device)
216     {
217         fprintf(stderr, "Failed to open loopback device!\n");
218         goto error;
219     }
220     /* Make sure the format is supported before setting them on the device. */
221     if(alcIsRenderFormatSupportedSOFT(playback.Device, attrs[5], attrs[1], attrs[3]) == ALC_FALSE)
222     {
223         fprintf(stderr, "Render format not supported: %s, %s, %dhz\n",
224                         ChannelsName(attrs[1]), TypeName(attrs[3]), attrs[5]);
225         goto error;
226     }
227     playback.Context = alcCreateContext(playback.Device, attrs);
228     if(!playback.Context || alcMakeContextCurrent(playback.Context) == ALC_FALSE)
229     {
230         fprintf(stderr, "Failed to set an OpenAL audio context\n");
231         goto error;
232     }
233 
234     /* Start SDL playing. Our callback (thus alcRenderSamplesSOFT) will now
235      * start being called regularly to update the AL playback state. */
236     SDL_PauseAudio(0);
237 
238     /* Load the sound into a buffer. */
239     buffer = CreateSineWave();
240     if(!buffer)
241     {
242         SDL_CloseAudio();
243         alcDestroyContext(playback.Context);
244         alcCloseDevice(playback.Device);
245         SDL_Quit();
246         return 1;
247     }
248 
249     /* Create the source to play the sound with. */
250     source = 0;
251     alGenSources(1, &source);
252     alSourcei(source, AL_BUFFER, (ALint)buffer);
253     assert(alGetError()==AL_NO_ERROR && "Failed to setup sound source");
254 
255     /* Play the sound until it finishes. */
256     alSourcePlay(source);
257     do {
258         al_nssleep(10000000);
259         alGetSourcei(source, AL_SOURCE_STATE, &state);
260     } while(alGetError() == AL_NO_ERROR && state == AL_PLAYING);
261 
262     /* All done. Delete resources, and close OpenAL. */
263     alDeleteSources(1, &source);
264     alDeleteBuffers(1, &buffer);
265 
266     /* Stop SDL playing. */
267     SDL_PauseAudio(1);
268 
269     /* Close up OpenAL and SDL. */
270     SDL_CloseAudio();
271     alcDestroyContext(playback.Context);
272     alcCloseDevice(playback.Device);
273     SDL_Quit();
274 
275     return 0;
276 
277 error:
278     SDL_CloseAudio();
279     if(playback.Context)
280         alcDestroyContext(playback.Context);
281     if(playback.Device)
282         alcCloseDevice(playback.Device);
283     SDL_Quit();
284 
285     return 1;
286 }
287