Simplify clearing an array
[openal-soft.git] / examples / alhrtf.c
blobbea87f56d6f49cbef5a1e399e20f1912b5c3032a
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 <assert.h>
28 #include <inttypes.h>
29 #include <limits.h>
30 #include <math.h>
31 #include <stdio.h>
32 #include <stdlib.h>
33 #include <string.h>
35 #include "sndfile.h"
37 #include "AL/al.h"
38 #include "AL/alc.h"
39 #include "AL/alext.h"
41 #include "common/alhelpers.h"
44 #ifndef M_PI
45 #define M_PI (3.14159265358979323846)
46 #endif
48 static LPALCGETSTRINGISOFT alcGetStringiSOFT;
49 static LPALCRESETDEVICESOFT alcResetDeviceSOFT;
51 /* LoadBuffer loads the named audio file into an OpenAL buffer object, and
52 * returns the new buffer ID.
54 static ALuint LoadSound(const char *filename)
56 ALenum err, format;
57 ALuint buffer;
58 SNDFILE *sndfile;
59 SF_INFO sfinfo;
60 short *membuf;
61 sf_count_t num_frames;
62 ALsizei num_bytes;
64 /* Open the audio file and check that it's usable. */
65 sndfile = sf_open(filename, SFM_READ, &sfinfo);
66 if(!sndfile)
68 fprintf(stderr, "Could not open audio in %s: %s\n", filename, sf_strerror(sndfile));
69 return 0;
71 if(sfinfo.frames < 1 || sfinfo.frames > (sf_count_t)(INT_MAX/sizeof(short))/sfinfo.channels)
73 fprintf(stderr, "Bad sample count in %s (%" PRId64 ")\n", filename, sfinfo.frames);
74 sf_close(sndfile);
75 return 0;
78 /* Get the sound format, and figure out the OpenAL format */
79 if(sfinfo.channels == 1)
80 format = AL_FORMAT_MONO16;
81 else if(sfinfo.channels == 2)
82 format = AL_FORMAT_STEREO16;
83 else
85 fprintf(stderr, "Unsupported channel count: %d\n", sfinfo.channels);
86 sf_close(sndfile);
87 return 0;
90 /* Decode the whole audio file to a buffer. */
91 membuf = malloc((size_t)(sfinfo.frames * sfinfo.channels) * sizeof(short));
93 num_frames = sf_readf_short(sndfile, membuf, sfinfo.frames);
94 if(num_frames < 1)
96 free(membuf);
97 sf_close(sndfile);
98 fprintf(stderr, "Failed to read samples in %s (%" PRId64 ")\n", filename, num_frames);
99 return 0;
101 num_bytes = (ALsizei)(num_frames * sfinfo.channels) * (ALsizei)sizeof(short);
103 /* Buffer the audio data into a new buffer object, then free the data and
104 * close the file.
106 buffer = 0;
107 alGenBuffers(1, &buffer);
108 alBufferData(buffer, format, membuf, num_bytes, sfinfo.samplerate);
110 free(membuf);
111 sf_close(sndfile);
113 /* Check if an error occured, and clean up if so. */
114 err = alGetError();
115 if(err != AL_NO_ERROR)
117 fprintf(stderr, "OpenAL Error: %s\n", alGetString(err));
118 if(buffer && alIsBuffer(buffer))
119 alDeleteBuffers(1, &buffer);
120 return 0;
123 return buffer;
127 int main(int argc, char **argv)
129 ALCdevice *device;
130 ALCcontext *context;
131 ALboolean has_angle_ext;
132 ALuint source, buffer;
133 const char *soundname;
134 const char *hrtfname;
135 ALCint hrtf_state;
136 ALCint num_hrtf;
137 ALdouble angle;
138 ALenum state;
140 /* Print out usage if no arguments were specified */
141 if(argc < 2)
143 fprintf(stderr, "Usage: %s [-device <name>] [-hrtf <name>] <soundfile>\n", argv[0]);
144 return 1;
147 /* Initialize OpenAL, and check for HRTF support. */
148 argv++; argc--;
149 if(InitAL(&argv, &argc) != 0)
150 return 1;
152 context = alcGetCurrentContext();
153 device = alcGetContextsDevice(context);
154 if(!alcIsExtensionPresent(device, "ALC_SOFT_HRTF"))
156 fprintf(stderr, "Error: ALC_SOFT_HRTF not supported\n");
157 CloseAL();
158 return 1;
161 /* Define a macro to help load the function pointers. */
162 #define LOAD_PROC(d, T, x) ((x) = (T)alcGetProcAddress((d), #x))
163 LOAD_PROC(device, LPALCGETSTRINGISOFT, alcGetStringiSOFT);
164 LOAD_PROC(device, LPALCRESETDEVICESOFT, alcResetDeviceSOFT);
165 #undef LOAD_PROC
167 /* Check for the AL_EXT_STEREO_ANGLES extension to be able to also rotate
168 * stereo sources.
170 has_angle_ext = alIsExtensionPresent("AL_EXT_STEREO_ANGLES");
171 printf("AL_EXT_STEREO_ANGLES %sfound\n", has_angle_ext?"":"not ");
173 /* Check for user-preferred HRTF */
174 if(strcmp(argv[0], "-hrtf") == 0)
176 hrtfname = argv[1];
177 soundname = argv[2];
179 else
181 hrtfname = NULL;
182 soundname = argv[0];
185 /* Enumerate available HRTFs, and reset the device using one. */
186 alcGetIntegerv(device, ALC_NUM_HRTF_SPECIFIERS_SOFT, 1, &num_hrtf);
187 if(!num_hrtf)
188 printf("No HRTFs found\n");
189 else
191 ALCint attr[5];
192 ALCint index = -1;
193 ALCint i;
195 printf("Available HRTFs:\n");
196 for(i = 0;i < num_hrtf;i++)
198 const ALCchar *name = alcGetStringiSOFT(device, ALC_HRTF_SPECIFIER_SOFT, i);
199 printf(" %d: %s\n", i, name);
201 /* Check if this is the HRTF the user requested. */
202 if(hrtfname && strcmp(name, hrtfname) == 0)
203 index = i;
206 i = 0;
207 attr[i++] = ALC_HRTF_SOFT;
208 attr[i++] = ALC_TRUE;
209 if(index == -1)
211 if(hrtfname)
212 printf("HRTF \"%s\" not found\n", hrtfname);
213 printf("Using default HRTF...\n");
215 else
217 printf("Selecting HRTF %d...\n", index);
218 attr[i++] = ALC_HRTF_ID_SOFT;
219 attr[i++] = index;
221 attr[i] = 0;
223 if(!alcResetDeviceSOFT(device, attr))
224 printf("Failed to reset device: %s\n", alcGetString(device, alcGetError(device)));
227 /* Check if HRTF is enabled, and show which is being used. */
228 alcGetIntegerv(device, ALC_HRTF_SOFT, 1, &hrtf_state);
229 if(!hrtf_state)
230 printf("HRTF not enabled!\n");
231 else
233 const ALchar *name = alcGetString(device, ALC_HRTF_SPECIFIER_SOFT);
234 printf("HRTF enabled, using %s\n", name);
236 fflush(stdout);
238 /* Load the sound into a buffer. */
239 buffer = LoadSound(soundname);
240 if(!buffer)
242 CloseAL();
243 return 1;
246 /* Create the source to play the sound with. */
247 source = 0;
248 alGenSources(1, &source);
249 alSourcei(source, AL_SOURCE_RELATIVE, AL_TRUE);
250 alSource3f(source, AL_POSITION, 0.0f, 0.0f, -1.0f);
251 alSourcei(source, AL_BUFFER, (ALint)buffer);
252 assert(alGetError()==AL_NO_ERROR && "Failed to setup sound source");
254 /* Play the sound until it finishes. */
255 angle = 0.0;
256 alSourcePlay(source);
257 do {
258 al_nssleep(10000000);
260 alcSuspendContext(context);
262 /* Rotate the source around the listener by about 1/4 cycle per second,
263 * and keep it within -pi...+pi.
265 angle += 0.01 * M_PI * 0.5;
266 if(angle > M_PI)
267 angle -= M_PI*2.0;
269 /* This only rotates mono sounds. */
270 alSource3f(source, AL_POSITION, (ALfloat)sin(angle), 0.0f, -(ALfloat)cos(angle));
272 if(has_angle_ext)
274 /* This rotates stereo sounds with the AL_EXT_STEREO_ANGLES
275 * extension. Angles are specified counter-clockwise in radians.
277 ALfloat angles[2] = { (ALfloat)(M_PI/6.0 - angle), (ALfloat)(-M_PI/6.0 - angle) };
278 alSourcefv(source, AL_STEREO_ANGLES, angles);
280 alcProcessContext(context);
282 alGetSourcei(source, AL_SOURCE_STATE, &state);
283 } while(alGetError() == AL_NO_ERROR && state == AL_PLAYING);
285 /* All done. Delete resources, and close down OpenAL. */
286 alDeleteSources(1, &source);
287 alDeleteBuffers(1, &buffer);
288 CloseAL();
290 return 0;