Avoid duplicating code using a macro
[openal-soft.git] / examples / alhrtf.c
blob3964a7c689fa4180ded638f969801fe86a878d47
1 /*
2 * OpenAL HRTF Example
4 * Copyright (c) 2015 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 selecting an HRTF. */
27 #include <stdio.h>
28 #include <assert.h>
29 #include <math.h>
31 #include "AL/al.h"
32 #include "AL/alc.h"
33 #include "AL/alext.h"
35 #include "common/alhelpers.h"
36 #include "common/sdl_sound.h"
39 #ifndef M_PI
40 #define M_PI (3.14159265358979323846)
41 #endif
43 static LPALCGETSTRINGISOFT alcGetStringiSOFT;
44 static LPALCRESETDEVICESOFT alcResetDeviceSOFT;
46 /* LoadBuffer loads the named audio file into an OpenAL buffer object, and
47 * returns the new buffer ID. */
48 static ALuint LoadSound(const char *filename)
50 ALenum err, format, type, channels;
51 ALuint rate, buffer;
52 size_t datalen;
53 void *data;
54 FilePtr sound;
56 /* Open the audio file */
57 sound = openAudioFile(filename, 1000);
58 if(!sound)
60 fprintf(stderr, "Could not open audio in %s\n", filename);
61 closeAudioFile(sound);
62 return 0;
65 /* Get the sound format, and figure out the OpenAL format */
66 if(getAudioInfo(sound, &rate, &channels, &type) != 0)
68 fprintf(stderr, "Error getting audio info for %s\n", filename);
69 closeAudioFile(sound);
70 return 0;
73 format = GetFormat(channels, type, NULL);
74 if(format == AL_NONE)
76 fprintf(stderr, "Unsupported format (%s, %s) for %s\n",
77 ChannelsName(channels), TypeName(type), filename);
78 closeAudioFile(sound);
79 return 0;
82 /* Decode the whole audio stream to a buffer. */
83 data = decodeAudioStream(sound, &datalen);
84 if(!data)
86 fprintf(stderr, "Failed to read audio from %s\n", filename);
87 closeAudioFile(sound);
88 return 0;
91 /* Buffer the audio data into a new buffer object, then free the data and
92 * close the file. */
93 buffer = 0;
94 alGenBuffers(1, &buffer);
95 alBufferData(buffer, format, data, datalen, rate);
96 free(data);
97 closeAudioFile(sound);
99 /* Check if an error occured, and clean up if so. */
100 err = alGetError();
101 if(err != AL_NO_ERROR)
103 fprintf(stderr, "OpenAL Error: %s\n", alGetString(err));
104 if(buffer && alIsBuffer(buffer))
105 alDeleteBuffers(1, &buffer);
106 return 0;
109 return buffer;
113 int main(int argc, char **argv)
115 ALCdevice *device;
116 ALboolean has_angle_ext;
117 ALuint source, buffer;
118 const char *soundname;
119 const char *hrtfname;
120 ALCint hrtf_state;
121 ALCint num_hrtf;
122 ALdouble angle;
123 ALenum state;
125 /* Print out usage if no arguments were specified */
126 if(argc < 2)
128 fprintf(stderr, "Usage: %s [-device <name>] [-hrtf <name>] <soundfile>\n", argv[0]);
129 return 1;
132 /* Initialize OpenAL, and check for HRTF support. */
133 argv++; argc--;
134 if(InitAL(&argv, &argc) != 0)
135 return 1;
137 device = alcGetContextsDevice(alcGetCurrentContext());
138 if(!alcIsExtensionPresent(device, "ALC_SOFT_HRTF"))
140 fprintf(stderr, "Error: ALC_SOFT_HRTF not supported\n");
141 CloseAL();
142 return 1;
145 /* Define a macro to help load the function pointers. */
146 #define LOAD_PROC(d, x) ((x) = alcGetProcAddress((d), #x))
147 LOAD_PROC(device, alcGetStringiSOFT);
148 LOAD_PROC(device, alcResetDeviceSOFT);
149 #undef LOAD_PROC
151 /* Check for the AL_EXT_STEREO_ANGLES extension to be able to also rotate
152 * stereo sources.
154 has_angle_ext = alIsExtensionPresent("AL_EXT_STEREO_ANGLES");
155 printf("AL_EXT_STEREO_ANGLES%s found\n", has_angle_ext?"":" not");
157 /* Check for user-preferred HRTF */
158 if(strcmp(argv[0], "-hrtf") == 0)
160 hrtfname = argv[1];
161 soundname = argv[2];
163 else
165 hrtfname = NULL;
166 soundname = argv[0];
169 /* Enumerate available HRTFs, and reset the device using one. */
170 alcGetIntegerv(device, ALC_NUM_HRTF_SPECIFIERS_SOFT, 1, &num_hrtf);
171 if(!num_hrtf)
172 printf("No HRTFs found\n");
173 else
175 ALCint attr[5];
176 ALCint index = -1;
177 ALCint i;
179 printf("Available HRTFs:\n");
180 for(i = 0;i < num_hrtf;i++)
182 const ALCchar *name = alcGetStringiSOFT(device, ALC_HRTF_SPECIFIER_SOFT, i);
183 printf(" %d: %s\n", i, name);
185 /* Check if this is the HRTF the user requested. */
186 if(hrtfname && strcmp(name, hrtfname) == 0)
187 index = i;
190 i = 0;
191 attr[i++] = ALC_HRTF_SOFT;
192 attr[i++] = ALC_TRUE;
193 if(index == -1)
195 if(hrtfname)
196 printf("HRTF \"%s\" not found\n", hrtfname);
197 printf("Using default HRTF...\n");
199 else
201 printf("Selecting HRTF %d...\n", index);
202 attr[i++] = ALC_HRTF_ID_SOFT;
203 attr[i++] = index;
205 attr[i] = 0;
207 if(!alcResetDeviceSOFT(device, attr))
208 printf("Failed to reset device: %s\n", alcGetString(device, alcGetError(device)));
211 /* Check if HRTF is enabled, and show which is being used. */
212 alcGetIntegerv(device, ALC_HRTF_SOFT, 1, &hrtf_state);
213 if(!hrtf_state)
214 printf("HRTF not enabled!\n");
215 else
217 const ALchar *name = alcGetString(device, ALC_HRTF_SPECIFIER_SOFT);
218 printf("HRTF enabled, using %s\n", name);
220 fflush(stdout);
222 /* Load the sound into a buffer. */
223 buffer = LoadSound(soundname);
224 if(!buffer)
226 CloseAL();
227 return 1;
230 /* Create the source to play the sound with. */
231 source = 0;
232 alGenSources(1, &source);
233 alSourcei(source, AL_SOURCE_RELATIVE, AL_TRUE);
234 alSource3f(source, AL_POSITION, 0.0f, 0.0f, -1.0f);
235 alSourcei(source, AL_BUFFER, buffer);
236 assert(alGetError()==AL_NO_ERROR && "Failed to setup sound source");
238 /* Play the sound until it finishes. */
239 angle = 0.0;
240 alSourcePlay(source);
241 do {
242 al_nssleep(10000000);
244 /* Rotate the source around the listener by about 1/4 cycle per second,
245 * and keep it within -pi...+pi.
247 angle += 0.01 * M_PI * 0.5;
248 if(angle > M_PI)
249 angle -= M_PI*2.0;
251 /* This only rotates mono sounds. */
252 alSource3f(source, AL_POSITION, (ALfloat)sin(angle), 0.0f, -(ALfloat)cos(angle));
254 if(has_angle_ext)
256 /* This rotates stereo sounds with the AL_EXT_STEREO_ANGLES
257 * extension. Angles are specified counter-clockwise in radians.
259 ALfloat angles[2] = { (ALfloat)(M_PI/6.0 - angle), (ALfloat)(-M_PI/6.0 - angle) };
260 alSourcefv(source, AL_STEREO_ANGLES, angles);
263 alGetSourcei(source, AL_SOURCE_STATE, &state);
264 } while(alGetError() == AL_NO_ERROR && state == AL_PLAYING);
266 /* All done. Delete resources, and close OpenAL. */
267 alDeleteSources(1, &source);
268 alDeleteBuffers(1, &buffer);
270 CloseAL();
272 return 0;