Replace a couple loops with algorithms
[openal-soft.git] / examples / alloopback.c
blob106d0d461ab15650728cd7c1944d6b258366c84a
1 /*
2 * OpenAL Loopback Example
4 * Copyright (c) 2013 by Chris Robinson <chris.kcat@gmail.com>
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:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
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.
25 /* This file contains an example for using the loopback device for custom
26 * output handling.
29 #include <assert.h>
30 #include <math.h>
31 #include <stdio.h>
32 #include <string.h>
34 #define SDL_MAIN_HANDLED
35 #include "SDL.h"
36 #include "SDL_audio.h"
37 #include "SDL_error.h"
38 #include "SDL_stdinc.h"
40 #include "AL/al.h"
41 #include "AL/alc.h"
42 #include "AL/alext.h"
44 #include "common/alhelpers.h"
46 #ifndef SDL_AUDIO_MASK_BITSIZE
47 #define SDL_AUDIO_MASK_BITSIZE (0xFF)
48 #endif
49 #ifndef SDL_AUDIO_BITSIZE
50 #define SDL_AUDIO_BITSIZE(x) (x & SDL_AUDIO_MASK_BITSIZE)
51 #endif
53 #ifndef M_PI
54 #define M_PI (3.14159265358979323846)
55 #endif
57 typedef struct {
58 ALCdevice *Device;
59 ALCcontext *Context;
61 ALCsizei FrameSize;
62 } PlaybackInfo;
64 static LPALCLOOPBACKOPENDEVICESOFT alcLoopbackOpenDeviceSOFT;
65 static LPALCISRENDERFORMATSUPPORTEDSOFT alcIsRenderFormatSupportedSOFT;
66 static LPALCRENDERSAMPLESSOFT alcRenderSamplesSOFT;
69 void SDLCALL RenderSDLSamples(void *userdata, Uint8 *stream, int len)
71 PlaybackInfo *playback = (PlaybackInfo*)userdata;
72 alcRenderSamplesSOFT(playback->Device, stream, len/playback->FrameSize);
76 static const char *ChannelsName(ALCenum chans)
78 switch(chans)
80 case ALC_MONO_SOFT: return "Mono";
81 case ALC_STEREO_SOFT: return "Stereo";
82 case ALC_QUAD_SOFT: return "Quadraphonic";
83 case ALC_5POINT1_SOFT: return "5.1 Surround";
84 case ALC_6POINT1_SOFT: return "6.1 Surround";
85 case ALC_7POINT1_SOFT: return "7.1 Surround";
87 return "Unknown Channels";
90 static const char *TypeName(ALCenum type)
92 switch(type)
94 case ALC_BYTE_SOFT: return "S8";
95 case ALC_UNSIGNED_BYTE_SOFT: return "U8";
96 case ALC_SHORT_SOFT: return "S16";
97 case ALC_UNSIGNED_SHORT_SOFT: return "U16";
98 case ALC_INT_SOFT: return "S32";
99 case ALC_UNSIGNED_INT_SOFT: return "U32";
100 case ALC_FLOAT_SOFT: return "Float32";
102 return "Unknown Type";
105 /* Creates a one second buffer containing a sine wave, and returns the new
106 * buffer ID. */
107 static ALuint CreateSineWave(void)
109 ALshort data[44100*4];
110 ALuint buffer;
111 ALenum err;
112 ALuint i;
114 for(i = 0;i < 44100*4;i++)
115 data[i] = (ALshort)(sin(i/44100.0 * 1000.0 * 2.0*M_PI) * 32767.0);
117 /* Buffer the audio data into a new buffer object. */
118 buffer = 0;
119 alGenBuffers(1, &buffer);
120 alBufferData(buffer, AL_FORMAT_MONO16, data, sizeof(data), 44100);
122 /* Check if an error occurred, and clean up if so. */
123 err = alGetError();
124 if(err != AL_NO_ERROR)
126 fprintf(stderr, "OpenAL Error: %s\n", alGetString(err));
127 if(alIsBuffer(buffer))
128 alDeleteBuffers(1, &buffer);
129 return 0;
132 return buffer;
136 int main(int argc, char *argv[])
138 PlaybackInfo playback = { NULL, NULL, 0 };
139 SDL_AudioSpec desired, obtained;
140 ALuint source, buffer;
141 ALCint attrs[16];
142 ALenum state;
143 (void)argc;
144 (void)argv;
146 SDL_SetMainReady();
148 /* Print out error if extension is missing. */
149 if(!alcIsExtensionPresent(NULL, "ALC_SOFT_loopback"))
151 fprintf(stderr, "Error: ALC_SOFT_loopback not supported!\n");
152 return 1;
155 /* Define a macro to help load the function pointers. */
156 #define LOAD_PROC(T, x) ((x) = FUNCTION_CAST(T, alcGetProcAddress(NULL, #x)))
157 LOAD_PROC(LPALCLOOPBACKOPENDEVICESOFT, alcLoopbackOpenDeviceSOFT);
158 LOAD_PROC(LPALCISRENDERFORMATSUPPORTEDSOFT, alcIsRenderFormatSupportedSOFT);
159 LOAD_PROC(LPALCRENDERSAMPLESSOFT, alcRenderSamplesSOFT);
160 #undef LOAD_PROC
162 if(SDL_Init(SDL_INIT_AUDIO) == -1)
164 fprintf(stderr, "Failed to init SDL audio: %s\n", SDL_GetError());
165 return 1;
168 /* Set up SDL audio with our requested format and callback. */
169 desired.channels = 2;
170 desired.format = AUDIO_S16SYS;
171 desired.freq = 44100;
172 desired.padding = 0;
173 desired.samples = 4096;
174 desired.callback = RenderSDLSamples;
175 desired.userdata = &playback;
176 if(SDL_OpenAudio(&desired, &obtained) != 0)
178 SDL_Quit();
179 fprintf(stderr, "Failed to open SDL audio: %s\n", SDL_GetError());
180 return 1;
183 /* Set up our OpenAL attributes based on what we got from SDL. */
184 attrs[0] = ALC_FORMAT_CHANNELS_SOFT;
185 if(obtained.channels == 1)
186 attrs[1] = ALC_MONO_SOFT;
187 else if(obtained.channels == 2)
188 attrs[1] = ALC_STEREO_SOFT;
189 else
191 fprintf(stderr, "Unhandled SDL channel count: %d\n", obtained.channels);
192 goto error;
195 attrs[2] = ALC_FORMAT_TYPE_SOFT;
196 if(obtained.format == AUDIO_U8)
197 attrs[3] = ALC_UNSIGNED_BYTE_SOFT;
198 else if(obtained.format == AUDIO_S8)
199 attrs[3] = ALC_BYTE_SOFT;
200 else if(obtained.format == AUDIO_U16SYS)
201 attrs[3] = ALC_UNSIGNED_SHORT_SOFT;
202 else if(obtained.format == AUDIO_S16SYS)
203 attrs[3] = ALC_SHORT_SOFT;
204 else if(obtained.format == AUDIO_S32SYS)
205 attrs[3] = ALC_INT_SOFT;
206 else if(obtained.format == AUDIO_F32SYS)
207 attrs[3] = ALC_FLOAT_SOFT;
208 else
210 fprintf(stderr, "Unhandled SDL format: 0x%04x\n", obtained.format);
211 goto error;
214 attrs[4] = ALC_FREQUENCY;
215 attrs[5] = obtained.freq;
217 attrs[6] = 0; /* end of list */
219 playback.FrameSize = obtained.channels * SDL_AUDIO_BITSIZE(obtained.format) / 8;
221 /* Initialize OpenAL loopback device, using our format attributes. */
222 playback.Device = alcLoopbackOpenDeviceSOFT(NULL);
223 if(!playback.Device)
225 fprintf(stderr, "Failed to open loopback device!\n");
226 goto error;
228 /* Make sure the format is supported before setting them on the device. */
229 if(alcIsRenderFormatSupportedSOFT(playback.Device, attrs[5], attrs[1], attrs[3]) == ALC_FALSE)
231 fprintf(stderr, "Render format not supported: %s, %s, %dhz\n",
232 ChannelsName(attrs[1]), TypeName(attrs[3]), attrs[5]);
233 goto error;
235 playback.Context = alcCreateContext(playback.Device, attrs);
236 if(!playback.Context || alcMakeContextCurrent(playback.Context) == ALC_FALSE)
238 fprintf(stderr, "Failed to set an OpenAL audio context\n");
239 goto error;
242 /* Start SDL playing. Our callback (thus alcRenderSamplesSOFT) will now
243 * start being called regularly to update the AL playback state. */
244 SDL_PauseAudio(0);
246 /* Load the sound into a buffer. */
247 buffer = CreateSineWave();
248 if(!buffer)
250 SDL_CloseAudio();
251 alcDestroyContext(playback.Context);
252 alcCloseDevice(playback.Device);
253 SDL_Quit();
254 return 1;
257 /* Create the source to play the sound with. */
258 source = 0;
259 alGenSources(1, &source);
260 alSourcei(source, AL_BUFFER, (ALint)buffer);
261 assert(alGetError()==AL_NO_ERROR && "Failed to setup sound source");
263 /* Play the sound until it finishes. */
264 alSourcePlay(source);
265 do {
266 al_nssleep(10000000);
267 alGetSourcei(source, AL_SOURCE_STATE, &state);
268 } while(alGetError() == AL_NO_ERROR && state == AL_PLAYING);
270 /* All done. Delete resources, and close OpenAL. */
271 alDeleteSources(1, &source);
272 alDeleteBuffers(1, &buffer);
274 /* Stop SDL playing. */
275 SDL_PauseAudio(1);
277 /* Close up OpenAL and SDL. */
278 SDL_CloseAudio();
279 alcDestroyContext(playback.Context);
280 alcCloseDevice(playback.Device);
281 SDL_Quit();
283 return 0;
285 error:
286 SDL_CloseAudio();
287 if(playback.Context)
288 alcDestroyContext(playback.Context);
289 if(playback.Device)
290 alcCloseDevice(playback.Device);
291 SDL_Quit();
293 return 1;