First Commit
This commit is contained in:
594
externals/openal-soft/examples/alconvolve.c
vendored
Normal file
594
externals/openal-soft/examples/alconvolve.c
vendored
Normal file
@@ -0,0 +1,594 @@
|
||||
/*
|
||||
* OpenAL Convolution Reverb Example
|
||||
*
|
||||
* Copyright (c) 2020 by Chris Robinson <chris.kcat@gmail.com>
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
* of this software and associated documentation files (the "Software"), to deal
|
||||
* in the Software without restriction, including without limitation the rights
|
||||
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
* copies of the Software, and to permit persons to whom the Software is
|
||||
* furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
* THE SOFTWARE.
|
||||
*/
|
||||
|
||||
/* This file contains an example for applying convolution reverb to a source. */
|
||||
|
||||
#include <assert.h>
|
||||
#include <inttypes.h>
|
||||
#include <limits.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#include "sndfile.h"
|
||||
|
||||
#include "AL/al.h"
|
||||
#include "AL/alext.h"
|
||||
|
||||
#include "common/alhelpers.h"
|
||||
|
||||
|
||||
#ifndef AL_SOFT_convolution_reverb
|
||||
#define AL_SOFT_convolution_reverb
|
||||
#define AL_EFFECT_CONVOLUTION_REVERB_SOFT 0xA000
|
||||
#endif
|
||||
|
||||
|
||||
/* Filter object functions */
|
||||
static LPALGENFILTERS alGenFilters;
|
||||
static LPALDELETEFILTERS alDeleteFilters;
|
||||
static LPALISFILTER alIsFilter;
|
||||
static LPALFILTERI alFilteri;
|
||||
static LPALFILTERIV alFilteriv;
|
||||
static LPALFILTERF alFilterf;
|
||||
static LPALFILTERFV alFilterfv;
|
||||
static LPALGETFILTERI alGetFilteri;
|
||||
static LPALGETFILTERIV alGetFilteriv;
|
||||
static LPALGETFILTERF alGetFilterf;
|
||||
static LPALGETFILTERFV alGetFilterfv;
|
||||
|
||||
/* Effect object functions */
|
||||
static LPALGENEFFECTS alGenEffects;
|
||||
static LPALDELETEEFFECTS alDeleteEffects;
|
||||
static LPALISEFFECT alIsEffect;
|
||||
static LPALEFFECTI alEffecti;
|
||||
static LPALEFFECTIV alEffectiv;
|
||||
static LPALEFFECTF alEffectf;
|
||||
static LPALEFFECTFV alEffectfv;
|
||||
static LPALGETEFFECTI alGetEffecti;
|
||||
static LPALGETEFFECTIV alGetEffectiv;
|
||||
static LPALGETEFFECTF alGetEffectf;
|
||||
static LPALGETEFFECTFV alGetEffectfv;
|
||||
|
||||
/* Auxiliary Effect Slot object functions */
|
||||
static LPALGENAUXILIARYEFFECTSLOTS alGenAuxiliaryEffectSlots;
|
||||
static LPALDELETEAUXILIARYEFFECTSLOTS alDeleteAuxiliaryEffectSlots;
|
||||
static LPALISAUXILIARYEFFECTSLOT alIsAuxiliaryEffectSlot;
|
||||
static LPALAUXILIARYEFFECTSLOTI alAuxiliaryEffectSloti;
|
||||
static LPALAUXILIARYEFFECTSLOTIV alAuxiliaryEffectSlotiv;
|
||||
static LPALAUXILIARYEFFECTSLOTF alAuxiliaryEffectSlotf;
|
||||
static LPALAUXILIARYEFFECTSLOTFV alAuxiliaryEffectSlotfv;
|
||||
static LPALGETAUXILIARYEFFECTSLOTI alGetAuxiliaryEffectSloti;
|
||||
static LPALGETAUXILIARYEFFECTSLOTIV alGetAuxiliaryEffectSlotiv;
|
||||
static LPALGETAUXILIARYEFFECTSLOTF alGetAuxiliaryEffectSlotf;
|
||||
static LPALGETAUXILIARYEFFECTSLOTFV alGetAuxiliaryEffectSlotfv;
|
||||
|
||||
|
||||
/* This stuff defines a simple streaming player object, the same as alstream.c.
|
||||
* Comments are removed for brevity, see alstream.c for more details.
|
||||
*/
|
||||
#define NUM_BUFFERS 4
|
||||
#define BUFFER_SAMPLES 8192
|
||||
|
||||
typedef struct StreamPlayer {
|
||||
ALuint buffers[NUM_BUFFERS];
|
||||
ALuint source;
|
||||
|
||||
SNDFILE *sndfile;
|
||||
SF_INFO sfinfo;
|
||||
float *membuf;
|
||||
|
||||
ALenum format;
|
||||
} StreamPlayer;
|
||||
|
||||
static StreamPlayer *NewPlayer(void)
|
||||
{
|
||||
StreamPlayer *player;
|
||||
|
||||
player = calloc(1, sizeof(*player));
|
||||
assert(player != NULL);
|
||||
|
||||
alGenBuffers(NUM_BUFFERS, player->buffers);
|
||||
assert(alGetError() == AL_NO_ERROR && "Could not create buffers");
|
||||
|
||||
alGenSources(1, &player->source);
|
||||
assert(alGetError() == AL_NO_ERROR && "Could not create source");
|
||||
|
||||
alSource3i(player->source, AL_POSITION, 0, 0, -1);
|
||||
alSourcei(player->source, AL_SOURCE_RELATIVE, AL_TRUE);
|
||||
alSourcei(player->source, AL_ROLLOFF_FACTOR, 0);
|
||||
assert(alGetError() == AL_NO_ERROR && "Could not set source parameters");
|
||||
|
||||
return player;
|
||||
}
|
||||
|
||||
static void ClosePlayerFile(StreamPlayer *player)
|
||||
{
|
||||
if(player->sndfile)
|
||||
sf_close(player->sndfile);
|
||||
player->sndfile = NULL;
|
||||
|
||||
free(player->membuf);
|
||||
player->membuf = NULL;
|
||||
}
|
||||
|
||||
static void DeletePlayer(StreamPlayer *player)
|
||||
{
|
||||
ClosePlayerFile(player);
|
||||
|
||||
alDeleteSources(1, &player->source);
|
||||
alDeleteBuffers(NUM_BUFFERS, player->buffers);
|
||||
if(alGetError() != AL_NO_ERROR)
|
||||
fprintf(stderr, "Failed to delete object IDs\n");
|
||||
|
||||
memset(player, 0, sizeof(*player));
|
||||
free(player);
|
||||
}
|
||||
|
||||
static int OpenPlayerFile(StreamPlayer *player, const char *filename)
|
||||
{
|
||||
size_t frame_size;
|
||||
|
||||
ClosePlayerFile(player);
|
||||
|
||||
player->sndfile = sf_open(filename, SFM_READ, &player->sfinfo);
|
||||
if(!player->sndfile)
|
||||
{
|
||||
fprintf(stderr, "Could not open audio in %s: %s\n", filename, sf_strerror(NULL));
|
||||
return 0;
|
||||
}
|
||||
|
||||
player->format = AL_NONE;
|
||||
if(player->sfinfo.channels == 1)
|
||||
player->format = AL_FORMAT_MONO_FLOAT32;
|
||||
else if(player->sfinfo.channels == 2)
|
||||
player->format = AL_FORMAT_STEREO_FLOAT32;
|
||||
else if(player->sfinfo.channels == 6)
|
||||
player->format = AL_FORMAT_51CHN32;
|
||||
else if(player->sfinfo.channels == 3)
|
||||
{
|
||||
if(sf_command(player->sndfile, SFC_WAVEX_GET_AMBISONIC, NULL, 0) == SF_AMBISONIC_B_FORMAT)
|
||||
player->format = AL_FORMAT_BFORMAT2D_FLOAT32;
|
||||
}
|
||||
else if(player->sfinfo.channels == 4)
|
||||
{
|
||||
if(sf_command(player->sndfile, SFC_WAVEX_GET_AMBISONIC, NULL, 0) == SF_AMBISONIC_B_FORMAT)
|
||||
player->format = AL_FORMAT_BFORMAT3D_FLOAT32;
|
||||
}
|
||||
if(!player->format)
|
||||
{
|
||||
fprintf(stderr, "Unsupported channel count: %d\n", player->sfinfo.channels);
|
||||
sf_close(player->sndfile);
|
||||
player->sndfile = NULL;
|
||||
return 0;
|
||||
}
|
||||
|
||||
frame_size = (size_t)(BUFFER_SAMPLES * player->sfinfo.channels) * sizeof(float);
|
||||
player->membuf = malloc(frame_size);
|
||||
|
||||
return 1;
|
||||
}
|
||||
|
||||
static int StartPlayer(StreamPlayer *player)
|
||||
{
|
||||
ALsizei i;
|
||||
|
||||
alSourceRewind(player->source);
|
||||
alSourcei(player->source, AL_BUFFER, 0);
|
||||
|
||||
for(i = 0;i < NUM_BUFFERS;i++)
|
||||
{
|
||||
sf_count_t slen = sf_readf_float(player->sndfile, player->membuf, BUFFER_SAMPLES);
|
||||
if(slen < 1) break;
|
||||
|
||||
slen *= player->sfinfo.channels * (sf_count_t)sizeof(float);
|
||||
alBufferData(player->buffers[i], player->format, player->membuf, (ALsizei)slen,
|
||||
player->sfinfo.samplerate);
|
||||
}
|
||||
if(alGetError() != AL_NO_ERROR)
|
||||
{
|
||||
fprintf(stderr, "Error buffering for playback\n");
|
||||
return 0;
|
||||
}
|
||||
|
||||
alSourceQueueBuffers(player->source, i, player->buffers);
|
||||
alSourcePlay(player->source);
|
||||
if(alGetError() != AL_NO_ERROR)
|
||||
{
|
||||
fprintf(stderr, "Error starting playback\n");
|
||||
return 0;
|
||||
}
|
||||
|
||||
return 1;
|
||||
}
|
||||
|
||||
static int UpdatePlayer(StreamPlayer *player)
|
||||
{
|
||||
ALint processed, state;
|
||||
|
||||
alGetSourcei(player->source, AL_SOURCE_STATE, &state);
|
||||
alGetSourcei(player->source, AL_BUFFERS_PROCESSED, &processed);
|
||||
if(alGetError() != AL_NO_ERROR)
|
||||
{
|
||||
fprintf(stderr, "Error checking source state\n");
|
||||
return 0;
|
||||
}
|
||||
|
||||
while(processed > 0)
|
||||
{
|
||||
ALuint bufid;
|
||||
sf_count_t slen;
|
||||
|
||||
alSourceUnqueueBuffers(player->source, 1, &bufid);
|
||||
processed--;
|
||||
|
||||
slen = sf_readf_float(player->sndfile, player->membuf, BUFFER_SAMPLES);
|
||||
if(slen > 0)
|
||||
{
|
||||
slen *= player->sfinfo.channels * (sf_count_t)sizeof(float);
|
||||
alBufferData(bufid, player->format, player->membuf, (ALsizei)slen,
|
||||
player->sfinfo.samplerate);
|
||||
alSourceQueueBuffers(player->source, 1, &bufid);
|
||||
}
|
||||
if(alGetError() != AL_NO_ERROR)
|
||||
{
|
||||
fprintf(stderr, "Error buffering data\n");
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
if(state != AL_PLAYING && state != AL_PAUSED)
|
||||
{
|
||||
ALint queued;
|
||||
|
||||
alGetSourcei(player->source, AL_BUFFERS_QUEUED, &queued);
|
||||
if(queued == 0)
|
||||
return 0;
|
||||
|
||||
alSourcePlay(player->source);
|
||||
if(alGetError() != AL_NO_ERROR)
|
||||
{
|
||||
fprintf(stderr, "Error restarting playback\n");
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
return 1;
|
||||
}
|
||||
|
||||
|
||||
/* CreateEffect creates a new OpenAL effect object with a convolution reverb
|
||||
* type, and returns the new effect ID.
|
||||
*/
|
||||
static ALuint CreateEffect(void)
|
||||
{
|
||||
ALuint effect = 0;
|
||||
ALenum err;
|
||||
|
||||
printf("Using Convolution Reverb\n");
|
||||
|
||||
/* Create the effect object and set the convolution reverb effect type. */
|
||||
alGenEffects(1, &effect);
|
||||
alEffecti(effect, AL_EFFECT_TYPE, AL_EFFECT_CONVOLUTION_REVERB_SOFT);
|
||||
|
||||
/* Check if an error occured, and clean up if so. */
|
||||
err = alGetError();
|
||||
if(err != AL_NO_ERROR)
|
||||
{
|
||||
fprintf(stderr, "OpenAL error: %s\n", alGetString(err));
|
||||
if(alIsEffect(effect))
|
||||
alDeleteEffects(1, &effect);
|
||||
return 0;
|
||||
}
|
||||
|
||||
return effect;
|
||||
}
|
||||
|
||||
/* LoadBuffer loads the named audio file into an OpenAL buffer object, and
|
||||
* returns the new buffer ID.
|
||||
*/
|
||||
static ALuint LoadSound(const char *filename)
|
||||
{
|
||||
const char *namepart;
|
||||
ALenum err, format;
|
||||
ALuint buffer;
|
||||
SNDFILE *sndfile;
|
||||
SF_INFO sfinfo;
|
||||
float *membuf;
|
||||
sf_count_t num_frames;
|
||||
ALsizei num_bytes;
|
||||
|
||||
/* Open the audio file and check that it's usable. */
|
||||
sndfile = sf_open(filename, SFM_READ, &sfinfo);
|
||||
if(!sndfile)
|
||||
{
|
||||
fprintf(stderr, "Could not open audio in %s: %s\n", filename, sf_strerror(sndfile));
|
||||
return 0;
|
||||
}
|
||||
if(sfinfo.frames < 1 || sfinfo.frames > (sf_count_t)(INT_MAX/sizeof(float))/sfinfo.channels)
|
||||
{
|
||||
fprintf(stderr, "Bad sample count in %s (%" PRId64 ")\n", filename, sfinfo.frames);
|
||||
sf_close(sndfile);
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* Get the sound format, and figure out the OpenAL format. Use floats since
|
||||
* impulse responses will usually have more than 16-bit precision.
|
||||
*/
|
||||
format = AL_NONE;
|
||||
if(sfinfo.channels == 1)
|
||||
format = AL_FORMAT_MONO_FLOAT32;
|
||||
else if(sfinfo.channels == 2)
|
||||
format = AL_FORMAT_STEREO_FLOAT32;
|
||||
else if(sfinfo.channels == 3)
|
||||
{
|
||||
if(sf_command(sndfile, SFC_WAVEX_GET_AMBISONIC, NULL, 0) == SF_AMBISONIC_B_FORMAT)
|
||||
format = AL_FORMAT_BFORMAT2D_FLOAT32;
|
||||
}
|
||||
else if(sfinfo.channels == 4)
|
||||
{
|
||||
if(sf_command(sndfile, SFC_WAVEX_GET_AMBISONIC, NULL, 0) == SF_AMBISONIC_B_FORMAT)
|
||||
format = AL_FORMAT_BFORMAT3D_FLOAT32;
|
||||
}
|
||||
if(!format)
|
||||
{
|
||||
fprintf(stderr, "Unsupported channel count: %d\n", sfinfo.channels);
|
||||
sf_close(sndfile);
|
||||
return 0;
|
||||
}
|
||||
|
||||
namepart = strrchr(filename, '/');
|
||||
if(namepart || (namepart=strrchr(filename, '\\')))
|
||||
namepart++;
|
||||
else
|
||||
namepart = filename;
|
||||
printf("Loading: %s (%s, %dhz, %" PRId64 " samples / %.2f seconds)\n", namepart,
|
||||
FormatName(format), sfinfo.samplerate, sfinfo.frames,
|
||||
(double)sfinfo.frames / sfinfo.samplerate);
|
||||
fflush(stdout);
|
||||
|
||||
/* Decode the whole audio file to a buffer. */
|
||||
membuf = malloc((size_t)(sfinfo.frames * sfinfo.channels) * sizeof(float));
|
||||
|
||||
num_frames = sf_readf_float(sndfile, membuf, sfinfo.frames);
|
||||
if(num_frames < 1)
|
||||
{
|
||||
free(membuf);
|
||||
sf_close(sndfile);
|
||||
fprintf(stderr, "Failed to read samples in %s (%" PRId64 ")\n", filename, num_frames);
|
||||
return 0;
|
||||
}
|
||||
num_bytes = (ALsizei)(num_frames * sfinfo.channels) * (ALsizei)sizeof(float);
|
||||
|
||||
/* Buffer the audio data into a new buffer object, then free the data and
|
||||
* close the file.
|
||||
*/
|
||||
buffer = 0;
|
||||
alGenBuffers(1, &buffer);
|
||||
alBufferData(buffer, format, membuf, num_bytes, sfinfo.samplerate);
|
||||
|
||||
free(membuf);
|
||||
sf_close(sndfile);
|
||||
|
||||
/* Check if an error occured, and clean up if so. */
|
||||
err = alGetError();
|
||||
if(err != AL_NO_ERROR)
|
||||
{
|
||||
fprintf(stderr, "OpenAL Error: %s\n", alGetString(err));
|
||||
if(buffer && alIsBuffer(buffer))
|
||||
alDeleteBuffers(1, &buffer);
|
||||
return 0;
|
||||
}
|
||||
|
||||
return buffer;
|
||||
}
|
||||
|
||||
|
||||
int main(int argc, char **argv)
|
||||
{
|
||||
ALuint ir_buffer, filter, effect, slot;
|
||||
StreamPlayer *player;
|
||||
int i;
|
||||
|
||||
/* Print out usage if no arguments were specified */
|
||||
if(argc < 2)
|
||||
{
|
||||
fprintf(stderr, "Usage: %s [-device <name>] <impulse response file> "
|
||||
"<[-dry | -nodry] filename>...\n", argv[0]);
|
||||
return 1;
|
||||
}
|
||||
|
||||
argv++; argc--;
|
||||
if(InitAL(&argv, &argc) != 0)
|
||||
return 1;
|
||||
|
||||
if(!alIsExtensionPresent("AL_SOFTX_convolution_reverb"))
|
||||
{
|
||||
CloseAL();
|
||||
fprintf(stderr, "Error: Convolution revern not supported\n");
|
||||
return 1;
|
||||
}
|
||||
|
||||
if(argc < 2)
|
||||
{
|
||||
CloseAL();
|
||||
fprintf(stderr, "Error: Missing impulse response or sound files\n");
|
||||
return 1;
|
||||
}
|
||||
|
||||
/* Define a macro to help load the function pointers. */
|
||||
#define LOAD_PROC(T, x) ((x) = FUNCTION_CAST(T, alGetProcAddress(#x)))
|
||||
LOAD_PROC(LPALGENFILTERS, alGenFilters);
|
||||
LOAD_PROC(LPALDELETEFILTERS, alDeleteFilters);
|
||||
LOAD_PROC(LPALISFILTER, alIsFilter);
|
||||
LOAD_PROC(LPALFILTERI, alFilteri);
|
||||
LOAD_PROC(LPALFILTERIV, alFilteriv);
|
||||
LOAD_PROC(LPALFILTERF, alFilterf);
|
||||
LOAD_PROC(LPALFILTERFV, alFilterfv);
|
||||
LOAD_PROC(LPALGETFILTERI, alGetFilteri);
|
||||
LOAD_PROC(LPALGETFILTERIV, alGetFilteriv);
|
||||
LOAD_PROC(LPALGETFILTERF, alGetFilterf);
|
||||
LOAD_PROC(LPALGETFILTERFV, alGetFilterfv);
|
||||
|
||||
LOAD_PROC(LPALGENEFFECTS, alGenEffects);
|
||||
LOAD_PROC(LPALDELETEEFFECTS, alDeleteEffects);
|
||||
LOAD_PROC(LPALISEFFECT, alIsEffect);
|
||||
LOAD_PROC(LPALEFFECTI, alEffecti);
|
||||
LOAD_PROC(LPALEFFECTIV, alEffectiv);
|
||||
LOAD_PROC(LPALEFFECTF, alEffectf);
|
||||
LOAD_PROC(LPALEFFECTFV, alEffectfv);
|
||||
LOAD_PROC(LPALGETEFFECTI, alGetEffecti);
|
||||
LOAD_PROC(LPALGETEFFECTIV, alGetEffectiv);
|
||||
LOAD_PROC(LPALGETEFFECTF, alGetEffectf);
|
||||
LOAD_PROC(LPALGETEFFECTFV, alGetEffectfv);
|
||||
|
||||
LOAD_PROC(LPALGENAUXILIARYEFFECTSLOTS, alGenAuxiliaryEffectSlots);
|
||||
LOAD_PROC(LPALDELETEAUXILIARYEFFECTSLOTS, alDeleteAuxiliaryEffectSlots);
|
||||
LOAD_PROC(LPALISAUXILIARYEFFECTSLOT, alIsAuxiliaryEffectSlot);
|
||||
LOAD_PROC(LPALAUXILIARYEFFECTSLOTI, alAuxiliaryEffectSloti);
|
||||
LOAD_PROC(LPALAUXILIARYEFFECTSLOTIV, alAuxiliaryEffectSlotiv);
|
||||
LOAD_PROC(LPALAUXILIARYEFFECTSLOTF, alAuxiliaryEffectSlotf);
|
||||
LOAD_PROC(LPALAUXILIARYEFFECTSLOTFV, alAuxiliaryEffectSlotfv);
|
||||
LOAD_PROC(LPALGETAUXILIARYEFFECTSLOTI, alGetAuxiliaryEffectSloti);
|
||||
LOAD_PROC(LPALGETAUXILIARYEFFECTSLOTIV, alGetAuxiliaryEffectSlotiv);
|
||||
LOAD_PROC(LPALGETAUXILIARYEFFECTSLOTF, alGetAuxiliaryEffectSlotf);
|
||||
LOAD_PROC(LPALGETAUXILIARYEFFECTSLOTFV, alGetAuxiliaryEffectSlotfv);
|
||||
#undef LOAD_PROC
|
||||
|
||||
/* Load the reverb into an effect. */
|
||||
effect = CreateEffect();
|
||||
if(!effect)
|
||||
{
|
||||
CloseAL();
|
||||
return 1;
|
||||
}
|
||||
|
||||
/* Load the impulse response sound into a buffer. */
|
||||
ir_buffer = LoadSound(argv[0]);
|
||||
if(!ir_buffer)
|
||||
{
|
||||
alDeleteEffects(1, &effect);
|
||||
CloseAL();
|
||||
return 1;
|
||||
}
|
||||
|
||||
/* Create the effect slot object. This is what "plays" an effect on sources
|
||||
* that connect to it.
|
||||
*/
|
||||
slot = 0;
|
||||
alGenAuxiliaryEffectSlots(1, &slot);
|
||||
|
||||
/* Set the impulse response sound buffer on the effect slot. This allows
|
||||
* effects to access it as needed. In this case, convolution reverb uses it
|
||||
* as the filter source. NOTE: Unlike the effect object, the buffer *is*
|
||||
* kept referenced and may not be changed or deleted as long as it's set,
|
||||
* just like with a source. When another buffer is set, or the effect slot
|
||||
* is deleted, the buffer reference is released.
|
||||
*
|
||||
* The effect slot's gain is reduced because the impulse responses I've
|
||||
* tested with result in excessively loud reverb. Is that normal? Even with
|
||||
* this, it seems a bit on the loud side.
|
||||
*
|
||||
* Also note: unlike standard or EAX reverb, there is no automatic
|
||||
* attenuation of a source's reverb response with distance, so the reverb
|
||||
* will remain full volume regardless of a given sound's distance from the
|
||||
* listener. You can use a send filter to alter a given source's
|
||||
* contribution to reverb.
|
||||
*/
|
||||
alAuxiliaryEffectSloti(slot, AL_BUFFER, (ALint)ir_buffer);
|
||||
alAuxiliaryEffectSlotf(slot, AL_EFFECTSLOT_GAIN, 1.0f / 16.0f);
|
||||
alAuxiliaryEffectSloti(slot, AL_EFFECTSLOT_EFFECT, (ALint)effect);
|
||||
assert(alGetError()==AL_NO_ERROR && "Failed to set effect slot");
|
||||
|
||||
/* Create a filter that can silence the dry path. */
|
||||
filter = 0;
|
||||
alGenFilters(1, &filter);
|
||||
alFilteri(filter, AL_FILTER_TYPE, AL_FILTER_LOWPASS);
|
||||
alFilterf(filter, AL_LOWPASS_GAIN, 0.0f);
|
||||
|
||||
player = NewPlayer();
|
||||
/* Connect the player's source to the effect slot. */
|
||||
alSource3i(player->source, AL_AUXILIARY_SEND_FILTER, (ALint)slot, 0, AL_FILTER_NULL);
|
||||
assert(alGetError()==AL_NO_ERROR && "Failed to setup sound source");
|
||||
|
||||
/* Play each file listed on the command line */
|
||||
for(i = 1;i < argc;i++)
|
||||
{
|
||||
const char *namepart;
|
||||
|
||||
if(argc-i > 1)
|
||||
{
|
||||
if(strcasecmp(argv[i], "-nodry") == 0)
|
||||
{
|
||||
alSourcei(player->source, AL_DIRECT_FILTER, (ALint)filter);
|
||||
++i;
|
||||
}
|
||||
else if(strcasecmp(argv[i], "-dry") == 0)
|
||||
{
|
||||
alSourcei(player->source, AL_DIRECT_FILTER, AL_FILTER_NULL);
|
||||
++i;
|
||||
}
|
||||
}
|
||||
|
||||
if(!OpenPlayerFile(player, argv[i]))
|
||||
continue;
|
||||
|
||||
namepart = strrchr(argv[i], '/');
|
||||
if(namepart || (namepart=strrchr(argv[i], '\\')))
|
||||
namepart++;
|
||||
else
|
||||
namepart = argv[i];
|
||||
|
||||
printf("Playing: %s (%s, %dhz)\n", namepart, FormatName(player->format),
|
||||
player->sfinfo.samplerate);
|
||||
fflush(stdout);
|
||||
|
||||
if(!StartPlayer(player))
|
||||
{
|
||||
ClosePlayerFile(player);
|
||||
continue;
|
||||
}
|
||||
|
||||
while(UpdatePlayer(player))
|
||||
al_nssleep(10000000);
|
||||
|
||||
ClosePlayerFile(player);
|
||||
}
|
||||
printf("Done.\n");
|
||||
|
||||
/* All files done. Delete the player and effect resources, and close down
|
||||
* OpenAL.
|
||||
*/
|
||||
DeletePlayer(player);
|
||||
player = NULL;
|
||||
|
||||
alDeleteAuxiliaryEffectSlots(1, &slot);
|
||||
alDeleteEffects(1, &effect);
|
||||
alDeleteFilters(1, &filter);
|
||||
alDeleteBuffers(1, &ir_buffer);
|
||||
|
||||
CloseAL();
|
||||
|
||||
return 0;
|
||||
}
|
||||
2181
externals/openal-soft/examples/alffplay.cpp
vendored
Normal file
2181
externals/openal-soft/examples/alffplay.cpp
vendored
Normal file
File diff suppressed because it is too large
Load Diff
302
externals/openal-soft/examples/alhrtf.c
vendored
Normal file
302
externals/openal-soft/examples/alhrtf.c
vendored
Normal file
@@ -0,0 +1,302 @@
|
||||
/*
|
||||
* OpenAL HRTF Example
|
||||
*
|
||||
* Copyright (c) 2015 by Chris Robinson <chris.kcat@gmail.com>
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
* of this software and associated documentation files (the "Software"), to deal
|
||||
* in the Software without restriction, including without limitation the rights
|
||||
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
* copies of the Software, and to permit persons to whom the Software is
|
||||
* furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
* THE SOFTWARE.
|
||||
*/
|
||||
|
||||
/* This file contains an example for selecting an HRTF. */
|
||||
|
||||
#include <assert.h>
|
||||
#include <inttypes.h>
|
||||
#include <limits.h>
|
||||
#include <math.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#include "sndfile.h"
|
||||
|
||||
#include "AL/al.h"
|
||||
#include "AL/alc.h"
|
||||
#include "AL/alext.h"
|
||||
|
||||
#include "common/alhelpers.h"
|
||||
|
||||
|
||||
#ifndef M_PI
|
||||
#define M_PI (3.14159265358979323846)
|
||||
#endif
|
||||
|
||||
static LPALCGETSTRINGISOFT alcGetStringiSOFT;
|
||||
static LPALCRESETDEVICESOFT alcResetDeviceSOFT;
|
||||
|
||||
/* LoadBuffer loads the named audio file into an OpenAL buffer object, and
|
||||
* returns the new buffer ID.
|
||||
*/
|
||||
static ALuint LoadSound(const char *filename)
|
||||
{
|
||||
ALenum err, format;
|
||||
ALuint buffer;
|
||||
SNDFILE *sndfile;
|
||||
SF_INFO sfinfo;
|
||||
short *membuf;
|
||||
sf_count_t num_frames;
|
||||
ALsizei num_bytes;
|
||||
|
||||
/* Open the audio file and check that it's usable. */
|
||||
sndfile = sf_open(filename, SFM_READ, &sfinfo);
|
||||
if(!sndfile)
|
||||
{
|
||||
fprintf(stderr, "Could not open audio in %s: %s\n", filename, sf_strerror(sndfile));
|
||||
return 0;
|
||||
}
|
||||
if(sfinfo.frames < 1 || sfinfo.frames > (sf_count_t)(INT_MAX/sizeof(short))/sfinfo.channels)
|
||||
{
|
||||
fprintf(stderr, "Bad sample count in %s (%" PRId64 ")\n", filename, sfinfo.frames);
|
||||
sf_close(sndfile);
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* Get the sound format, and figure out the OpenAL format */
|
||||
format = AL_NONE;
|
||||
if(sfinfo.channels == 1)
|
||||
format = AL_FORMAT_MONO16;
|
||||
else if(sfinfo.channels == 2)
|
||||
format = AL_FORMAT_STEREO16;
|
||||
else if(sfinfo.channels == 3)
|
||||
{
|
||||
if(sf_command(sndfile, SFC_WAVEX_GET_AMBISONIC, NULL, 0) == SF_AMBISONIC_B_FORMAT)
|
||||
format = AL_FORMAT_BFORMAT2D_16;
|
||||
}
|
||||
else if(sfinfo.channels == 4)
|
||||
{
|
||||
if(sf_command(sndfile, SFC_WAVEX_GET_AMBISONIC, NULL, 0) == SF_AMBISONIC_B_FORMAT)
|
||||
format = AL_FORMAT_BFORMAT3D_16;
|
||||
}
|
||||
if(!format)
|
||||
{
|
||||
fprintf(stderr, "Unsupported channel count: %d\n", sfinfo.channels);
|
||||
sf_close(sndfile);
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* Decode the whole audio file to a buffer. */
|
||||
membuf = malloc((size_t)(sfinfo.frames * sfinfo.channels) * sizeof(short));
|
||||
|
||||
num_frames = sf_readf_short(sndfile, membuf, sfinfo.frames);
|
||||
if(num_frames < 1)
|
||||
{
|
||||
free(membuf);
|
||||
sf_close(sndfile);
|
||||
fprintf(stderr, "Failed to read samples in %s (%" PRId64 ")\n", filename, num_frames);
|
||||
return 0;
|
||||
}
|
||||
num_bytes = (ALsizei)(num_frames * sfinfo.channels) * (ALsizei)sizeof(short);
|
||||
|
||||
/* Buffer the audio data into a new buffer object, then free the data and
|
||||
* close the file.
|
||||
*/
|
||||
buffer = 0;
|
||||
alGenBuffers(1, &buffer);
|
||||
alBufferData(buffer, format, membuf, num_bytes, sfinfo.samplerate);
|
||||
|
||||
free(membuf);
|
||||
sf_close(sndfile);
|
||||
|
||||
/* Check if an error occured, and clean up if so. */
|
||||
err = alGetError();
|
||||
if(err != AL_NO_ERROR)
|
||||
{
|
||||
fprintf(stderr, "OpenAL Error: %s\n", alGetString(err));
|
||||
if(buffer && alIsBuffer(buffer))
|
||||
alDeleteBuffers(1, &buffer);
|
||||
return 0;
|
||||
}
|
||||
|
||||
return buffer;
|
||||
}
|
||||
|
||||
|
||||
int main(int argc, char **argv)
|
||||
{
|
||||
ALCdevice *device;
|
||||
ALCcontext *context;
|
||||
ALboolean has_angle_ext;
|
||||
ALuint source, buffer;
|
||||
const char *soundname;
|
||||
const char *hrtfname;
|
||||
ALCint hrtf_state;
|
||||
ALCint num_hrtf;
|
||||
ALdouble angle;
|
||||
ALenum state;
|
||||
|
||||
/* Print out usage if no arguments were specified */
|
||||
if(argc < 2)
|
||||
{
|
||||
fprintf(stderr, "Usage: %s [-device <name>] [-hrtf <name>] <soundfile>\n", argv[0]);
|
||||
return 1;
|
||||
}
|
||||
|
||||
/* Initialize OpenAL, and check for HRTF support. */
|
||||
argv++; argc--;
|
||||
if(InitAL(&argv, &argc) != 0)
|
||||
return 1;
|
||||
|
||||
context = alcGetCurrentContext();
|
||||
device = alcGetContextsDevice(context);
|
||||
if(!alcIsExtensionPresent(device, "ALC_SOFT_HRTF"))
|
||||
{
|
||||
fprintf(stderr, "Error: ALC_SOFT_HRTF not supported\n");
|
||||
CloseAL();
|
||||
return 1;
|
||||
}
|
||||
|
||||
/* Define a macro to help load the function pointers. */
|
||||
#define LOAD_PROC(d, T, x) ((x) = FUNCTION_CAST(T, alcGetProcAddress((d), #x)))
|
||||
LOAD_PROC(device, LPALCGETSTRINGISOFT, alcGetStringiSOFT);
|
||||
LOAD_PROC(device, LPALCRESETDEVICESOFT, alcResetDeviceSOFT);
|
||||
#undef LOAD_PROC
|
||||
|
||||
/* Check for the AL_EXT_STEREO_ANGLES extension to be able to also rotate
|
||||
* stereo sources.
|
||||
*/
|
||||
has_angle_ext = alIsExtensionPresent("AL_EXT_STEREO_ANGLES");
|
||||
printf("AL_EXT_STEREO_ANGLES %sfound\n", has_angle_ext?"":"not ");
|
||||
|
||||
/* Check for user-preferred HRTF */
|
||||
if(strcmp(argv[0], "-hrtf") == 0)
|
||||
{
|
||||
hrtfname = argv[1];
|
||||
soundname = argv[2];
|
||||
}
|
||||
else
|
||||
{
|
||||
hrtfname = NULL;
|
||||
soundname = argv[0];
|
||||
}
|
||||
|
||||
/* Enumerate available HRTFs, and reset the device using one. */
|
||||
alcGetIntegerv(device, ALC_NUM_HRTF_SPECIFIERS_SOFT, 1, &num_hrtf);
|
||||
if(!num_hrtf)
|
||||
printf("No HRTFs found\n");
|
||||
else
|
||||
{
|
||||
ALCint attr[5];
|
||||
ALCint index = -1;
|
||||
ALCint i;
|
||||
|
||||
printf("Available HRTFs:\n");
|
||||
for(i = 0;i < num_hrtf;i++)
|
||||
{
|
||||
const ALCchar *name = alcGetStringiSOFT(device, ALC_HRTF_SPECIFIER_SOFT, i);
|
||||
printf(" %d: %s\n", i, name);
|
||||
|
||||
/* Check if this is the HRTF the user requested. */
|
||||
if(hrtfname && strcmp(name, hrtfname) == 0)
|
||||
index = i;
|
||||
}
|
||||
|
||||
i = 0;
|
||||
attr[i++] = ALC_HRTF_SOFT;
|
||||
attr[i++] = ALC_TRUE;
|
||||
if(index == -1)
|
||||
{
|
||||
if(hrtfname)
|
||||
printf("HRTF \"%s\" not found\n", hrtfname);
|
||||
printf("Using default HRTF...\n");
|
||||
}
|
||||
else
|
||||
{
|
||||
printf("Selecting HRTF %d...\n", index);
|
||||
attr[i++] = ALC_HRTF_ID_SOFT;
|
||||
attr[i++] = index;
|
||||
}
|
||||
attr[i] = 0;
|
||||
|
||||
if(!alcResetDeviceSOFT(device, attr))
|
||||
printf("Failed to reset device: %s\n", alcGetString(device, alcGetError(device)));
|
||||
}
|
||||
|
||||
/* Check if HRTF is enabled, and show which is being used. */
|
||||
alcGetIntegerv(device, ALC_HRTF_SOFT, 1, &hrtf_state);
|
||||
if(!hrtf_state)
|
||||
printf("HRTF not enabled!\n");
|
||||
else
|
||||
{
|
||||
const ALchar *name = alcGetString(device, ALC_HRTF_SPECIFIER_SOFT);
|
||||
printf("HRTF enabled, using %s\n", name);
|
||||
}
|
||||
fflush(stdout);
|
||||
|
||||
/* Load the sound into a buffer. */
|
||||
buffer = LoadSound(soundname);
|
||||
if(!buffer)
|
||||
{
|
||||
CloseAL();
|
||||
return 1;
|
||||
}
|
||||
|
||||
/* Create the source to play the sound with. */
|
||||
source = 0;
|
||||
alGenSources(1, &source);
|
||||
alSourcei(source, AL_SOURCE_RELATIVE, AL_TRUE);
|
||||
alSource3f(source, AL_POSITION, 0.0f, 0.0f, -1.0f);
|
||||
alSourcei(source, AL_BUFFER, (ALint)buffer);
|
||||
assert(alGetError()==AL_NO_ERROR && "Failed to setup sound source");
|
||||
|
||||
/* Play the sound until it finishes. */
|
||||
angle = 0.0;
|
||||
alSourcePlay(source);
|
||||
do {
|
||||
al_nssleep(10000000);
|
||||
|
||||
alcSuspendContext(context);
|
||||
|
||||
/* Rotate the source around the listener by about 1/4 cycle per second,
|
||||
* and keep it within -pi...+pi.
|
||||
*/
|
||||
angle += 0.01 * M_PI * 0.5;
|
||||
if(angle > M_PI)
|
||||
angle -= M_PI*2.0;
|
||||
|
||||
/* This only rotates mono sounds. */
|
||||
alSource3f(source, AL_POSITION, (ALfloat)sin(angle), 0.0f, -(ALfloat)cos(angle));
|
||||
|
||||
if(has_angle_ext)
|
||||
{
|
||||
/* This rotates stereo sounds with the AL_EXT_STEREO_ANGLES
|
||||
* extension. Angles are specified counter-clockwise in radians.
|
||||
*/
|
||||
ALfloat angles[2] = { (ALfloat)(M_PI/6.0 - angle), (ALfloat)(-M_PI/6.0 - angle) };
|
||||
alSourcefv(source, AL_STEREO_ANGLES, angles);
|
||||
}
|
||||
alcProcessContext(context);
|
||||
|
||||
alGetSourcei(source, AL_SOURCE_STATE, &state);
|
||||
} while(alGetError() == AL_NO_ERROR && state == AL_PLAYING);
|
||||
|
||||
/* All done. Delete resources, and close down OpenAL. */
|
||||
alDeleteSources(1, &source);
|
||||
alDeleteBuffers(1, &buffer);
|
||||
CloseAL();
|
||||
|
||||
return 0;
|
||||
}
|
||||
217
externals/openal-soft/examples/allatency.c
vendored
Normal file
217
externals/openal-soft/examples/allatency.c
vendored
Normal file
@@ -0,0 +1,217 @@
|
||||
/*
|
||||
* OpenAL Source Latency Example
|
||||
*
|
||||
* Copyright (c) 2012 by Chris Robinson <chris.kcat@gmail.com>
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
* of this software and associated documentation files (the "Software"), to deal
|
||||
* in the Software without restriction, including without limitation the rights
|
||||
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
* copies of the Software, and to permit persons to whom the Software is
|
||||
* furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
* THE SOFTWARE.
|
||||
*/
|
||||
|
||||
/* This file contains an example for checking the latency of a sound. */
|
||||
|
||||
#include <assert.h>
|
||||
#include <inttypes.h>
|
||||
#include <limits.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
|
||||
#include "sndfile.h"
|
||||
|
||||
#include "AL/al.h"
|
||||
#include "AL/alext.h"
|
||||
|
||||
#include "common/alhelpers.h"
|
||||
|
||||
|
||||
static LPALSOURCEDSOFT alSourcedSOFT;
|
||||
static LPALSOURCE3DSOFT alSource3dSOFT;
|
||||
static LPALSOURCEDVSOFT alSourcedvSOFT;
|
||||
static LPALGETSOURCEDSOFT alGetSourcedSOFT;
|
||||
static LPALGETSOURCE3DSOFT alGetSource3dSOFT;
|
||||
static LPALGETSOURCEDVSOFT alGetSourcedvSOFT;
|
||||
static LPALSOURCEI64SOFT alSourcei64SOFT;
|
||||
static LPALSOURCE3I64SOFT alSource3i64SOFT;
|
||||
static LPALSOURCEI64VSOFT alSourcei64vSOFT;
|
||||
static LPALGETSOURCEI64SOFT alGetSourcei64SOFT;
|
||||
static LPALGETSOURCE3I64SOFT alGetSource3i64SOFT;
|
||||
static LPALGETSOURCEI64VSOFT alGetSourcei64vSOFT;
|
||||
|
||||
/* LoadBuffer loads the named audio file into an OpenAL buffer object, and
|
||||
* returns the new buffer ID.
|
||||
*/
|
||||
static ALuint LoadSound(const char *filename)
|
||||
{
|
||||
ALenum err, format;
|
||||
ALuint buffer;
|
||||
SNDFILE *sndfile;
|
||||
SF_INFO sfinfo;
|
||||
short *membuf;
|
||||
sf_count_t num_frames;
|
||||
ALsizei num_bytes;
|
||||
|
||||
/* Open the audio file and check that it's usable. */
|
||||
sndfile = sf_open(filename, SFM_READ, &sfinfo);
|
||||
if(!sndfile)
|
||||
{
|
||||
fprintf(stderr, "Could not open audio in %s: %s\n", filename, sf_strerror(sndfile));
|
||||
return 0;
|
||||
}
|
||||
if(sfinfo.frames < 1 || sfinfo.frames > (sf_count_t)(INT_MAX/sizeof(short))/sfinfo.channels)
|
||||
{
|
||||
fprintf(stderr, "Bad sample count in %s (%" PRId64 ")\n", filename, sfinfo.frames);
|
||||
sf_close(sndfile);
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* Get the sound format, and figure out the OpenAL format */
|
||||
format = AL_NONE;
|
||||
if(sfinfo.channels == 1)
|
||||
format = AL_FORMAT_MONO16;
|
||||
else if(sfinfo.channels == 2)
|
||||
format = AL_FORMAT_STEREO16;
|
||||
else if(sfinfo.channels == 3)
|
||||
{
|
||||
if(sf_command(sndfile, SFC_WAVEX_GET_AMBISONIC, NULL, 0) == SF_AMBISONIC_B_FORMAT)
|
||||
format = AL_FORMAT_BFORMAT2D_16;
|
||||
}
|
||||
else if(sfinfo.channels == 4)
|
||||
{
|
||||
if(sf_command(sndfile, SFC_WAVEX_GET_AMBISONIC, NULL, 0) == SF_AMBISONIC_B_FORMAT)
|
||||
format = AL_FORMAT_BFORMAT3D_16;
|
||||
}
|
||||
if(!format)
|
||||
{
|
||||
fprintf(stderr, "Unsupported channel count: %d\n", sfinfo.channels);
|
||||
sf_close(sndfile);
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* Decode the whole audio file to a buffer. */
|
||||
membuf = malloc((size_t)(sfinfo.frames * sfinfo.channels) * sizeof(short));
|
||||
|
||||
num_frames = sf_readf_short(sndfile, membuf, sfinfo.frames);
|
||||
if(num_frames < 1)
|
||||
{
|
||||
free(membuf);
|
||||
sf_close(sndfile);
|
||||
fprintf(stderr, "Failed to read samples in %s (%" PRId64 ")\n", filename, num_frames);
|
||||
return 0;
|
||||
}
|
||||
num_bytes = (ALsizei)(num_frames * sfinfo.channels) * (ALsizei)sizeof(short);
|
||||
|
||||
/* Buffer the audio data into a new buffer object, then free the data and
|
||||
* close the file.
|
||||
*/
|
||||
buffer = 0;
|
||||
alGenBuffers(1, &buffer);
|
||||
alBufferData(buffer, format, membuf, num_bytes, sfinfo.samplerate);
|
||||
|
||||
free(membuf);
|
||||
sf_close(sndfile);
|
||||
|
||||
/* Check if an error occured, and clean up if so. */
|
||||
err = alGetError();
|
||||
if(err != AL_NO_ERROR)
|
||||
{
|
||||
fprintf(stderr, "OpenAL Error: %s\n", alGetString(err));
|
||||
if(buffer && alIsBuffer(buffer))
|
||||
alDeleteBuffers(1, &buffer);
|
||||
return 0;
|
||||
}
|
||||
|
||||
return buffer;
|
||||
}
|
||||
|
||||
|
||||
int main(int argc, char **argv)
|
||||
{
|
||||
ALuint source, buffer;
|
||||
ALdouble offsets[2];
|
||||
ALenum state;
|
||||
|
||||
/* Print out usage if no arguments were specified */
|
||||
if(argc < 2)
|
||||
{
|
||||
fprintf(stderr, "Usage: %s [-device <name>] <filename>\n", argv[0]);
|
||||
return 1;
|
||||
}
|
||||
|
||||
/* Initialize OpenAL, and check for source_latency support. */
|
||||
argv++; argc--;
|
||||
if(InitAL(&argv, &argc) != 0)
|
||||
return 1;
|
||||
|
||||
if(!alIsExtensionPresent("AL_SOFT_source_latency"))
|
||||
{
|
||||
fprintf(stderr, "Error: AL_SOFT_source_latency not supported\n");
|
||||
CloseAL();
|
||||
return 1;
|
||||
}
|
||||
|
||||
/* Define a macro to help load the function pointers. */
|
||||
#define LOAD_PROC(T, x) ((x) = FUNCTION_CAST(T, alGetProcAddress(#x)))
|
||||
LOAD_PROC(LPALSOURCEDSOFT, alSourcedSOFT);
|
||||
LOAD_PROC(LPALSOURCE3DSOFT, alSource3dSOFT);
|
||||
LOAD_PROC(LPALSOURCEDVSOFT, alSourcedvSOFT);
|
||||
LOAD_PROC(LPALGETSOURCEDSOFT, alGetSourcedSOFT);
|
||||
LOAD_PROC(LPALGETSOURCE3DSOFT, alGetSource3dSOFT);
|
||||
LOAD_PROC(LPALGETSOURCEDVSOFT, alGetSourcedvSOFT);
|
||||
LOAD_PROC(LPALSOURCEI64SOFT, alSourcei64SOFT);
|
||||
LOAD_PROC(LPALSOURCE3I64SOFT, alSource3i64SOFT);
|
||||
LOAD_PROC(LPALSOURCEI64VSOFT, alSourcei64vSOFT);
|
||||
LOAD_PROC(LPALGETSOURCEI64SOFT, alGetSourcei64SOFT);
|
||||
LOAD_PROC(LPALGETSOURCE3I64SOFT, alGetSource3i64SOFT);
|
||||
LOAD_PROC(LPALGETSOURCEI64VSOFT, alGetSourcei64vSOFT);
|
||||
#undef LOAD_PROC
|
||||
|
||||
/* Load the sound into a buffer. */
|
||||
buffer = LoadSound(argv[0]);
|
||||
if(!buffer)
|
||||
{
|
||||
CloseAL();
|
||||
return 1;
|
||||
}
|
||||
|
||||
/* Create the source to play the sound with. */
|
||||
source = 0;
|
||||
alGenSources(1, &source);
|
||||
alSourcei(source, AL_BUFFER, (ALint)buffer);
|
||||
assert(alGetError()==AL_NO_ERROR && "Failed to setup sound source");
|
||||
|
||||
/* Play the sound until it finishes. */
|
||||
alSourcePlay(source);
|
||||
do {
|
||||
al_nssleep(10000000);
|
||||
alGetSourcei(source, AL_SOURCE_STATE, &state);
|
||||
|
||||
/* Get the source offset and latency. AL_SEC_OFFSET_LATENCY_SOFT will
|
||||
* place the offset (in seconds) in offsets[0], and the time until that
|
||||
* offset will be heard (in seconds) in offsets[1]. */
|
||||
alGetSourcedvSOFT(source, AL_SEC_OFFSET_LATENCY_SOFT, offsets);
|
||||
printf("\rOffset: %f - Latency:%3u ms ", offsets[0], (ALuint)(offsets[1]*1000));
|
||||
fflush(stdout);
|
||||
} while(alGetError() == AL_NO_ERROR && state == AL_PLAYING);
|
||||
printf("\n");
|
||||
|
||||
/* All done. Delete resources, and close down OpenAL. */
|
||||
alDeleteSources(1, &source);
|
||||
alDeleteBuffers(1, &buffer);
|
||||
CloseAL();
|
||||
|
||||
return 0;
|
||||
}
|
||||
293
externals/openal-soft/examples/alloopback.c
vendored
Normal file
293
externals/openal-soft/examples/alloopback.c
vendored
Normal file
@@ -0,0 +1,293 @@
|
||||
/*
|
||||
* OpenAL Loopback Example
|
||||
*
|
||||
* Copyright (c) 2013 by Chris Robinson <chris.kcat@gmail.com>
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
* of this software and associated documentation files (the "Software"), to deal
|
||||
* in the Software without restriction, including without limitation the rights
|
||||
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
* copies of the Software, and to permit persons to whom the Software is
|
||||
* furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
* THE SOFTWARE.
|
||||
*/
|
||||
|
||||
/* This file contains an example for using the loopback device for custom
|
||||
* output handling.
|
||||
*/
|
||||
|
||||
#include <assert.h>
|
||||
#include <math.h>
|
||||
#include <stdio.h>
|
||||
|
||||
#define SDL_MAIN_HANDLED
|
||||
#include "SDL.h"
|
||||
#include "SDL_audio.h"
|
||||
#include "SDL_error.h"
|
||||
#include "SDL_stdinc.h"
|
||||
|
||||
#include "AL/al.h"
|
||||
#include "AL/alc.h"
|
||||
#include "AL/alext.h"
|
||||
|
||||
#include "common/alhelpers.h"
|
||||
|
||||
#ifndef SDL_AUDIO_MASK_BITSIZE
|
||||
#define SDL_AUDIO_MASK_BITSIZE (0xFF)
|
||||
#endif
|
||||
#ifndef SDL_AUDIO_BITSIZE
|
||||
#define SDL_AUDIO_BITSIZE(x) (x & SDL_AUDIO_MASK_BITSIZE)
|
||||
#endif
|
||||
|
||||
#ifndef M_PI
|
||||
#define M_PI (3.14159265358979323846)
|
||||
#endif
|
||||
|
||||
typedef struct {
|
||||
ALCdevice *Device;
|
||||
ALCcontext *Context;
|
||||
|
||||
ALCsizei FrameSize;
|
||||
} PlaybackInfo;
|
||||
|
||||
static LPALCLOOPBACKOPENDEVICESOFT alcLoopbackOpenDeviceSOFT;
|
||||
static LPALCISRENDERFORMATSUPPORTEDSOFT alcIsRenderFormatSupportedSOFT;
|
||||
static LPALCRENDERSAMPLESSOFT alcRenderSamplesSOFT;
|
||||
|
||||
|
||||
void SDLCALL RenderSDLSamples(void *userdata, Uint8 *stream, int len)
|
||||
{
|
||||
PlaybackInfo *playback = (PlaybackInfo*)userdata;
|
||||
alcRenderSamplesSOFT(playback->Device, stream, len/playback->FrameSize);
|
||||
}
|
||||
|
||||
|
||||
static const char *ChannelsName(ALCenum chans)
|
||||
{
|
||||
switch(chans)
|
||||
{
|
||||
case ALC_MONO_SOFT: return "Mono";
|
||||
case ALC_STEREO_SOFT: return "Stereo";
|
||||
case ALC_QUAD_SOFT: return "Quadraphonic";
|
||||
case ALC_5POINT1_SOFT: return "5.1 Surround";
|
||||
case ALC_6POINT1_SOFT: return "6.1 Surround";
|
||||
case ALC_7POINT1_SOFT: return "7.1 Surround";
|
||||
}
|
||||
return "Unknown Channels";
|
||||
}
|
||||
|
||||
static const char *TypeName(ALCenum type)
|
||||
{
|
||||
switch(type)
|
||||
{
|
||||
case ALC_BYTE_SOFT: return "S8";
|
||||
case ALC_UNSIGNED_BYTE_SOFT: return "U8";
|
||||
case ALC_SHORT_SOFT: return "S16";
|
||||
case ALC_UNSIGNED_SHORT_SOFT: return "U16";
|
||||
case ALC_INT_SOFT: return "S32";
|
||||
case ALC_UNSIGNED_INT_SOFT: return "U32";
|
||||
case ALC_FLOAT_SOFT: return "Float32";
|
||||
}
|
||||
return "Unknown Type";
|
||||
}
|
||||
|
||||
/* Creates a one second buffer containing a sine wave, and returns the new
|
||||
* buffer ID. */
|
||||
static ALuint CreateSineWave(void)
|
||||
{
|
||||
ALshort data[44100*4];
|
||||
ALuint buffer;
|
||||
ALenum err;
|
||||
ALuint i;
|
||||
|
||||
for(i = 0;i < 44100*4;i++)
|
||||
data[i] = (ALshort)(sin(i/44100.0 * 1000.0 * 2.0*M_PI) * 32767.0);
|
||||
|
||||
/* Buffer the audio data into a new buffer object. */
|
||||
buffer = 0;
|
||||
alGenBuffers(1, &buffer);
|
||||
alBufferData(buffer, AL_FORMAT_MONO16, data, sizeof(data), 44100);
|
||||
|
||||
/* Check if an error occured, and clean up if so. */
|
||||
err = alGetError();
|
||||
if(err != AL_NO_ERROR)
|
||||
{
|
||||
fprintf(stderr, "OpenAL Error: %s\n", alGetString(err));
|
||||
if(alIsBuffer(buffer))
|
||||
alDeleteBuffers(1, &buffer);
|
||||
return 0;
|
||||
}
|
||||
|
||||
return buffer;
|
||||
}
|
||||
|
||||
|
||||
int main(int argc, char *argv[])
|
||||
{
|
||||
PlaybackInfo playback = { NULL, NULL, 0 };
|
||||
SDL_AudioSpec desired, obtained;
|
||||
ALuint source, buffer;
|
||||
ALCint attrs[16];
|
||||
ALenum state;
|
||||
(void)argc;
|
||||
(void)argv;
|
||||
|
||||
SDL_SetMainReady();
|
||||
|
||||
/* Print out error if extension is missing. */
|
||||
if(!alcIsExtensionPresent(NULL, "ALC_SOFT_loopback"))
|
||||
{
|
||||
fprintf(stderr, "Error: ALC_SOFT_loopback not supported!\n");
|
||||
return 1;
|
||||
}
|
||||
|
||||
/* Define a macro to help load the function pointers. */
|
||||
#define LOAD_PROC(T, x) ((x) = FUNCTION_CAST(T, alcGetProcAddress(NULL, #x)))
|
||||
LOAD_PROC(LPALCLOOPBACKOPENDEVICESOFT, alcLoopbackOpenDeviceSOFT);
|
||||
LOAD_PROC(LPALCISRENDERFORMATSUPPORTEDSOFT, alcIsRenderFormatSupportedSOFT);
|
||||
LOAD_PROC(LPALCRENDERSAMPLESSOFT, alcRenderSamplesSOFT);
|
||||
#undef LOAD_PROC
|
||||
|
||||
if(SDL_Init(SDL_INIT_AUDIO) == -1)
|
||||
{
|
||||
fprintf(stderr, "Failed to init SDL audio: %s\n", SDL_GetError());
|
||||
return 1;
|
||||
}
|
||||
|
||||
/* Set up SDL audio with our requested format and callback. */
|
||||
desired.channels = 2;
|
||||
desired.format = AUDIO_S16SYS;
|
||||
desired.freq = 44100;
|
||||
desired.padding = 0;
|
||||
desired.samples = 4096;
|
||||
desired.callback = RenderSDLSamples;
|
||||
desired.userdata = &playback;
|
||||
if(SDL_OpenAudio(&desired, &obtained) != 0)
|
||||
{
|
||||
SDL_Quit();
|
||||
fprintf(stderr, "Failed to open SDL audio: %s\n", SDL_GetError());
|
||||
return 1;
|
||||
}
|
||||
|
||||
/* Set up our OpenAL attributes based on what we got from SDL. */
|
||||
attrs[0] = ALC_FORMAT_CHANNELS_SOFT;
|
||||
if(obtained.channels == 1)
|
||||
attrs[1] = ALC_MONO_SOFT;
|
||||
else if(obtained.channels == 2)
|
||||
attrs[1] = ALC_STEREO_SOFT;
|
||||
else
|
||||
{
|
||||
fprintf(stderr, "Unhandled SDL channel count: %d\n", obtained.channels);
|
||||
goto error;
|
||||
}
|
||||
|
||||
attrs[2] = ALC_FORMAT_TYPE_SOFT;
|
||||
if(obtained.format == AUDIO_U8)
|
||||
attrs[3] = ALC_UNSIGNED_BYTE_SOFT;
|
||||
else if(obtained.format == AUDIO_S8)
|
||||
attrs[3] = ALC_BYTE_SOFT;
|
||||
else if(obtained.format == AUDIO_U16SYS)
|
||||
attrs[3] = ALC_UNSIGNED_SHORT_SOFT;
|
||||
else if(obtained.format == AUDIO_S16SYS)
|
||||
attrs[3] = ALC_SHORT_SOFT;
|
||||
else if(obtained.format == AUDIO_S32SYS)
|
||||
attrs[3] = ALC_INT_SOFT;
|
||||
else if(obtained.format == AUDIO_F32SYS)
|
||||
attrs[3] = ALC_FLOAT_SOFT;
|
||||
else
|
||||
{
|
||||
fprintf(stderr, "Unhandled SDL format: 0x%04x\n", obtained.format);
|
||||
goto error;
|
||||
}
|
||||
|
||||
attrs[4] = ALC_FREQUENCY;
|
||||
attrs[5] = obtained.freq;
|
||||
|
||||
attrs[6] = 0; /* end of list */
|
||||
|
||||
playback.FrameSize = obtained.channels * SDL_AUDIO_BITSIZE(obtained.format) / 8;
|
||||
|
||||
/* Initialize OpenAL loopback device, using our format attributes. */
|
||||
playback.Device = alcLoopbackOpenDeviceSOFT(NULL);
|
||||
if(!playback.Device)
|
||||
{
|
||||
fprintf(stderr, "Failed to open loopback device!\n");
|
||||
goto error;
|
||||
}
|
||||
/* Make sure the format is supported before setting them on the device. */
|
||||
if(alcIsRenderFormatSupportedSOFT(playback.Device, attrs[5], attrs[1], attrs[3]) == ALC_FALSE)
|
||||
{
|
||||
fprintf(stderr, "Render format not supported: %s, %s, %dhz\n",
|
||||
ChannelsName(attrs[1]), TypeName(attrs[3]), attrs[5]);
|
||||
goto error;
|
||||
}
|
||||
playback.Context = alcCreateContext(playback.Device, attrs);
|
||||
if(!playback.Context || alcMakeContextCurrent(playback.Context) == ALC_FALSE)
|
||||
{
|
||||
fprintf(stderr, "Failed to set an OpenAL audio context\n");
|
||||
goto error;
|
||||
}
|
||||
|
||||
/* Start SDL playing. Our callback (thus alcRenderSamplesSOFT) will now
|
||||
* start being called regularly to update the AL playback state. */
|
||||
SDL_PauseAudio(0);
|
||||
|
||||
/* Load the sound into a buffer. */
|
||||
buffer = CreateSineWave();
|
||||
if(!buffer)
|
||||
{
|
||||
SDL_CloseAudio();
|
||||
alcDestroyContext(playback.Context);
|
||||
alcCloseDevice(playback.Device);
|
||||
SDL_Quit();
|
||||
return 1;
|
||||
}
|
||||
|
||||
/* Create the source to play the sound with. */
|
||||
source = 0;
|
||||
alGenSources(1, &source);
|
||||
alSourcei(source, AL_BUFFER, (ALint)buffer);
|
||||
assert(alGetError()==AL_NO_ERROR && "Failed to setup sound source");
|
||||
|
||||
/* Play the sound until it finishes. */
|
||||
alSourcePlay(source);
|
||||
do {
|
||||
al_nssleep(10000000);
|
||||
alGetSourcei(source, AL_SOURCE_STATE, &state);
|
||||
} while(alGetError() == AL_NO_ERROR && state == AL_PLAYING);
|
||||
|
||||
/* All done. Delete resources, and close OpenAL. */
|
||||
alDeleteSources(1, &source);
|
||||
alDeleteBuffers(1, &buffer);
|
||||
|
||||
/* Stop SDL playing. */
|
||||
SDL_PauseAudio(1);
|
||||
|
||||
/* Close up OpenAL and SDL. */
|
||||
SDL_CloseAudio();
|
||||
alcDestroyContext(playback.Context);
|
||||
alcCloseDevice(playback.Device);
|
||||
SDL_Quit();
|
||||
|
||||
return 0;
|
||||
|
||||
error:
|
||||
SDL_CloseAudio();
|
||||
if(playback.Context)
|
||||
alcDestroyContext(playback.Context);
|
||||
if(playback.Device)
|
||||
alcCloseDevice(playback.Device);
|
||||
SDL_Quit();
|
||||
|
||||
return 1;
|
||||
}
|
||||
688
externals/openal-soft/examples/almultireverb.c
vendored
Normal file
688
externals/openal-soft/examples/almultireverb.c
vendored
Normal file
@@ -0,0 +1,688 @@
|
||||
/*
|
||||
* OpenAL Multi-Zone Reverb Example
|
||||
*
|
||||
* Copyright (c) 2018 by Chris Robinson <chris.kcat@gmail.com>
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
* of this software and associated documentation files (the "Software"), to deal
|
||||
* in the Software without restriction, including without limitation the rights
|
||||
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
* copies of the Software, and to permit persons to whom the Software is
|
||||
* furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
* THE SOFTWARE.
|
||||
*/
|
||||
|
||||
/* This file contains an example for controlling multiple reverb zones to
|
||||
* smoothly transition between reverb environments. The general concept is to
|
||||
* extend single-reverb by also tracking the closest adjacent environment, and
|
||||
* utilize EAX Reverb's panning vectors to position them relative to the
|
||||
* listener.
|
||||
*/
|
||||
|
||||
|
||||
#include <assert.h>
|
||||
#include <inttypes.h>
|
||||
#include <limits.h>
|
||||
#include <math.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#include "sndfile.h"
|
||||
|
||||
#include "AL/al.h"
|
||||
#include "AL/alc.h"
|
||||
#include "AL/efx.h"
|
||||
#include "AL/efx-presets.h"
|
||||
|
||||
#include "common/alhelpers.h"
|
||||
|
||||
|
||||
#ifndef M_PI
|
||||
#define M_PI 3.14159265358979323846
|
||||
#endif
|
||||
|
||||
|
||||
/* Filter object functions */
|
||||
static LPALGENFILTERS alGenFilters;
|
||||
static LPALDELETEFILTERS alDeleteFilters;
|
||||
static LPALISFILTER alIsFilter;
|
||||
static LPALFILTERI alFilteri;
|
||||
static LPALFILTERIV alFilteriv;
|
||||
static LPALFILTERF alFilterf;
|
||||
static LPALFILTERFV alFilterfv;
|
||||
static LPALGETFILTERI alGetFilteri;
|
||||
static LPALGETFILTERIV alGetFilteriv;
|
||||
static LPALGETFILTERF alGetFilterf;
|
||||
static LPALGETFILTERFV alGetFilterfv;
|
||||
|
||||
/* Effect object functions */
|
||||
static LPALGENEFFECTS alGenEffects;
|
||||
static LPALDELETEEFFECTS alDeleteEffects;
|
||||
static LPALISEFFECT alIsEffect;
|
||||
static LPALEFFECTI alEffecti;
|
||||
static LPALEFFECTIV alEffectiv;
|
||||
static LPALEFFECTF alEffectf;
|
||||
static LPALEFFECTFV alEffectfv;
|
||||
static LPALGETEFFECTI alGetEffecti;
|
||||
static LPALGETEFFECTIV alGetEffectiv;
|
||||
static LPALGETEFFECTF alGetEffectf;
|
||||
static LPALGETEFFECTFV alGetEffectfv;
|
||||
|
||||
/* Auxiliary Effect Slot object functions */
|
||||
static LPALGENAUXILIARYEFFECTSLOTS alGenAuxiliaryEffectSlots;
|
||||
static LPALDELETEAUXILIARYEFFECTSLOTS alDeleteAuxiliaryEffectSlots;
|
||||
static LPALISAUXILIARYEFFECTSLOT alIsAuxiliaryEffectSlot;
|
||||
static LPALAUXILIARYEFFECTSLOTI alAuxiliaryEffectSloti;
|
||||
static LPALAUXILIARYEFFECTSLOTIV alAuxiliaryEffectSlotiv;
|
||||
static LPALAUXILIARYEFFECTSLOTF alAuxiliaryEffectSlotf;
|
||||
static LPALAUXILIARYEFFECTSLOTFV alAuxiliaryEffectSlotfv;
|
||||
static LPALGETAUXILIARYEFFECTSLOTI alGetAuxiliaryEffectSloti;
|
||||
static LPALGETAUXILIARYEFFECTSLOTIV alGetAuxiliaryEffectSlotiv;
|
||||
static LPALGETAUXILIARYEFFECTSLOTF alGetAuxiliaryEffectSlotf;
|
||||
static LPALGETAUXILIARYEFFECTSLOTFV alGetAuxiliaryEffectSlotfv;
|
||||
|
||||
|
||||
/* LoadEffect loads the given initial reverb properties into the given OpenAL
|
||||
* effect object, and returns non-zero on success.
|
||||
*/
|
||||
static int LoadEffect(ALuint effect, const EFXEAXREVERBPROPERTIES *reverb)
|
||||
{
|
||||
ALenum err;
|
||||
|
||||
alGetError();
|
||||
|
||||
/* Prepare the effect for EAX Reverb (standard reverb doesn't contain
|
||||
* the needed panning vectors).
|
||||
*/
|
||||
alEffecti(effect, AL_EFFECT_TYPE, AL_EFFECT_EAXREVERB);
|
||||
if((err=alGetError()) != AL_NO_ERROR)
|
||||
{
|
||||
fprintf(stderr, "Failed to set EAX Reverb: %s (0x%04x)\n", alGetString(err), err);
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* Load the reverb properties. */
|
||||
alEffectf(effect, AL_EAXREVERB_DENSITY, reverb->flDensity);
|
||||
alEffectf(effect, AL_EAXREVERB_DIFFUSION, reverb->flDiffusion);
|
||||
alEffectf(effect, AL_EAXREVERB_GAIN, reverb->flGain);
|
||||
alEffectf(effect, AL_EAXREVERB_GAINHF, reverb->flGainHF);
|
||||
alEffectf(effect, AL_EAXREVERB_GAINLF, reverb->flGainLF);
|
||||
alEffectf(effect, AL_EAXREVERB_DECAY_TIME, reverb->flDecayTime);
|
||||
alEffectf(effect, AL_EAXREVERB_DECAY_HFRATIO, reverb->flDecayHFRatio);
|
||||
alEffectf(effect, AL_EAXREVERB_DECAY_LFRATIO, reverb->flDecayLFRatio);
|
||||
alEffectf(effect, AL_EAXREVERB_REFLECTIONS_GAIN, reverb->flReflectionsGain);
|
||||
alEffectf(effect, AL_EAXREVERB_REFLECTIONS_DELAY, reverb->flReflectionsDelay);
|
||||
alEffectfv(effect, AL_EAXREVERB_REFLECTIONS_PAN, reverb->flReflectionsPan);
|
||||
alEffectf(effect, AL_EAXREVERB_LATE_REVERB_GAIN, reverb->flLateReverbGain);
|
||||
alEffectf(effect, AL_EAXREVERB_LATE_REVERB_DELAY, reverb->flLateReverbDelay);
|
||||
alEffectfv(effect, AL_EAXREVERB_LATE_REVERB_PAN, reverb->flLateReverbPan);
|
||||
alEffectf(effect, AL_EAXREVERB_ECHO_TIME, reverb->flEchoTime);
|
||||
alEffectf(effect, AL_EAXREVERB_ECHO_DEPTH, reverb->flEchoDepth);
|
||||
alEffectf(effect, AL_EAXREVERB_MODULATION_TIME, reverb->flModulationTime);
|
||||
alEffectf(effect, AL_EAXREVERB_MODULATION_DEPTH, reverb->flModulationDepth);
|
||||
alEffectf(effect, AL_EAXREVERB_AIR_ABSORPTION_GAINHF, reverb->flAirAbsorptionGainHF);
|
||||
alEffectf(effect, AL_EAXREVERB_HFREFERENCE, reverb->flHFReference);
|
||||
alEffectf(effect, AL_EAXREVERB_LFREFERENCE, reverb->flLFReference);
|
||||
alEffectf(effect, AL_EAXREVERB_ROOM_ROLLOFF_FACTOR, reverb->flRoomRolloffFactor);
|
||||
alEffecti(effect, AL_EAXREVERB_DECAY_HFLIMIT, reverb->iDecayHFLimit);
|
||||
|
||||
/* Check if an error occured, and return failure if so. */
|
||||
if((err=alGetError()) != AL_NO_ERROR)
|
||||
{
|
||||
fprintf(stderr, "Error setting up reverb: %s\n", alGetString(err));
|
||||
return 0;
|
||||
}
|
||||
|
||||
return 1;
|
||||
}
|
||||
|
||||
|
||||
/* LoadBuffer loads the named audio file into an OpenAL buffer object, and
|
||||
* returns the new buffer ID.
|
||||
*/
|
||||
static ALuint LoadSound(const char *filename)
|
||||
{
|
||||
ALenum err, format;
|
||||
ALuint buffer;
|
||||
SNDFILE *sndfile;
|
||||
SF_INFO sfinfo;
|
||||
short *membuf;
|
||||
sf_count_t num_frames;
|
||||
ALsizei num_bytes;
|
||||
|
||||
/* Open the audio file and check that it's usable. */
|
||||
sndfile = sf_open(filename, SFM_READ, &sfinfo);
|
||||
if(!sndfile)
|
||||
{
|
||||
fprintf(stderr, "Could not open audio in %s: %s\n", filename, sf_strerror(sndfile));
|
||||
return 0;
|
||||
}
|
||||
if(sfinfo.frames < 1 || sfinfo.frames > (sf_count_t)(INT_MAX/sizeof(short))/sfinfo.channels)
|
||||
{
|
||||
fprintf(stderr, "Bad sample count in %s (%" PRId64 ")\n", filename, sfinfo.frames);
|
||||
sf_close(sndfile);
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* Get the sound format, and figure out the OpenAL format */
|
||||
if(sfinfo.channels == 1)
|
||||
format = AL_FORMAT_MONO16;
|
||||
else if(sfinfo.channels == 2)
|
||||
format = AL_FORMAT_STEREO16;
|
||||
else
|
||||
{
|
||||
fprintf(stderr, "Unsupported channel count: %d\n", sfinfo.channels);
|
||||
sf_close(sndfile);
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* Decode the whole audio file to a buffer. */
|
||||
membuf = malloc((size_t)(sfinfo.frames * sfinfo.channels) * sizeof(short));
|
||||
|
||||
num_frames = sf_readf_short(sndfile, membuf, sfinfo.frames);
|
||||
if(num_frames < 1)
|
||||
{
|
||||
free(membuf);
|
||||
sf_close(sndfile);
|
||||
fprintf(stderr, "Failed to read samples in %s (%" PRId64 ")\n", filename, num_frames);
|
||||
return 0;
|
||||
}
|
||||
num_bytes = (ALsizei)(num_frames * sfinfo.channels) * (ALsizei)sizeof(short);
|
||||
|
||||
/* Buffer the audio data into a new buffer object, then free the data and
|
||||
* close the file.
|
||||
*/
|
||||
buffer = 0;
|
||||
alGenBuffers(1, &buffer);
|
||||
alBufferData(buffer, format, membuf, num_bytes, sfinfo.samplerate);
|
||||
|
||||
free(membuf);
|
||||
sf_close(sndfile);
|
||||
|
||||
/* Check if an error occured, and clean up if so. */
|
||||
err = alGetError();
|
||||
if(err != AL_NO_ERROR)
|
||||
{
|
||||
fprintf(stderr, "OpenAL Error: %s\n", alGetString(err));
|
||||
if(buffer && alIsBuffer(buffer))
|
||||
alDeleteBuffers(1, &buffer);
|
||||
return 0;
|
||||
}
|
||||
|
||||
return buffer;
|
||||
}
|
||||
|
||||
|
||||
/* Helper to calculate the dot-product of the two given vectors. */
|
||||
static ALfloat dot_product(const ALfloat vec0[3], const ALfloat vec1[3])
|
||||
{
|
||||
return vec0[0]*vec1[0] + vec0[1]*vec1[1] + vec0[2]*vec1[2];
|
||||
}
|
||||
|
||||
/* Helper to normalize a given vector. */
|
||||
static void normalize(ALfloat vec[3])
|
||||
{
|
||||
ALfloat mag = sqrtf(dot_product(vec, vec));
|
||||
if(mag > 0.00001f)
|
||||
{
|
||||
vec[0] /= mag;
|
||||
vec[1] /= mag;
|
||||
vec[2] /= mag;
|
||||
}
|
||||
else
|
||||
{
|
||||
vec[0] = 0.0f;
|
||||
vec[1] = 0.0f;
|
||||
vec[2] = 0.0f;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/* The main update function to update the listener and environment effects. */
|
||||
static void UpdateListenerAndEffects(float timediff, const ALuint slots[2], const ALuint effects[2], const EFXEAXREVERBPROPERTIES reverbs[2])
|
||||
{
|
||||
static const ALfloat listener_move_scale = 10.0f;
|
||||
/* Individual reverb zones are connected via "portals". Each portal has a
|
||||
* position (center point of the connecting area), a normal (facing
|
||||
* direction), and a radius (approximate size of the connecting area).
|
||||
*/
|
||||
const ALfloat portal_pos[3] = { 0.0f, 0.0f, 0.0f };
|
||||
const ALfloat portal_norm[3] = { sqrtf(0.5f), 0.0f, -sqrtf(0.5f) };
|
||||
const ALfloat portal_radius = 2.5f;
|
||||
ALfloat other_dir[3], this_dir[3];
|
||||
ALfloat listener_pos[3];
|
||||
ALfloat local_norm[3];
|
||||
ALfloat local_dir[3];
|
||||
ALfloat near_edge[3];
|
||||
ALfloat far_edge[3];
|
||||
ALfloat dist, edist;
|
||||
|
||||
/* Update the listener position for the amount of time passed. This uses a
|
||||
* simple triangular LFO to offset the position (moves along the X axis
|
||||
* between -listener_move_scale and +listener_move_scale for each
|
||||
* transition).
|
||||
*/
|
||||
listener_pos[0] = (fabsf(2.0f - timediff/2.0f) - 1.0f) * listener_move_scale;
|
||||
listener_pos[1] = 0.0f;
|
||||
listener_pos[2] = 0.0f;
|
||||
alListenerfv(AL_POSITION, listener_pos);
|
||||
|
||||
/* Calculate local_dir, which represents the listener-relative point to the
|
||||
* adjacent zone (should also include orientation). Because EAX Reverb uses
|
||||
* left-handed coordinates instead of right-handed like the rest of OpenAL,
|
||||
* negate Z for the local values.
|
||||
*/
|
||||
local_dir[0] = portal_pos[0] - listener_pos[0];
|
||||
local_dir[1] = portal_pos[1] - listener_pos[1];
|
||||
local_dir[2] = -(portal_pos[2] - listener_pos[2]);
|
||||
/* A normal application would also rotate the portal's normal given the
|
||||
* listener orientation, to get the listener-relative normal.
|
||||
*/
|
||||
local_norm[0] = portal_norm[0];
|
||||
local_norm[1] = portal_norm[1];
|
||||
local_norm[2] = -portal_norm[2];
|
||||
|
||||
/* Calculate the distance from the listener to the portal, and ensure it's
|
||||
* far enough away to not suffer severe floating-point precision issues.
|
||||
*/
|
||||
dist = sqrtf(dot_product(local_dir, local_dir));
|
||||
if(dist > 0.00001f)
|
||||
{
|
||||
const EFXEAXREVERBPROPERTIES *other_reverb, *this_reverb;
|
||||
ALuint other_effect, this_effect;
|
||||
ALfloat magnitude, dir_dot_norm;
|
||||
|
||||
/* Normalize the direction to the portal. */
|
||||
local_dir[0] /= dist;
|
||||
local_dir[1] /= dist;
|
||||
local_dir[2] /= dist;
|
||||
|
||||
/* Calculate the dot product of the portal's local direction and local
|
||||
* normal, which is used for angular and side checks later on.
|
||||
*/
|
||||
dir_dot_norm = dot_product(local_dir, local_norm);
|
||||
|
||||
/* Figure out which zone we're in. */
|
||||
if(dir_dot_norm <= 0.0f)
|
||||
{
|
||||
/* We're in front of the portal, so we're in Zone 0. */
|
||||
this_effect = effects[0];
|
||||
other_effect = effects[1];
|
||||
this_reverb = &reverbs[0];
|
||||
other_reverb = &reverbs[1];
|
||||
}
|
||||
else
|
||||
{
|
||||
/* We're behind the portal, so we're in Zone 1. */
|
||||
this_effect = effects[1];
|
||||
other_effect = effects[0];
|
||||
this_reverb = &reverbs[1];
|
||||
other_reverb = &reverbs[0];
|
||||
}
|
||||
|
||||
/* Calculate the listener-relative extents of the portal. */
|
||||
/* First, project the listener-to-portal vector onto the portal's plane
|
||||
* to get the portal-relative direction along the plane that goes away
|
||||
* from the listener (toward the farthest edge of the portal).
|
||||
*/
|
||||
far_edge[0] = local_dir[0] - local_norm[0]*dir_dot_norm;
|
||||
far_edge[1] = local_dir[1] - local_norm[1]*dir_dot_norm;
|
||||
far_edge[2] = local_dir[2] - local_norm[2]*dir_dot_norm;
|
||||
|
||||
edist = sqrtf(dot_product(far_edge, far_edge));
|
||||
if(edist > 0.0001f)
|
||||
{
|
||||
/* Rescale the portal-relative vector to be at the radius edge. */
|
||||
ALfloat mag = portal_radius / edist;
|
||||
far_edge[0] *= mag;
|
||||
far_edge[1] *= mag;
|
||||
far_edge[2] *= mag;
|
||||
|
||||
/* Calculate the closest edge of the portal by negating the
|
||||
* farthest, and add an offset to make them both relative to the
|
||||
* listener.
|
||||
*/
|
||||
near_edge[0] = local_dir[0]*dist - far_edge[0];
|
||||
near_edge[1] = local_dir[1]*dist - far_edge[1];
|
||||
near_edge[2] = local_dir[2]*dist - far_edge[2];
|
||||
far_edge[0] += local_dir[0]*dist;
|
||||
far_edge[1] += local_dir[1]*dist;
|
||||
far_edge[2] += local_dir[2]*dist;
|
||||
|
||||
/* Normalize the listener-relative extents of the portal, then
|
||||
* calculate the panning magnitude for the other zone given the
|
||||
* apparent size of the opening. The panning magnitude affects the
|
||||
* envelopment of the environment, with 1 being a point, 0.5 being
|
||||
* half coverage around the listener, and 0 being full coverage.
|
||||
*/
|
||||
normalize(far_edge);
|
||||
normalize(near_edge);
|
||||
magnitude = 1.0f - acosf(dot_product(far_edge, near_edge))/(float)(M_PI*2.0);
|
||||
|
||||
/* Recalculate the panning direction, to be directly between the
|
||||
* direction of the two extents.
|
||||
*/
|
||||
local_dir[0] = far_edge[0] + near_edge[0];
|
||||
local_dir[1] = far_edge[1] + near_edge[1];
|
||||
local_dir[2] = far_edge[2] + near_edge[2];
|
||||
normalize(local_dir);
|
||||
}
|
||||
else
|
||||
{
|
||||
/* If we get here, the listener is directly in front of or behind
|
||||
* the center of the portal, making all aperture edges effectively
|
||||
* equidistant. Calculating the panning magnitude is simplified,
|
||||
* using the arctangent of the radius and distance.
|
||||
*/
|
||||
magnitude = 1.0f - (atan2f(portal_radius, dist) / (float)M_PI);
|
||||
}
|
||||
|
||||
/* Scale the other zone's panning vector. */
|
||||
other_dir[0] = local_dir[0] * magnitude;
|
||||
other_dir[1] = local_dir[1] * magnitude;
|
||||
other_dir[2] = local_dir[2] * magnitude;
|
||||
/* Pan the current zone to the opposite direction of the portal, and
|
||||
* take the remaining percentage of the portal's magnitude.
|
||||
*/
|
||||
this_dir[0] = local_dir[0] * (magnitude-1.0f);
|
||||
this_dir[1] = local_dir[1] * (magnitude-1.0f);
|
||||
this_dir[2] = local_dir[2] * (magnitude-1.0f);
|
||||
|
||||
/* Now set the effects' panning vectors and gain. Energy is shared
|
||||
* between environments, so attenuate according to each zone's
|
||||
* contribution (note: gain^2 = energy).
|
||||
*/
|
||||
alEffectf(this_effect, AL_EAXREVERB_REFLECTIONS_GAIN, this_reverb->flReflectionsGain * sqrtf(magnitude));
|
||||
alEffectf(this_effect, AL_EAXREVERB_LATE_REVERB_GAIN, this_reverb->flLateReverbGain * sqrtf(magnitude));
|
||||
alEffectfv(this_effect, AL_EAXREVERB_REFLECTIONS_PAN, this_dir);
|
||||
alEffectfv(this_effect, AL_EAXREVERB_LATE_REVERB_PAN, this_dir);
|
||||
|
||||
alEffectf(other_effect, AL_EAXREVERB_REFLECTIONS_GAIN, other_reverb->flReflectionsGain * sqrtf(1.0f-magnitude));
|
||||
alEffectf(other_effect, AL_EAXREVERB_LATE_REVERB_GAIN, other_reverb->flLateReverbGain * sqrtf(1.0f-magnitude));
|
||||
alEffectfv(other_effect, AL_EAXREVERB_REFLECTIONS_PAN, other_dir);
|
||||
alEffectfv(other_effect, AL_EAXREVERB_LATE_REVERB_PAN, other_dir);
|
||||
}
|
||||
else
|
||||
{
|
||||
/* We're practically in the center of the portal. Give the panning
|
||||
* vectors a 50/50 split, with Zone 0 covering the half in front of
|
||||
* the normal, and Zone 1 covering the half behind.
|
||||
*/
|
||||
this_dir[0] = local_norm[0] / 2.0f;
|
||||
this_dir[1] = local_norm[1] / 2.0f;
|
||||
this_dir[2] = local_norm[2] / 2.0f;
|
||||
|
||||
other_dir[0] = local_norm[0] / -2.0f;
|
||||
other_dir[1] = local_norm[1] / -2.0f;
|
||||
other_dir[2] = local_norm[2] / -2.0f;
|
||||
|
||||
alEffectf(effects[0], AL_EAXREVERB_REFLECTIONS_GAIN, reverbs[0].flReflectionsGain * sqrtf(0.5f));
|
||||
alEffectf(effects[0], AL_EAXREVERB_LATE_REVERB_GAIN, reverbs[0].flLateReverbGain * sqrtf(0.5f));
|
||||
alEffectfv(effects[0], AL_EAXREVERB_REFLECTIONS_PAN, this_dir);
|
||||
alEffectfv(effects[0], AL_EAXREVERB_LATE_REVERB_PAN, this_dir);
|
||||
|
||||
alEffectf(effects[1], AL_EAXREVERB_REFLECTIONS_GAIN, reverbs[1].flReflectionsGain * sqrtf(0.5f));
|
||||
alEffectf(effects[1], AL_EAXREVERB_LATE_REVERB_GAIN, reverbs[1].flLateReverbGain * sqrtf(0.5f));
|
||||
alEffectfv(effects[1], AL_EAXREVERB_REFLECTIONS_PAN, other_dir);
|
||||
alEffectfv(effects[1], AL_EAXREVERB_LATE_REVERB_PAN, other_dir);
|
||||
}
|
||||
|
||||
/* Finally, update the effect slots with the updated effect parameters. */
|
||||
alAuxiliaryEffectSloti(slots[0], AL_EFFECTSLOT_EFFECT, (ALint)effects[0]);
|
||||
alAuxiliaryEffectSloti(slots[1], AL_EFFECTSLOT_EFFECT, (ALint)effects[1]);
|
||||
}
|
||||
|
||||
|
||||
int main(int argc, char **argv)
|
||||
{
|
||||
static const int MaxTransitions = 8;
|
||||
EFXEAXREVERBPROPERTIES reverbs[2] = {
|
||||
EFX_REVERB_PRESET_CARPETEDHALLWAY,
|
||||
EFX_REVERB_PRESET_BATHROOM
|
||||
};
|
||||
ALCdevice *device = NULL;
|
||||
ALCcontext *context = NULL;
|
||||
ALuint effects[2] = { 0, 0 };
|
||||
ALuint slots[2] = { 0, 0 };
|
||||
ALuint direct_filter = 0;
|
||||
ALuint buffer = 0;
|
||||
ALuint source = 0;
|
||||
ALCint num_sends = 0;
|
||||
ALenum state = AL_INITIAL;
|
||||
ALfloat direct_gain = 1.0f;
|
||||
int basetime = 0;
|
||||
int loops = 0;
|
||||
|
||||
/* Print out usage if no arguments were specified */
|
||||
if(argc < 2)
|
||||
{
|
||||
fprintf(stderr, "Usage: %s [-device <name>] [options] <filename>\n\n"
|
||||
"Options:\n"
|
||||
"\t-nodirect\tSilence direct path output (easier to hear reverb)\n\n",
|
||||
argv[0]);
|
||||
return 1;
|
||||
}
|
||||
|
||||
/* Initialize OpenAL, and check for EFX support with at least 2 auxiliary
|
||||
* sends (if multiple sends are supported, 2 are provided by default; if
|
||||
* you want more, you have to request it through alcCreateContext).
|
||||
*/
|
||||
argv++; argc--;
|
||||
if(InitAL(&argv, &argc) != 0)
|
||||
return 1;
|
||||
|
||||
while(argc > 0)
|
||||
{
|
||||
if(strcmp(argv[0], "-nodirect") == 0)
|
||||
direct_gain = 0.0f;
|
||||
else
|
||||
break;
|
||||
argv++;
|
||||
argc--;
|
||||
}
|
||||
if(argc < 1)
|
||||
{
|
||||
fprintf(stderr, "No filename spacified.\n");
|
||||
CloseAL();
|
||||
return 1;
|
||||
}
|
||||
|
||||
context = alcGetCurrentContext();
|
||||
device = alcGetContextsDevice(context);
|
||||
|
||||
if(!alcIsExtensionPresent(device, "ALC_EXT_EFX"))
|
||||
{
|
||||
fprintf(stderr, "Error: EFX not supported\n");
|
||||
CloseAL();
|
||||
return 1;
|
||||
}
|
||||
|
||||
num_sends = 0;
|
||||
alcGetIntegerv(device, ALC_MAX_AUXILIARY_SENDS, 1, &num_sends);
|
||||
if(alcGetError(device) != ALC_NO_ERROR || num_sends < 2)
|
||||
{
|
||||
fprintf(stderr, "Error: Device does not support multiple sends (got %d, need 2)\n",
|
||||
num_sends);
|
||||
CloseAL();
|
||||
return 1;
|
||||
}
|
||||
|
||||
/* Define a macro to help load the function pointers. */
|
||||
#define LOAD_PROC(T, x) ((x) = FUNCTION_CAST(T, alGetProcAddress(#x)))
|
||||
LOAD_PROC(LPALGENFILTERS, alGenFilters);
|
||||
LOAD_PROC(LPALDELETEFILTERS, alDeleteFilters);
|
||||
LOAD_PROC(LPALISFILTER, alIsFilter);
|
||||
LOAD_PROC(LPALFILTERI, alFilteri);
|
||||
LOAD_PROC(LPALFILTERIV, alFilteriv);
|
||||
LOAD_PROC(LPALFILTERF, alFilterf);
|
||||
LOAD_PROC(LPALFILTERFV, alFilterfv);
|
||||
LOAD_PROC(LPALGETFILTERI, alGetFilteri);
|
||||
LOAD_PROC(LPALGETFILTERIV, alGetFilteriv);
|
||||
LOAD_PROC(LPALGETFILTERF, alGetFilterf);
|
||||
LOAD_PROC(LPALGETFILTERFV, alGetFilterfv);
|
||||
|
||||
LOAD_PROC(LPALGENEFFECTS, alGenEffects);
|
||||
LOAD_PROC(LPALDELETEEFFECTS, alDeleteEffects);
|
||||
LOAD_PROC(LPALISEFFECT, alIsEffect);
|
||||
LOAD_PROC(LPALEFFECTI, alEffecti);
|
||||
LOAD_PROC(LPALEFFECTIV, alEffectiv);
|
||||
LOAD_PROC(LPALEFFECTF, alEffectf);
|
||||
LOAD_PROC(LPALEFFECTFV, alEffectfv);
|
||||
LOAD_PROC(LPALGETEFFECTI, alGetEffecti);
|
||||
LOAD_PROC(LPALGETEFFECTIV, alGetEffectiv);
|
||||
LOAD_PROC(LPALGETEFFECTF, alGetEffectf);
|
||||
LOAD_PROC(LPALGETEFFECTFV, alGetEffectfv);
|
||||
|
||||
LOAD_PROC(LPALGENAUXILIARYEFFECTSLOTS, alGenAuxiliaryEffectSlots);
|
||||
LOAD_PROC(LPALDELETEAUXILIARYEFFECTSLOTS, alDeleteAuxiliaryEffectSlots);
|
||||
LOAD_PROC(LPALISAUXILIARYEFFECTSLOT, alIsAuxiliaryEffectSlot);
|
||||
LOAD_PROC(LPALAUXILIARYEFFECTSLOTI, alAuxiliaryEffectSloti);
|
||||
LOAD_PROC(LPALAUXILIARYEFFECTSLOTIV, alAuxiliaryEffectSlotiv);
|
||||
LOAD_PROC(LPALAUXILIARYEFFECTSLOTF, alAuxiliaryEffectSlotf);
|
||||
LOAD_PROC(LPALAUXILIARYEFFECTSLOTFV, alAuxiliaryEffectSlotfv);
|
||||
LOAD_PROC(LPALGETAUXILIARYEFFECTSLOTI, alGetAuxiliaryEffectSloti);
|
||||
LOAD_PROC(LPALGETAUXILIARYEFFECTSLOTIV, alGetAuxiliaryEffectSlotiv);
|
||||
LOAD_PROC(LPALGETAUXILIARYEFFECTSLOTF, alGetAuxiliaryEffectSlotf);
|
||||
LOAD_PROC(LPALGETAUXILIARYEFFECTSLOTFV, alGetAuxiliaryEffectSlotfv);
|
||||
#undef LOAD_PROC
|
||||
|
||||
/* Load the sound into a buffer. */
|
||||
buffer = LoadSound(argv[0]);
|
||||
if(!buffer)
|
||||
{
|
||||
CloseAL();
|
||||
return 1;
|
||||
}
|
||||
|
||||
/* Generate two effects for two "zones", and load a reverb into each one.
|
||||
* Note that unlike single-zone reverb, where you can store one effect per
|
||||
* preset, for multi-zone reverb you should have one effect per environment
|
||||
* instance, or one per audible zone. This is because we'll be changing the
|
||||
* effects' properties in real-time based on the environment instance
|
||||
* relative to the listener.
|
||||
*/
|
||||
alGenEffects(2, effects);
|
||||
if(!LoadEffect(effects[0], &reverbs[0]) || !LoadEffect(effects[1], &reverbs[1]))
|
||||
{
|
||||
alDeleteEffects(2, effects);
|
||||
alDeleteBuffers(1, &buffer);
|
||||
CloseAL();
|
||||
return 1;
|
||||
}
|
||||
|
||||
/* Create the effect slot objects, one for each "active" effect. */
|
||||
alGenAuxiliaryEffectSlots(2, slots);
|
||||
|
||||
/* Tell the effect slots to use the loaded effect objects, with slot 0 for
|
||||
* Zone 0 and slot 1 for Zone 1. Note that this effectively copies the
|
||||
* effect properties. Modifying or deleting the effect object afterward
|
||||
* won't directly affect the effect slot until they're reapplied like this.
|
||||
*/
|
||||
alAuxiliaryEffectSloti(slots[0], AL_EFFECTSLOT_EFFECT, (ALint)effects[0]);
|
||||
alAuxiliaryEffectSloti(slots[1], AL_EFFECTSLOT_EFFECT, (ALint)effects[1]);
|
||||
assert(alGetError()==AL_NO_ERROR && "Failed to set effect slot");
|
||||
|
||||
/* For the purposes of this example, prepare a filter that optionally
|
||||
* silences the direct path which allows us to hear just the reverberation.
|
||||
* A filter like this is normally used for obstruction, where the path
|
||||
* directly between the listener and source is blocked (the exact
|
||||
* properties depending on the type and thickness of the obstructing
|
||||
* material).
|
||||
*/
|
||||
alGenFilters(1, &direct_filter);
|
||||
alFilteri(direct_filter, AL_FILTER_TYPE, AL_FILTER_LOWPASS);
|
||||
alFilterf(direct_filter, AL_LOWPASS_GAIN, direct_gain);
|
||||
assert(alGetError()==AL_NO_ERROR && "Failed to set direct filter");
|
||||
|
||||
/* Create the source to play the sound with, place it in front of the
|
||||
* listener's path in the left zone.
|
||||
*/
|
||||
source = 0;
|
||||
alGenSources(1, &source);
|
||||
alSourcei(source, AL_LOOPING, AL_TRUE);
|
||||
alSource3f(source, AL_POSITION, -5.0f, 0.0f, -2.0f);
|
||||
alSourcei(source, AL_DIRECT_FILTER, (ALint)direct_filter);
|
||||
alSourcei(source, AL_BUFFER, (ALint)buffer);
|
||||
|
||||
/* Connect the source to the effect slots. Here, we connect source send 0
|
||||
* to Zone 0's slot, and send 1 to Zone 1's slot. Filters can be specified
|
||||
* to occlude the source from each zone by varying amounts; for example, a
|
||||
* source within a particular zone would be unfiltered, while a source that
|
||||
* can only see a zone through a window or thin wall may be attenuated for
|
||||
* that zone.
|
||||
*/
|
||||
alSource3i(source, AL_AUXILIARY_SEND_FILTER, (ALint)slots[0], 0, AL_FILTER_NULL);
|
||||
alSource3i(source, AL_AUXILIARY_SEND_FILTER, (ALint)slots[1], 1, AL_FILTER_NULL);
|
||||
assert(alGetError()==AL_NO_ERROR && "Failed to setup sound source");
|
||||
|
||||
/* Get the current time as the base for timing in the main loop. */
|
||||
basetime = altime_get();
|
||||
loops = 0;
|
||||
printf("Transition %d of %d...\n", loops+1, MaxTransitions);
|
||||
|
||||
/* Play the sound for a while. */
|
||||
alSourcePlay(source);
|
||||
do {
|
||||
int curtime;
|
||||
ALfloat timediff;
|
||||
|
||||
/* Start a batch update, to ensure all changes apply simultaneously. */
|
||||
alcSuspendContext(context);
|
||||
|
||||
/* Get the current time to track the amount of time that passed.
|
||||
* Convert the difference to seconds.
|
||||
*/
|
||||
curtime = altime_get();
|
||||
timediff = (float)(curtime - basetime) / 1000.0f;
|
||||
|
||||
/* Avoid negative time deltas, in case of non-monotonic clocks. */
|
||||
if(timediff < 0.0f)
|
||||
timediff = 0.0f;
|
||||
else while(timediff >= 4.0f*(float)((loops&1)+1))
|
||||
{
|
||||
/* For this example, each transition occurs over 4 seconds, and
|
||||
* there's 2 transitions per cycle.
|
||||
*/
|
||||
if(++loops < MaxTransitions)
|
||||
printf("Transition %d of %d...\n", loops+1, MaxTransitions);
|
||||
if(!(loops&1))
|
||||
{
|
||||
/* Cycle completed. Decrease the delta and increase the base
|
||||
* time to start a new cycle.
|
||||
*/
|
||||
timediff -= 8.0f;
|
||||
basetime += 8000;
|
||||
}
|
||||
}
|
||||
|
||||
/* Update the listener and effects, and finish the batch. */
|
||||
UpdateListenerAndEffects(timediff, slots, effects, reverbs);
|
||||
alcProcessContext(context);
|
||||
|
||||
al_nssleep(10000000);
|
||||
|
||||
alGetSourcei(source, AL_SOURCE_STATE, &state);
|
||||
} while(alGetError() == AL_NO_ERROR && state == AL_PLAYING && loops < MaxTransitions);
|
||||
|
||||
/* All done. Delete resources, and close down OpenAL. */
|
||||
alDeleteSources(1, &source);
|
||||
alDeleteAuxiliaryEffectSlots(2, slots);
|
||||
alDeleteEffects(2, effects);
|
||||
alDeleteFilters(1, &direct_filter);
|
||||
alDeleteBuffers(1, &buffer);
|
||||
|
||||
CloseAL();
|
||||
|
||||
return 0;
|
||||
}
|
||||
335
externals/openal-soft/examples/alplay.c
vendored
Normal file
335
externals/openal-soft/examples/alplay.c
vendored
Normal file
@@ -0,0 +1,335 @@
|
||||
/*
|
||||
* OpenAL Source Play Example
|
||||
*
|
||||
* Copyright (c) 2017 by Chris Robinson <chris.kcat@gmail.com>
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
* of this software and associated documentation files (the "Software"), to deal
|
||||
* in the Software without restriction, including without limitation the rights
|
||||
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
* copies of the Software, and to permit persons to whom the Software is
|
||||
* furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
* THE SOFTWARE.
|
||||
*/
|
||||
|
||||
/* This file contains an example for playing a sound buffer. */
|
||||
|
||||
#include <assert.h>
|
||||
#include <inttypes.h>
|
||||
#include <limits.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
|
||||
#include "sndfile.h"
|
||||
|
||||
#include "AL/al.h"
|
||||
#include "AL/alext.h"
|
||||
|
||||
#include "common/alhelpers.h"
|
||||
|
||||
|
||||
enum FormatType {
|
||||
Int16,
|
||||
Float,
|
||||
IMA4,
|
||||
MSADPCM
|
||||
};
|
||||
|
||||
/* LoadBuffer loads the named audio file into an OpenAL buffer object, and
|
||||
* returns the new buffer ID.
|
||||
*/
|
||||
static ALuint LoadSound(const char *filename)
|
||||
{
|
||||
enum FormatType sample_format = Int16;
|
||||
ALint byteblockalign = 0;
|
||||
ALint splblockalign = 0;
|
||||
sf_count_t num_frames;
|
||||
ALenum err, format;
|
||||
ALsizei num_bytes;
|
||||
SNDFILE *sndfile;
|
||||
SF_INFO sfinfo;
|
||||
ALuint buffer;
|
||||
void *membuf;
|
||||
|
||||
/* Open the audio file and check that it's usable. */
|
||||
sndfile = sf_open(filename, SFM_READ, &sfinfo);
|
||||
if(!sndfile)
|
||||
{
|
||||
fprintf(stderr, "Could not open audio in %s: %s\n", filename, sf_strerror(sndfile));
|
||||
return 0;
|
||||
}
|
||||
if(sfinfo.frames < 1)
|
||||
{
|
||||
fprintf(stderr, "Bad sample count in %s (%" PRId64 ")\n", filename, sfinfo.frames);
|
||||
sf_close(sndfile);
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* Detect a suitable format to load. Formats like Vorbis and Opus use float
|
||||
* natively, so load as float to avoid clipping when possible. Formats
|
||||
* larger than 16-bit can also use float to preserve a bit more precision.
|
||||
*/
|
||||
switch((sfinfo.format&SF_FORMAT_SUBMASK))
|
||||
{
|
||||
case SF_FORMAT_PCM_24:
|
||||
case SF_FORMAT_PCM_32:
|
||||
case SF_FORMAT_FLOAT:
|
||||
case SF_FORMAT_DOUBLE:
|
||||
case SF_FORMAT_VORBIS:
|
||||
case SF_FORMAT_OPUS:
|
||||
case SF_FORMAT_ALAC_20:
|
||||
case SF_FORMAT_ALAC_24:
|
||||
case SF_FORMAT_ALAC_32:
|
||||
case 0x0080/*SF_FORMAT_MPEG_LAYER_I*/:
|
||||
case 0x0081/*SF_FORMAT_MPEG_LAYER_II*/:
|
||||
case 0x0082/*SF_FORMAT_MPEG_LAYER_III*/:
|
||||
if(alIsExtensionPresent("AL_EXT_FLOAT32"))
|
||||
sample_format = Float;
|
||||
break;
|
||||
case SF_FORMAT_IMA_ADPCM:
|
||||
/* ADPCM formats require setting a block alignment as specified in the
|
||||
* file, which needs to be read from the wave 'fmt ' chunk manually
|
||||
* since libsndfile doesn't provide it in a format-agnostic way.
|
||||
*/
|
||||
if(sfinfo.channels <= 2 && (sfinfo.format&SF_FORMAT_TYPEMASK) == SF_FORMAT_WAV
|
||||
&& alIsExtensionPresent("AL_EXT_IMA4")
|
||||
&& alIsExtensionPresent("AL_SOFT_block_alignment"))
|
||||
sample_format = IMA4;
|
||||
break;
|
||||
case SF_FORMAT_MS_ADPCM:
|
||||
if(sfinfo.channels <= 2 && (sfinfo.format&SF_FORMAT_TYPEMASK) == SF_FORMAT_WAV
|
||||
&& alIsExtensionPresent("AL_SOFT_MSADPCM")
|
||||
&& alIsExtensionPresent("AL_SOFT_block_alignment"))
|
||||
sample_format = MSADPCM;
|
||||
break;
|
||||
}
|
||||
|
||||
if(sample_format == IMA4 || sample_format == MSADPCM)
|
||||
{
|
||||
/* For ADPCM, lookup the wave file's "fmt " chunk, which is a
|
||||
* WAVEFORMATEX-based structure for the audio format.
|
||||
*/
|
||||
SF_CHUNK_INFO inf = { "fmt ", 4, 0, NULL };
|
||||
SF_CHUNK_ITERATOR *iter = sf_get_chunk_iterator(sndfile, &inf);
|
||||
|
||||
/* If there's an issue getting the chunk or block alignment, load as
|
||||
* 16-bit and have libsndfile do the conversion.
|
||||
*/
|
||||
if(!iter || sf_get_chunk_size(iter, &inf) != SF_ERR_NO_ERROR || inf.datalen < 14)
|
||||
sample_format = Int16;
|
||||
else
|
||||
{
|
||||
ALubyte *fmtbuf = calloc(inf.datalen, 1);
|
||||
inf.data = fmtbuf;
|
||||
if(sf_get_chunk_data(iter, &inf) != SF_ERR_NO_ERROR)
|
||||
sample_format = Int16;
|
||||
else
|
||||
{
|
||||
/* Read the nBlockAlign field, and convert from bytes- to
|
||||
* samples-per-block (verifying it's valid by converting back
|
||||
* and comparing to the original value).
|
||||
*/
|
||||
byteblockalign = fmtbuf[12] | (fmtbuf[13]<<8);
|
||||
if(sample_format == IMA4)
|
||||
{
|
||||
splblockalign = (byteblockalign/sfinfo.channels - 4)/4*8 + 1;
|
||||
if(splblockalign < 1
|
||||
|| ((splblockalign-1)/2 + 4)*sfinfo.channels != byteblockalign)
|
||||
sample_format = Int16;
|
||||
}
|
||||
else
|
||||
{
|
||||
splblockalign = (byteblockalign/sfinfo.channels - 7)*2 + 2;
|
||||
if(splblockalign < 2
|
||||
|| ((splblockalign-2)/2 + 7)*sfinfo.channels != byteblockalign)
|
||||
sample_format = Int16;
|
||||
}
|
||||
}
|
||||
free(fmtbuf);
|
||||
}
|
||||
}
|
||||
|
||||
if(sample_format == Int16)
|
||||
{
|
||||
splblockalign = 1;
|
||||
byteblockalign = sfinfo.channels * 2;
|
||||
}
|
||||
else if(sample_format == Float)
|
||||
{
|
||||
splblockalign = 1;
|
||||
byteblockalign = sfinfo.channels * 4;
|
||||
}
|
||||
|
||||
/* Figure out the OpenAL format from the file and desired sample type. */
|
||||
format = AL_NONE;
|
||||
if(sfinfo.channels == 1)
|
||||
{
|
||||
if(sample_format == Int16)
|
||||
format = AL_FORMAT_MONO16;
|
||||
else if(sample_format == Float)
|
||||
format = AL_FORMAT_MONO_FLOAT32;
|
||||
else if(sample_format == IMA4)
|
||||
format = AL_FORMAT_MONO_IMA4;
|
||||
else if(sample_format == MSADPCM)
|
||||
format = AL_FORMAT_MONO_MSADPCM_SOFT;
|
||||
}
|
||||
else if(sfinfo.channels == 2)
|
||||
{
|
||||
if(sample_format == Int16)
|
||||
format = AL_FORMAT_STEREO16;
|
||||
else if(sample_format == Float)
|
||||
format = AL_FORMAT_STEREO_FLOAT32;
|
||||
else if(sample_format == IMA4)
|
||||
format = AL_FORMAT_STEREO_IMA4;
|
||||
else if(sample_format == MSADPCM)
|
||||
format = AL_FORMAT_STEREO_MSADPCM_SOFT;
|
||||
}
|
||||
else if(sfinfo.channels == 3)
|
||||
{
|
||||
if(sf_command(sndfile, SFC_WAVEX_GET_AMBISONIC, NULL, 0) == SF_AMBISONIC_B_FORMAT)
|
||||
{
|
||||
if(sample_format == Int16)
|
||||
format = AL_FORMAT_BFORMAT2D_16;
|
||||
else if(sample_format == Float)
|
||||
format = AL_FORMAT_BFORMAT2D_FLOAT32;
|
||||
}
|
||||
}
|
||||
else if(sfinfo.channels == 4)
|
||||
{
|
||||
if(sf_command(sndfile, SFC_WAVEX_GET_AMBISONIC, NULL, 0) == SF_AMBISONIC_B_FORMAT)
|
||||
{
|
||||
if(sample_format == Int16)
|
||||
format = AL_FORMAT_BFORMAT3D_16;
|
||||
else if(sample_format == Float)
|
||||
format = AL_FORMAT_BFORMAT3D_FLOAT32;
|
||||
}
|
||||
}
|
||||
if(!format)
|
||||
{
|
||||
fprintf(stderr, "Unsupported channel count: %d\n", sfinfo.channels);
|
||||
sf_close(sndfile);
|
||||
return 0;
|
||||
}
|
||||
|
||||
if(sfinfo.frames/splblockalign > (sf_count_t)(INT_MAX/byteblockalign))
|
||||
{
|
||||
fprintf(stderr, "Too many samples in %s (%" PRId64 ")\n", filename, sfinfo.frames);
|
||||
sf_close(sndfile);
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* Decode the whole audio file to a buffer. */
|
||||
membuf = malloc((size_t)(sfinfo.frames / splblockalign * byteblockalign));
|
||||
|
||||
if(sample_format == Int16)
|
||||
num_frames = sf_readf_short(sndfile, membuf, sfinfo.frames);
|
||||
else if(sample_format == Float)
|
||||
num_frames = sf_readf_float(sndfile, membuf, sfinfo.frames);
|
||||
else
|
||||
{
|
||||
sf_count_t count = sfinfo.frames / splblockalign * byteblockalign;
|
||||
num_frames = sf_read_raw(sndfile, membuf, count);
|
||||
if(num_frames > 0)
|
||||
num_frames = num_frames / byteblockalign * splblockalign;
|
||||
}
|
||||
if(num_frames < 1)
|
||||
{
|
||||
free(membuf);
|
||||
sf_close(sndfile);
|
||||
fprintf(stderr, "Failed to read samples in %s (%" PRId64 ")\n", filename, num_frames);
|
||||
return 0;
|
||||
}
|
||||
num_bytes = (ALsizei)(num_frames / splblockalign * byteblockalign);
|
||||
|
||||
printf("Loading: %s (%s, %dhz)\n", filename, FormatName(format), sfinfo.samplerate);
|
||||
fflush(stdout);
|
||||
|
||||
/* Buffer the audio data into a new buffer object, then free the data and
|
||||
* close the file.
|
||||
*/
|
||||
buffer = 0;
|
||||
alGenBuffers(1, &buffer);
|
||||
if(splblockalign > 1)
|
||||
alBufferi(buffer, AL_UNPACK_BLOCK_ALIGNMENT_SOFT, splblockalign);
|
||||
alBufferData(buffer, format, membuf, num_bytes, sfinfo.samplerate);
|
||||
|
||||
free(membuf);
|
||||
sf_close(sndfile);
|
||||
|
||||
/* Check if an error occured, and clean up if so. */
|
||||
err = alGetError();
|
||||
if(err != AL_NO_ERROR)
|
||||
{
|
||||
fprintf(stderr, "OpenAL Error: %s\n", alGetString(err));
|
||||
if(buffer && alIsBuffer(buffer))
|
||||
alDeleteBuffers(1, &buffer);
|
||||
return 0;
|
||||
}
|
||||
|
||||
return buffer;
|
||||
}
|
||||
|
||||
|
||||
int main(int argc, char **argv)
|
||||
{
|
||||
ALuint source, buffer;
|
||||
ALfloat offset;
|
||||
ALenum state;
|
||||
|
||||
/* Print out usage if no arguments were specified */
|
||||
if(argc < 2)
|
||||
{
|
||||
fprintf(stderr, "Usage: %s [-device <name>] <filename>\n", argv[0]);
|
||||
return 1;
|
||||
}
|
||||
|
||||
/* Initialize OpenAL. */
|
||||
argv++; argc--;
|
||||
if(InitAL(&argv, &argc) != 0)
|
||||
return 1;
|
||||
|
||||
/* Load the sound into a buffer. */
|
||||
buffer = LoadSound(argv[0]);
|
||||
if(!buffer)
|
||||
{
|
||||
CloseAL();
|
||||
return 1;
|
||||
}
|
||||
|
||||
/* Create the source to play the sound with. */
|
||||
source = 0;
|
||||
alGenSources(1, &source);
|
||||
alSourcei(source, AL_BUFFER, (ALint)buffer);
|
||||
assert(alGetError()==AL_NO_ERROR && "Failed to setup sound source");
|
||||
|
||||
/* Play the sound until it finishes. */
|
||||
alSourcePlay(source);
|
||||
do {
|
||||
al_nssleep(10000000);
|
||||
alGetSourcei(source, AL_SOURCE_STATE, &state);
|
||||
|
||||
/* Get the source offset. */
|
||||
alGetSourcef(source, AL_SEC_OFFSET, &offset);
|
||||
printf("\rOffset: %f ", offset);
|
||||
fflush(stdout);
|
||||
} while(alGetError() == AL_NO_ERROR && state == AL_PLAYING);
|
||||
printf("\n");
|
||||
|
||||
/* All done. Delete resources, and close down OpenAL. */
|
||||
alDeleteSources(1, &source);
|
||||
alDeleteBuffers(1, &buffer);
|
||||
|
||||
CloseAL();
|
||||
|
||||
return 0;
|
||||
}
|
||||
403
externals/openal-soft/examples/alrecord.c
vendored
Normal file
403
externals/openal-soft/examples/alrecord.c
vendored
Normal file
@@ -0,0 +1,403 @@
|
||||
/*
|
||||
* OpenAL Recording Example
|
||||
*
|
||||
* Copyright (c) 2017 by Chris Robinson <chris.kcat@gmail.com>
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
* of this software and associated documentation files (the "Software"), to deal
|
||||
* in the Software without restriction, including without limitation the rights
|
||||
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
* copies of the Software, and to permit persons to whom the Software is
|
||||
* furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
* THE SOFTWARE.
|
||||
*/
|
||||
|
||||
/* This file contains a relatively simple recorder. */
|
||||
|
||||
#include <string.h>
|
||||
#include <stdlib.h>
|
||||
#include <stdio.h>
|
||||
#include <errno.h>
|
||||
|
||||
#include "AL/al.h"
|
||||
#include "AL/alc.h"
|
||||
#include "AL/alext.h"
|
||||
|
||||
#include "common/alhelpers.h"
|
||||
|
||||
#include "win_main_utf8.h"
|
||||
|
||||
|
||||
#if defined(_WIN64)
|
||||
#define SZFMT "%I64u"
|
||||
#elif defined(_WIN32)
|
||||
#define SZFMT "%u"
|
||||
#else
|
||||
#define SZFMT "%zu"
|
||||
#endif
|
||||
|
||||
|
||||
#if defined(_MSC_VER) && (_MSC_VER < 1900)
|
||||
static float msvc_strtof(const char *str, char **end)
|
||||
{ return (float)strtod(str, end); }
|
||||
#define strtof msvc_strtof
|
||||
#endif
|
||||
|
||||
|
||||
static void fwrite16le(ALushort val, FILE *f)
|
||||
{
|
||||
ALubyte data[2];
|
||||
data[0] = (ALubyte)(val&0xff);
|
||||
data[1] = (ALubyte)(val>>8);
|
||||
fwrite(data, 1, 2, f);
|
||||
}
|
||||
|
||||
static void fwrite32le(ALuint val, FILE *f)
|
||||
{
|
||||
ALubyte data[4];
|
||||
data[0] = (ALubyte)(val&0xff);
|
||||
data[1] = (ALubyte)((val>>8)&0xff);
|
||||
data[2] = (ALubyte)((val>>16)&0xff);
|
||||
data[3] = (ALubyte)(val>>24);
|
||||
fwrite(data, 1, 4, f);
|
||||
}
|
||||
|
||||
|
||||
typedef struct Recorder {
|
||||
ALCdevice *mDevice;
|
||||
|
||||
FILE *mFile;
|
||||
long mDataSizeOffset;
|
||||
ALuint mDataSize;
|
||||
float mRecTime;
|
||||
|
||||
ALuint mChannels;
|
||||
ALuint mBits;
|
||||
ALuint mSampleRate;
|
||||
ALuint mFrameSize;
|
||||
ALbyte *mBuffer;
|
||||
ALsizei mBufferSize;
|
||||
} Recorder;
|
||||
|
||||
int main(int argc, char **argv)
|
||||
{
|
||||
static const char optlist[] =
|
||||
" --channels/-c <channels> Set channel count (1 or 2)\n"
|
||||
" --bits/-b <bits> Set channel count (8, 16, or 32)\n"
|
||||
" --rate/-r <rate> Set sample rate (8000 to 96000)\n"
|
||||
" --time/-t <time> Time in seconds to record (1 to 10)\n"
|
||||
" --outfile/-o <filename> Output filename (default: record.wav)";
|
||||
const char *fname = "record.wav";
|
||||
const char *devname = NULL;
|
||||
const char *progname;
|
||||
Recorder recorder;
|
||||
long total_size;
|
||||
ALenum format;
|
||||
ALCenum err;
|
||||
|
||||
progname = argv[0];
|
||||
if(argc < 2)
|
||||
{
|
||||
fprintf(stderr, "Record from a device to a wav file.\n\n"
|
||||
"Usage: %s [-device <name>] [options...]\n\n"
|
||||
"Available options:\n%s\n", progname, optlist);
|
||||
return 0;
|
||||
}
|
||||
|
||||
recorder.mDevice = NULL;
|
||||
recorder.mFile = NULL;
|
||||
recorder.mDataSizeOffset = 0;
|
||||
recorder.mDataSize = 0;
|
||||
recorder.mRecTime = 4.0f;
|
||||
recorder.mChannels = 1;
|
||||
recorder.mBits = 16;
|
||||
recorder.mSampleRate = 44100;
|
||||
recorder.mFrameSize = recorder.mChannels * recorder.mBits / 8;
|
||||
recorder.mBuffer = NULL;
|
||||
recorder.mBufferSize = 0;
|
||||
|
||||
argv++; argc--;
|
||||
if(argc > 1 && strcmp(argv[0], "-device") == 0)
|
||||
{
|
||||
devname = argv[1];
|
||||
argv += 2;
|
||||
argc -= 2;
|
||||
}
|
||||
|
||||
while(argc > 0)
|
||||
{
|
||||
char *end;
|
||||
if(strcmp(argv[0], "--") == 0)
|
||||
break;
|
||||
else if(strcmp(argv[0], "--channels") == 0 || strcmp(argv[0], "-c") == 0)
|
||||
{
|
||||
if(argc < 2)
|
||||
{
|
||||
fprintf(stderr, "Missing argument for option: %s\n", argv[0]);
|
||||
return 1;
|
||||
}
|
||||
|
||||
recorder.mChannels = (ALuint)strtoul(argv[1], &end, 0);
|
||||
if((recorder.mChannels != 1 && recorder.mChannels != 2) || (end && *end != '\0'))
|
||||
{
|
||||
fprintf(stderr, "Invalid channels: %s\n", argv[1]);
|
||||
return 1;
|
||||
}
|
||||
argv += 2;
|
||||
argc -= 2;
|
||||
}
|
||||
else if(strcmp(argv[0], "--bits") == 0 || strcmp(argv[0], "-b") == 0)
|
||||
{
|
||||
if(argc < 2)
|
||||
{
|
||||
fprintf(stderr, "Missing argument for option: %s\n", argv[0]);
|
||||
return 1;
|
||||
}
|
||||
|
||||
recorder.mBits = (ALuint)strtoul(argv[1], &end, 0);
|
||||
if((recorder.mBits != 8 && recorder.mBits != 16 && recorder.mBits != 32) ||
|
||||
(end && *end != '\0'))
|
||||
{
|
||||
fprintf(stderr, "Invalid bit count: %s\n", argv[1]);
|
||||
return 1;
|
||||
}
|
||||
argv += 2;
|
||||
argc -= 2;
|
||||
}
|
||||
else if(strcmp(argv[0], "--rate") == 0 || strcmp(argv[0], "-r") == 0)
|
||||
{
|
||||
if(argc < 2)
|
||||
{
|
||||
fprintf(stderr, "Missing argument for option: %s\n", argv[0]);
|
||||
return 1;
|
||||
}
|
||||
|
||||
recorder.mSampleRate = (ALuint)strtoul(argv[1], &end, 0);
|
||||
if(!(recorder.mSampleRate >= 8000 && recorder.mSampleRate <= 96000) || (end && *end != '\0'))
|
||||
{
|
||||
fprintf(stderr, "Invalid sample rate: %s\n", argv[1]);
|
||||
return 1;
|
||||
}
|
||||
argv += 2;
|
||||
argc -= 2;
|
||||
}
|
||||
else if(strcmp(argv[0], "--time") == 0 || strcmp(argv[0], "-t") == 0)
|
||||
{
|
||||
if(argc < 2)
|
||||
{
|
||||
fprintf(stderr, "Missing argument for option: %s\n", argv[0]);
|
||||
return 1;
|
||||
}
|
||||
|
||||
recorder.mRecTime = strtof(argv[1], &end);
|
||||
if(!(recorder.mRecTime >= 1.0f && recorder.mRecTime <= 10.0f) || (end && *end != '\0'))
|
||||
{
|
||||
fprintf(stderr, "Invalid record time: %s\n", argv[1]);
|
||||
return 1;
|
||||
}
|
||||
argv += 2;
|
||||
argc -= 2;
|
||||
}
|
||||
else if(strcmp(argv[0], "--outfile") == 0 || strcmp(argv[0], "-o") == 0)
|
||||
{
|
||||
if(argc < 2)
|
||||
{
|
||||
fprintf(stderr, "Missing argument for option: %s\n", argv[0]);
|
||||
return 1;
|
||||
}
|
||||
|
||||
fname = argv[1];
|
||||
argv += 2;
|
||||
argc -= 2;
|
||||
}
|
||||
else if(strcmp(argv[0], "--help") == 0 || strcmp(argv[0], "-h") == 0)
|
||||
{
|
||||
fprintf(stderr, "Record from a device to a wav file.\n\n"
|
||||
"Usage: %s [-device <name>] [options...]\n\n"
|
||||
"Available options:\n%s\n", progname, optlist);
|
||||
return 0;
|
||||
}
|
||||
else
|
||||
{
|
||||
fprintf(stderr, "Invalid option '%s'.\n\n"
|
||||
"Usage: %s [-device <name>] [options...]\n\n"
|
||||
"Available options:\n%s\n", argv[0], progname, optlist);
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
recorder.mFrameSize = recorder.mChannels * recorder.mBits / 8;
|
||||
|
||||
format = AL_NONE;
|
||||
if(recorder.mChannels == 1)
|
||||
{
|
||||
if(recorder.mBits == 8)
|
||||
format = AL_FORMAT_MONO8;
|
||||
else if(recorder.mBits == 16)
|
||||
format = AL_FORMAT_MONO16;
|
||||
else if(recorder.mBits == 32)
|
||||
format = AL_FORMAT_MONO_FLOAT32;
|
||||
}
|
||||
else if(recorder.mChannels == 2)
|
||||
{
|
||||
if(recorder.mBits == 8)
|
||||
format = AL_FORMAT_STEREO8;
|
||||
else if(recorder.mBits == 16)
|
||||
format = AL_FORMAT_STEREO16;
|
||||
else if(recorder.mBits == 32)
|
||||
format = AL_FORMAT_STEREO_FLOAT32;
|
||||
}
|
||||
|
||||
recorder.mDevice = alcCaptureOpenDevice(devname, recorder.mSampleRate, format, 32768);
|
||||
if(!recorder.mDevice)
|
||||
{
|
||||
fprintf(stderr, "Failed to open %s, %s %d-bit, %s, %dhz (%d samples)\n",
|
||||
devname ? devname : "default device",
|
||||
(recorder.mBits == 32) ? "Float" :
|
||||
(recorder.mBits != 8) ? "Signed" : "Unsigned", recorder.mBits,
|
||||
(recorder.mChannels == 1) ? "Mono" : "Stereo", recorder.mSampleRate,
|
||||
32768
|
||||
);
|
||||
return 1;
|
||||
}
|
||||
fprintf(stderr, "Opened \"%s\"\n", alcGetString(
|
||||
recorder.mDevice, ALC_CAPTURE_DEVICE_SPECIFIER
|
||||
));
|
||||
|
||||
recorder.mFile = fopen(fname, "wb");
|
||||
if(!recorder.mFile)
|
||||
{
|
||||
fprintf(stderr, "Failed to open '%s' for writing\n", fname);
|
||||
alcCaptureCloseDevice(recorder.mDevice);
|
||||
return 1;
|
||||
}
|
||||
|
||||
fputs("RIFF", recorder.mFile);
|
||||
fwrite32le(0xFFFFFFFF, recorder.mFile); // 'RIFF' header len; filled in at close
|
||||
|
||||
fputs("WAVE", recorder.mFile);
|
||||
|
||||
fputs("fmt ", recorder.mFile);
|
||||
fwrite32le(18, recorder.mFile); // 'fmt ' header len
|
||||
|
||||
// 16-bit val, format type id (1 = integer PCM, 3 = float PCM)
|
||||
fwrite16le((recorder.mBits == 32) ? 0x0003 : 0x0001, recorder.mFile);
|
||||
// 16-bit val, channel count
|
||||
fwrite16le((ALushort)recorder.mChannels, recorder.mFile);
|
||||
// 32-bit val, frequency
|
||||
fwrite32le(recorder.mSampleRate, recorder.mFile);
|
||||
// 32-bit val, bytes per second
|
||||
fwrite32le(recorder.mSampleRate * recorder.mFrameSize, recorder.mFile);
|
||||
// 16-bit val, frame size
|
||||
fwrite16le((ALushort)recorder.mFrameSize, recorder.mFile);
|
||||
// 16-bit val, bits per sample
|
||||
fwrite16le((ALushort)recorder.mBits, recorder.mFile);
|
||||
// 16-bit val, extra byte count
|
||||
fwrite16le(0, recorder.mFile);
|
||||
|
||||
fputs("data", recorder.mFile);
|
||||
fwrite32le(0xFFFFFFFF, recorder.mFile); // 'data' header len; filled in at close
|
||||
|
||||
recorder.mDataSizeOffset = ftell(recorder.mFile) - 4;
|
||||
if(ferror(recorder.mFile) || recorder.mDataSizeOffset < 0)
|
||||
{
|
||||
fprintf(stderr, "Error writing header: %s\n", strerror(errno));
|
||||
fclose(recorder.mFile);
|
||||
alcCaptureCloseDevice(recorder.mDevice);
|
||||
return 1;
|
||||
}
|
||||
|
||||
fprintf(stderr, "Recording '%s', %s %d-bit, %s, %dhz (%g second%s)\n", fname,
|
||||
(recorder.mBits == 32) ? "Float" :
|
||||
(recorder.mBits != 8) ? "Signed" : "Unsigned", recorder.mBits,
|
||||
(recorder.mChannels == 1) ? "Mono" : "Stereo", recorder.mSampleRate,
|
||||
recorder.mRecTime, (recorder.mRecTime != 1.0f) ? "s" : ""
|
||||
);
|
||||
|
||||
err = ALC_NO_ERROR;
|
||||
alcCaptureStart(recorder.mDevice);
|
||||
while((double)recorder.mDataSize/(double)recorder.mSampleRate < recorder.mRecTime &&
|
||||
(err=alcGetError(recorder.mDevice)) == ALC_NO_ERROR && !ferror(recorder.mFile))
|
||||
{
|
||||
ALCint count = 0;
|
||||
fprintf(stderr, "\rCaptured %u samples", recorder.mDataSize);
|
||||
alcGetIntegerv(recorder.mDevice, ALC_CAPTURE_SAMPLES, 1, &count);
|
||||
if(count < 1)
|
||||
{
|
||||
al_nssleep(10000000);
|
||||
continue;
|
||||
}
|
||||
if(count > recorder.mBufferSize)
|
||||
{
|
||||
ALbyte *data = calloc(recorder.mFrameSize, (ALuint)count);
|
||||
free(recorder.mBuffer);
|
||||
recorder.mBuffer = data;
|
||||
recorder.mBufferSize = count;
|
||||
}
|
||||
alcCaptureSamples(recorder.mDevice, recorder.mBuffer, count);
|
||||
#if defined(__BYTE_ORDER) && __BYTE_ORDER == __BIG_ENDIAN
|
||||
/* Byteswap multibyte samples on big-endian systems (wav needs little-
|
||||
* endian, and OpenAL gives the system's native-endian).
|
||||
*/
|
||||
if(recorder.mBits == 16)
|
||||
{
|
||||
ALCint i;
|
||||
for(i = 0;i < count*recorder.mChannels;i++)
|
||||
{
|
||||
ALbyte b = recorder.mBuffer[i*2 + 0];
|
||||
recorder.mBuffer[i*2 + 0] = recorder.mBuffer[i*2 + 1];
|
||||
recorder.mBuffer[i*2 + 1] = b;
|
||||
}
|
||||
}
|
||||
else if(recorder.mBits == 32)
|
||||
{
|
||||
ALCint i;
|
||||
for(i = 0;i < count*recorder.mChannels;i++)
|
||||
{
|
||||
ALbyte b0 = recorder.mBuffer[i*4 + 0];
|
||||
ALbyte b1 = recorder.mBuffer[i*4 + 1];
|
||||
recorder.mBuffer[i*4 + 0] = recorder.mBuffer[i*4 + 3];
|
||||
recorder.mBuffer[i*4 + 1] = recorder.mBuffer[i*4 + 2];
|
||||
recorder.mBuffer[i*4 + 2] = b1;
|
||||
recorder.mBuffer[i*4 + 3] = b0;
|
||||
}
|
||||
}
|
||||
#endif
|
||||
recorder.mDataSize += (ALuint)fwrite(recorder.mBuffer, recorder.mFrameSize, (ALuint)count,
|
||||
recorder.mFile);
|
||||
}
|
||||
alcCaptureStop(recorder.mDevice);
|
||||
fprintf(stderr, "\rCaptured %u samples\n", recorder.mDataSize);
|
||||
if(err != ALC_NO_ERROR)
|
||||
fprintf(stderr, "Got device error 0x%04x: %s\n", err, alcGetString(recorder.mDevice, err));
|
||||
|
||||
alcCaptureCloseDevice(recorder.mDevice);
|
||||
recorder.mDevice = NULL;
|
||||
|
||||
free(recorder.mBuffer);
|
||||
recorder.mBuffer = NULL;
|
||||
recorder.mBufferSize = 0;
|
||||
|
||||
total_size = ftell(recorder.mFile);
|
||||
if(fseek(recorder.mFile, recorder.mDataSizeOffset, SEEK_SET) == 0)
|
||||
{
|
||||
fwrite32le(recorder.mDataSize*recorder.mFrameSize, recorder.mFile);
|
||||
if(fseek(recorder.mFile, 4, SEEK_SET) == 0)
|
||||
fwrite32le((ALuint)total_size - 8, recorder.mFile);
|
||||
}
|
||||
|
||||
fclose(recorder.mFile);
|
||||
recorder.mFile = NULL;
|
||||
|
||||
return 0;
|
||||
}
|
||||
344
externals/openal-soft/examples/alreverb.c
vendored
Normal file
344
externals/openal-soft/examples/alreverb.c
vendored
Normal file
@@ -0,0 +1,344 @@
|
||||
/*
|
||||
* OpenAL Reverb Example
|
||||
*
|
||||
* Copyright (c) 2012 by Chris Robinson <chris.kcat@gmail.com>
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
* of this software and associated documentation files (the "Software"), to deal
|
||||
* in the Software without restriction, including without limitation the rights
|
||||
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
* copies of the Software, and to permit persons to whom the Software is
|
||||
* furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
* THE SOFTWARE.
|
||||
*/
|
||||
|
||||
/* This file contains an example for applying reverb to a sound. */
|
||||
|
||||
#include <assert.h>
|
||||
#include <inttypes.h>
|
||||
#include <limits.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
|
||||
#include "sndfile.h"
|
||||
|
||||
#include "AL/al.h"
|
||||
#include "AL/alc.h"
|
||||
#include "AL/alext.h"
|
||||
#include "AL/efx.h"
|
||||
#include "AL/efx-presets.h"
|
||||
|
||||
#include "common/alhelpers.h"
|
||||
|
||||
|
||||
/* Effect object functions */
|
||||
static LPALGENEFFECTS alGenEffects;
|
||||
static LPALDELETEEFFECTS alDeleteEffects;
|
||||
static LPALISEFFECT alIsEffect;
|
||||
static LPALEFFECTI alEffecti;
|
||||
static LPALEFFECTIV alEffectiv;
|
||||
static LPALEFFECTF alEffectf;
|
||||
static LPALEFFECTFV alEffectfv;
|
||||
static LPALGETEFFECTI alGetEffecti;
|
||||
static LPALGETEFFECTIV alGetEffectiv;
|
||||
static LPALGETEFFECTF alGetEffectf;
|
||||
static LPALGETEFFECTFV alGetEffectfv;
|
||||
|
||||
/* Auxiliary Effect Slot object functions */
|
||||
static LPALGENAUXILIARYEFFECTSLOTS alGenAuxiliaryEffectSlots;
|
||||
static LPALDELETEAUXILIARYEFFECTSLOTS alDeleteAuxiliaryEffectSlots;
|
||||
static LPALISAUXILIARYEFFECTSLOT alIsAuxiliaryEffectSlot;
|
||||
static LPALAUXILIARYEFFECTSLOTI alAuxiliaryEffectSloti;
|
||||
static LPALAUXILIARYEFFECTSLOTIV alAuxiliaryEffectSlotiv;
|
||||
static LPALAUXILIARYEFFECTSLOTF alAuxiliaryEffectSlotf;
|
||||
static LPALAUXILIARYEFFECTSLOTFV alAuxiliaryEffectSlotfv;
|
||||
static LPALGETAUXILIARYEFFECTSLOTI alGetAuxiliaryEffectSloti;
|
||||
static LPALGETAUXILIARYEFFECTSLOTIV alGetAuxiliaryEffectSlotiv;
|
||||
static LPALGETAUXILIARYEFFECTSLOTF alGetAuxiliaryEffectSlotf;
|
||||
static LPALGETAUXILIARYEFFECTSLOTFV alGetAuxiliaryEffectSlotfv;
|
||||
|
||||
|
||||
/* LoadEffect loads the given reverb properties into a new OpenAL effect
|
||||
* object, and returns the new effect ID. */
|
||||
static ALuint LoadEffect(const EFXEAXREVERBPROPERTIES *reverb)
|
||||
{
|
||||
ALuint effect = 0;
|
||||
ALenum err;
|
||||
|
||||
/* Create the effect object and check if we can do EAX reverb. */
|
||||
alGenEffects(1, &effect);
|
||||
if(alGetEnumValue("AL_EFFECT_EAXREVERB") != 0)
|
||||
{
|
||||
printf("Using EAX Reverb\n");
|
||||
|
||||
/* EAX Reverb is available. Set the EAX effect type then load the
|
||||
* reverb properties. */
|
||||
alEffecti(effect, AL_EFFECT_TYPE, AL_EFFECT_EAXREVERB);
|
||||
|
||||
alEffectf(effect, AL_EAXREVERB_DENSITY, reverb->flDensity);
|
||||
alEffectf(effect, AL_EAXREVERB_DIFFUSION, reverb->flDiffusion);
|
||||
alEffectf(effect, AL_EAXREVERB_GAIN, reverb->flGain);
|
||||
alEffectf(effect, AL_EAXREVERB_GAINHF, reverb->flGainHF);
|
||||
alEffectf(effect, AL_EAXREVERB_GAINLF, reverb->flGainLF);
|
||||
alEffectf(effect, AL_EAXREVERB_DECAY_TIME, reverb->flDecayTime);
|
||||
alEffectf(effect, AL_EAXREVERB_DECAY_HFRATIO, reverb->flDecayHFRatio);
|
||||
alEffectf(effect, AL_EAXREVERB_DECAY_LFRATIO, reverb->flDecayLFRatio);
|
||||
alEffectf(effect, AL_EAXREVERB_REFLECTIONS_GAIN, reverb->flReflectionsGain);
|
||||
alEffectf(effect, AL_EAXREVERB_REFLECTIONS_DELAY, reverb->flReflectionsDelay);
|
||||
alEffectfv(effect, AL_EAXREVERB_REFLECTIONS_PAN, reverb->flReflectionsPan);
|
||||
alEffectf(effect, AL_EAXREVERB_LATE_REVERB_GAIN, reverb->flLateReverbGain);
|
||||
alEffectf(effect, AL_EAXREVERB_LATE_REVERB_DELAY, reverb->flLateReverbDelay);
|
||||
alEffectfv(effect, AL_EAXREVERB_LATE_REVERB_PAN, reverb->flLateReverbPan);
|
||||
alEffectf(effect, AL_EAXREVERB_ECHO_TIME, reverb->flEchoTime);
|
||||
alEffectf(effect, AL_EAXREVERB_ECHO_DEPTH, reverb->flEchoDepth);
|
||||
alEffectf(effect, AL_EAXREVERB_MODULATION_TIME, reverb->flModulationTime);
|
||||
alEffectf(effect, AL_EAXREVERB_MODULATION_DEPTH, reverb->flModulationDepth);
|
||||
alEffectf(effect, AL_EAXREVERB_AIR_ABSORPTION_GAINHF, reverb->flAirAbsorptionGainHF);
|
||||
alEffectf(effect, AL_EAXREVERB_HFREFERENCE, reverb->flHFReference);
|
||||
alEffectf(effect, AL_EAXREVERB_LFREFERENCE, reverb->flLFReference);
|
||||
alEffectf(effect, AL_EAXREVERB_ROOM_ROLLOFF_FACTOR, reverb->flRoomRolloffFactor);
|
||||
alEffecti(effect, AL_EAXREVERB_DECAY_HFLIMIT, reverb->iDecayHFLimit);
|
||||
}
|
||||
else
|
||||
{
|
||||
printf("Using Standard Reverb\n");
|
||||
|
||||
/* No EAX Reverb. Set the standard reverb effect type then load the
|
||||
* available reverb properties. */
|
||||
alEffecti(effect, AL_EFFECT_TYPE, AL_EFFECT_REVERB);
|
||||
|
||||
alEffectf(effect, AL_REVERB_DENSITY, reverb->flDensity);
|
||||
alEffectf(effect, AL_REVERB_DIFFUSION, reverb->flDiffusion);
|
||||
alEffectf(effect, AL_REVERB_GAIN, reverb->flGain);
|
||||
alEffectf(effect, AL_REVERB_GAINHF, reverb->flGainHF);
|
||||
alEffectf(effect, AL_REVERB_DECAY_TIME, reverb->flDecayTime);
|
||||
alEffectf(effect, AL_REVERB_DECAY_HFRATIO, reverb->flDecayHFRatio);
|
||||
alEffectf(effect, AL_REVERB_REFLECTIONS_GAIN, reverb->flReflectionsGain);
|
||||
alEffectf(effect, AL_REVERB_REFLECTIONS_DELAY, reverb->flReflectionsDelay);
|
||||
alEffectf(effect, AL_REVERB_LATE_REVERB_GAIN, reverb->flLateReverbGain);
|
||||
alEffectf(effect, AL_REVERB_LATE_REVERB_DELAY, reverb->flLateReverbDelay);
|
||||
alEffectf(effect, AL_REVERB_AIR_ABSORPTION_GAINHF, reverb->flAirAbsorptionGainHF);
|
||||
alEffectf(effect, AL_REVERB_ROOM_ROLLOFF_FACTOR, reverb->flRoomRolloffFactor);
|
||||
alEffecti(effect, AL_REVERB_DECAY_HFLIMIT, reverb->iDecayHFLimit);
|
||||
}
|
||||
|
||||
/* Check if an error occured, and clean up if so. */
|
||||
err = alGetError();
|
||||
if(err != AL_NO_ERROR)
|
||||
{
|
||||
fprintf(stderr, "OpenAL error: %s\n", alGetString(err));
|
||||
if(alIsEffect(effect))
|
||||
alDeleteEffects(1, &effect);
|
||||
return 0;
|
||||
}
|
||||
|
||||
return effect;
|
||||
}
|
||||
|
||||
|
||||
/* LoadBuffer loads the named audio file into an OpenAL buffer object, and
|
||||
* returns the new buffer ID.
|
||||
*/
|
||||
static ALuint LoadSound(const char *filename)
|
||||
{
|
||||
ALenum err, format;
|
||||
ALuint buffer;
|
||||
SNDFILE *sndfile;
|
||||
SF_INFO sfinfo;
|
||||
short *membuf;
|
||||
sf_count_t num_frames;
|
||||
ALsizei num_bytes;
|
||||
|
||||
/* Open the audio file and check that it's usable. */
|
||||
sndfile = sf_open(filename, SFM_READ, &sfinfo);
|
||||
if(!sndfile)
|
||||
{
|
||||
fprintf(stderr, "Could not open audio in %s: %s\n", filename, sf_strerror(sndfile));
|
||||
return 0;
|
||||
}
|
||||
if(sfinfo.frames < 1 || sfinfo.frames > (sf_count_t)(INT_MAX/sizeof(short))/sfinfo.channels)
|
||||
{
|
||||
fprintf(stderr, "Bad sample count in %s (%" PRId64 ")\n", filename, sfinfo.frames);
|
||||
sf_close(sndfile);
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* Get the sound format, and figure out the OpenAL format */
|
||||
format = AL_NONE;
|
||||
if(sfinfo.channels == 1)
|
||||
format = AL_FORMAT_MONO16;
|
||||
else if(sfinfo.channels == 2)
|
||||
format = AL_FORMAT_STEREO16;
|
||||
else if(sfinfo.channels == 3)
|
||||
{
|
||||
if(sf_command(sndfile, SFC_WAVEX_GET_AMBISONIC, NULL, 0) == SF_AMBISONIC_B_FORMAT)
|
||||
format = AL_FORMAT_BFORMAT2D_16;
|
||||
}
|
||||
else if(sfinfo.channels == 4)
|
||||
{
|
||||
if(sf_command(sndfile, SFC_WAVEX_GET_AMBISONIC, NULL, 0) == SF_AMBISONIC_B_FORMAT)
|
||||
format = AL_FORMAT_BFORMAT3D_16;
|
||||
}
|
||||
if(!format)
|
||||
{
|
||||
fprintf(stderr, "Unsupported channel count: %d\n", sfinfo.channels);
|
||||
sf_close(sndfile);
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* Decode the whole audio file to a buffer. */
|
||||
membuf = malloc((size_t)(sfinfo.frames * sfinfo.channels) * sizeof(short));
|
||||
|
||||
num_frames = sf_readf_short(sndfile, membuf, sfinfo.frames);
|
||||
if(num_frames < 1)
|
||||
{
|
||||
free(membuf);
|
||||
sf_close(sndfile);
|
||||
fprintf(stderr, "Failed to read samples in %s (%" PRId64 ")\n", filename, num_frames);
|
||||
return 0;
|
||||
}
|
||||
num_bytes = (ALsizei)(num_frames * sfinfo.channels) * (ALsizei)sizeof(short);
|
||||
|
||||
/* Buffer the audio data into a new buffer object, then free the data and
|
||||
* close the file.
|
||||
*/
|
||||
buffer = 0;
|
||||
alGenBuffers(1, &buffer);
|
||||
alBufferData(buffer, format, membuf, num_bytes, sfinfo.samplerate);
|
||||
|
||||
free(membuf);
|
||||
sf_close(sndfile);
|
||||
|
||||
/* Check if an error occured, and clean up if so. */
|
||||
err = alGetError();
|
||||
if(err != AL_NO_ERROR)
|
||||
{
|
||||
fprintf(stderr, "OpenAL Error: %s\n", alGetString(err));
|
||||
if(buffer && alIsBuffer(buffer))
|
||||
alDeleteBuffers(1, &buffer);
|
||||
return 0;
|
||||
}
|
||||
|
||||
return buffer;
|
||||
}
|
||||
|
||||
|
||||
int main(int argc, char **argv)
|
||||
{
|
||||
EFXEAXREVERBPROPERTIES reverb = EFX_REVERB_PRESET_GENERIC;
|
||||
ALuint source, buffer, effect, slot;
|
||||
ALenum state;
|
||||
|
||||
/* Print out usage if no arguments were specified */
|
||||
if(argc < 2)
|
||||
{
|
||||
fprintf(stderr, "Usage: %s [-device <name] <filename>\n", argv[0]);
|
||||
return 1;
|
||||
}
|
||||
|
||||
/* Initialize OpenAL, and check for EFX support. */
|
||||
argv++; argc--;
|
||||
if(InitAL(&argv, &argc) != 0)
|
||||
return 1;
|
||||
|
||||
if(!alcIsExtensionPresent(alcGetContextsDevice(alcGetCurrentContext()), "ALC_EXT_EFX"))
|
||||
{
|
||||
fprintf(stderr, "Error: EFX not supported\n");
|
||||
CloseAL();
|
||||
return 1;
|
||||
}
|
||||
|
||||
/* Define a macro to help load the function pointers. */
|
||||
#define LOAD_PROC(T, x) ((x) = FUNCTION_CAST(T, alGetProcAddress(#x)))
|
||||
LOAD_PROC(LPALGENEFFECTS, alGenEffects);
|
||||
LOAD_PROC(LPALDELETEEFFECTS, alDeleteEffects);
|
||||
LOAD_PROC(LPALISEFFECT, alIsEffect);
|
||||
LOAD_PROC(LPALEFFECTI, alEffecti);
|
||||
LOAD_PROC(LPALEFFECTIV, alEffectiv);
|
||||
LOAD_PROC(LPALEFFECTF, alEffectf);
|
||||
LOAD_PROC(LPALEFFECTFV, alEffectfv);
|
||||
LOAD_PROC(LPALGETEFFECTI, alGetEffecti);
|
||||
LOAD_PROC(LPALGETEFFECTIV, alGetEffectiv);
|
||||
LOAD_PROC(LPALGETEFFECTF, alGetEffectf);
|
||||
LOAD_PROC(LPALGETEFFECTFV, alGetEffectfv);
|
||||
|
||||
LOAD_PROC(LPALGENAUXILIARYEFFECTSLOTS, alGenAuxiliaryEffectSlots);
|
||||
LOAD_PROC(LPALDELETEAUXILIARYEFFECTSLOTS, alDeleteAuxiliaryEffectSlots);
|
||||
LOAD_PROC(LPALISAUXILIARYEFFECTSLOT, alIsAuxiliaryEffectSlot);
|
||||
LOAD_PROC(LPALAUXILIARYEFFECTSLOTI, alAuxiliaryEffectSloti);
|
||||
LOAD_PROC(LPALAUXILIARYEFFECTSLOTIV, alAuxiliaryEffectSlotiv);
|
||||
LOAD_PROC(LPALAUXILIARYEFFECTSLOTF, alAuxiliaryEffectSlotf);
|
||||
LOAD_PROC(LPALAUXILIARYEFFECTSLOTFV, alAuxiliaryEffectSlotfv);
|
||||
LOAD_PROC(LPALGETAUXILIARYEFFECTSLOTI, alGetAuxiliaryEffectSloti);
|
||||
LOAD_PROC(LPALGETAUXILIARYEFFECTSLOTIV, alGetAuxiliaryEffectSlotiv);
|
||||
LOAD_PROC(LPALGETAUXILIARYEFFECTSLOTF, alGetAuxiliaryEffectSlotf);
|
||||
LOAD_PROC(LPALGETAUXILIARYEFFECTSLOTFV, alGetAuxiliaryEffectSlotfv);
|
||||
#undef LOAD_PROC
|
||||
|
||||
/* Load the sound into a buffer. */
|
||||
buffer = LoadSound(argv[0]);
|
||||
if(!buffer)
|
||||
{
|
||||
CloseAL();
|
||||
return 1;
|
||||
}
|
||||
|
||||
/* Load the reverb into an effect. */
|
||||
effect = LoadEffect(&reverb);
|
||||
if(!effect)
|
||||
{
|
||||
alDeleteBuffers(1, &buffer);
|
||||
CloseAL();
|
||||
return 1;
|
||||
}
|
||||
|
||||
/* Create the effect slot object. This is what "plays" an effect on sources
|
||||
* that connect to it. */
|
||||
slot = 0;
|
||||
alGenAuxiliaryEffectSlots(1, &slot);
|
||||
|
||||
/* Tell the effect slot to use the loaded effect object. Note that the this
|
||||
* effectively copies the effect properties. You can modify or delete the
|
||||
* effect object afterward without affecting the effect slot.
|
||||
*/
|
||||
alAuxiliaryEffectSloti(slot, AL_EFFECTSLOT_EFFECT, (ALint)effect);
|
||||
assert(alGetError()==AL_NO_ERROR && "Failed to set effect slot");
|
||||
|
||||
/* Create the source to play the sound with. */
|
||||
source = 0;
|
||||
alGenSources(1, &source);
|
||||
alSourcei(source, AL_BUFFER, (ALint)buffer);
|
||||
|
||||
/* Connect the source to the effect slot. This tells the source to use the
|
||||
* effect slot 'slot', on send #0 with the AL_FILTER_NULL filter object.
|
||||
*/
|
||||
alSource3i(source, AL_AUXILIARY_SEND_FILTER, (ALint)slot, 0, AL_FILTER_NULL);
|
||||
assert(alGetError()==AL_NO_ERROR && "Failed to setup sound source");
|
||||
|
||||
/* Play the sound until it finishes. */
|
||||
alSourcePlay(source);
|
||||
do {
|
||||
al_nssleep(10000000);
|
||||
alGetSourcei(source, AL_SOURCE_STATE, &state);
|
||||
} while(alGetError() == AL_NO_ERROR && state == AL_PLAYING);
|
||||
|
||||
/* All done. Delete resources, and close down OpenAL. */
|
||||
alDeleteSources(1, &source);
|
||||
alDeleteAuxiliaryEffectSlots(1, &slot);
|
||||
alDeleteEffects(1, &effect);
|
||||
alDeleteBuffers(1, &buffer);
|
||||
|
||||
CloseAL();
|
||||
|
||||
return 0;
|
||||
}
|
||||
519
externals/openal-soft/examples/alstream.c
vendored
Normal file
519
externals/openal-soft/examples/alstream.c
vendored
Normal file
@@ -0,0 +1,519 @@
|
||||
/*
|
||||
* OpenAL Audio Stream Example
|
||||
*
|
||||
* Copyright (c) 2011 by Chris Robinson <chris.kcat@gmail.com>
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
* of this software and associated documentation files (the "Software"), to deal
|
||||
* in the Software without restriction, including without limitation the rights
|
||||
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
* copies of the Software, and to permit persons to whom the Software is
|
||||
* furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
* THE SOFTWARE.
|
||||
*/
|
||||
|
||||
/* This file contains a relatively simple streaming audio player. */
|
||||
|
||||
#include <assert.h>
|
||||
#include <inttypes.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#include "sndfile.h"
|
||||
|
||||
#include "AL/al.h"
|
||||
#include "AL/alext.h"
|
||||
|
||||
#include "common/alhelpers.h"
|
||||
|
||||
|
||||
/* Define the number of buffers and buffer size (in milliseconds) to use. 4
|
||||
* buffers at 200ms each gives a nice per-chunk size, and lets the queue last
|
||||
* for almost one second.
|
||||
*/
|
||||
#define NUM_BUFFERS 4
|
||||
#define BUFFER_MILLISEC 200
|
||||
|
||||
typedef enum SampleType {
|
||||
Int16, Float, IMA4, MSADPCM
|
||||
} SampleType;
|
||||
|
||||
typedef struct StreamPlayer {
|
||||
/* These are the buffers and source to play out through OpenAL with. */
|
||||
ALuint buffers[NUM_BUFFERS];
|
||||
ALuint source;
|
||||
|
||||
/* Handle for the audio file */
|
||||
SNDFILE *sndfile;
|
||||
SF_INFO sfinfo;
|
||||
void *membuf;
|
||||
|
||||
/* The sample type and block/frame size being read for the buffer. */
|
||||
SampleType sample_type;
|
||||
int byteblockalign;
|
||||
int sampleblockalign;
|
||||
int block_count;
|
||||
|
||||
/* The format of the output stream (sample rate is in sfinfo) */
|
||||
ALenum format;
|
||||
} StreamPlayer;
|
||||
|
||||
static StreamPlayer *NewPlayer(void);
|
||||
static void DeletePlayer(StreamPlayer *player);
|
||||
static int OpenPlayerFile(StreamPlayer *player, const char *filename);
|
||||
static void ClosePlayerFile(StreamPlayer *player);
|
||||
static int StartPlayer(StreamPlayer *player);
|
||||
static int UpdatePlayer(StreamPlayer *player);
|
||||
|
||||
/* Creates a new player object, and allocates the needed OpenAL source and
|
||||
* buffer objects. Error checking is simplified for the purposes of this
|
||||
* example, and will cause an abort if needed.
|
||||
*/
|
||||
static StreamPlayer *NewPlayer(void)
|
||||
{
|
||||
StreamPlayer *player;
|
||||
|
||||
player = calloc(1, sizeof(*player));
|
||||
assert(player != NULL);
|
||||
|
||||
/* Generate the buffers and source */
|
||||
alGenBuffers(NUM_BUFFERS, player->buffers);
|
||||
assert(alGetError() == AL_NO_ERROR && "Could not create buffers");
|
||||
|
||||
alGenSources(1, &player->source);
|
||||
assert(alGetError() == AL_NO_ERROR && "Could not create source");
|
||||
|
||||
/* Set parameters so mono sources play out the front-center speaker and
|
||||
* won't distance attenuate. */
|
||||
alSource3i(player->source, AL_POSITION, 0, 0, -1);
|
||||
alSourcei(player->source, AL_SOURCE_RELATIVE, AL_TRUE);
|
||||
alSourcei(player->source, AL_ROLLOFF_FACTOR, 0);
|
||||
assert(alGetError() == AL_NO_ERROR && "Could not set source parameters");
|
||||
|
||||
return player;
|
||||
}
|
||||
|
||||
/* Destroys a player object, deleting the source and buffers. No error handling
|
||||
* since these calls shouldn't fail with a properly-made player object. */
|
||||
static void DeletePlayer(StreamPlayer *player)
|
||||
{
|
||||
ClosePlayerFile(player);
|
||||
|
||||
alDeleteSources(1, &player->source);
|
||||
alDeleteBuffers(NUM_BUFFERS, player->buffers);
|
||||
if(alGetError() != AL_NO_ERROR)
|
||||
fprintf(stderr, "Failed to delete object IDs\n");
|
||||
|
||||
memset(player, 0, sizeof(*player));
|
||||
free(player);
|
||||
}
|
||||
|
||||
|
||||
/* Opens the first audio stream of the named file. If a file is already open,
|
||||
* it will be closed first. */
|
||||
static int OpenPlayerFile(StreamPlayer *player, const char *filename)
|
||||
{
|
||||
int byteblockalign=0, splblockalign=0;
|
||||
|
||||
ClosePlayerFile(player);
|
||||
|
||||
/* Open the audio file and check that it's usable. */
|
||||
player->sndfile = sf_open(filename, SFM_READ, &player->sfinfo);
|
||||
if(!player->sndfile)
|
||||
{
|
||||
fprintf(stderr, "Could not open audio in %s: %s\n", filename, sf_strerror(NULL));
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* Detect a suitable format to load. Formats like Vorbis and Opus use float
|
||||
* natively, so load as float to avoid clipping when possible. Formats
|
||||
* larger than 16-bit can also use float to preserve a bit more precision.
|
||||
*/
|
||||
switch((player->sfinfo.format&SF_FORMAT_SUBMASK))
|
||||
{
|
||||
case SF_FORMAT_PCM_24:
|
||||
case SF_FORMAT_PCM_32:
|
||||
case SF_FORMAT_FLOAT:
|
||||
case SF_FORMAT_DOUBLE:
|
||||
case SF_FORMAT_VORBIS:
|
||||
case SF_FORMAT_OPUS:
|
||||
case SF_FORMAT_ALAC_20:
|
||||
case SF_FORMAT_ALAC_24:
|
||||
case SF_FORMAT_ALAC_32:
|
||||
case 0x0080/*SF_FORMAT_MPEG_LAYER_I*/:
|
||||
case 0x0081/*SF_FORMAT_MPEG_LAYER_II*/:
|
||||
case 0x0082/*SF_FORMAT_MPEG_LAYER_III*/:
|
||||
if(alIsExtensionPresent("AL_EXT_FLOAT32"))
|
||||
player->sample_type = Float;
|
||||
break;
|
||||
case SF_FORMAT_IMA_ADPCM:
|
||||
/* ADPCM formats require setting a block alignment as specified in the
|
||||
* file, which needs to be read from the wave 'fmt ' chunk manually
|
||||
* since libsndfile doesn't provide it in a format-agnostic way.
|
||||
*/
|
||||
if(player->sfinfo.channels <= 2
|
||||
&& (player->sfinfo.format&SF_FORMAT_TYPEMASK) == SF_FORMAT_WAV
|
||||
&& alIsExtensionPresent("AL_EXT_IMA4")
|
||||
&& alIsExtensionPresent("AL_SOFT_block_alignment"))
|
||||
player->sample_type = IMA4;
|
||||
break;
|
||||
case SF_FORMAT_MS_ADPCM:
|
||||
if(player->sfinfo.channels <= 2
|
||||
&& (player->sfinfo.format&SF_FORMAT_TYPEMASK) == SF_FORMAT_WAV
|
||||
&& alIsExtensionPresent("AL_SOFT_MSADPCM")
|
||||
&& alIsExtensionPresent("AL_SOFT_block_alignment"))
|
||||
player->sample_type = MSADPCM;
|
||||
break;
|
||||
}
|
||||
|
||||
if(player->sample_type == IMA4 || player->sample_type == MSADPCM)
|
||||
{
|
||||
/* For ADPCM, lookup the wave file's "fmt " chunk, which is a
|
||||
* WAVEFORMATEX-based structure for the audio format.
|
||||
*/
|
||||
SF_CHUNK_INFO inf = { "fmt ", 4, 0, NULL };
|
||||
SF_CHUNK_ITERATOR *iter = sf_get_chunk_iterator(player->sndfile, &inf);
|
||||
|
||||
/* If there's an issue getting the chunk or block alignment, load as
|
||||
* 16-bit and have libsndfile do the conversion.
|
||||
*/
|
||||
if(!iter || sf_get_chunk_size(iter, &inf) != SF_ERR_NO_ERROR || inf.datalen < 14)
|
||||
player->sample_type = Int16;
|
||||
else
|
||||
{
|
||||
ALubyte *fmtbuf = calloc(inf.datalen, 1);
|
||||
inf.data = fmtbuf;
|
||||
if(sf_get_chunk_data(iter, &inf) != SF_ERR_NO_ERROR)
|
||||
player->sample_type = Int16;
|
||||
else
|
||||
{
|
||||
/* Read the nBlockAlign field, and convert from bytes- to
|
||||
* samples-per-block (verifying it's valid by converting back
|
||||
* and comparing to the original value).
|
||||
*/
|
||||
byteblockalign = fmtbuf[12] | (fmtbuf[13]<<8);
|
||||
if(player->sample_type == IMA4)
|
||||
{
|
||||
splblockalign = (byteblockalign/player->sfinfo.channels - 4)/4*8 + 1;
|
||||
if(splblockalign < 1
|
||||
|| ((splblockalign-1)/2 + 4)*player->sfinfo.channels != byteblockalign)
|
||||
player->sample_type = Int16;
|
||||
}
|
||||
else
|
||||
{
|
||||
splblockalign = (byteblockalign/player->sfinfo.channels - 7)*2 + 2;
|
||||
if(splblockalign < 2
|
||||
|| ((splblockalign-2)/2 + 7)*player->sfinfo.channels != byteblockalign)
|
||||
player->sample_type = Int16;
|
||||
}
|
||||
}
|
||||
free(fmtbuf);
|
||||
}
|
||||
}
|
||||
|
||||
if(player->sample_type == Int16)
|
||||
{
|
||||
player->sampleblockalign = 1;
|
||||
player->byteblockalign = player->sfinfo.channels * 2;
|
||||
}
|
||||
else if(player->sample_type == Float)
|
||||
{
|
||||
player->sampleblockalign = 1;
|
||||
player->byteblockalign = player->sfinfo.channels * 4;
|
||||
}
|
||||
else
|
||||
{
|
||||
player->sampleblockalign = splblockalign;
|
||||
player->byteblockalign = byteblockalign;
|
||||
}
|
||||
|
||||
/* Figure out the OpenAL format from the file and desired sample type. */
|
||||
player->format = AL_NONE;
|
||||
if(player->sfinfo.channels == 1)
|
||||
{
|
||||
if(player->sample_type == Int16)
|
||||
player->format = AL_FORMAT_MONO16;
|
||||
else if(player->sample_type == Float)
|
||||
player->format = AL_FORMAT_MONO_FLOAT32;
|
||||
else if(player->sample_type == IMA4)
|
||||
player->format = AL_FORMAT_MONO_IMA4;
|
||||
else if(player->sample_type == MSADPCM)
|
||||
player->format = AL_FORMAT_MONO_MSADPCM_SOFT;
|
||||
}
|
||||
else if(player->sfinfo.channels == 2)
|
||||
{
|
||||
if(player->sample_type == Int16)
|
||||
player->format = AL_FORMAT_STEREO16;
|
||||
else if(player->sample_type == Float)
|
||||
player->format = AL_FORMAT_STEREO_FLOAT32;
|
||||
else if(player->sample_type == IMA4)
|
||||
player->format = AL_FORMAT_STEREO_IMA4;
|
||||
else if(player->sample_type == MSADPCM)
|
||||
player->format = AL_FORMAT_STEREO_MSADPCM_SOFT;
|
||||
}
|
||||
else if(player->sfinfo.channels == 3)
|
||||
{
|
||||
if(sf_command(player->sndfile, SFC_WAVEX_GET_AMBISONIC, NULL, 0) == SF_AMBISONIC_B_FORMAT)
|
||||
{
|
||||
if(player->sample_type == Int16)
|
||||
player->format = AL_FORMAT_BFORMAT2D_16;
|
||||
else if(player->sample_type == Float)
|
||||
player->format = AL_FORMAT_BFORMAT2D_FLOAT32;
|
||||
}
|
||||
}
|
||||
else if(player->sfinfo.channels == 4)
|
||||
{
|
||||
if(sf_command(player->sndfile, SFC_WAVEX_GET_AMBISONIC, NULL, 0) == SF_AMBISONIC_B_FORMAT)
|
||||
{
|
||||
if(player->sample_type == Int16)
|
||||
player->format = AL_FORMAT_BFORMAT3D_16;
|
||||
else if(player->sample_type == Float)
|
||||
player->format = AL_FORMAT_BFORMAT3D_FLOAT32;
|
||||
}
|
||||
}
|
||||
if(!player->format)
|
||||
{
|
||||
fprintf(stderr, "Unsupported channel count: %d\n", player->sfinfo.channels);
|
||||
sf_close(player->sndfile);
|
||||
player->sndfile = NULL;
|
||||
return 0;
|
||||
}
|
||||
|
||||
player->block_count = player->sfinfo.samplerate / player->sampleblockalign;
|
||||
player->block_count = player->block_count * BUFFER_MILLISEC / 1000;
|
||||
player->membuf = malloc((size_t)(player->block_count * player->byteblockalign));
|
||||
|
||||
return 1;
|
||||
}
|
||||
|
||||
/* Closes the audio file stream */
|
||||
static void ClosePlayerFile(StreamPlayer *player)
|
||||
{
|
||||
if(player->sndfile)
|
||||
sf_close(player->sndfile);
|
||||
player->sndfile = NULL;
|
||||
|
||||
free(player->membuf);
|
||||
player->membuf = NULL;
|
||||
|
||||
if(player->sampleblockalign > 1)
|
||||
{
|
||||
ALsizei i;
|
||||
for(i = 0;i < NUM_BUFFERS;i++)
|
||||
alBufferi(player->buffers[i], AL_UNPACK_BLOCK_ALIGNMENT_SOFT, 0);
|
||||
player->sampleblockalign = 0;
|
||||
player->byteblockalign = 0;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/* Prebuffers some audio from the file, and starts playing the source */
|
||||
static int StartPlayer(StreamPlayer *player)
|
||||
{
|
||||
ALsizei i;
|
||||
|
||||
/* Rewind the source position and clear the buffer queue */
|
||||
alSourceRewind(player->source);
|
||||
alSourcei(player->source, AL_BUFFER, 0);
|
||||
|
||||
/* Fill the buffer queue */
|
||||
for(i = 0;i < NUM_BUFFERS;i++)
|
||||
{
|
||||
sf_count_t slen;
|
||||
|
||||
/* Get some data to give it to the buffer */
|
||||
if(player->sample_type == Int16)
|
||||
{
|
||||
slen = sf_readf_short(player->sndfile, player->membuf,
|
||||
player->block_count * player->sampleblockalign);
|
||||
if(slen < 1) break;
|
||||
slen *= player->byteblockalign;
|
||||
}
|
||||
else if(player->sample_type == Float)
|
||||
{
|
||||
slen = sf_readf_float(player->sndfile, player->membuf,
|
||||
player->block_count * player->sampleblockalign);
|
||||
if(slen < 1) break;
|
||||
slen *= player->byteblockalign;
|
||||
}
|
||||
else
|
||||
{
|
||||
slen = sf_read_raw(player->sndfile, player->membuf,
|
||||
player->block_count * player->byteblockalign);
|
||||
if(slen > 0) slen -= slen%player->byteblockalign;
|
||||
if(slen < 1) break;
|
||||
}
|
||||
|
||||
if(player->sampleblockalign > 1)
|
||||
alBufferi(player->buffers[i], AL_UNPACK_BLOCK_ALIGNMENT_SOFT,
|
||||
player->sampleblockalign);
|
||||
|
||||
alBufferData(player->buffers[i], player->format, player->membuf, (ALsizei)slen,
|
||||
player->sfinfo.samplerate);
|
||||
}
|
||||
if(alGetError() != AL_NO_ERROR)
|
||||
{
|
||||
fprintf(stderr, "Error buffering for playback\n");
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* Now queue and start playback! */
|
||||
alSourceQueueBuffers(player->source, i, player->buffers);
|
||||
alSourcePlay(player->source);
|
||||
if(alGetError() != AL_NO_ERROR)
|
||||
{
|
||||
fprintf(stderr, "Error starting playback\n");
|
||||
return 0;
|
||||
}
|
||||
|
||||
return 1;
|
||||
}
|
||||
|
||||
static int UpdatePlayer(StreamPlayer *player)
|
||||
{
|
||||
ALint processed, state;
|
||||
|
||||
/* Get relevant source info */
|
||||
alGetSourcei(player->source, AL_SOURCE_STATE, &state);
|
||||
alGetSourcei(player->source, AL_BUFFERS_PROCESSED, &processed);
|
||||
if(alGetError() != AL_NO_ERROR)
|
||||
{
|
||||
fprintf(stderr, "Error checking source state\n");
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* Unqueue and handle each processed buffer */
|
||||
while(processed > 0)
|
||||
{
|
||||
ALuint bufid;
|
||||
sf_count_t slen;
|
||||
|
||||
alSourceUnqueueBuffers(player->source, 1, &bufid);
|
||||
processed--;
|
||||
|
||||
/* Read the next chunk of data, refill the buffer, and queue it
|
||||
* back on the source */
|
||||
if(player->sample_type == Int16)
|
||||
{
|
||||
slen = sf_readf_short(player->sndfile, player->membuf,
|
||||
player->block_count * player->sampleblockalign);
|
||||
if(slen > 0) slen *= player->byteblockalign;
|
||||
}
|
||||
else if(player->sample_type == Float)
|
||||
{
|
||||
slen = sf_readf_float(player->sndfile, player->membuf,
|
||||
player->block_count * player->sampleblockalign);
|
||||
if(slen > 0) slen *= player->byteblockalign;
|
||||
}
|
||||
else
|
||||
{
|
||||
slen = sf_read_raw(player->sndfile, player->membuf,
|
||||
player->block_count * player->byteblockalign);
|
||||
if(slen > 0) slen -= slen%player->byteblockalign;
|
||||
}
|
||||
|
||||
if(slen > 0)
|
||||
{
|
||||
alBufferData(bufid, player->format, player->membuf, (ALsizei)slen,
|
||||
player->sfinfo.samplerate);
|
||||
alSourceQueueBuffers(player->source, 1, &bufid);
|
||||
}
|
||||
if(alGetError() != AL_NO_ERROR)
|
||||
{
|
||||
fprintf(stderr, "Error buffering data\n");
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
/* Make sure the source hasn't underrun */
|
||||
if(state != AL_PLAYING && state != AL_PAUSED)
|
||||
{
|
||||
ALint queued;
|
||||
|
||||
/* If no buffers are queued, playback is finished */
|
||||
alGetSourcei(player->source, AL_BUFFERS_QUEUED, &queued);
|
||||
if(queued == 0)
|
||||
return 0;
|
||||
|
||||
alSourcePlay(player->source);
|
||||
if(alGetError() != AL_NO_ERROR)
|
||||
{
|
||||
fprintf(stderr, "Error restarting playback\n");
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
return 1;
|
||||
}
|
||||
|
||||
|
||||
int main(int argc, char **argv)
|
||||
{
|
||||
StreamPlayer *player;
|
||||
int i;
|
||||
|
||||
/* Print out usage if no arguments were specified */
|
||||
if(argc < 2)
|
||||
{
|
||||
fprintf(stderr, "Usage: %s [-device <name>] <filenames...>\n", argv[0]);
|
||||
return 1;
|
||||
}
|
||||
|
||||
argv++; argc--;
|
||||
if(InitAL(&argv, &argc) != 0)
|
||||
return 1;
|
||||
|
||||
player = NewPlayer();
|
||||
|
||||
/* Play each file listed on the command line */
|
||||
for(i = 0;i < argc;i++)
|
||||
{
|
||||
const char *namepart;
|
||||
|
||||
if(!OpenPlayerFile(player, argv[i]))
|
||||
continue;
|
||||
|
||||
/* Get the name portion, without the path, for display. */
|
||||
namepart = strrchr(argv[i], '/');
|
||||
if(namepart || (namepart=strrchr(argv[i], '\\')))
|
||||
namepart++;
|
||||
else
|
||||
namepart = argv[i];
|
||||
|
||||
printf("Playing: %s (%s, %dhz)\n", namepart, FormatName(player->format),
|
||||
player->sfinfo.samplerate);
|
||||
fflush(stdout);
|
||||
|
||||
if(!StartPlayer(player))
|
||||
{
|
||||
ClosePlayerFile(player);
|
||||
continue;
|
||||
}
|
||||
|
||||
while(UpdatePlayer(player))
|
||||
al_nssleep(10000000);
|
||||
|
||||
/* All done with this file. Close it and go to the next */
|
||||
ClosePlayerFile(player);
|
||||
}
|
||||
printf("Done.\n");
|
||||
|
||||
/* All files done. Delete the player, and close down OpenAL */
|
||||
DeletePlayer(player);
|
||||
player = NULL;
|
||||
|
||||
CloseAL();
|
||||
|
||||
return 0;
|
||||
}
|
||||
551
externals/openal-soft/examples/alstreamcb.cpp
vendored
Normal file
551
externals/openal-soft/examples/alstreamcb.cpp
vendored
Normal file
@@ -0,0 +1,551 @@
|
||||
/*
|
||||
* OpenAL Callback-based Stream Example
|
||||
*
|
||||
* Copyright (c) 2020 by Chris Robinson <chris.kcat@gmail.com>
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
* of this software and associated documentation files (the "Software"), to deal
|
||||
* in the Software without restriction, including without limitation the rights
|
||||
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
* copies of the Software, and to permit persons to whom the Software is
|
||||
* furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
* THE SOFTWARE.
|
||||
*/
|
||||
|
||||
/* This file contains a streaming audio player using a callback buffer. */
|
||||
|
||||
#include <string.h>
|
||||
#include <stdlib.h>
|
||||
#include <stdio.h>
|
||||
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <memory>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
#include "sndfile.h"
|
||||
|
||||
#include "AL/al.h"
|
||||
#include "AL/alc.h"
|
||||
#include "AL/alext.h"
|
||||
|
||||
#include "common/alhelpers.h"
|
||||
|
||||
|
||||
namespace {
|
||||
|
||||
using std::chrono::seconds;
|
||||
using std::chrono::nanoseconds;
|
||||
|
||||
LPALBUFFERCALLBACKSOFT alBufferCallbackSOFT;
|
||||
|
||||
struct StreamPlayer {
|
||||
/* A lockless ring-buffer (supports single-provider, single-consumer
|
||||
* operation).
|
||||
*/
|
||||
std::unique_ptr<ALbyte[]> mBufferData;
|
||||
size_t mBufferDataSize{0};
|
||||
std::atomic<size_t> mReadPos{0};
|
||||
std::atomic<size_t> mWritePos{0};
|
||||
size_t mSamplesPerBlock{1};
|
||||
size_t mBytesPerBlock{1};
|
||||
|
||||
enum class SampleType {
|
||||
Int16, Float, IMA4, MSADPCM
|
||||
};
|
||||
SampleType mSampleFormat{SampleType::Int16};
|
||||
|
||||
/* The buffer to get the callback, and source to play with. */
|
||||
ALuint mBuffer{0}, mSource{0};
|
||||
size_t mStartOffset{0};
|
||||
|
||||
/* Handle for the audio file to decode. */
|
||||
SNDFILE *mSndfile{nullptr};
|
||||
SF_INFO mSfInfo{};
|
||||
size_t mDecoderOffset{0};
|
||||
|
||||
/* The format of the callback samples. */
|
||||
ALenum mFormat;
|
||||
|
||||
StreamPlayer()
|
||||
{
|
||||
alGenBuffers(1, &mBuffer);
|
||||
if(alGetError() != AL_NO_ERROR)
|
||||
throw std::runtime_error{"alGenBuffers failed"};
|
||||
alGenSources(1, &mSource);
|
||||
if(alGetError() != AL_NO_ERROR)
|
||||
{
|
||||
alDeleteBuffers(1, &mBuffer);
|
||||
throw std::runtime_error{"alGenSources failed"};
|
||||
}
|
||||
}
|
||||
~StreamPlayer()
|
||||
{
|
||||
alDeleteSources(1, &mSource);
|
||||
alDeleteBuffers(1, &mBuffer);
|
||||
if(mSndfile)
|
||||
sf_close(mSndfile);
|
||||
}
|
||||
|
||||
void close()
|
||||
{
|
||||
if(mSamplesPerBlock > 1)
|
||||
alBufferi(mBuffer, AL_UNPACK_BLOCK_ALIGNMENT_SOFT, 0);
|
||||
|
||||
if(mSndfile)
|
||||
{
|
||||
alSourceRewind(mSource);
|
||||
alSourcei(mSource, AL_BUFFER, 0);
|
||||
sf_close(mSndfile);
|
||||
mSndfile = nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
bool open(const char *filename)
|
||||
{
|
||||
close();
|
||||
|
||||
/* Open the file and figure out the OpenAL format. */
|
||||
mSndfile = sf_open(filename, SFM_READ, &mSfInfo);
|
||||
if(!mSndfile)
|
||||
{
|
||||
fprintf(stderr, "Could not open audio in %s: %s\n", filename, sf_strerror(mSndfile));
|
||||
return false;
|
||||
}
|
||||
|
||||
switch((mSfInfo.format&SF_FORMAT_SUBMASK))
|
||||
{
|
||||
case SF_FORMAT_PCM_24:
|
||||
case SF_FORMAT_PCM_32:
|
||||
case SF_FORMAT_FLOAT:
|
||||
case SF_FORMAT_DOUBLE:
|
||||
case SF_FORMAT_VORBIS:
|
||||
case SF_FORMAT_OPUS:
|
||||
case SF_FORMAT_ALAC_20:
|
||||
case SF_FORMAT_ALAC_24:
|
||||
case SF_FORMAT_ALAC_32:
|
||||
case 0x0080/*SF_FORMAT_MPEG_LAYER_I*/:
|
||||
case 0x0081/*SF_FORMAT_MPEG_LAYER_II*/:
|
||||
case 0x0082/*SF_FORMAT_MPEG_LAYER_III*/:
|
||||
if(alIsExtensionPresent("AL_EXT_FLOAT32"))
|
||||
mSampleFormat = SampleType::Float;
|
||||
break;
|
||||
case SF_FORMAT_IMA_ADPCM:
|
||||
if(mSfInfo.channels <= 2 && (mSfInfo.format&SF_FORMAT_TYPEMASK) == SF_FORMAT_WAV
|
||||
&& alIsExtensionPresent("AL_EXT_IMA4")
|
||||
&& alIsExtensionPresent("AL_SOFT_block_alignment"))
|
||||
mSampleFormat = SampleType::IMA4;
|
||||
break;
|
||||
case SF_FORMAT_MS_ADPCM:
|
||||
if(mSfInfo.channels <= 2 && (mSfInfo.format&SF_FORMAT_TYPEMASK) == SF_FORMAT_WAV
|
||||
&& alIsExtensionPresent("AL_SOFT_MSADPCM")
|
||||
&& alIsExtensionPresent("AL_SOFT_block_alignment"))
|
||||
mSampleFormat = SampleType::MSADPCM;
|
||||
break;
|
||||
}
|
||||
|
||||
int splblocksize{}, byteblocksize{};
|
||||
if(mSampleFormat == SampleType::IMA4 || mSampleFormat == SampleType::MSADPCM)
|
||||
{
|
||||
SF_CHUNK_INFO inf{ "fmt ", 4, 0, nullptr };
|
||||
SF_CHUNK_ITERATOR *iter = sf_get_chunk_iterator(mSndfile, &inf);
|
||||
if(!iter || sf_get_chunk_size(iter, &inf) != SF_ERR_NO_ERROR || inf.datalen < 14)
|
||||
mSampleFormat = SampleType::Int16;
|
||||
else
|
||||
{
|
||||
auto fmtbuf = std::make_unique<ALubyte[]>(inf.datalen);
|
||||
inf.data = fmtbuf.get();
|
||||
if(sf_get_chunk_data(iter, &inf) != SF_ERR_NO_ERROR)
|
||||
mSampleFormat = SampleType::Int16;
|
||||
else
|
||||
{
|
||||
byteblocksize = fmtbuf[12] | (fmtbuf[13]<<8u);
|
||||
if(mSampleFormat == SampleType::IMA4)
|
||||
{
|
||||
splblocksize = (byteblocksize/mSfInfo.channels - 4)/4*8 + 1;
|
||||
if(splblocksize < 1
|
||||
|| ((splblocksize-1)/2 + 4)*mSfInfo.channels != byteblocksize)
|
||||
mSampleFormat = SampleType::Int16;
|
||||
}
|
||||
else
|
||||
{
|
||||
splblocksize = (byteblocksize/mSfInfo.channels - 7)*2 + 2;
|
||||
if(splblocksize < 2
|
||||
|| ((splblocksize-2)/2 + 7)*mSfInfo.channels != byteblocksize)
|
||||
mSampleFormat = SampleType::Int16;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if(mSampleFormat == SampleType::Int16)
|
||||
{
|
||||
mSamplesPerBlock = 1;
|
||||
mBytesPerBlock = static_cast<size_t>(mSfInfo.channels * 2);
|
||||
}
|
||||
else if(mSampleFormat == SampleType::Float)
|
||||
{
|
||||
mSamplesPerBlock = 1;
|
||||
mBytesPerBlock = static_cast<size_t>(mSfInfo.channels * 4);
|
||||
}
|
||||
else
|
||||
{
|
||||
mSamplesPerBlock = static_cast<size_t>(splblocksize);
|
||||
mBytesPerBlock = static_cast<size_t>(byteblocksize);
|
||||
}
|
||||
|
||||
mFormat = AL_NONE;
|
||||
if(mSfInfo.channels == 1)
|
||||
{
|
||||
if(mSampleFormat == SampleType::Int16)
|
||||
mFormat = AL_FORMAT_MONO16;
|
||||
else if(mSampleFormat == SampleType::Float)
|
||||
mFormat = AL_FORMAT_MONO_FLOAT32;
|
||||
else if(mSampleFormat == SampleType::IMA4)
|
||||
mFormat = AL_FORMAT_MONO_IMA4;
|
||||
else if(mSampleFormat == SampleType::MSADPCM)
|
||||
mFormat = AL_FORMAT_MONO_MSADPCM_SOFT;
|
||||
}
|
||||
else if(mSfInfo.channels == 2)
|
||||
{
|
||||
if(mSampleFormat == SampleType::Int16)
|
||||
mFormat = AL_FORMAT_STEREO16;
|
||||
else if(mSampleFormat == SampleType::Float)
|
||||
mFormat = AL_FORMAT_STEREO_FLOAT32;
|
||||
else if(mSampleFormat == SampleType::IMA4)
|
||||
mFormat = AL_FORMAT_STEREO_IMA4;
|
||||
else if(mSampleFormat == SampleType::MSADPCM)
|
||||
mFormat = AL_FORMAT_STEREO_MSADPCM_SOFT;
|
||||
}
|
||||
else if(mSfInfo.channels == 3)
|
||||
{
|
||||
if(sf_command(mSndfile, SFC_WAVEX_GET_AMBISONIC, NULL, 0) == SF_AMBISONIC_B_FORMAT)
|
||||
{
|
||||
if(mSampleFormat == SampleType::Int16)
|
||||
mFormat = AL_FORMAT_BFORMAT2D_16;
|
||||
else if(mSampleFormat == SampleType::Float)
|
||||
mFormat = AL_FORMAT_BFORMAT2D_FLOAT32;
|
||||
}
|
||||
}
|
||||
else if(mSfInfo.channels == 4)
|
||||
{
|
||||
if(sf_command(mSndfile, SFC_WAVEX_GET_AMBISONIC, NULL, 0) == SF_AMBISONIC_B_FORMAT)
|
||||
{
|
||||
if(mSampleFormat == SampleType::Int16)
|
||||
mFormat = AL_FORMAT_BFORMAT3D_16;
|
||||
else if(mSampleFormat == SampleType::Float)
|
||||
mFormat = AL_FORMAT_BFORMAT3D_FLOAT32;
|
||||
}
|
||||
}
|
||||
if(!mFormat)
|
||||
{
|
||||
fprintf(stderr, "Unsupported channel count: %d\n", mSfInfo.channels);
|
||||
sf_close(mSndfile);
|
||||
mSndfile = nullptr;
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/* Set a 1s ring buffer size. */
|
||||
size_t numblocks{(static_cast<ALuint>(mSfInfo.samplerate) + mSamplesPerBlock-1)
|
||||
/ mSamplesPerBlock};
|
||||
mBufferDataSize = static_cast<ALuint>(numblocks * mBytesPerBlock);
|
||||
mBufferData.reset(new ALbyte[mBufferDataSize]);
|
||||
mReadPos.store(0, std::memory_order_relaxed);
|
||||
mWritePos.store(0, std::memory_order_relaxed);
|
||||
mDecoderOffset = 0;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/* The actual C-style callback just forwards to the non-static method. Not
|
||||
* strictly needed and the compiler will optimize it to a normal function,
|
||||
* but it allows the callback implementation to have a nice 'this' pointer
|
||||
* with normal member access.
|
||||
*/
|
||||
static ALsizei AL_APIENTRY bufferCallbackC(void *userptr, void *data, ALsizei size)
|
||||
{ return static_cast<StreamPlayer*>(userptr)->bufferCallback(data, size); }
|
||||
ALsizei bufferCallback(void *data, ALsizei size)
|
||||
{
|
||||
/* NOTE: The callback *MUST* be real-time safe! That means no blocking,
|
||||
* no allocations or deallocations, no I/O, no page faults, or calls to
|
||||
* functions that could do these things (this includes calling to
|
||||
* libraries like SDL_sound, libsndfile, ffmpeg, etc). Nothing should
|
||||
* unexpectedly stall this call since the audio has to get to the
|
||||
* device on time.
|
||||
*/
|
||||
ALsizei got{0};
|
||||
|
||||
size_t roffset{mReadPos.load(std::memory_order_acquire)};
|
||||
while(got < size)
|
||||
{
|
||||
/* If the write offset == read offset, there's nothing left in the
|
||||
* ring-buffer. Break from the loop and give what has been written.
|
||||
*/
|
||||
const size_t woffset{mWritePos.load(std::memory_order_relaxed)};
|
||||
if(woffset == roffset) break;
|
||||
|
||||
/* If the write offset is behind the read offset, the readable
|
||||
* portion wrapped around. Just read up to the end of the buffer in
|
||||
* that case, otherwise read up to the write offset. Also limit the
|
||||
* amount to copy given how much is remaining to write.
|
||||
*/
|
||||
size_t todo{((woffset < roffset) ? mBufferDataSize : woffset) - roffset};
|
||||
todo = std::min<size_t>(todo, static_cast<ALuint>(size-got));
|
||||
|
||||
/* Copy from the ring buffer to the provided output buffer. Wrap
|
||||
* the resulting read offset if it reached the end of the ring-
|
||||
* buffer.
|
||||
*/
|
||||
memcpy(data, &mBufferData[roffset], todo);
|
||||
data = static_cast<ALbyte*>(data) + todo;
|
||||
got += static_cast<ALsizei>(todo);
|
||||
|
||||
roffset += todo;
|
||||
if(roffset == mBufferDataSize)
|
||||
roffset = 0;
|
||||
}
|
||||
/* Finally, store the updated read offset, and return how many bytes
|
||||
* have been written.
|
||||
*/
|
||||
mReadPos.store(roffset, std::memory_order_release);
|
||||
|
||||
return got;
|
||||
}
|
||||
|
||||
bool prepare()
|
||||
{
|
||||
if(mSamplesPerBlock > 1)
|
||||
alBufferi(mBuffer, AL_UNPACK_BLOCK_ALIGNMENT_SOFT, static_cast<int>(mSamplesPerBlock));
|
||||
alBufferCallbackSOFT(mBuffer, mFormat, mSfInfo.samplerate, bufferCallbackC, this);
|
||||
alSourcei(mSource, AL_BUFFER, static_cast<ALint>(mBuffer));
|
||||
if(ALenum err{alGetError()})
|
||||
{
|
||||
fprintf(stderr, "Failed to set callback: %s (0x%04x)\n", alGetString(err), err);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool update()
|
||||
{
|
||||
ALenum state;
|
||||
ALint pos;
|
||||
alGetSourcei(mSource, AL_SAMPLE_OFFSET, &pos);
|
||||
alGetSourcei(mSource, AL_SOURCE_STATE, &state);
|
||||
|
||||
size_t woffset{mWritePos.load(std::memory_order_acquire)};
|
||||
if(state != AL_INITIAL)
|
||||
{
|
||||
const size_t roffset{mReadPos.load(std::memory_order_relaxed)};
|
||||
const size_t readable{((woffset >= roffset) ? woffset : (mBufferDataSize+woffset)) -
|
||||
roffset};
|
||||
/* For a stopped (underrun) source, the current playback offset is
|
||||
* the current decoder offset excluding the readable buffered data.
|
||||
* For a playing/paused source, it's the source's offset including
|
||||
* the playback offset the source was started with.
|
||||
*/
|
||||
const size_t curtime{((state == AL_STOPPED)
|
||||
? (mDecoderOffset-readable) / mBytesPerBlock * mSamplesPerBlock
|
||||
: (static_cast<ALuint>(pos) + mStartOffset/mBytesPerBlock*mSamplesPerBlock))
|
||||
/ static_cast<ALuint>(mSfInfo.samplerate)};
|
||||
printf("\r%3zus (%3zu%% full)", curtime, readable * 100 / mBufferDataSize);
|
||||
}
|
||||
else
|
||||
fputs("Starting...", stdout);
|
||||
fflush(stdout);
|
||||
|
||||
while(!sf_error(mSndfile))
|
||||
{
|
||||
size_t read_bytes;
|
||||
const size_t roffset{mReadPos.load(std::memory_order_relaxed)};
|
||||
if(roffset > woffset)
|
||||
{
|
||||
/* Note that the ring buffer's writable space is one byte less
|
||||
* than the available area because the write offset ending up
|
||||
* at the read offset would be interpreted as being empty
|
||||
* instead of full.
|
||||
*/
|
||||
const size_t writable{(roffset-woffset-1) / mBytesPerBlock};
|
||||
if(!writable) break;
|
||||
|
||||
if(mSampleFormat == SampleType::Int16)
|
||||
{
|
||||
sf_count_t num_frames{sf_readf_short(mSndfile,
|
||||
reinterpret_cast<short*>(&mBufferData[woffset]),
|
||||
static_cast<sf_count_t>(writable*mSamplesPerBlock))};
|
||||
if(num_frames < 1) break;
|
||||
read_bytes = static_cast<size_t>(num_frames) * mBytesPerBlock;
|
||||
}
|
||||
else if(mSampleFormat == SampleType::Float)
|
||||
{
|
||||
sf_count_t num_frames{sf_readf_float(mSndfile,
|
||||
reinterpret_cast<float*>(&mBufferData[woffset]),
|
||||
static_cast<sf_count_t>(writable*mSamplesPerBlock))};
|
||||
if(num_frames < 1) break;
|
||||
read_bytes = static_cast<size_t>(num_frames) * mBytesPerBlock;
|
||||
}
|
||||
else
|
||||
{
|
||||
sf_count_t numbytes{sf_read_raw(mSndfile, &mBufferData[woffset],
|
||||
static_cast<sf_count_t>(writable*mBytesPerBlock))};
|
||||
if(numbytes < 1) break;
|
||||
read_bytes = static_cast<size_t>(numbytes);
|
||||
}
|
||||
|
||||
woffset += read_bytes;
|
||||
}
|
||||
else
|
||||
{
|
||||
/* If the read offset is at or behind the write offset, the
|
||||
* writeable area (might) wrap around. Make sure the sample
|
||||
* data can fit, and calculate how much can go in front before
|
||||
* wrapping.
|
||||
*/
|
||||
const size_t writable{(!roffset ? mBufferDataSize-woffset-1 :
|
||||
(mBufferDataSize-woffset)) / mBytesPerBlock};
|
||||
if(!writable) break;
|
||||
|
||||
if(mSampleFormat == SampleType::Int16)
|
||||
{
|
||||
sf_count_t num_frames{sf_readf_short(mSndfile,
|
||||
reinterpret_cast<short*>(&mBufferData[woffset]),
|
||||
static_cast<sf_count_t>(writable*mSamplesPerBlock))};
|
||||
if(num_frames < 1) break;
|
||||
read_bytes = static_cast<size_t>(num_frames) * mBytesPerBlock;
|
||||
}
|
||||
else if(mSampleFormat == SampleType::Float)
|
||||
{
|
||||
sf_count_t num_frames{sf_readf_float(mSndfile,
|
||||
reinterpret_cast<float*>(&mBufferData[woffset]),
|
||||
static_cast<sf_count_t>(writable*mSamplesPerBlock))};
|
||||
if(num_frames < 1) break;
|
||||
read_bytes = static_cast<size_t>(num_frames) * mBytesPerBlock;
|
||||
}
|
||||
else
|
||||
{
|
||||
sf_count_t numbytes{sf_read_raw(mSndfile, &mBufferData[woffset],
|
||||
static_cast<sf_count_t>(writable*mBytesPerBlock))};
|
||||
if(numbytes < 1) break;
|
||||
read_bytes = static_cast<size_t>(numbytes);
|
||||
}
|
||||
|
||||
woffset += read_bytes;
|
||||
if(woffset == mBufferDataSize)
|
||||
woffset = 0;
|
||||
}
|
||||
mWritePos.store(woffset, std::memory_order_release);
|
||||
mDecoderOffset += read_bytes;
|
||||
}
|
||||
|
||||
if(state != AL_PLAYING && state != AL_PAUSED)
|
||||
{
|
||||
/* If the source is not playing or paused, it either underrun
|
||||
* (AL_STOPPED) or is just getting started (AL_INITIAL). If the
|
||||
* ring buffer is empty, it's done, otherwise play the source with
|
||||
* what's available.
|
||||
*/
|
||||
const size_t roffset{mReadPos.load(std::memory_order_relaxed)};
|
||||
const size_t readable{((woffset >= roffset) ? woffset : (mBufferDataSize+woffset)) -
|
||||
roffset};
|
||||
if(readable == 0)
|
||||
return false;
|
||||
|
||||
/* Store the playback offset that the source will start reading
|
||||
* from, so it can be tracked during playback.
|
||||
*/
|
||||
mStartOffset = mDecoderOffset - readable;
|
||||
alSourcePlay(mSource);
|
||||
if(alGetError() != AL_NO_ERROR)
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace
|
||||
|
||||
int main(int argc, char **argv)
|
||||
{
|
||||
/* A simple RAII container for OpenAL startup and shutdown. */
|
||||
struct AudioManager {
|
||||
AudioManager(char ***argv_, int *argc_)
|
||||
{
|
||||
if(InitAL(argv_, argc_) != 0)
|
||||
throw std::runtime_error{"Failed to initialize OpenAL"};
|
||||
}
|
||||
~AudioManager() { CloseAL(); }
|
||||
};
|
||||
|
||||
/* Print out usage if no arguments were specified */
|
||||
if(argc < 2)
|
||||
{
|
||||
fprintf(stderr, "Usage: %s [-device <name>] <filenames...>\n", argv[0]);
|
||||
return 1;
|
||||
}
|
||||
|
||||
argv++; argc--;
|
||||
AudioManager almgr{&argv, &argc};
|
||||
|
||||
if(!alIsExtensionPresent("AL_SOFT_callback_buffer"))
|
||||
{
|
||||
fprintf(stderr, "AL_SOFT_callback_buffer extension not available\n");
|
||||
return 1;
|
||||
}
|
||||
|
||||
alBufferCallbackSOFT = reinterpret_cast<LPALBUFFERCALLBACKSOFT>(
|
||||
alGetProcAddress("alBufferCallbackSOFT"));
|
||||
|
||||
ALCint refresh{25};
|
||||
alcGetIntegerv(alcGetContextsDevice(alcGetCurrentContext()), ALC_REFRESH, 1, &refresh);
|
||||
|
||||
std::unique_ptr<StreamPlayer> player{new StreamPlayer{}};
|
||||
|
||||
/* Play each file listed on the command line */
|
||||
for(int i{0};i < argc;++i)
|
||||
{
|
||||
if(!player->open(argv[i]))
|
||||
continue;
|
||||
|
||||
/* Get the name portion, without the path, for display. */
|
||||
const char *namepart{strrchr(argv[i], '/')};
|
||||
if(namepart || (namepart=strrchr(argv[i], '\\')))
|
||||
++namepart;
|
||||
else
|
||||
namepart = argv[i];
|
||||
|
||||
printf("Playing: %s (%s, %dhz)\n", namepart, FormatName(player->mFormat),
|
||||
player->mSfInfo.samplerate);
|
||||
fflush(stdout);
|
||||
|
||||
if(!player->prepare())
|
||||
{
|
||||
player->close();
|
||||
continue;
|
||||
}
|
||||
|
||||
while(player->update())
|
||||
std::this_thread::sleep_for(nanoseconds{seconds{1}} / refresh);
|
||||
putc('\n', stdout);
|
||||
|
||||
/* All done with this file. Close it and go to the next */
|
||||
player->close();
|
||||
}
|
||||
/* All done. */
|
||||
printf("Done.\n");
|
||||
|
||||
return 0;
|
||||
}
|
||||
330
externals/openal-soft/examples/altonegen.c
vendored
Normal file
330
externals/openal-soft/examples/altonegen.c
vendored
Normal file
@@ -0,0 +1,330 @@
|
||||
/*
|
||||
* OpenAL Tone Generator Test
|
||||
*
|
||||
* Copyright (c) 2015 by Chris Robinson <chris.kcat@gmail.com>
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
* of this software and associated documentation files (the "Software"), to deal
|
||||
* in the Software without restriction, including without limitation the rights
|
||||
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
* copies of the Software, and to permit persons to whom the Software is
|
||||
* furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
* THE SOFTWARE.
|
||||
*/
|
||||
|
||||
/* This file contains a test for generating waveforms and plays them for a
|
||||
* given length of time. Intended to inspect the behavior of the mixer by
|
||||
* checking the output with a spectrum analyzer and oscilloscope.
|
||||
*
|
||||
* TODO: This would actually be nicer as a GUI app with buttons to start and
|
||||
* stop individual waveforms, include additional whitenoise and pinknoise
|
||||
* generators, and have the ability to hook up EFX filters and effects.
|
||||
*/
|
||||
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <assert.h>
|
||||
#include <limits.h>
|
||||
#include <math.h>
|
||||
|
||||
#include "AL/al.h"
|
||||
#include "AL/alc.h"
|
||||
#include "AL/alext.h"
|
||||
|
||||
#include "common/alhelpers.h"
|
||||
|
||||
#include "win_main_utf8.h"
|
||||
|
||||
#ifndef M_PI
|
||||
#define M_PI (3.14159265358979323846)
|
||||
#endif
|
||||
|
||||
enum WaveType {
|
||||
WT_Sine,
|
||||
WT_Square,
|
||||
WT_Sawtooth,
|
||||
WT_Triangle,
|
||||
WT_Impulse,
|
||||
WT_WhiteNoise,
|
||||
};
|
||||
|
||||
static const char *GetWaveTypeName(enum WaveType type)
|
||||
{
|
||||
switch(type)
|
||||
{
|
||||
case WT_Sine: return "sine";
|
||||
case WT_Square: return "square";
|
||||
case WT_Sawtooth: return "sawtooth";
|
||||
case WT_Triangle: return "triangle";
|
||||
case WT_Impulse: return "impulse";
|
||||
case WT_WhiteNoise: return "noise";
|
||||
}
|
||||
return "(unknown)";
|
||||
}
|
||||
|
||||
static inline ALuint dither_rng(ALuint *seed)
|
||||
{
|
||||
*seed = (*seed * 96314165) + 907633515;
|
||||
return *seed;
|
||||
}
|
||||
|
||||
static void ApplySin(ALfloat *data, ALdouble g, ALuint srate, ALuint freq)
|
||||
{
|
||||
ALdouble smps_per_cycle = (ALdouble)srate / freq;
|
||||
ALuint i;
|
||||
for(i = 0;i < srate;i++)
|
||||
{
|
||||
ALdouble ival;
|
||||
data[i] += (ALfloat)(sin(modf(i/smps_per_cycle, &ival) * 2.0*M_PI) * g);
|
||||
}
|
||||
}
|
||||
|
||||
/* Generates waveforms using additive synthesis. Each waveform is constructed
|
||||
* by summing one or more sine waves, up to (and excluding) nyquist.
|
||||
*/
|
||||
static ALuint CreateWave(enum WaveType type, ALuint freq, ALuint srate, ALfloat gain)
|
||||
{
|
||||
ALuint seed = 22222;
|
||||
ALuint data_size;
|
||||
ALfloat *data;
|
||||
ALuint buffer;
|
||||
ALenum err;
|
||||
ALuint i;
|
||||
|
||||
data_size = (ALuint)(srate * sizeof(ALfloat));
|
||||
data = calloc(1, data_size);
|
||||
switch(type)
|
||||
{
|
||||
case WT_Sine:
|
||||
ApplySin(data, 1.0, srate, freq);
|
||||
break;
|
||||
case WT_Square:
|
||||
for(i = 1;freq*i < srate/2;i+=2)
|
||||
ApplySin(data, 4.0/M_PI * 1.0/i, srate, freq*i);
|
||||
break;
|
||||
case WT_Sawtooth:
|
||||
for(i = 1;freq*i < srate/2;i++)
|
||||
ApplySin(data, 2.0/M_PI * ((i&1)*2 - 1.0) / i, srate, freq*i);
|
||||
break;
|
||||
case WT_Triangle:
|
||||
for(i = 1;freq*i < srate/2;i+=2)
|
||||
ApplySin(data, 8.0/(M_PI*M_PI) * (1.0 - (i&2)) / (i*i), srate, freq*i);
|
||||
break;
|
||||
case WT_Impulse:
|
||||
/* NOTE: Impulse isn't handled using additive synthesis, and is
|
||||
* instead just a non-0 sample at a given rate. This can still be
|
||||
* useful to test (other than resampling, the ALSOFT_DEFAULT_REVERB
|
||||
* environment variable can prove useful here to test the reverb
|
||||
* response).
|
||||
*/
|
||||
for(i = 0;i < srate;i++)
|
||||
data[i] = (i%(srate/freq)) ? 0.0f : 1.0f;
|
||||
break;
|
||||
case WT_WhiteNoise:
|
||||
/* NOTE: WhiteNoise is just uniform set of uncorrelated values, and
|
||||
* is not influenced by the waveform frequency.
|
||||
*/
|
||||
for(i = 0;i < srate;i++)
|
||||
{
|
||||
ALuint rng0 = dither_rng(&seed);
|
||||
ALuint rng1 = dither_rng(&seed);
|
||||
data[i] = (ALfloat)(rng0*(1.0/UINT_MAX) - rng1*(1.0/UINT_MAX));
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
if(gain != 1.0f)
|
||||
{
|
||||
for(i = 0;i < srate;i++)
|
||||
data[i] *= gain;
|
||||
}
|
||||
|
||||
/* Buffer the audio data into a new buffer object. */
|
||||
buffer = 0;
|
||||
alGenBuffers(1, &buffer);
|
||||
alBufferData(buffer, AL_FORMAT_MONO_FLOAT32, data, (ALsizei)data_size, (ALsizei)srate);
|
||||
free(data);
|
||||
|
||||
/* Check if an error occured, and clean up if so. */
|
||||
err = alGetError();
|
||||
if(err != AL_NO_ERROR)
|
||||
{
|
||||
fprintf(stderr, "OpenAL Error: %s\n", alGetString(err));
|
||||
if(alIsBuffer(buffer))
|
||||
alDeleteBuffers(1, &buffer);
|
||||
return 0;
|
||||
}
|
||||
|
||||
return buffer;
|
||||
}
|
||||
|
||||
|
||||
int main(int argc, char *argv[])
|
||||
{
|
||||
enum WaveType wavetype = WT_Sine;
|
||||
const char *appname = argv[0];
|
||||
ALuint source, buffer;
|
||||
ALint last_pos, num_loops;
|
||||
ALint max_loops = 4;
|
||||
ALint srate = -1;
|
||||
ALint tone_freq = 1000;
|
||||
ALCint dev_rate;
|
||||
ALenum state;
|
||||
ALfloat gain = 1.0f;
|
||||
int i;
|
||||
|
||||
argv++; argc--;
|
||||
if(InitAL(&argv, &argc) != 0)
|
||||
return 1;
|
||||
|
||||
if(!alIsExtensionPresent("AL_EXT_FLOAT32"))
|
||||
{
|
||||
fprintf(stderr, "Required AL_EXT_FLOAT32 extension not supported on this device!\n");
|
||||
CloseAL();
|
||||
return 1;
|
||||
}
|
||||
|
||||
for(i = 0;i < argc;i++)
|
||||
{
|
||||
if(strcmp(argv[i], "-h") == 0 || strcmp(argv[i], "-?") == 0
|
||||
|| strcmp(argv[i], "--help") == 0)
|
||||
{
|
||||
fprintf(stderr, "OpenAL Tone Generator\n"
|
||||
"\n"
|
||||
"Usage: %s [-device <name>] <options>\n"
|
||||
"\n"
|
||||
"Available options:\n"
|
||||
" --help/-h This help text\n"
|
||||
" -t <seconds> Time to play a tone (default 5 seconds)\n"
|
||||
" --waveform/-w <type> Waveform type: sine (default), square, sawtooth,\n"
|
||||
" triangle, impulse, noise\n"
|
||||
" --freq/-f <hz> Tone frequency (default 1000 hz)\n"
|
||||
" --gain/-g <gain> gain 0.0 to 1 (default 1)\n"
|
||||
" --srate/-s <sample rate> Sampling rate (default output rate)\n",
|
||||
appname
|
||||
);
|
||||
CloseAL();
|
||||
return 1;
|
||||
}
|
||||
else if(i+1 < argc && strcmp(argv[i], "-t") == 0)
|
||||
{
|
||||
i++;
|
||||
max_loops = atoi(argv[i]) - 1;
|
||||
}
|
||||
else if(i+1 < argc && (strcmp(argv[i], "--waveform") == 0 || strcmp(argv[i], "-w") == 0))
|
||||
{
|
||||
i++;
|
||||
if(strcmp(argv[i], "sine") == 0)
|
||||
wavetype = WT_Sine;
|
||||
else if(strcmp(argv[i], "square") == 0)
|
||||
wavetype = WT_Square;
|
||||
else if(strcmp(argv[i], "sawtooth") == 0)
|
||||
wavetype = WT_Sawtooth;
|
||||
else if(strcmp(argv[i], "triangle") == 0)
|
||||
wavetype = WT_Triangle;
|
||||
else if(strcmp(argv[i], "impulse") == 0)
|
||||
wavetype = WT_Impulse;
|
||||
else if(strcmp(argv[i], "noise") == 0)
|
||||
wavetype = WT_WhiteNoise;
|
||||
else
|
||||
fprintf(stderr, "Unhandled waveform: %s\n", argv[i]);
|
||||
}
|
||||
else if(i+1 < argc && (strcmp(argv[i], "--freq") == 0 || strcmp(argv[i], "-f") == 0))
|
||||
{
|
||||
i++;
|
||||
tone_freq = atoi(argv[i]);
|
||||
if(tone_freq < 1)
|
||||
{
|
||||
fprintf(stderr, "Invalid tone frequency: %s (min: 1hz)\n", argv[i]);
|
||||
tone_freq = 1;
|
||||
}
|
||||
}
|
||||
else if(i+1 < argc && (strcmp(argv[i], "--gain") == 0 || strcmp(argv[i], "-g") == 0))
|
||||
{
|
||||
i++;
|
||||
gain = (ALfloat)atof(argv[i]);
|
||||
if(gain < 0.0f || gain > 1.0f)
|
||||
{
|
||||
fprintf(stderr, "Invalid gain: %s (min: 0.0, max 1.0)\n", argv[i]);
|
||||
gain = 1.0f;
|
||||
}
|
||||
}
|
||||
else if(i+1 < argc && (strcmp(argv[i], "--srate") == 0 || strcmp(argv[i], "-s") == 0))
|
||||
{
|
||||
i++;
|
||||
srate = atoi(argv[i]);
|
||||
if(srate < 40)
|
||||
{
|
||||
fprintf(stderr, "Invalid sample rate: %s (min: 40hz)\n", argv[i]);
|
||||
srate = 40;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
{
|
||||
ALCdevice *device = alcGetContextsDevice(alcGetCurrentContext());
|
||||
alcGetIntegerv(device, ALC_FREQUENCY, 1, &dev_rate);
|
||||
assert(alcGetError(device)==ALC_NO_ERROR && "Failed to get device sample rate");
|
||||
}
|
||||
if(srate < 0)
|
||||
srate = dev_rate;
|
||||
|
||||
/* Load the sound into a buffer. */
|
||||
buffer = CreateWave(wavetype, (ALuint)tone_freq, (ALuint)srate, gain);
|
||||
if(!buffer)
|
||||
{
|
||||
CloseAL();
|
||||
return 1;
|
||||
}
|
||||
|
||||
printf("Playing %dhz %s-wave tone with %dhz sample rate and %dhz output, for %d second%s...\n",
|
||||
tone_freq, GetWaveTypeName(wavetype), srate, dev_rate, max_loops+1, max_loops?"s":"");
|
||||
fflush(stdout);
|
||||
|
||||
/* Create the source to play the sound with. */
|
||||
source = 0;
|
||||
alGenSources(1, &source);
|
||||
alSourcei(source, AL_BUFFER, (ALint)buffer);
|
||||
assert(alGetError()==AL_NO_ERROR && "Failed to setup sound source");
|
||||
|
||||
/* Play the sound for a while. */
|
||||
num_loops = 0;
|
||||
last_pos = 0;
|
||||
alSourcei(source, AL_LOOPING, (max_loops > 0) ? AL_TRUE : AL_FALSE);
|
||||
alSourcePlay(source);
|
||||
do {
|
||||
ALint pos;
|
||||
al_nssleep(10000000);
|
||||
alGetSourcei(source, AL_SAMPLE_OFFSET, &pos);
|
||||
alGetSourcei(source, AL_SOURCE_STATE, &state);
|
||||
if(pos < last_pos && state == AL_PLAYING)
|
||||
{
|
||||
++num_loops;
|
||||
if(num_loops >= max_loops)
|
||||
alSourcei(source, AL_LOOPING, AL_FALSE);
|
||||
printf("%d...\n", max_loops - num_loops + 1);
|
||||
fflush(stdout);
|
||||
}
|
||||
last_pos = pos;
|
||||
} while(alGetError() == AL_NO_ERROR && state == AL_PLAYING);
|
||||
|
||||
/* All done. Delete resources, and close OpenAL. */
|
||||
alDeleteSources(1, &source);
|
||||
alDeleteBuffers(1, &buffer);
|
||||
|
||||
/* Close up OpenAL. */
|
||||
CloseAL();
|
||||
|
||||
return 0;
|
||||
}
|
||||
228
externals/openal-soft/examples/common/alhelpers.c
vendored
Normal file
228
externals/openal-soft/examples/common/alhelpers.c
vendored
Normal file
@@ -0,0 +1,228 @@
|
||||
/*
|
||||
* OpenAL Helpers
|
||||
*
|
||||
* Copyright (c) 2011 by Chris Robinson <chris.kcat@gmail.com>
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
* of this software and associated documentation files (the "Software"), to deal
|
||||
* in the Software without restriction, including without limitation the rights
|
||||
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
* copies of the Software, and to permit persons to whom the Software is
|
||||
* furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
* THE SOFTWARE.
|
||||
*/
|
||||
|
||||
/* This file contains routines to help with some menial OpenAL-related tasks,
|
||||
* such as opening a device and setting up a context, closing the device and
|
||||
* destroying its context, converting between frame counts and byte lengths,
|
||||
* finding an appropriate buffer format, and getting readable strings for
|
||||
* channel configs and sample types. */
|
||||
|
||||
#include "alhelpers.h"
|
||||
|
||||
#include <stdio.h>
|
||||
#include <errno.h>
|
||||
#include <string.h>
|
||||
|
||||
#include "AL/al.h"
|
||||
#include "AL/alc.h"
|
||||
#include "AL/alext.h"
|
||||
|
||||
|
||||
/* InitAL opens a device and sets up a context using default attributes, making
|
||||
* the program ready to call OpenAL functions. */
|
||||
int InitAL(char ***argv, int *argc)
|
||||
{
|
||||
const ALCchar *name;
|
||||
ALCdevice *device;
|
||||
ALCcontext *ctx;
|
||||
|
||||
/* Open and initialize a device */
|
||||
device = NULL;
|
||||
if(argc && argv && *argc > 1 && strcmp((*argv)[0], "-device") == 0)
|
||||
{
|
||||
device = alcOpenDevice((*argv)[1]);
|
||||
if(!device)
|
||||
fprintf(stderr, "Failed to open \"%s\", trying default\n", (*argv)[1]);
|
||||
(*argv) += 2;
|
||||
(*argc) -= 2;
|
||||
}
|
||||
if(!device)
|
||||
device = alcOpenDevice(NULL);
|
||||
if(!device)
|
||||
{
|
||||
fprintf(stderr, "Could not open a device!\n");
|
||||
return 1;
|
||||
}
|
||||
|
||||
ctx = alcCreateContext(device, NULL);
|
||||
if(ctx == NULL || alcMakeContextCurrent(ctx) == ALC_FALSE)
|
||||
{
|
||||
if(ctx != NULL)
|
||||
alcDestroyContext(ctx);
|
||||
alcCloseDevice(device);
|
||||
fprintf(stderr, "Could not set a context!\n");
|
||||
return 1;
|
||||
}
|
||||
|
||||
name = NULL;
|
||||
if(alcIsExtensionPresent(device, "ALC_ENUMERATE_ALL_EXT"))
|
||||
name = alcGetString(device, ALC_ALL_DEVICES_SPECIFIER);
|
||||
if(!name || alcGetError(device) != AL_NO_ERROR)
|
||||
name = alcGetString(device, ALC_DEVICE_SPECIFIER);
|
||||
printf("Opened \"%s\"\n", name);
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* CloseAL closes the device belonging to the current context, and destroys the
|
||||
* context. */
|
||||
void CloseAL(void)
|
||||
{
|
||||
ALCdevice *device;
|
||||
ALCcontext *ctx;
|
||||
|
||||
ctx = alcGetCurrentContext();
|
||||
if(ctx == NULL)
|
||||
return;
|
||||
|
||||
device = alcGetContextsDevice(ctx);
|
||||
|
||||
alcMakeContextCurrent(NULL);
|
||||
alcDestroyContext(ctx);
|
||||
alcCloseDevice(device);
|
||||
}
|
||||
|
||||
|
||||
const char *FormatName(ALenum format)
|
||||
{
|
||||
switch(format)
|
||||
{
|
||||
case AL_FORMAT_MONO8: return "Mono, U8";
|
||||
case AL_FORMAT_MONO16: return "Mono, S16";
|
||||
case AL_FORMAT_MONO_FLOAT32: return "Mono, Float32";
|
||||
case AL_FORMAT_MONO_MULAW: return "Mono, muLaw";
|
||||
case AL_FORMAT_MONO_ALAW_EXT: return "Mono, aLaw";
|
||||
case AL_FORMAT_MONO_IMA4: return "Mono, IMA4 ADPCM";
|
||||
case AL_FORMAT_MONO_MSADPCM_SOFT: return "Mono, MS ADPCM";
|
||||
case AL_FORMAT_STEREO8: return "Stereo, U8";
|
||||
case AL_FORMAT_STEREO16: return "Stereo, S16";
|
||||
case AL_FORMAT_STEREO_FLOAT32: return "Stereo, Float32";
|
||||
case AL_FORMAT_STEREO_MULAW: return "Stereo, muLaw";
|
||||
case AL_FORMAT_STEREO_ALAW_EXT: return "Stereo, aLaw";
|
||||
case AL_FORMAT_STEREO_IMA4: return "Stereo, IMA4 ADPCM";
|
||||
case AL_FORMAT_STEREO_MSADPCM_SOFT: return "Stereo, MS ADPCM";
|
||||
case AL_FORMAT_QUAD8: return "Quadraphonic, U8";
|
||||
case AL_FORMAT_QUAD16: return "Quadraphonic, S16";
|
||||
case AL_FORMAT_QUAD32: return "Quadraphonic, Float32";
|
||||
case AL_FORMAT_QUAD_MULAW: return "Quadraphonic, muLaw";
|
||||
case AL_FORMAT_51CHN8: return "5.1 Surround, U8";
|
||||
case AL_FORMAT_51CHN16: return "5.1 Surround, S16";
|
||||
case AL_FORMAT_51CHN32: return "5.1 Surround, Float32";
|
||||
case AL_FORMAT_51CHN_MULAW: return "5.1 Surround, muLaw";
|
||||
case AL_FORMAT_61CHN8: return "6.1 Surround, U8";
|
||||
case AL_FORMAT_61CHN16: return "6.1 Surround, S16";
|
||||
case AL_FORMAT_61CHN32: return "6.1 Surround, Float32";
|
||||
case AL_FORMAT_61CHN_MULAW: return "6.1 Surround, muLaw";
|
||||
case AL_FORMAT_71CHN8: return "7.1 Surround, U8";
|
||||
case AL_FORMAT_71CHN16: return "7.1 Surround, S16";
|
||||
case AL_FORMAT_71CHN32: return "7.1 Surround, Float32";
|
||||
case AL_FORMAT_71CHN_MULAW: return "7.1 Surround, muLaw";
|
||||
case AL_FORMAT_BFORMAT2D_8: return "B-Format 2D, U8";
|
||||
case AL_FORMAT_BFORMAT2D_16: return "B-Format 2D, S16";
|
||||
case AL_FORMAT_BFORMAT2D_FLOAT32: return "B-Format 2D, Float32";
|
||||
case AL_FORMAT_BFORMAT2D_MULAW: return "B-Format 2D, muLaw";
|
||||
case AL_FORMAT_BFORMAT3D_8: return "B-Format 3D, U8";
|
||||
case AL_FORMAT_BFORMAT3D_16: return "B-Format 3D, S16";
|
||||
case AL_FORMAT_BFORMAT3D_FLOAT32: return "B-Format 3D, Float32";
|
||||
case AL_FORMAT_BFORMAT3D_MULAW: return "B-Format 3D, muLaw";
|
||||
case AL_FORMAT_UHJ2CHN8_SOFT: return "UHJ 2-channel, U8";
|
||||
case AL_FORMAT_UHJ2CHN16_SOFT: return "UHJ 2-channel, S16";
|
||||
case AL_FORMAT_UHJ2CHN_FLOAT32_SOFT: return "UHJ 2-channel, Float32";
|
||||
case AL_FORMAT_UHJ3CHN8_SOFT: return "UHJ 3-channel, U8";
|
||||
case AL_FORMAT_UHJ3CHN16_SOFT: return "UHJ 3-channel, S16";
|
||||
case AL_FORMAT_UHJ3CHN_FLOAT32_SOFT: return "UHJ 3-channel, Float32";
|
||||
case AL_FORMAT_UHJ4CHN8_SOFT: return "UHJ 4-channel, U8";
|
||||
case AL_FORMAT_UHJ4CHN16_SOFT: return "UHJ 4-channel, S16";
|
||||
case AL_FORMAT_UHJ4CHN_FLOAT32_SOFT: return "UHJ 4-channel, Float32";
|
||||
}
|
||||
return "Unknown Format";
|
||||
}
|
||||
|
||||
|
||||
#ifdef _WIN32
|
||||
|
||||
#define WIN32_LEAN_AND_MEAN
|
||||
#include <windows.h>
|
||||
#include <mmsystem.h>
|
||||
|
||||
int altime_get(void)
|
||||
{
|
||||
static int start_time = 0;
|
||||
int cur_time;
|
||||
union {
|
||||
FILETIME ftime;
|
||||
ULARGE_INTEGER ulint;
|
||||
} systime;
|
||||
GetSystemTimeAsFileTime(&systime.ftime);
|
||||
/* FILETIME is in 100-nanosecond units, or 1/10th of a microsecond. */
|
||||
cur_time = (int)(systime.ulint.QuadPart/10000);
|
||||
|
||||
if(!start_time)
|
||||
start_time = cur_time;
|
||||
return cur_time - start_time;
|
||||
}
|
||||
|
||||
void al_nssleep(unsigned long nsec)
|
||||
{
|
||||
Sleep(nsec / 1000000);
|
||||
}
|
||||
|
||||
#else
|
||||
|
||||
#include <sys/time.h>
|
||||
#include <unistd.h>
|
||||
#include <time.h>
|
||||
|
||||
int altime_get(void)
|
||||
{
|
||||
static int start_time = 0u;
|
||||
int cur_time;
|
||||
|
||||
#if _POSIX_TIMERS > 0
|
||||
struct timespec ts;
|
||||
int ret = clock_gettime(CLOCK_REALTIME, &ts);
|
||||
if(ret != 0) return 0;
|
||||
cur_time = (int)(ts.tv_sec*1000 + ts.tv_nsec/1000000);
|
||||
#else /* _POSIX_TIMERS > 0 */
|
||||
struct timeval tv;
|
||||
int ret = gettimeofday(&tv, NULL);
|
||||
if(ret != 0) return 0;
|
||||
cur_time = (int)(tv.tv_sec*1000 + tv.tv_usec/1000);
|
||||
#endif
|
||||
|
||||
if(!start_time)
|
||||
start_time = cur_time;
|
||||
return cur_time - start_time;
|
||||
}
|
||||
|
||||
void al_nssleep(unsigned long nsec)
|
||||
{
|
||||
struct timespec ts, rem;
|
||||
ts.tv_sec = (time_t)(nsec / 1000000000ul);
|
||||
ts.tv_nsec = (long)(nsec % 1000000000ul);
|
||||
while(nanosleep(&ts, &rem) == -1 && errno == EINTR)
|
||||
ts = rem;
|
||||
}
|
||||
|
||||
#endif
|
||||
38
externals/openal-soft/examples/common/alhelpers.h
vendored
Normal file
38
externals/openal-soft/examples/common/alhelpers.h
vendored
Normal file
@@ -0,0 +1,38 @@
|
||||
#ifndef ALHELPERS_H
|
||||
#define ALHELPERS_H
|
||||
|
||||
#include "AL/al.h"
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
/* Some helper functions to get the name from the format enums. */
|
||||
const char *FormatName(ALenum type);
|
||||
|
||||
/* Easy device init/deinit functions. InitAL returns 0 on success. */
|
||||
int InitAL(char ***argv, int *argc);
|
||||
void CloseAL(void);
|
||||
|
||||
/* Cross-platform timeget and sleep functions. */
|
||||
int altime_get(void);
|
||||
void al_nssleep(unsigned long nsec);
|
||||
|
||||
/* C doesn't allow casting between function and non-function pointer types, so
|
||||
* with C99 we need to use a union to reinterpret the pointer type. Pre-C99
|
||||
* still needs to use a normal cast and live with the warning (C++ is fine with
|
||||
* a regular reinterpret_cast).
|
||||
*/
|
||||
#if __STDC_VERSION__ >= 199901L
|
||||
#define FUNCTION_CAST(T, ptr) (union{void *p; T f;}){ptr}.f
|
||||
#elif defined(__cplusplus)
|
||||
#define FUNCTION_CAST(T, ptr) reinterpret_cast<T>(ptr)
|
||||
#else
|
||||
#define FUNCTION_CAST(T, ptr) (T)(ptr)
|
||||
#endif
|
||||
|
||||
#ifdef __cplusplus
|
||||
} // extern "C"
|
||||
#endif
|
||||
|
||||
#endif /* ALHELPERS_H */
|
||||
Reference in New Issue
Block a user