Add a config option for reverse-z
[openal-soft.git] / examples / alconvolve.c
blob8979e7a39855fb6dee5b6b21cca08c6e4c91d07f
1 /*
2 * OpenAL Convolution Reverb Example
4 * Copyright (c) 2020 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 applying convolution reverb to a source. */
27 #include <assert.h>
28 #include <inttypes.h>
29 #include <limits.h>
30 #include <stdio.h>
31 #include <stdlib.h>
32 #include <string.h>
34 #include "sndfile.h"
36 #include "AL/al.h"
37 #include "AL/alext.h"
39 #include "common/alhelpers.h"
42 #ifndef AL_SOFT_convolution_reverb
43 #define AL_SOFT_convolution_reverb
44 #define AL_EFFECT_CONVOLUTION_REVERB_SOFT 0xA000
45 #endif
48 /* Filter object functions */
49 static LPALGENFILTERS alGenFilters;
50 static LPALDELETEFILTERS alDeleteFilters;
51 static LPALISFILTER alIsFilter;
52 static LPALFILTERI alFilteri;
53 static LPALFILTERIV alFilteriv;
54 static LPALFILTERF alFilterf;
55 static LPALFILTERFV alFilterfv;
56 static LPALGETFILTERI alGetFilteri;
57 static LPALGETFILTERIV alGetFilteriv;
58 static LPALGETFILTERF alGetFilterf;
59 static LPALGETFILTERFV alGetFilterfv;
61 /* Effect object functions */
62 static LPALGENEFFECTS alGenEffects;
63 static LPALDELETEEFFECTS alDeleteEffects;
64 static LPALISEFFECT alIsEffect;
65 static LPALEFFECTI alEffecti;
66 static LPALEFFECTIV alEffectiv;
67 static LPALEFFECTF alEffectf;
68 static LPALEFFECTFV alEffectfv;
69 static LPALGETEFFECTI alGetEffecti;
70 static LPALGETEFFECTIV alGetEffectiv;
71 static LPALGETEFFECTF alGetEffectf;
72 static LPALGETEFFECTFV alGetEffectfv;
74 /* Auxiliary Effect Slot object functions */
75 static LPALGENAUXILIARYEFFECTSLOTS alGenAuxiliaryEffectSlots;
76 static LPALDELETEAUXILIARYEFFECTSLOTS alDeleteAuxiliaryEffectSlots;
77 static LPALISAUXILIARYEFFECTSLOT alIsAuxiliaryEffectSlot;
78 static LPALAUXILIARYEFFECTSLOTI alAuxiliaryEffectSloti;
79 static LPALAUXILIARYEFFECTSLOTIV alAuxiliaryEffectSlotiv;
80 static LPALAUXILIARYEFFECTSLOTF alAuxiliaryEffectSlotf;
81 static LPALAUXILIARYEFFECTSLOTFV alAuxiliaryEffectSlotfv;
82 static LPALGETAUXILIARYEFFECTSLOTI alGetAuxiliaryEffectSloti;
83 static LPALGETAUXILIARYEFFECTSLOTIV alGetAuxiliaryEffectSlotiv;
84 static LPALGETAUXILIARYEFFECTSLOTF alGetAuxiliaryEffectSlotf;
85 static LPALGETAUXILIARYEFFECTSLOTFV alGetAuxiliaryEffectSlotfv;
87 /* C doesn't allow casting between function and non-function pointer types, so
88 * with C99 we need to use a union to reinterpret the pointer type. Pre-C99
89 * still needs to use a normal cast and live with the warning (C++ is fine with
90 * a regular reinterpret_cast).
92 #if __STDC_VERSION__ >= 199901L
93 #define FUNCTION_CAST(T, ptr) (union{void *p; T f;}){ptr}.f
94 #else
95 #define FUNCTION_CAST(T, ptr) (T)(ptr)
96 #endif
99 /* This stuff defines a simple streaming player object, the same as alstream.c.
100 * Comments are removed for brevity, see alstream.c for more details.
102 #define NUM_BUFFERS 4
103 #define BUFFER_SAMPLES 8192
105 typedef struct StreamPlayer {
106 ALuint buffers[NUM_BUFFERS];
107 ALuint source;
109 SNDFILE *sndfile;
110 SF_INFO sfinfo;
111 float *membuf;
113 ALenum format;
114 } StreamPlayer;
116 static StreamPlayer *NewPlayer(void)
118 StreamPlayer *player;
120 player = calloc(1, sizeof(*player));
121 assert(player != NULL);
123 alGenBuffers(NUM_BUFFERS, player->buffers);
124 assert(alGetError() == AL_NO_ERROR && "Could not create buffers");
126 alGenSources(1, &player->source);
127 assert(alGetError() == AL_NO_ERROR && "Could not create source");
129 alSource3i(player->source, AL_POSITION, 0, 0, -1);
130 alSourcei(player->source, AL_SOURCE_RELATIVE, AL_TRUE);
131 alSourcei(player->source, AL_ROLLOFF_FACTOR, 0);
132 assert(alGetError() == AL_NO_ERROR && "Could not set source parameters");
134 return player;
137 static void ClosePlayerFile(StreamPlayer *player)
139 if(player->sndfile)
140 sf_close(player->sndfile);
141 player->sndfile = NULL;
143 free(player->membuf);
144 player->membuf = NULL;
147 static void DeletePlayer(StreamPlayer *player)
149 ClosePlayerFile(player);
151 alDeleteSources(1, &player->source);
152 alDeleteBuffers(NUM_BUFFERS, player->buffers);
153 if(alGetError() != AL_NO_ERROR)
154 fprintf(stderr, "Failed to delete object IDs\n");
156 memset(player, 0, sizeof(*player));
157 free(player);
160 static int OpenPlayerFile(StreamPlayer *player, const char *filename)
162 size_t frame_size;
164 ClosePlayerFile(player);
166 player->sndfile = sf_open(filename, SFM_READ, &player->sfinfo);
167 if(!player->sndfile)
169 fprintf(stderr, "Could not open audio in %s: %s\n", filename, sf_strerror(NULL));
170 return 0;
173 player->format = AL_NONE;
174 if(player->sfinfo.channels == 1)
175 player->format = AL_FORMAT_MONO_FLOAT32;
176 else if(player->sfinfo.channels == 2)
177 player->format = AL_FORMAT_STEREO_FLOAT32;
178 else if(player->sfinfo.channels == 6)
179 player->format = AL_FORMAT_51CHN32;
180 else if(player->sfinfo.channels == 3)
182 if(sf_command(player->sndfile, SFC_WAVEX_GET_AMBISONIC, NULL, 0) == SF_AMBISONIC_B_FORMAT)
183 player->format = AL_FORMAT_BFORMAT2D_FLOAT32;
185 else if(player->sfinfo.channels == 4)
187 if(sf_command(player->sndfile, SFC_WAVEX_GET_AMBISONIC, NULL, 0) == SF_AMBISONIC_B_FORMAT)
188 player->format = AL_FORMAT_BFORMAT3D_FLOAT32;
190 if(!player->format)
192 fprintf(stderr, "Unsupported channel count: %d\n", player->sfinfo.channels);
193 sf_close(player->sndfile);
194 player->sndfile = NULL;
195 return 0;
198 frame_size = (size_t)(BUFFER_SAMPLES * player->sfinfo.channels) * sizeof(float);
199 player->membuf = malloc(frame_size);
201 return 1;
204 static int StartPlayer(StreamPlayer *player)
206 ALsizei i;
208 alSourceRewind(player->source);
209 alSourcei(player->source, AL_BUFFER, 0);
211 for(i = 0;i < NUM_BUFFERS;i++)
213 sf_count_t slen = sf_readf_float(player->sndfile, player->membuf, BUFFER_SAMPLES);
214 if(slen < 1) break;
216 slen *= player->sfinfo.channels * (sf_count_t)sizeof(float);
217 alBufferData(player->buffers[i], player->format, player->membuf, (ALsizei)slen,
218 player->sfinfo.samplerate);
220 if(alGetError() != AL_NO_ERROR)
222 fprintf(stderr, "Error buffering for playback\n");
223 return 0;
226 alSourceQueueBuffers(player->source, i, player->buffers);
227 alSourcePlay(player->source);
228 if(alGetError() != AL_NO_ERROR)
230 fprintf(stderr, "Error starting playback\n");
231 return 0;
234 return 1;
237 static int UpdatePlayer(StreamPlayer *player)
239 ALint processed, state;
241 alGetSourcei(player->source, AL_SOURCE_STATE, &state);
242 alGetSourcei(player->source, AL_BUFFERS_PROCESSED, &processed);
243 if(alGetError() != AL_NO_ERROR)
245 fprintf(stderr, "Error checking source state\n");
246 return 0;
249 while(processed > 0)
251 ALuint bufid;
252 sf_count_t slen;
254 alSourceUnqueueBuffers(player->source, 1, &bufid);
255 processed--;
257 slen = sf_readf_float(player->sndfile, player->membuf, BUFFER_SAMPLES);
258 if(slen > 0)
260 slen *= player->sfinfo.channels * (sf_count_t)sizeof(float);
261 alBufferData(bufid, player->format, player->membuf, (ALsizei)slen,
262 player->sfinfo.samplerate);
263 alSourceQueueBuffers(player->source, 1, &bufid);
265 if(alGetError() != AL_NO_ERROR)
267 fprintf(stderr, "Error buffering data\n");
268 return 0;
272 if(state != AL_PLAYING && state != AL_PAUSED)
274 ALint queued;
276 alGetSourcei(player->source, AL_BUFFERS_QUEUED, &queued);
277 if(queued == 0)
278 return 0;
280 alSourcePlay(player->source);
281 if(alGetError() != AL_NO_ERROR)
283 fprintf(stderr, "Error restarting playback\n");
284 return 0;
288 return 1;
292 /* CreateEffect creates a new OpenAL effect object with a convolution reverb
293 * type, and returns the new effect ID.
295 static ALuint CreateEffect(void)
297 ALuint effect = 0;
298 ALenum err;
300 printf("Using Convolution Reverb\n");
302 /* Create the effect object and set the convolution reverb effect type. */
303 alGenEffects(1, &effect);
304 alEffecti(effect, AL_EFFECT_TYPE, AL_EFFECT_CONVOLUTION_REVERB_SOFT);
306 /* Check if an error occured, and clean up if so. */
307 err = alGetError();
308 if(err != AL_NO_ERROR)
310 fprintf(stderr, "OpenAL error: %s\n", alGetString(err));
311 if(alIsEffect(effect))
312 alDeleteEffects(1, &effect);
313 return 0;
316 return effect;
319 /* LoadBuffer loads the named audio file into an OpenAL buffer object, and
320 * returns the new buffer ID.
322 static ALuint LoadSound(const char *filename)
324 const char *namepart;
325 ALenum err, format;
326 ALuint buffer;
327 SNDFILE *sndfile;
328 SF_INFO sfinfo;
329 float *membuf;
330 sf_count_t num_frames;
331 ALsizei num_bytes;
333 /* Open the audio file and check that it's usable. */
334 sndfile = sf_open(filename, SFM_READ, &sfinfo);
335 if(!sndfile)
337 fprintf(stderr, "Could not open audio in %s: %s\n", filename, sf_strerror(sndfile));
338 return 0;
340 if(sfinfo.frames < 1 || sfinfo.frames > (sf_count_t)(INT_MAX/sizeof(float))/sfinfo.channels)
342 fprintf(stderr, "Bad sample count in %s (%" PRId64 ")\n", filename, sfinfo.frames);
343 sf_close(sndfile);
344 return 0;
347 /* Get the sound format, and figure out the OpenAL format. Use floats since
348 * impulse responses will usually have more than 16-bit precision.
350 format = AL_NONE;
351 if(sfinfo.channels == 1)
352 format = AL_FORMAT_MONO_FLOAT32;
353 else if(sfinfo.channels == 2)
354 format = AL_FORMAT_STEREO_FLOAT32;
355 else if(sfinfo.channels == 3)
357 if(sf_command(sndfile, SFC_WAVEX_GET_AMBISONIC, NULL, 0) == SF_AMBISONIC_B_FORMAT)
358 format = AL_FORMAT_BFORMAT2D_FLOAT32;
360 else if(sfinfo.channels == 4)
362 if(sf_command(sndfile, SFC_WAVEX_GET_AMBISONIC, NULL, 0) == SF_AMBISONIC_B_FORMAT)
363 format = AL_FORMAT_BFORMAT3D_FLOAT32;
365 if(!format)
367 fprintf(stderr, "Unsupported channel count: %d\n", sfinfo.channels);
368 sf_close(sndfile);
369 return 0;
372 namepart = strrchr(filename, '/');
373 if(namepart || (namepart=strrchr(filename, '\\')))
374 namepart++;
375 else
376 namepart = filename;
377 printf("Loading: %s (%s, %dhz, %" PRId64 " samples / %.2f seconds)\n", namepart,
378 FormatName(format), sfinfo.samplerate, sfinfo.frames,
379 (double)sfinfo.frames / sfinfo.samplerate);
380 fflush(stdout);
382 /* Decode the whole audio file to a buffer. */
383 membuf = malloc((size_t)(sfinfo.frames * sfinfo.channels) * sizeof(float));
385 num_frames = sf_readf_float(sndfile, membuf, sfinfo.frames);
386 if(num_frames < 1)
388 free(membuf);
389 sf_close(sndfile);
390 fprintf(stderr, "Failed to read samples in %s (%" PRId64 ")\n", filename, num_frames);
391 return 0;
393 num_bytes = (ALsizei)(num_frames * sfinfo.channels) * (ALsizei)sizeof(float);
395 /* Buffer the audio data into a new buffer object, then free the data and
396 * close the file.
398 buffer = 0;
399 alGenBuffers(1, &buffer);
400 alBufferData(buffer, format, membuf, num_bytes, sfinfo.samplerate);
402 free(membuf);
403 sf_close(sndfile);
405 /* Check if an error occured, and clean up if so. */
406 err = alGetError();
407 if(err != AL_NO_ERROR)
409 fprintf(stderr, "OpenAL Error: %s\n", alGetString(err));
410 if(buffer && alIsBuffer(buffer))
411 alDeleteBuffers(1, &buffer);
412 return 0;
415 return buffer;
419 int main(int argc, char **argv)
421 ALuint ir_buffer, filter, effect, slot;
422 StreamPlayer *player;
423 int i;
425 /* Print out usage if no arguments were specified */
426 if(argc < 2)
428 fprintf(stderr, "Usage: %s [-device <name>] <impulse response file> "
429 "<[-dry | -nodry] filename>...\n", argv[0]);
430 return 1;
433 argv++; argc--;
434 if(InitAL(&argv, &argc) != 0)
435 return 1;
437 if(!alIsExtensionPresent("AL_SOFTX_convolution_reverb"))
439 CloseAL();
440 fprintf(stderr, "Error: Convolution revern not supported\n");
441 return 1;
444 if(argc < 2)
446 CloseAL();
447 fprintf(stderr, "Error: Missing impulse response or sound files\n");
448 return 1;
451 /* Define a macro to help load the function pointers. */
452 #define LOAD_PROC(T, x) ((x) = FUNCTION_CAST(T, alGetProcAddress(#x)))
453 LOAD_PROC(LPALGENFILTERS, alGenFilters);
454 LOAD_PROC(LPALDELETEFILTERS, alDeleteFilters);
455 LOAD_PROC(LPALISFILTER, alIsFilter);
456 LOAD_PROC(LPALFILTERI, alFilteri);
457 LOAD_PROC(LPALFILTERIV, alFilteriv);
458 LOAD_PROC(LPALFILTERF, alFilterf);
459 LOAD_PROC(LPALFILTERFV, alFilterfv);
460 LOAD_PROC(LPALGETFILTERI, alGetFilteri);
461 LOAD_PROC(LPALGETFILTERIV, alGetFilteriv);
462 LOAD_PROC(LPALGETFILTERF, alGetFilterf);
463 LOAD_PROC(LPALGETFILTERFV, alGetFilterfv);
465 LOAD_PROC(LPALGENEFFECTS, alGenEffects);
466 LOAD_PROC(LPALDELETEEFFECTS, alDeleteEffects);
467 LOAD_PROC(LPALISEFFECT, alIsEffect);
468 LOAD_PROC(LPALEFFECTI, alEffecti);
469 LOAD_PROC(LPALEFFECTIV, alEffectiv);
470 LOAD_PROC(LPALEFFECTF, alEffectf);
471 LOAD_PROC(LPALEFFECTFV, alEffectfv);
472 LOAD_PROC(LPALGETEFFECTI, alGetEffecti);
473 LOAD_PROC(LPALGETEFFECTIV, alGetEffectiv);
474 LOAD_PROC(LPALGETEFFECTF, alGetEffectf);
475 LOAD_PROC(LPALGETEFFECTFV, alGetEffectfv);
477 LOAD_PROC(LPALGENAUXILIARYEFFECTSLOTS, alGenAuxiliaryEffectSlots);
478 LOAD_PROC(LPALDELETEAUXILIARYEFFECTSLOTS, alDeleteAuxiliaryEffectSlots);
479 LOAD_PROC(LPALISAUXILIARYEFFECTSLOT, alIsAuxiliaryEffectSlot);
480 LOAD_PROC(LPALAUXILIARYEFFECTSLOTI, alAuxiliaryEffectSloti);
481 LOAD_PROC(LPALAUXILIARYEFFECTSLOTIV, alAuxiliaryEffectSlotiv);
482 LOAD_PROC(LPALAUXILIARYEFFECTSLOTF, alAuxiliaryEffectSlotf);
483 LOAD_PROC(LPALAUXILIARYEFFECTSLOTFV, alAuxiliaryEffectSlotfv);
484 LOAD_PROC(LPALGETAUXILIARYEFFECTSLOTI, alGetAuxiliaryEffectSloti);
485 LOAD_PROC(LPALGETAUXILIARYEFFECTSLOTIV, alGetAuxiliaryEffectSlotiv);
486 LOAD_PROC(LPALGETAUXILIARYEFFECTSLOTF, alGetAuxiliaryEffectSlotf);
487 LOAD_PROC(LPALGETAUXILIARYEFFECTSLOTFV, alGetAuxiliaryEffectSlotfv);
488 #undef LOAD_PROC
490 /* Load the reverb into an effect. */
491 effect = CreateEffect();
492 if(!effect)
494 CloseAL();
495 return 1;
498 /* Load the impulse response sound into a buffer. */
499 ir_buffer = LoadSound(argv[0]);
500 if(!ir_buffer)
502 alDeleteEffects(1, &effect);
503 CloseAL();
504 return 1;
507 /* Create the effect slot object. This is what "plays" an effect on sources
508 * that connect to it.
510 slot = 0;
511 alGenAuxiliaryEffectSlots(1, &slot);
513 /* Set the impulse response sound buffer on the effect slot. This allows
514 * effects to access it as needed. In this case, convolution reverb uses it
515 * as the filter source. NOTE: Unlike the effect object, the buffer *is*
516 * kept referenced and may not be changed or deleted as long as it's set,
517 * just like with a source. When another buffer is set, or the effect slot
518 * is deleted, the buffer reference is released.
520 * The effect slot's gain is reduced because the impulse responses I've
521 * tested with result in excessively loud reverb. Is that normal? Even with
522 * this, it seems a bit on the loud side.
524 * Also note: unlike standard or EAX reverb, there is no automatic
525 * attenuation of a source's reverb response with distance, so the reverb
526 * will remain full volume regardless of a given sound's distance from the
527 * listener. You can use a send filter to alter a given source's
528 * contribution to reverb.
530 alAuxiliaryEffectSloti(slot, AL_BUFFER, (ALint)ir_buffer);
531 alAuxiliaryEffectSlotf(slot, AL_EFFECTSLOT_GAIN, 1.0f / 16.0f);
532 alAuxiliaryEffectSloti(slot, AL_EFFECTSLOT_EFFECT, (ALint)effect);
533 assert(alGetError()==AL_NO_ERROR && "Failed to set effect slot");
535 /* Create a filter that can silence the dry path. */
536 filter = 0;
537 alGenFilters(1, &filter);
538 alFilteri(filter, AL_FILTER_TYPE, AL_FILTER_LOWPASS);
539 alFilterf(filter, AL_LOWPASS_GAIN, 0.0f);
541 player = NewPlayer();
542 /* Connect the player's source to the effect slot. */
543 alSource3i(player->source, AL_AUXILIARY_SEND_FILTER, (ALint)slot, 0, AL_FILTER_NULL);
544 assert(alGetError()==AL_NO_ERROR && "Failed to setup sound source");
546 /* Play each file listed on the command line */
547 for(i = 1;i < argc;i++)
549 const char *namepart;
551 if(argc-i > 1)
553 if(strcasecmp(argv[i], "-nodry") == 0)
555 alSourcei(player->source, AL_DIRECT_FILTER, (ALint)filter);
556 ++i;
558 else if(strcasecmp(argv[i], "-dry") == 0)
560 alSourcei(player->source, AL_DIRECT_FILTER, AL_FILTER_NULL);
561 ++i;
565 if(!OpenPlayerFile(player, argv[i]))
566 continue;
568 namepart = strrchr(argv[i], '/');
569 if(namepart || (namepart=strrchr(argv[i], '\\')))
570 namepart++;
571 else
572 namepart = argv[i];
574 printf("Playing: %s (%s, %dhz)\n", namepart, FormatName(player->format),
575 player->sfinfo.samplerate);
576 fflush(stdout);
578 if(!StartPlayer(player))
580 ClosePlayerFile(player);
581 continue;
584 while(UpdatePlayer(player))
585 al_nssleep(10000000);
587 ClosePlayerFile(player);
589 printf("Done.\n");
591 /* All files done. Delete the player and effect resources, and close down
592 * OpenAL.
594 DeletePlayer(player);
595 player = NULL;
597 alDeleteAuxiliaryEffectSlots(1, &slot);
598 alDeleteEffects(1, &effect);
599 alDeleteFilters(1, &filter);
600 alDeleteBuffers(1, &ir_buffer);
602 CloseAL();
604 return 0;