1 /*
2  * OpenAL Multi-Zone Reverb Example
3  *
4  * Copyright (c) 2018 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 controlling multiple reverb zones to
26  * smoothly transition between reverb environments. The general concept is to
27  * extend single-reverb by also tracking the closest adjacent environment, and
28  * utilize EAX Reverb's panning vectors to position them relative to the
29  * listener.
30  */
31 
32 
33 #include <assert.h>
34 #include <inttypes.h>
35 #include <limits.h>
36 #include <math.h>
37 #include <stdio.h>
38 #include <stdlib.h>
39 #include <string.h>
40 
41 #include "sndfile.h"
42 
43 #include "AL/al.h"
44 #include "AL/alc.h"
45 #include "AL/efx.h"
46 #include "AL/efx-presets.h"
47 
48 #include "common/alhelpers.h"
49 
50 
51 #ifndef M_PI
52 #define M_PI 3.14159265358979323846
53 #endif
54 
55 
56 /* Filter object functions */
57 static LPALGENFILTERS alGenFilters;
58 static LPALDELETEFILTERS alDeleteFilters;
59 static LPALISFILTER alIsFilter;
60 static LPALFILTERI alFilteri;
61 static LPALFILTERIV alFilteriv;
62 static LPALFILTERF alFilterf;
63 static LPALFILTERFV alFilterfv;
64 static LPALGETFILTERI alGetFilteri;
65 static LPALGETFILTERIV alGetFilteriv;
66 static LPALGETFILTERF alGetFilterf;
67 static LPALGETFILTERFV alGetFilterfv;
68 
69 /* Effect object functions */
70 static LPALGENEFFECTS alGenEffects;
71 static LPALDELETEEFFECTS alDeleteEffects;
72 static LPALISEFFECT alIsEffect;
73 static LPALEFFECTI alEffecti;
74 static LPALEFFECTIV alEffectiv;
75 static LPALEFFECTF alEffectf;
76 static LPALEFFECTFV alEffectfv;
77 static LPALGETEFFECTI alGetEffecti;
78 static LPALGETEFFECTIV alGetEffectiv;
79 static LPALGETEFFECTF alGetEffectf;
80 static LPALGETEFFECTFV alGetEffectfv;
81 
82 /* Auxiliary Effect Slot object functions */
83 static LPALGENAUXILIARYEFFECTSLOTS alGenAuxiliaryEffectSlots;
84 static LPALDELETEAUXILIARYEFFECTSLOTS alDeleteAuxiliaryEffectSlots;
85 static LPALISAUXILIARYEFFECTSLOT alIsAuxiliaryEffectSlot;
86 static LPALAUXILIARYEFFECTSLOTI alAuxiliaryEffectSloti;
87 static LPALAUXILIARYEFFECTSLOTIV alAuxiliaryEffectSlotiv;
88 static LPALAUXILIARYEFFECTSLOTF alAuxiliaryEffectSlotf;
89 static LPALAUXILIARYEFFECTSLOTFV alAuxiliaryEffectSlotfv;
90 static LPALGETAUXILIARYEFFECTSLOTI alGetAuxiliaryEffectSloti;
91 static LPALGETAUXILIARYEFFECTSLOTIV alGetAuxiliaryEffectSlotiv;
92 static LPALGETAUXILIARYEFFECTSLOTF alGetAuxiliaryEffectSlotf;
93 static LPALGETAUXILIARYEFFECTSLOTFV alGetAuxiliaryEffectSlotfv;
94 
95 
96 /* LoadEffect loads the given initial reverb properties into the given OpenAL
97  * effect object, and returns non-zero on success.
98  */
LoadEffect(ALuint effect,const EFXEAXREVERBPROPERTIES * reverb)99 static int LoadEffect(ALuint effect, const EFXEAXREVERBPROPERTIES *reverb)
100 {
101     ALenum err;
102 
103     alGetError();
104 
105     /* Prepare the effect for EAX Reverb (standard reverb doesn't contain
106      * the needed panning vectors).
107      */
108     alEffecti(effect, AL_EFFECT_TYPE, AL_EFFECT_EAXREVERB);
109     if((err=alGetError()) != AL_NO_ERROR)
110     {
111         fprintf(stderr, "Failed to set EAX Reverb: %s (0x%04x)\n", alGetString(err), err);
112         return 0;
113     }
114 
115     /* Load the reverb properties. */
116     alEffectf(effect, AL_EAXREVERB_DENSITY, reverb->flDensity);
117     alEffectf(effect, AL_EAXREVERB_DIFFUSION, reverb->flDiffusion);
118     alEffectf(effect, AL_EAXREVERB_GAIN, reverb->flGain);
119     alEffectf(effect, AL_EAXREVERB_GAINHF, reverb->flGainHF);
120     alEffectf(effect, AL_EAXREVERB_GAINLF, reverb->flGainLF);
121     alEffectf(effect, AL_EAXREVERB_DECAY_TIME, reverb->flDecayTime);
122     alEffectf(effect, AL_EAXREVERB_DECAY_HFRATIO, reverb->flDecayHFRatio);
123     alEffectf(effect, AL_EAXREVERB_DECAY_LFRATIO, reverb->flDecayLFRatio);
124     alEffectf(effect, AL_EAXREVERB_REFLECTIONS_GAIN, reverb->flReflectionsGain);
125     alEffectf(effect, AL_EAXREVERB_REFLECTIONS_DELAY, reverb->flReflectionsDelay);
126     alEffectfv(effect, AL_EAXREVERB_REFLECTIONS_PAN, reverb->flReflectionsPan);
127     alEffectf(effect, AL_EAXREVERB_LATE_REVERB_GAIN, reverb->flLateReverbGain);
128     alEffectf(effect, AL_EAXREVERB_LATE_REVERB_DELAY, reverb->flLateReverbDelay);
129     alEffectfv(effect, AL_EAXREVERB_LATE_REVERB_PAN, reverb->flLateReverbPan);
130     alEffectf(effect, AL_EAXREVERB_ECHO_TIME, reverb->flEchoTime);
131     alEffectf(effect, AL_EAXREVERB_ECHO_DEPTH, reverb->flEchoDepth);
132     alEffectf(effect, AL_EAXREVERB_MODULATION_TIME, reverb->flModulationTime);
133     alEffectf(effect, AL_EAXREVERB_MODULATION_DEPTH, reverb->flModulationDepth);
134     alEffectf(effect, AL_EAXREVERB_AIR_ABSORPTION_GAINHF, reverb->flAirAbsorptionGainHF);
135     alEffectf(effect, AL_EAXREVERB_HFREFERENCE, reverb->flHFReference);
136     alEffectf(effect, AL_EAXREVERB_LFREFERENCE, reverb->flLFReference);
137     alEffectf(effect, AL_EAXREVERB_ROOM_ROLLOFF_FACTOR, reverb->flRoomRolloffFactor);
138     alEffecti(effect, AL_EAXREVERB_DECAY_HFLIMIT, reverb->iDecayHFLimit);
139 
140     /* Check if an error occured, and return failure if so. */
141     if((err=alGetError()) != AL_NO_ERROR)
142     {
143         fprintf(stderr, "Error setting up reverb: %s\n", alGetString(err));
144         return 0;
145     }
146 
147     return 1;
148 }
149 
150 
151 /* LoadBuffer loads the named audio file into an OpenAL buffer object, and
152  * returns the new buffer ID.
153  */
LoadSound(const char * filename)154 static ALuint LoadSound(const char *filename)
155 {
156     ALenum err, format;
157     ALuint buffer;
158     SNDFILE *sndfile;
159     SF_INFO sfinfo;
160     short *membuf;
161     sf_count_t num_frames;
162     ALsizei num_bytes;
163 
164     /* Open the audio file and check that it's usable. */
165     sndfile = sf_open(filename, SFM_READ, &sfinfo);
166     if(!sndfile)
167     {
168         fprintf(stderr, "Could not open audio in %s: %s\n", filename, sf_strerror(sndfile));
169         return 0;
170     }
171     if(sfinfo.frames < 1 || sfinfo.frames > (sf_count_t)(INT_MAX/sizeof(short))/sfinfo.channels)
172     {
173         fprintf(stderr, "Bad sample count in %s (%" PRId64 ")\n", filename, sfinfo.frames);
174         sf_close(sndfile);
175         return 0;
176     }
177 
178     /* Get the sound format, and figure out the OpenAL format */
179     if(sfinfo.channels == 1)
180         format = AL_FORMAT_MONO16;
181     else if(sfinfo.channels == 2)
182         format = AL_FORMAT_STEREO16;
183     else
184     {
185         fprintf(stderr, "Unsupported channel count: %d\n", sfinfo.channels);
186         sf_close(sndfile);
187         return 0;
188     }
189 
190     /* Decode the whole audio file to a buffer. */
191     membuf = malloc((size_t)(sfinfo.frames * sfinfo.channels) * sizeof(short));
192 
193     num_frames = sf_readf_short(sndfile, membuf, sfinfo.frames);
194     if(num_frames < 1)
195     {
196         free(membuf);
197         sf_close(sndfile);
198         fprintf(stderr, "Failed to read samples in %s (%" PRId64 ")\n", filename, num_frames);
199         return 0;
200     }
201     num_bytes = (ALsizei)(num_frames * sfinfo.channels) * (ALsizei)sizeof(short);
202 
203     /* Buffer the audio data into a new buffer object, then free the data and
204      * close the file.
205      */
206     buffer = 0;
207     alGenBuffers(1, &buffer);
208     alBufferData(buffer, format, membuf, num_bytes, sfinfo.samplerate);
209 
210     free(membuf);
211     sf_close(sndfile);
212 
213     /* Check if an error occured, and clean up if so. */
214     err = alGetError();
215     if(err != AL_NO_ERROR)
216     {
217         fprintf(stderr, "OpenAL Error: %s\n", alGetString(err));
218         if(buffer && alIsBuffer(buffer))
219             alDeleteBuffers(1, &buffer);
220         return 0;
221     }
222 
223     return buffer;
224 }
225 
226 
227 /* Helper to calculate the dot-product of the two given vectors. */
dot_product(const ALfloat vec0[3],const ALfloat vec1[3])228 static ALfloat dot_product(const ALfloat vec0[3], const ALfloat vec1[3])
229 {
230     return vec0[0]*vec1[0] + vec0[1]*vec1[1] + vec0[2]*vec1[2];
231 }
232 
233 /* Helper to normalize a given vector. */
normalize(ALfloat vec[3])234 static void normalize(ALfloat vec[3])
235 {
236     ALfloat mag = sqrtf(dot_product(vec, vec));
237     if(mag > 0.00001f)
238     {
239         vec[0] /= mag;
240         vec[1] /= mag;
241         vec[2] /= mag;
242     }
243     else
244     {
245         vec[0] = 0.0f;
246         vec[1] = 0.0f;
247         vec[2] = 0.0f;
248     }
249 }
250 
251 
252 /* The main update function to update the listener and environment effects. */
UpdateListenerAndEffects(float timediff,const ALuint slots[2],const ALuint effects[2],const EFXEAXREVERBPROPERTIES reverbs[2])253 static void UpdateListenerAndEffects(float timediff, const ALuint slots[2], const ALuint effects[2], const EFXEAXREVERBPROPERTIES reverbs[2])
254 {
255     static const ALfloat listener_move_scale = 10.0f;
256     /* Individual reverb zones are connected via "portals". Each portal has a
257      * position (center point of the connecting area), a normal (facing
258      * direction), and a radius (approximate size of the connecting area).
259      */
260     const ALfloat portal_pos[3] = { 0.0f, 0.0f, 0.0f };
261     const ALfloat portal_norm[3] = { sqrtf(0.5f), 0.0f, -sqrtf(0.5f) };
262     const ALfloat portal_radius = 2.5f;
263     ALfloat other_dir[3], this_dir[3];
264     ALfloat listener_pos[3];
265     ALfloat local_norm[3];
266     ALfloat local_dir[3];
267     ALfloat near_edge[3];
268     ALfloat far_edge[3];
269     ALfloat dist, edist;
270 
271     /* Update the listener position for the amount of time passed. This uses a
272      * simple triangular LFO to offset the position (moves along the X axis
273      * between -listener_move_scale and +listener_move_scale for each
274      * transition).
275      */
276     listener_pos[0] = (fabsf(2.0f - timediff/2.0f) - 1.0f) * listener_move_scale;
277     listener_pos[1] = 0.0f;
278     listener_pos[2] = 0.0f;
279     alListenerfv(AL_POSITION, listener_pos);
280 
281     /* Calculate local_dir, which represents the listener-relative point to the
282      * adjacent zone (should also include orientation). Because EAX Reverb uses
283      * left-handed coordinates instead of right-handed like the rest of OpenAL,
284      * negate Z for the local values.
285      */
286     local_dir[0] = portal_pos[0] - listener_pos[0];
287     local_dir[1] = portal_pos[1] - listener_pos[1];
288     local_dir[2] = -(portal_pos[2] - listener_pos[2]);
289     /* A normal application would also rotate the portal's normal given the
290      * listener orientation, to get the listener-relative normal.
291      */
292     local_norm[0] = portal_norm[0];
293     local_norm[1] = portal_norm[1];
294     local_norm[2] = -portal_norm[2];
295 
296     /* Calculate the distance from the listener to the portal, and ensure it's
297      * far enough away to not suffer severe floating-point precision issues.
298      */
299     dist = sqrtf(dot_product(local_dir, local_dir));
300     if(dist > 0.00001f)
301     {
302         const EFXEAXREVERBPROPERTIES *other_reverb, *this_reverb;
303         ALuint other_effect, this_effect;
304         ALfloat magnitude, dir_dot_norm;
305 
306         /* Normalize the direction to the portal. */
307         local_dir[0] /= dist;
308         local_dir[1] /= dist;
309         local_dir[2] /= dist;
310 
311         /* Calculate the dot product of the portal's local direction and local
312          * normal, which is used for angular and side checks later on.
313          */
314         dir_dot_norm = dot_product(local_dir, local_norm);
315 
316         /* Figure out which zone we're in. */
317         if(dir_dot_norm <= 0.0f)
318         {
319             /* We're in front of the portal, so we're in Zone 0. */
320             this_effect = effects[0];
321             other_effect = effects[1];
322             this_reverb = &reverbs[0];
323             other_reverb = &reverbs[1];
324         }
325         else
326         {
327             /* We're behind the portal, so we're in Zone 1. */
328             this_effect = effects[1];
329             other_effect = effects[0];
330             this_reverb = &reverbs[1];
331             other_reverb = &reverbs[0];
332         }
333 
334         /* Calculate the listener-relative extents of the portal. */
335         /* First, project the listener-to-portal vector onto the portal's plane
336          * to get the portal-relative direction along the plane that goes away
337          * from the listener (toward the farthest edge of the portal).
338          */
339         far_edge[0] = local_dir[0] - local_norm[0]*dir_dot_norm;
340         far_edge[1] = local_dir[1] - local_norm[1]*dir_dot_norm;
341         far_edge[2] = local_dir[2] - local_norm[2]*dir_dot_norm;
342 
343         edist = sqrtf(dot_product(far_edge, far_edge));
344         if(edist > 0.0001f)
345         {
346             /* Rescale the portal-relative vector to be at the radius edge. */
347             ALfloat mag = portal_radius / edist;
348             far_edge[0] *= mag;
349             far_edge[1] *= mag;
350             far_edge[2] *= mag;
351 
352             /* Calculate the closest edge of the portal by negating the
353              * farthest, and add an offset to make them both relative to the
354              * listener.
355              */
356             near_edge[0] = local_dir[0]*dist - far_edge[0];
357             near_edge[1] = local_dir[1]*dist - far_edge[1];
358             near_edge[2] = local_dir[2]*dist - far_edge[2];
359             far_edge[0] += local_dir[0]*dist;
360             far_edge[1] += local_dir[1]*dist;
361             far_edge[2] += local_dir[2]*dist;
362 
363             /* Normalize the listener-relative extents of the portal, then
364              * calculate the panning magnitude for the other zone given the
365              * apparent size of the opening. The panning magnitude affects the
366              * envelopment of the environment, with 1 being a point, 0.5 being
367              * half coverage around the listener, and 0 being full coverage.
368              */
369             normalize(far_edge);
370             normalize(near_edge);
371             magnitude = 1.0f - acosf(dot_product(far_edge, near_edge))/(float)(M_PI*2.0);
372 
373             /* Recalculate the panning direction, to be directly between the
374              * direction of the two extents.
375              */
376             local_dir[0] = far_edge[0] + near_edge[0];
377             local_dir[1] = far_edge[1] + near_edge[1];
378             local_dir[2] = far_edge[2] + near_edge[2];
379             normalize(local_dir);
380         }
381         else
382         {
383             /* If we get here, the listener is directly in front of or behind
384              * the center of the portal, making all aperture edges effectively
385              * equidistant. Calculating the panning magnitude is simplified,
386              * using the arctangent of the radius and distance.
387              */
388             magnitude = 1.0f - (atan2f(portal_radius, dist) / (float)M_PI);
389         }
390 
391         /* Scale the other zone's panning vector. */
392         other_dir[0] = local_dir[0] * magnitude;
393         other_dir[1] = local_dir[1] * magnitude;
394         other_dir[2] = local_dir[2] * magnitude;
395         /* Pan the current zone to the opposite direction of the portal, and
396          * take the remaining percentage of the portal's magnitude.
397          */
398         this_dir[0] = local_dir[0] * (magnitude-1.0f);
399         this_dir[1] = local_dir[1] * (magnitude-1.0f);
400         this_dir[2] = local_dir[2] * (magnitude-1.0f);
401 
402         /* Now set the effects' panning vectors and gain. Energy is shared
403          * between environments, so attenuate according to each zone's
404          * contribution (note: gain^2 = energy).
405          */
406         alEffectf(this_effect, AL_EAXREVERB_REFLECTIONS_GAIN, this_reverb->flReflectionsGain * sqrtf(magnitude));
407         alEffectf(this_effect, AL_EAXREVERB_LATE_REVERB_GAIN, this_reverb->flLateReverbGain * sqrtf(magnitude));
408         alEffectfv(this_effect, AL_EAXREVERB_REFLECTIONS_PAN, this_dir);
409         alEffectfv(this_effect, AL_EAXREVERB_LATE_REVERB_PAN, this_dir);
410 
411         alEffectf(other_effect, AL_EAXREVERB_REFLECTIONS_GAIN, other_reverb->flReflectionsGain * sqrtf(1.0f-magnitude));
412         alEffectf(other_effect, AL_EAXREVERB_LATE_REVERB_GAIN, other_reverb->flLateReverbGain * sqrtf(1.0f-magnitude));
413         alEffectfv(other_effect, AL_EAXREVERB_REFLECTIONS_PAN, other_dir);
414         alEffectfv(other_effect, AL_EAXREVERB_LATE_REVERB_PAN, other_dir);
415     }
416     else
417     {
418         /* We're practically in the center of the portal. Give the panning
419          * vectors a 50/50 split, with Zone 0 covering the half in front of
420          * the normal, and Zone 1 covering the half behind.
421          */
422         this_dir[0] = local_norm[0] / 2.0f;
423         this_dir[1] = local_norm[1] / 2.0f;
424         this_dir[2] = local_norm[2] / 2.0f;
425 
426         other_dir[0] = local_norm[0] / -2.0f;
427         other_dir[1] = local_norm[1] / -2.0f;
428         other_dir[2] = local_norm[2] / -2.0f;
429 
430         alEffectf(effects[0], AL_EAXREVERB_REFLECTIONS_GAIN, reverbs[0].flReflectionsGain * sqrtf(0.5f));
431         alEffectf(effects[0], AL_EAXREVERB_LATE_REVERB_GAIN, reverbs[0].flLateReverbGain * sqrtf(0.5f));
432         alEffectfv(effects[0], AL_EAXREVERB_REFLECTIONS_PAN, this_dir);
433         alEffectfv(effects[0], AL_EAXREVERB_LATE_REVERB_PAN, this_dir);
434 
435         alEffectf(effects[1], AL_EAXREVERB_REFLECTIONS_GAIN, reverbs[1].flReflectionsGain * sqrtf(0.5f));
436         alEffectf(effects[1], AL_EAXREVERB_LATE_REVERB_GAIN, reverbs[1].flLateReverbGain * sqrtf(0.5f));
437         alEffectfv(effects[1], AL_EAXREVERB_REFLECTIONS_PAN, other_dir);
438         alEffectfv(effects[1], AL_EAXREVERB_LATE_REVERB_PAN, other_dir);
439     }
440 
441     /* Finally, update the effect slots with the updated effect parameters. */
442     alAuxiliaryEffectSloti(slots[0], AL_EFFECTSLOT_EFFECT, (ALint)effects[0]);
443     alAuxiliaryEffectSloti(slots[1], AL_EFFECTSLOT_EFFECT, (ALint)effects[1]);
444 }
445 
446 
main(int argc,char ** argv)447 int main(int argc, char **argv)
448 {
449     static const int MaxTransitions = 8;
450     EFXEAXREVERBPROPERTIES reverbs[2] = {
451         EFX_REVERB_PRESET_CARPETEDHALLWAY,
452         EFX_REVERB_PRESET_BATHROOM
453     };
454     ALCdevice *device = NULL;
455     ALCcontext *context = NULL;
456     ALuint effects[2] = { 0, 0 };
457     ALuint slots[2] = { 0, 0 };
458     ALuint direct_filter = 0;
459     ALuint buffer = 0;
460     ALuint source = 0;
461     ALCint num_sends = 0;
462     ALenum state = AL_INITIAL;
463     ALfloat direct_gain = 1.0f;
464     int basetime = 0;
465     int loops = 0;
466 
467     /* Print out usage if no arguments were specified */
468     if(argc < 2)
469     {
470         fprintf(stderr, "Usage: %s [-device <name>] [options] <filename>\n\n"
471         "Options:\n"
472         "\t-nodirect\tSilence direct path output (easier to hear reverb)\n\n",
473         argv[0]);
474         return 1;
475     }
476 
477     /* Initialize OpenAL, and check for EFX support with at least 2 auxiliary
478      * sends (if multiple sends are supported, 2 are provided by default; if
479      * you want more, you have to request it through alcCreateContext).
480      */
481     argv++; argc--;
482     if(InitAL(&argv, &argc) != 0)
483         return 1;
484 
485     while(argc > 0)
486     {
487         if(strcmp(argv[0], "-nodirect") == 0)
488             direct_gain = 0.0f;
489         else
490             break;
491         argv++;
492         argc--;
493     }
494     if(argc < 1)
495     {
496         fprintf(stderr, "No filename spacified.\n");
497         CloseAL();
498         return 1;
499     }
500 
501     context = alcGetCurrentContext();
502     device = alcGetContextsDevice(context);
503 
504     if(!alcIsExtensionPresent(device, "ALC_EXT_EFX"))
505     {
506         fprintf(stderr, "Error: EFX not supported\n");
507         CloseAL();
508         return 1;
509     }
510 
511     num_sends = 0;
512     alcGetIntegerv(device, ALC_MAX_AUXILIARY_SENDS, 1, &num_sends);
513     if(alcGetError(device) != ALC_NO_ERROR || num_sends < 2)
514     {
515         fprintf(stderr, "Error: Device does not support multiple sends (got %d, need 2)\n",
516                 num_sends);
517         CloseAL();
518         return 1;
519     }
520 
521     /* Define a macro to help load the function pointers. */
522 #define LOAD_PROC(T, x)  ((x) = (T)alGetProcAddress(#x))
523     LOAD_PROC(LPALGENFILTERS, alGenFilters);
524     LOAD_PROC(LPALDELETEFILTERS, alDeleteFilters);
525     LOAD_PROC(LPALISFILTER, alIsFilter);
526     LOAD_PROC(LPALFILTERI, alFilteri);
527     LOAD_PROC(LPALFILTERIV, alFilteriv);
528     LOAD_PROC(LPALFILTERF, alFilterf);
529     LOAD_PROC(LPALFILTERFV, alFilterfv);
530     LOAD_PROC(LPALGETFILTERI, alGetFilteri);
531     LOAD_PROC(LPALGETFILTERIV, alGetFilteriv);
532     LOAD_PROC(LPALGETFILTERF, alGetFilterf);
533     LOAD_PROC(LPALGETFILTERFV, alGetFilterfv);
534 
535     LOAD_PROC(LPALGENEFFECTS, alGenEffects);
536     LOAD_PROC(LPALDELETEEFFECTS, alDeleteEffects);
537     LOAD_PROC(LPALISEFFECT, alIsEffect);
538     LOAD_PROC(LPALEFFECTI, alEffecti);
539     LOAD_PROC(LPALEFFECTIV, alEffectiv);
540     LOAD_PROC(LPALEFFECTF, alEffectf);
541     LOAD_PROC(LPALEFFECTFV, alEffectfv);
542     LOAD_PROC(LPALGETEFFECTI, alGetEffecti);
543     LOAD_PROC(LPALGETEFFECTIV, alGetEffectiv);
544     LOAD_PROC(LPALGETEFFECTF, alGetEffectf);
545     LOAD_PROC(LPALGETEFFECTFV, alGetEffectfv);
546 
547     LOAD_PROC(LPALGENAUXILIARYEFFECTSLOTS, alGenAuxiliaryEffectSlots);
548     LOAD_PROC(LPALDELETEAUXILIARYEFFECTSLOTS, alDeleteAuxiliaryEffectSlots);
549     LOAD_PROC(LPALISAUXILIARYEFFECTSLOT, alIsAuxiliaryEffectSlot);
550     LOAD_PROC(LPALAUXILIARYEFFECTSLOTI, alAuxiliaryEffectSloti);
551     LOAD_PROC(LPALAUXILIARYEFFECTSLOTIV, alAuxiliaryEffectSlotiv);
552     LOAD_PROC(LPALAUXILIARYEFFECTSLOTF, alAuxiliaryEffectSlotf);
553     LOAD_PROC(LPALAUXILIARYEFFECTSLOTFV, alAuxiliaryEffectSlotfv);
554     LOAD_PROC(LPALGETAUXILIARYEFFECTSLOTI, alGetAuxiliaryEffectSloti);
555     LOAD_PROC(LPALGETAUXILIARYEFFECTSLOTIV, alGetAuxiliaryEffectSlotiv);
556     LOAD_PROC(LPALGETAUXILIARYEFFECTSLOTF, alGetAuxiliaryEffectSlotf);
557     LOAD_PROC(LPALGETAUXILIARYEFFECTSLOTFV, alGetAuxiliaryEffectSlotfv);
558 #undef LOAD_PROC
559 
560     /* Load the sound into a buffer. */
561     buffer = LoadSound(argv[0]);
562     if(!buffer)
563     {
564         CloseAL();
565         return 1;
566     }
567 
568     /* Generate two effects for two "zones", and load a reverb into each one.
569      * Note that unlike single-zone reverb, where you can store one effect per
570      * preset, for multi-zone reverb you should have one effect per environment
571      * instance, or one per audible zone. This is because we'll be changing the
572      * effects' properties in real-time based on the environment instance
573      * relative to the listener.
574      */
575     alGenEffects(2, effects);
576     if(!LoadEffect(effects[0], &reverbs[0]) || !LoadEffect(effects[1], &reverbs[1]))
577     {
578         alDeleteEffects(2, effects);
579         alDeleteBuffers(1, &buffer);
580         CloseAL();
581         return 1;
582     }
583 
584     /* Create the effect slot objects, one for each "active" effect. */
585     alGenAuxiliaryEffectSlots(2, slots);
586 
587     /* Tell the effect slots to use the loaded effect objects, with slot 0 for
588      * Zone 0 and slot 1 for Zone 1. Note that this effectively copies the
589      * effect properties. Modifying or deleting the effect object afterward
590      * won't directly affect the effect slot until they're reapplied like this.
591      */
592     alAuxiliaryEffectSloti(slots[0], AL_EFFECTSLOT_EFFECT, (ALint)effects[0]);
593     alAuxiliaryEffectSloti(slots[1], AL_EFFECTSLOT_EFFECT, (ALint)effects[1]);
594     assert(alGetError()==AL_NO_ERROR && "Failed to set effect slot");
595 
596     /* For the purposes of this example, prepare a filter that optionally
597      * silences the direct path which allows us to hear just the reverberation.
598      * A filter like this is normally used for obstruction, where the path
599      * directly between the listener and source is blocked (the exact
600      * properties depending on the type and thickness of the obstructing
601      * material).
602      */
603     alGenFilters(1, &direct_filter);
604     alFilteri(direct_filter, AL_FILTER_TYPE, AL_FILTER_LOWPASS);
605     alFilterf(direct_filter, AL_LOWPASS_GAIN, direct_gain);
606     assert(alGetError()==AL_NO_ERROR && "Failed to set direct filter");
607 
608     /* Create the source to play the sound with, place it in front of the
609      * listener's path in the left zone.
610      */
611     source = 0;
612     alGenSources(1, &source);
613     alSourcei(source, AL_LOOPING, AL_TRUE);
614     alSource3f(source, AL_POSITION, -5.0f, 0.0f, -2.0f);
615     alSourcei(source, AL_DIRECT_FILTER, (ALint)direct_filter);
616     alSourcei(source, AL_BUFFER, (ALint)buffer);
617 
618     /* Connect the source to the effect slots. Here, we connect source send 0
619      * to Zone 0's slot, and send 1 to Zone 1's slot. Filters can be specified
620      * to occlude the source from each zone by varying amounts; for example, a
621      * source within a particular zone would be unfiltered, while a source that
622      * can only see a zone through a window or thin wall may be attenuated for
623      * that zone.
624      */
625     alSource3i(source, AL_AUXILIARY_SEND_FILTER, (ALint)slots[0], 0, AL_FILTER_NULL);
626     alSource3i(source, AL_AUXILIARY_SEND_FILTER, (ALint)slots[1], 1, AL_FILTER_NULL);
627     assert(alGetError()==AL_NO_ERROR && "Failed to setup sound source");
628 
629     /* Get the current time as the base for timing in the main loop. */
630     basetime = altime_get();
631     loops = 0;
632     printf("Transition %d of %d...\n", loops+1, MaxTransitions);
633 
634     /* Play the sound for a while. */
635     alSourcePlay(source);
636     do {
637         int curtime;
638         ALfloat timediff;
639 
640         /* Start a batch update, to ensure all changes apply simultaneously. */
641         alcSuspendContext(context);
642 
643         /* Get the current time to track the amount of time that passed.
644          * Convert the difference to seconds.
645          */
646         curtime = altime_get();
647         timediff = (float)(curtime - basetime) / 1000.0f;
648 
649         /* Avoid negative time deltas, in case of non-monotonic clocks. */
650         if(timediff < 0.0f)
651             timediff = 0.0f;
652         else while(timediff >= 4.0f*(float)((loops&1)+1))
653         {
654             /* For this example, each transition occurs over 4 seconds, and
655              * there's 2 transitions per cycle.
656              */
657             if(++loops < MaxTransitions)
658                 printf("Transition %d of %d...\n", loops+1, MaxTransitions);
659             if(!(loops&1))
660             {
661                 /* Cycle completed. Decrease the delta and increase the base
662                  * time to start a new cycle.
663                  */
664                 timediff -= 8.0f;
665                 basetime += 8000;
666             }
667         }
668 
669         /* Update the listener and effects, and finish the batch. */
670         UpdateListenerAndEffects(timediff, slots, effects, reverbs);
671         alcProcessContext(context);
672 
673         al_nssleep(10000000);
674 
675         alGetSourcei(source, AL_SOURCE_STATE, &state);
676     } while(alGetError() == AL_NO_ERROR && state == AL_PLAYING && loops < MaxTransitions);
677 
678     /* All done. Delete resources, and close down OpenAL. */
679     alDeleteSources(1, &source);
680     alDeleteAuxiliaryEffectSlots(2, slots);
681     alDeleteEffects(2, effects);
682     alDeleteFilters(1, &direct_filter);
683     alDeleteBuffers(1, &buffer);
684 
685     CloseAL();
686 
687     return 0;
688 }
689