Update OpenAL-soft to 1.21.1

This commit is contained in:
Miku AuahDark
2021-02-11 18:04:50 +08:00
parent 08f227997e
commit 904cc75ba8
358 changed files with 61122 additions and 60973 deletions
+594
View 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) = (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;
}
File diff suppressed because it is too large Load Diff
+62 -54
View File
@@ -24,11 +24,15 @@
/* This file contains an example for selecting an HRTF. */
#include <stdio.h>
#include <assert.h>
#include <inttypes.h>
#include <limits.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <SDL_sound.h>
#include "sndfile.h"
#include "AL/al.h"
#include "AL/alc.h"
@@ -49,68 +53,73 @@ static LPALCRESETDEVICESOFT alcResetDeviceSOFT;
*/
static ALuint LoadSound(const char *filename)
{
Sound_Sample *sample;
ALenum err, format;
ALuint buffer;
Uint32 slen;
SNDFILE *sndfile;
SF_INFO sfinfo;
short *membuf;
sf_count_t num_frames;
ALsizei num_bytes;
/* Open the audio file */
sample = Sound_NewSampleFromFile(filename, NULL, 65536);
if(!sample)
/* 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\n", filename);
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(sample->actual.channels == 1)
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(sample->actual.format == AUDIO_U8)
format = AL_FORMAT_MONO8;
else if(sample->actual.format == AUDIO_S16SYS)
format = AL_FORMAT_MONO16;
else
{
fprintf(stderr, "Unsupported sample format: 0x%04x\n", sample->actual.format);
Sound_FreeSample(sample);
return 0;
}
if(sf_command(sndfile, SFC_WAVEX_GET_AMBISONIC, NULL, 0) == SF_AMBISONIC_B_FORMAT)
format = AL_FORMAT_BFORMAT2D_16;
}
else if(sample->actual.channels == 2)
else if(sfinfo.channels == 4)
{
if(sample->actual.format == AUDIO_U8)
format = AL_FORMAT_STEREO8;
else if(sample->actual.format == AUDIO_S16SYS)
format = AL_FORMAT_STEREO16;
else
{
fprintf(stderr, "Unsupported sample format: 0x%04x\n", sample->actual.format);
Sound_FreeSample(sample);
return 0;
}
if(sf_command(sndfile, SFC_WAVEX_GET_AMBISONIC, NULL, 0) == SF_AMBISONIC_B_FORMAT)
format = AL_FORMAT_BFORMAT3D_16;
}
else
if(!format)
{
fprintf(stderr, "Unsupported channel count: %d\n", sample->actual.channels);
Sound_FreeSample(sample);
fprintf(stderr, "Unsupported channel count: %d\n", sfinfo.channels);
sf_close(sndfile);
return 0;
}
/* Decode the whole audio stream to a buffer. */
slen = Sound_DecodeAll(sample);
if(!sample->buffer || slen == 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)
{
fprintf(stderr, "Failed to read audio from %s\n", filename);
Sound_FreeSample(sample);
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. */
* close the file.
*/
buffer = 0;
alGenBuffers(1, &buffer);
alBufferData(buffer, format, sample->buffer, slen, sample->actual.rate);
Sound_FreeSample(sample);
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();
@@ -129,6 +138,7 @@ static ALuint LoadSound(const char *filename)
int main(int argc, char **argv)
{
ALCdevice *device;
ALCcontext *context;
ALboolean has_angle_ext;
ALuint source, buffer;
const char *soundname;
@@ -150,7 +160,8 @@ int main(int argc, char **argv)
if(InitAL(&argv, &argc) != 0)
return 1;
device = alcGetContextsDevice(alcGetCurrentContext());
context = alcGetCurrentContext();
device = alcGetContextsDevice(context);
if(!alcIsExtensionPresent(device, "ALC_SOFT_HRTF"))
{
fprintf(stderr, "Error: ALC_SOFT_HRTF not supported\n");
@@ -159,16 +170,16 @@ int main(int argc, char **argv)
}
/* Define a macro to help load the function pointers. */
#define LOAD_PROC(d, x) ((x) = alcGetProcAddress((d), #x))
LOAD_PROC(device, alcGetStringiSOFT);
LOAD_PROC(device, alcResetDeviceSOFT);
#define LOAD_PROC(d, T, x) ((x) = (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%s found\n", has_angle_ext?"":" not");
printf("AL_EXT_STEREO_ANGLES %sfound\n", has_angle_ext?"":"not ");
/* Check for user-preferred HRTF */
if(strcmp(argv[0], "-hrtf") == 0)
@@ -235,14 +246,10 @@ int main(int argc, char **argv)
}
fflush(stdout);
/* Initialize SDL_sound. */
Sound_Init();
/* Load the sound into a buffer. */
buffer = LoadSound(soundname);
if(!buffer)
{
Sound_Quit();
CloseAL();
return 1;
}
@@ -252,7 +259,7 @@ int main(int argc, char **argv)
alGenSources(1, &source);
alSourcei(source, AL_SOURCE_RELATIVE, AL_TRUE);
alSource3f(source, AL_POSITION, 0.0f, 0.0f, -1.0f);
alSourcei(source, AL_BUFFER, buffer);
alSourcei(source, AL_BUFFER, (ALint)buffer);
assert(alGetError()==AL_NO_ERROR && "Failed to setup sound source");
/* Play the sound until it finishes. */
@@ -261,6 +268,8 @@ int main(int argc, char **argv)
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.
*/
@@ -279,15 +288,14 @@ int main(int argc, char **argv)
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 SDL_sound and OpenAL. */
/* All done. Delete resources, and close down OpenAL. */
alDeleteSources(1, &source);
alDeleteBuffers(1, &buffer);
Sound_Quit();
CloseAL();
return 0;
+64 -63
View File
@@ -24,13 +24,15 @@
/* This file contains an example for checking the latency of a sound. */
#include <stdio.h>
#include <assert.h>
#include <inttypes.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <SDL_sound.h>
#include "sndfile.h"
#include "AL/al.h"
#include "AL/alc.h"
#include "AL/alext.h"
#include "common/alhelpers.h"
@@ -54,68 +56,73 @@ static LPALGETSOURCEI64VSOFT alGetSourcei64vSOFT;
*/
static ALuint LoadSound(const char *filename)
{
Sound_Sample *sample;
ALenum err, format;
ALuint buffer;
Uint32 slen;
SNDFILE *sndfile;
SF_INFO sfinfo;
short *membuf;
sf_count_t num_frames;
ALsizei num_bytes;
/* Open the audio file */
sample = Sound_NewSampleFromFile(filename, NULL, 65536);
if(!sample)
/* 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\n", filename);
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(sample->actual.channels == 1)
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(sample->actual.format == AUDIO_U8)
format = AL_FORMAT_MONO8;
else if(sample->actual.format == AUDIO_S16SYS)
format = AL_FORMAT_MONO16;
else
{
fprintf(stderr, "Unsupported sample format: 0x%04x\n", sample->actual.format);
Sound_FreeSample(sample);
return 0;
}
if(sf_command(sndfile, SFC_WAVEX_GET_AMBISONIC, NULL, 0) == SF_AMBISONIC_B_FORMAT)
format = AL_FORMAT_BFORMAT2D_16;
}
else if(sample->actual.channels == 2)
else if(sfinfo.channels == 4)
{
if(sample->actual.format == AUDIO_U8)
format = AL_FORMAT_STEREO8;
else if(sample->actual.format == AUDIO_S16SYS)
format = AL_FORMAT_STEREO16;
else
{
fprintf(stderr, "Unsupported sample format: 0x%04x\n", sample->actual.format);
Sound_FreeSample(sample);
return 0;
}
if(sf_command(sndfile, SFC_WAVEX_GET_AMBISONIC, NULL, 0) == SF_AMBISONIC_B_FORMAT)
format = AL_FORMAT_BFORMAT3D_16;
}
else
if(!format)
{
fprintf(stderr, "Unsupported channel count: %d\n", sample->actual.channels);
Sound_FreeSample(sample);
fprintf(stderr, "Unsupported channel count: %d\n", sfinfo.channels);
sf_close(sndfile);
return 0;
}
/* Decode the whole audio stream to a buffer. */
slen = Sound_DecodeAll(sample);
if(!sample->buffer || slen == 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)
{
fprintf(stderr, "Failed to read audio from %s\n", filename);
Sound_FreeSample(sample);
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. */
* close the file.
*/
buffer = 0;
alGenBuffers(1, &buffer);
alBufferData(buffer, format, sample->buffer, slen, sample->actual.rate);
Sound_FreeSample(sample);
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();
@@ -157,29 +164,25 @@ int main(int argc, char **argv)
}
/* Define a macro to help load the function pointers. */
#define LOAD_PROC(x) ((x) = alGetProcAddress(#x))
LOAD_PROC(alSourcedSOFT);
LOAD_PROC(alSource3dSOFT);
LOAD_PROC(alSourcedvSOFT);
LOAD_PROC(alGetSourcedSOFT);
LOAD_PROC(alGetSource3dSOFT);
LOAD_PROC(alGetSourcedvSOFT);
LOAD_PROC(alSourcei64SOFT);
LOAD_PROC(alSource3i64SOFT);
LOAD_PROC(alSourcei64vSOFT);
LOAD_PROC(alGetSourcei64SOFT);
LOAD_PROC(alGetSource3i64SOFT);
LOAD_PROC(alGetSourcei64vSOFT);
#define LOAD_PROC(T, x) ((x) = (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
/* Initialize SDL_sound. */
Sound_Init();
/* Load the sound into a buffer. */
buffer = LoadSound(argv[0]);
if(!buffer)
{
Sound_Quit();
CloseAL();
return 1;
}
@@ -187,7 +190,7 @@ int main(int argc, char **argv)
/* Create the source to play the sound with. */
source = 0;
alGenSources(1, &source);
alSourcei(source, AL_BUFFER, buffer);
alSourcei(source, AL_BUFFER, (ALint)buffer);
assert(alGetError()==AL_NO_ERROR && "Failed to setup sound source");
/* Play the sound until it finishes. */
@@ -205,11 +208,9 @@ int main(int argc, char **argv)
} while(alGetError() == AL_NO_ERROR && state == AL_PLAYING);
printf("\n");
/* All done. Delete resources, and close down SDL_sound and OpenAL. */
/* All done. Delete resources, and close down OpenAL. */
alDeleteSources(1, &source);
alDeleteBuffers(1, &buffer);
Sound_Quit();
CloseAL();
return 0;
+10 -7
View File
@@ -26,11 +26,14 @@
* output handling.
*/
#include <stdio.h>
#include <assert.h>
#include <math.h>
#include <stdio.h>
#include <SDL.h>
#include "SDL.h"
#include "SDL_audio.h"
#include "SDL_error.h"
#include "SDL_stdinc.h"
#include "AL/al.h"
#include "AL/alc.h"
@@ -146,10 +149,10 @@ int main(int argc, char *argv[])
}
/* Define a macro to help load the function pointers. */
#define LOAD_PROC(x) ((x) = alcGetProcAddress(NULL, #x))
LOAD_PROC(alcLoopbackOpenDeviceSOFT);
LOAD_PROC(alcIsRenderFormatSupportedSOFT);
LOAD_PROC(alcRenderSamplesSOFT);
#define LOAD_PROC(T, x) ((x) = (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)
@@ -246,7 +249,7 @@ int main(int argc, char *argv[])
/* Create the source to play the sound with. */
source = 0;
alGenSources(1, &source);
alSourcei(source, AL_BUFFER, buffer);
alSourcei(source, AL_BUFFER, (ALint)buffer);
assert(alGetError()==AL_NO_ERROR && "Failed to setup sound source");
/* Play the sound until it finishes. */
+96 -104
View File
@@ -29,15 +29,20 @@
* listener.
*/
#include <stdio.h>
#include <assert.h>
#include <math.h>
#include <SDL_sound.h>
#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 "AL/efx.h"
#include "AL/efx-presets.h"
#include "common/alhelpers.h"
@@ -148,68 +153,62 @@ static int LoadEffect(ALuint effect, const EFXEAXREVERBPROPERTIES *reverb)
*/
static ALuint LoadSound(const char *filename)
{
Sound_Sample *sample;
ALenum err, format;
ALuint buffer;
Uint32 slen;
SNDFILE *sndfile;
SF_INFO sfinfo;
short *membuf;
sf_count_t num_frames;
ALsizei num_bytes;
/* Open the audio file */
sample = Sound_NewSampleFromFile(filename, NULL, 65536);
if(!sample)
/* 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\n", filename);
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(sample->actual.channels == 1)
{
if(sample->actual.format == AUDIO_U8)
format = AL_FORMAT_MONO8;
else if(sample->actual.format == AUDIO_S16SYS)
format = AL_FORMAT_MONO16;
else
{
fprintf(stderr, "Unsupported sample format: 0x%04x\n", sample->actual.format);
Sound_FreeSample(sample);
return 0;
}
}
else if(sample->actual.channels == 2)
{
if(sample->actual.format == AUDIO_U8)
format = AL_FORMAT_STEREO8;
else if(sample->actual.format == AUDIO_S16SYS)
format = AL_FORMAT_STEREO16;
else
{
fprintf(stderr, "Unsupported sample format: 0x%04x\n", sample->actual.format);
Sound_FreeSample(sample);
return 0;
}
}
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", sample->actual.channels);
Sound_FreeSample(sample);
fprintf(stderr, "Unsupported channel count: %d\n", sfinfo.channels);
sf_close(sndfile);
return 0;
}
/* Decode the whole audio stream to a buffer. */
slen = Sound_DecodeAll(sample);
if(!sample->buffer || slen == 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)
{
fprintf(stderr, "Failed to read audio from %s\n", filename);
Sound_FreeSample(sample);
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. */
* close the file.
*/
buffer = 0;
alGenBuffers(1, &buffer);
alBufferData(buffer, format, sample->buffer, slen, sample->actual.rate);
Sound_FreeSample(sample);
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();
@@ -440,8 +439,8 @@ static void UpdateListenerAndEffects(float timediff, const ALuint slots[2], cons
}
/* Finally, update the effect slots with the updated effect parameters. */
alAuxiliaryEffectSloti(slots[0], AL_EFFECTSLOT_EFFECT, effects[0]);
alAuxiliaryEffectSloti(slots[1], AL_EFFECTSLOT_EFFECT, effects[1]);
alAuxiliaryEffectSloti(slots[0], AL_EFFECTSLOT_EFFECT, (ALint)effects[0]);
alAuxiliaryEffectSloti(slots[1], AL_EFFECTSLOT_EFFECT, (ALint)effects[1]);
}
@@ -452,7 +451,6 @@ int main(int argc, char **argv)
EFX_REVERB_PRESET_CARPETEDHALLWAY,
EFX_REVERB_PRESET_BATHROOM
};
struct timespec basetime;
ALCdevice *device = NULL;
ALCcontext *context = NULL;
ALuint effects[2] = { 0, 0 };
@@ -463,6 +461,7 @@ int main(int argc, char **argv)
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 */
@@ -520,53 +519,49 @@ int main(int argc, char **argv)
}
/* Define a macro to help load the function pointers. */
#define LOAD_PROC(x) ((x) = alGetProcAddress(#x))
LOAD_PROC(alGenFilters);
LOAD_PROC(alDeleteFilters);
LOAD_PROC(alIsFilter);
LOAD_PROC(alFilteri);
LOAD_PROC(alFilteriv);
LOAD_PROC(alFilterf);
LOAD_PROC(alFilterfv);
LOAD_PROC(alGetFilteri);
LOAD_PROC(alGetFilteriv);
LOAD_PROC(alGetFilterf);
LOAD_PROC(alGetFilterfv);
#define LOAD_PROC(T, x) ((x) = (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(alGenEffects);
LOAD_PROC(alDeleteEffects);
LOAD_PROC(alIsEffect);
LOAD_PROC(alEffecti);
LOAD_PROC(alEffectiv);
LOAD_PROC(alEffectf);
LOAD_PROC(alEffectfv);
LOAD_PROC(alGetEffecti);
LOAD_PROC(alGetEffectiv);
LOAD_PROC(alGetEffectf);
LOAD_PROC(alGetEffectfv);
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(alGenAuxiliaryEffectSlots);
LOAD_PROC(alDeleteAuxiliaryEffectSlots);
LOAD_PROC(alIsAuxiliaryEffectSlot);
LOAD_PROC(alAuxiliaryEffectSloti);
LOAD_PROC(alAuxiliaryEffectSlotiv);
LOAD_PROC(alAuxiliaryEffectSlotf);
LOAD_PROC(alAuxiliaryEffectSlotfv);
LOAD_PROC(alGetAuxiliaryEffectSloti);
LOAD_PROC(alGetAuxiliaryEffectSlotiv);
LOAD_PROC(alGetAuxiliaryEffectSlotf);
LOAD_PROC(alGetAuxiliaryEffectSlotfv);
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
/* Initialize SDL_sound. */
Sound_Init();
/* Load the sound into a buffer. */
buffer = LoadSound(argv[0]);
if(!buffer)
{
CloseAL();
Sound_Quit();
return 1;
}
@@ -582,7 +577,6 @@ int main(int argc, char **argv)
{
alDeleteEffects(2, effects);
alDeleteBuffers(1, &buffer);
Sound_Quit();
CloseAL();
return 1;
}
@@ -595,8 +589,8 @@ int main(int argc, char **argv)
* 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, effects[0]);
alAuxiliaryEffectSloti(slots[1], AL_EFFECTSLOT_EFFECT, effects[1]);
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
@@ -618,8 +612,8 @@ int main(int argc, char **argv)
alGenSources(1, &source);
alSourcei(source, AL_LOOPING, AL_TRUE);
alSource3f(source, AL_POSITION, -5.0f, 0.0f, -2.0f);
alSourcei(source, AL_DIRECT_FILTER, direct_filter);
alSourcei(source, AL_BUFFER, buffer);
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
@@ -628,19 +622,19 @@ int main(int argc, char **argv)
* can only see a zone through a window or thin wall may be attenuated for
* that zone.
*/
alSource3i(source, AL_AUXILIARY_SEND_FILTER, slots[0], 0, AL_FILTER_NULL);
alSource3i(source, AL_AUXILIARY_SEND_FILTER, slots[1], 1, AL_FILTER_NULL);
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. */
altimespec_get(&basetime, AL_TIME_UTC);
basetime = altime_get();
loops = 0;
printf("Transition %d of %d...\n", loops+1, MaxTransitions);
/* Play the sound for a while. */
alSourcePlay(source);
do {
struct timespec curtime;
int curtime;
ALfloat timediff;
/* Start a batch update, to ensure all changes apply simultaneously. */
@@ -649,14 +643,13 @@ int main(int argc, char **argv)
/* Get the current time to track the amount of time that passed.
* Convert the difference to seconds.
*/
altimespec_get(&curtime, AL_TIME_UTC);
timediff = (ALfloat)(curtime.tv_sec - basetime.tv_sec);
timediff += (ALfloat)(curtime.tv_nsec - basetime.tv_nsec) / 1000000000.0f;
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*((loops&1)+1))
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.
@@ -669,7 +662,7 @@ int main(int argc, char **argv)
* time to start a new cycle.
*/
timediff -= 8.0f;
basetime.tv_sec += 8;
basetime += 8000;
}
}
@@ -682,14 +675,13 @@ int main(int argc, char **argv)
alGetSourcei(source, AL_SOURCE_STATE, &state);
} while(alGetError() == AL_NO_ERROR && state == AL_PLAYING && loops < MaxTransitions);
/* All done. Delete resources, and close down SDL_sound and OpenAL. */
/* All done. Delete resources, and close down OpenAL. */
alDeleteSources(1, &source);
alDeleteAuxiliaryEffectSlots(2, slots);
alDeleteEffects(2, effects);
alDeleteFilters(1, &direct_filter);
alDeleteBuffers(1, &buffer);
Sound_Quit();
CloseAL();
return 0;
+52 -49
View File
@@ -24,13 +24,16 @@
/* This file contains an example for playing a sound buffer. */
#include <stdio.h>
#include <assert.h>
#include <inttypes.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <SDL_sound.h>
#include "sndfile.h"
#include "AL/al.h"
#include "AL/alc.h"
#include "AL/alext.h"
#include "common/alhelpers.h"
@@ -40,68 +43,73 @@
*/
static ALuint LoadSound(const char *filename)
{
Sound_Sample *sample;
ALenum err, format;
ALuint buffer;
Uint32 slen;
SNDFILE *sndfile;
SF_INFO sfinfo;
short *membuf;
sf_count_t num_frames;
ALsizei num_bytes;
/* Open the audio file */
sample = Sound_NewSampleFromFile(filename, NULL, 65536);
if(!sample)
/* 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\n", filename);
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(sample->actual.channels == 1)
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(sample->actual.format == AUDIO_U8)
format = AL_FORMAT_MONO8;
else if(sample->actual.format == AUDIO_S16SYS)
format = AL_FORMAT_MONO16;
else
{
fprintf(stderr, "Unsupported sample format: 0x%04x\n", sample->actual.format);
Sound_FreeSample(sample);
return 0;
}
if(sf_command(sndfile, SFC_WAVEX_GET_AMBISONIC, NULL, 0) == SF_AMBISONIC_B_FORMAT)
format = AL_FORMAT_BFORMAT2D_16;
}
else if(sample->actual.channels == 2)
else if(sfinfo.channels == 4)
{
if(sample->actual.format == AUDIO_U8)
format = AL_FORMAT_STEREO8;
else if(sample->actual.format == AUDIO_S16SYS)
format = AL_FORMAT_STEREO16;
else
{
fprintf(stderr, "Unsupported sample format: 0x%04x\n", sample->actual.format);
Sound_FreeSample(sample);
return 0;
}
if(sf_command(sndfile, SFC_WAVEX_GET_AMBISONIC, NULL, 0) == SF_AMBISONIC_B_FORMAT)
format = AL_FORMAT_BFORMAT3D_16;
}
else
if(!format)
{
fprintf(stderr, "Unsupported channel count: %d\n", sample->actual.channels);
Sound_FreeSample(sample);
fprintf(stderr, "Unsupported channel count: %d\n", sfinfo.channels);
sf_close(sndfile);
return 0;
}
/* Decode the whole audio stream to a buffer. */
slen = Sound_DecodeAll(sample);
if(!sample->buffer || slen == 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)
{
fprintf(stderr, "Failed to read audio from %s\n", filename);
Sound_FreeSample(sample);
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. */
* close the file.
*/
buffer = 0;
alGenBuffers(1, &buffer);
alBufferData(buffer, format, sample->buffer, slen, sample->actual.rate);
Sound_FreeSample(sample);
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();
@@ -135,14 +143,10 @@ int main(int argc, char **argv)
if(InitAL(&argv, &argc) != 0)
return 1;
/* Initialize SDL_sound. */
Sound_Init();
/* Load the sound into a buffer. */
buffer = LoadSound(argv[0]);
if(!buffer)
{
Sound_Quit();
CloseAL();
return 1;
}
@@ -150,7 +154,7 @@ int main(int argc, char **argv)
/* Create the source to play the sound with. */
source = 0;
alGenSources(1, &source);
alSourcei(source, AL_BUFFER, buffer);
alSourcei(source, AL_BUFFER, (ALint)buffer);
assert(alGetError()==AL_NO_ERROR && "Failed to setup sound source");
/* Play the sound until it finishes. */
@@ -166,11 +170,10 @@ int main(int argc, char **argv)
} while(alGetError() == AL_NO_ERROR && state == AL_PLAYING);
printf("\n");
/* All done. Delete resources, and close down SDL_sound and OpenAL. */
/* All done. Delete resources, and close down OpenAL. */
alDeleteSources(1, &source);
alDeleteBuffers(1, &buffer);
Sound_Quit();
CloseAL();
return 0;
+29 -20
View File
@@ -27,7 +27,7 @@
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <errno.h>
#include "AL/al.h"
#include "AL/alc.h"
@@ -35,6 +35,8 @@
#include "common/alhelpers.h"
#include "win_main_utf8.h"
#if defined(_WIN64)
#define SZFMT "%I64u"
@@ -54,13 +56,19 @@ static float msvc_strtof(const char *str, char **end)
static void fwrite16le(ALushort val, FILE *f)
{
ALubyte data[2] = { val&0xff, (val>>8)&0xff };
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] = { val&0xff, (val>>8)&0xff, (val>>16)&0xff, (val>>24)&0xff };
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);
}
@@ -73,9 +81,9 @@ typedef struct Recorder {
ALuint mDataSize;
float mRecTime;
int mChannels;
int mBits;
int mSampleRate;
ALuint mChannels;
ALuint mBits;
ALuint mSampleRate;
ALuint mFrameSize;
ALbyte *mBuffer;
ALsizei mBufferSize;
@@ -133,13 +141,13 @@ int main(int argc, char **argv)
break;
else if(strcmp(argv[0], "--channels") == 0 || strcmp(argv[0], "-c") == 0)
{
if(!(argc > 1))
if(argc < 2)
{
fprintf(stderr, "Missing argument for option: %s\n", argv[0]);
return 1;
}
recorder.mChannels = strtol(argv[1], &end, 0);
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]);
@@ -150,13 +158,13 @@ int main(int argc, char **argv)
}
else if(strcmp(argv[0], "--bits") == 0 || strcmp(argv[0], "-b") == 0)
{
if(!(argc > 1))
if(argc < 2)
{
fprintf(stderr, "Missing argument for option: %s\n", argv[0]);
return 1;
}
recorder.mBits = strtol(argv[1], &end, 0);
recorder.mBits = (ALuint)strtoul(argv[1], &end, 0);
if((recorder.mBits != 8 && recorder.mBits != 16 && recorder.mBits != 32) ||
(end && *end != '\0'))
{
@@ -168,13 +176,13 @@ int main(int argc, char **argv)
}
else if(strcmp(argv[0], "--rate") == 0 || strcmp(argv[0], "-r") == 0)
{
if(!(argc > 1))
if(argc < 2)
{
fprintf(stderr, "Missing argument for option: %s\n", argv[0]);
return 1;
}
recorder.mSampleRate = strtol(argv[1], &end, 0);
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]);
@@ -185,7 +193,7 @@ int main(int argc, char **argv)
}
else if(strcmp(argv[0], "--time") == 0 || strcmp(argv[0], "-t") == 0)
{
if(!(argc > 1))
if(argc < 2)
{
fprintf(stderr, "Missing argument for option: %s\n", argv[0]);
return 1;
@@ -202,7 +210,7 @@ int main(int argc, char **argv)
}
else if(strcmp(argv[0], "--outfile") == 0 || strcmp(argv[0], "-o") == 0)
{
if(!(argc > 1))
if(argc < 2)
{
fprintf(stderr, "Missing argument for option: %s\n", argv[0]);
return 1;
@@ -285,15 +293,15 @@ int main(int argc, char **argv)
// 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(recorder.mChannels, recorder.mFile);
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(recorder.mFrameSize, recorder.mFile);
fwrite16le((ALushort)recorder.mFrameSize, recorder.mFile);
// 16-bit val, bits per sample
fwrite16le(recorder.mBits, recorder.mFile);
fwrite16le((ALushort)recorder.mBits, recorder.mFile);
// 16-bit val, extra byte count
fwrite16le(0, recorder.mFile);
@@ -316,6 +324,7 @@ int main(int argc, char **argv)
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))
@@ -330,7 +339,7 @@ int main(int argc, char **argv)
}
if(count > recorder.mBufferSize)
{
ALbyte *data = calloc(recorder.mFrameSize, count);
ALbyte *data = calloc(recorder.mFrameSize, (ALuint)count);
free(recorder.mBuffer);
recorder.mBuffer = data;
recorder.mBufferSize = count;
@@ -364,7 +373,7 @@ int main(int argc, char **argv)
}
}
#endif
recorder.mDataSize += (ALuint)fwrite(recorder.mBuffer, recorder.mFrameSize, count,
recorder.mDataSize += (ALuint)fwrite(recorder.mBuffer, recorder.mFrameSize, (ALuint)count,
recorder.mFile);
}
alcCaptureStop(recorder.mDevice);
@@ -384,7 +393,7 @@ int main(int argc, char **argv)
{
fwrite32le(recorder.mDataSize*recorder.mFrameSize, recorder.mFile);
if(fseek(recorder.mFile, 4, SEEK_SET) == 0)
fwrite32le(total_size - 8, recorder.mFile);
fwrite32le((ALuint)total_size - 8, recorder.mFile);
}
fclose(recorder.mFile);
+77 -74
View File
@@ -24,14 +24,18 @@
/* This file contains an example for applying reverb to a sound. */
#include <stdio.h>
#include <assert.h>
#include <inttypes.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <SDL_sound.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"
@@ -147,68 +151,73 @@ static ALuint LoadEffect(const EFXEAXREVERBPROPERTIES *reverb)
*/
static ALuint LoadSound(const char *filename)
{
Sound_Sample *sample;
ALenum err, format;
ALuint buffer;
Uint32 slen;
SNDFILE *sndfile;
SF_INFO sfinfo;
short *membuf;
sf_count_t num_frames;
ALsizei num_bytes;
/* Open the audio file */
sample = Sound_NewSampleFromFile(filename, NULL, 65536);
if(!sample)
/* 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\n", filename);
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(sample->actual.channels == 1)
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(sample->actual.format == AUDIO_U8)
format = AL_FORMAT_MONO8;
else if(sample->actual.format == AUDIO_S16SYS)
format = AL_FORMAT_MONO16;
else
{
fprintf(stderr, "Unsupported sample format: 0x%04x\n", sample->actual.format);
Sound_FreeSample(sample);
return 0;
}
if(sf_command(sndfile, SFC_WAVEX_GET_AMBISONIC, NULL, 0) == SF_AMBISONIC_B_FORMAT)
format = AL_FORMAT_BFORMAT2D_16;
}
else if(sample->actual.channels == 2)
else if(sfinfo.channels == 4)
{
if(sample->actual.format == AUDIO_U8)
format = AL_FORMAT_STEREO8;
else if(sample->actual.format == AUDIO_S16SYS)
format = AL_FORMAT_STEREO16;
else
{
fprintf(stderr, "Unsupported sample format: 0x%04x\n", sample->actual.format);
Sound_FreeSample(sample);
return 0;
}
if(sf_command(sndfile, SFC_WAVEX_GET_AMBISONIC, NULL, 0) == SF_AMBISONIC_B_FORMAT)
format = AL_FORMAT_BFORMAT3D_16;
}
else
if(!format)
{
fprintf(stderr, "Unsupported channel count: %d\n", sample->actual.channels);
Sound_FreeSample(sample);
fprintf(stderr, "Unsupported channel count: %d\n", sfinfo.channels);
sf_close(sndfile);
return 0;
}
/* Decode the whole audio stream to a buffer. */
slen = Sound_DecodeAll(sample);
if(!sample->buffer || slen == 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)
{
fprintf(stderr, "Failed to read audio from %s\n", filename);
Sound_FreeSample(sample);
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. */
* close the file.
*/
buffer = 0;
alGenBuffers(1, &buffer);
alBufferData(buffer, format, sample->buffer, slen, sample->actual.rate);
Sound_FreeSample(sample);
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();
@@ -250,41 +259,37 @@ int main(int argc, char **argv)
}
/* Define a macro to help load the function pointers. */
#define LOAD_PROC(x) ((x) = alGetProcAddress(#x))
LOAD_PROC(alGenEffects);
LOAD_PROC(alDeleteEffects);
LOAD_PROC(alIsEffect);
LOAD_PROC(alEffecti);
LOAD_PROC(alEffectiv);
LOAD_PROC(alEffectf);
LOAD_PROC(alEffectfv);
LOAD_PROC(alGetEffecti);
LOAD_PROC(alGetEffectiv);
LOAD_PROC(alGetEffectf);
LOAD_PROC(alGetEffectfv);
#define LOAD_PROC(T, x) ((x) = (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(alGenAuxiliaryEffectSlots);
LOAD_PROC(alDeleteAuxiliaryEffectSlots);
LOAD_PROC(alIsAuxiliaryEffectSlot);
LOAD_PROC(alAuxiliaryEffectSloti);
LOAD_PROC(alAuxiliaryEffectSlotiv);
LOAD_PROC(alAuxiliaryEffectSlotf);
LOAD_PROC(alAuxiliaryEffectSlotfv);
LOAD_PROC(alGetAuxiliaryEffectSloti);
LOAD_PROC(alGetAuxiliaryEffectSlotiv);
LOAD_PROC(alGetAuxiliaryEffectSlotf);
LOAD_PROC(alGetAuxiliaryEffectSlotfv);
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
/* Initialize SDL_sound. */
Sound_Init();
/* Load the sound into a buffer. */
buffer = LoadSound(argv[0]);
if(!buffer)
{
CloseAL();
Sound_Quit();
return 1;
}
@@ -293,7 +298,6 @@ int main(int argc, char **argv)
if(!effect)
{
alDeleteBuffers(1, &buffer);
Sound_Quit();
CloseAL();
return 1;
}
@@ -307,18 +311,18 @@ int main(int argc, char **argv)
* effectively copies the effect properties. You can modify or delete the
* effect object afterward without affecting the effect slot.
*/
alAuxiliaryEffectSloti(slot, AL_EFFECTSLOT_EFFECT, effect);
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, buffer);
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, slot, 0, AL_FILTER_NULL);
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. */
@@ -328,13 +332,12 @@ int main(int argc, char **argv)
alGetSourcei(source, AL_SOURCE_STATE, &state);
} while(alGetError() == AL_NO_ERROR && state == AL_PLAYING);
/* All done. Delete resources, and close down SDL_sound and OpenAL. */
/* All done. Delete resources, and close down OpenAL. */
alDeleteSources(1, &source);
alDeleteAuxiliaryEffectSlots(1, &slot);
alDeleteEffects(1, &effect);
alDeleteBuffers(1, &buffer);
Sound_Quit();
CloseAL();
return 0;
+55 -83
View File
@@ -24,33 +24,25 @@
/* This file contains a relatively simple streaming audio player. */
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <signal.h>
#include <assert.h>
#include <inttypes.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <SDL_sound.h>
#include "sndfile.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
/* Define the number of buffers and buffer size (in milliseconds) to use. 4
* buffers with 200ms each gives a nice per-chunk size, and lets the queue last
* for almost one second. */
* buffers with 8192 samples each gives a nice per-chunk size, and lets the
* queue last for almost one second at 44.1khz. */
#define NUM_BUFFERS 4
#define BUFFER_TIME_MS 200
#define BUFFER_SAMPLES 8192
typedef struct StreamPlayer {
/* These are the buffers and source to play out through OpenAL with */
@@ -58,11 +50,12 @@ typedef struct StreamPlayer {
ALuint source;
/* Handle for the audio file */
Sound_Sample *sample;
SNDFILE *sndfile;
SF_INFO sfinfo;
short *membuf;
/* The format of the output stream */
/* The format of the output stream (sample rate is in sfinfo) */
ALenum format;
ALsizei srate;
} StreamPlayer;
static StreamPlayer *NewPlayer(void);
@@ -119,80 +112,63 @@ static void DeletePlayer(StreamPlayer *player)
* it will be closed first. */
static int OpenPlayerFile(StreamPlayer *player, const char *filename)
{
Uint32 frame_size;
size_t frame_size;
ClosePlayerFile(player);
/* Open the file and get the first stream from it */
player->sample = Sound_NewSampleFromFile(filename, NULL, 0);
if(!player->sample)
/* 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\n", filename);
goto error;
fprintf(stderr, "Could not open audio in %s: %s\n", filename, sf_strerror(NULL));
return 0;
}
/* Get the stream format, and figure out the OpenAL format */
if(player->sample->actual.channels == 1)
/* Get the sound format, and figure out the OpenAL format */
if(player->sfinfo.channels == 1)
player->format = AL_FORMAT_MONO16;
else if(player->sfinfo.channels == 2)
player->format = AL_FORMAT_STEREO16;
else if(player->sfinfo.channels == 3)
{
if(player->sample->actual.format == AUDIO_U8)
player->format = AL_FORMAT_MONO8;
else if(player->sample->actual.format == AUDIO_S16SYS)
player->format = AL_FORMAT_MONO16;
else
{
fprintf(stderr, "Unsupported sample format: 0x%04x\n", player->sample->actual.format);
goto error;
}
if(sf_command(player->sndfile, SFC_WAVEX_GET_AMBISONIC, NULL, 0) == SF_AMBISONIC_B_FORMAT)
player->format = AL_FORMAT_BFORMAT2D_16;
}
else if(player->sample->actual.channels == 2)
else if(player->sfinfo.channels == 4)
{
if(player->sample->actual.format == AUDIO_U8)
player->format = AL_FORMAT_STEREO8;
else if(player->sample->actual.format == AUDIO_S16SYS)
player->format = AL_FORMAT_STEREO16;
else
{
fprintf(stderr, "Unsupported sample format: 0x%04x\n", player->sample->actual.format);
goto error;
}
if(sf_command(player->sndfile, SFC_WAVEX_GET_AMBISONIC, NULL, 0) == SF_AMBISONIC_B_FORMAT)
player->format = AL_FORMAT_BFORMAT3D_16;
}
else
if(!player->format)
{
fprintf(stderr, "Unsupported channel count: %d\n", player->sample->actual.channels);
goto error;
fprintf(stderr, "Unsupported channel count: %d\n", player->sfinfo.channels);
sf_close(player->sndfile);
player->sndfile = NULL;
return 0;
}
player->srate = player->sample->actual.rate;
frame_size = player->sample->actual.channels *
SDL_AUDIO_BITSIZE(player->sample->actual.format) / 8;
/* Set the buffer size, given the desired millisecond length. */
Sound_SetBufferSize(player->sample, (Uint32)((Uint64)player->srate*BUFFER_TIME_MS/1000) *
frame_size);
frame_size = (size_t)(BUFFER_SAMPLES * player->sfinfo.channels) * sizeof(short);
player->membuf = malloc(frame_size);
return 1;
error:
if(player->sample)
Sound_FreeSample(player->sample);
player->sample = NULL;
return 0;
}
/* Closes the audio file stream */
static void ClosePlayerFile(StreamPlayer *player)
{
if(player->sample)
Sound_FreeSample(player->sample);
player->sample = NULL;
if(player->sndfile)
sf_close(player->sndfile);
player->sndfile = NULL;
free(player->membuf);
player->membuf = NULL;
}
/* Prebuffers some audio from the file, and starts playing the source */
static int StartPlayer(StreamPlayer *player)
{
size_t i;
ALsizei i;
/* Rewind the source position and clear the buffer queue */
alSourceRewind(player->source);
@@ -202,11 +178,12 @@ static int StartPlayer(StreamPlayer *player)
for(i = 0;i < NUM_BUFFERS;i++)
{
/* Get some data to give it to the buffer */
Uint32 slen = Sound_Decode(player->sample);
if(slen == 0) break;
sf_count_t slen = sf_readf_short(player->sndfile, player->membuf, BUFFER_SAMPLES);
if(slen < 1) break;
alBufferData(player->buffers[i], player->format,
player->sample->buffer, slen, player->srate);
slen *= player->sfinfo.channels * (sf_count_t)sizeof(short);
alBufferData(player->buffers[i], player->format, player->membuf, (ALsizei)slen,
player->sfinfo.samplerate);
}
if(alGetError() != AL_NO_ERROR)
{
@@ -243,21 +220,19 @@ static int UpdatePlayer(StreamPlayer *player)
while(processed > 0)
{
ALuint bufid;
Uint32 slen;
sf_count_t slen;
alSourceUnqueueBuffers(player->source, 1, &bufid);
processed--;
if((player->sample->flags&(SOUND_SAMPLEFLAG_EOF|SOUND_SAMPLEFLAG_ERROR)))
continue;
/* Read the next chunk of data, refill the buffer, and queue it
* back on the source */
slen = Sound_Decode(player->sample);
slen = sf_readf_short(player->sndfile, player->membuf, BUFFER_SAMPLES);
if(slen > 0)
{
alBufferData(bufid, player->format, player->sample->buffer, slen,
player->srate);
slen *= player->sfinfo.channels * (sf_count_t)sizeof(short);
alBufferData(bufid, player->format, player->membuf, (ALsizei)slen,
player->sfinfo.samplerate);
alSourceQueueBuffers(player->source, 1, &bufid);
}
if(alGetError() != AL_NO_ERROR)
@@ -305,8 +280,6 @@ int main(int argc, char **argv)
if(InitAL(&argv, &argc) != 0)
return 1;
Sound_Init();
player = NewPlayer();
/* Play each file listed on the command line */
@@ -325,7 +298,7 @@ int main(int argc, char **argv)
namepart = argv[i];
printf("Playing: %s (%s, %dhz)\n", namepart, FormatName(player->format),
player->srate);
player->sfinfo.samplerate);
fflush(stdout);
if(!StartPlayer(player))
@@ -342,11 +315,10 @@ int main(int argc, char **argv)
}
printf("Done.\n");
/* All files done. Delete the player, and close down SDL_sound and OpenAL */
/* All files done. Delete the player, and close down OpenAL */
DeletePlayer(player);
player = NULL;
Sound_Quit();
CloseAL();
return 0;
+404
View File
@@ -0,0 +1,404 @@
/*
* 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"
#ifndef AL_SOFT_callback_buffer
#define AL_SOFT_callback_buffer
typedef unsigned int ALbitfieldSOFT;
#define AL_BUFFER_CALLBACK_FUNCTION_SOFT 0x19A0
#define AL_BUFFER_CALLBACK_USER_PARAM_SOFT 0x19A1
typedef ALsizei (AL_APIENTRY*LPALBUFFERCALLBACKTYPESOFT)(ALvoid *userptr, ALvoid *sampledata, ALsizei numsamples);
typedef void (AL_APIENTRY*LPALBUFFERCALLBACKSOFT)(ALuint buffer, ALenum format, ALsizei freq, LPALBUFFERCALLBACKTYPESOFT callback, ALvoid *userptr, ALbitfieldSOFT flags);
typedef void (AL_APIENTRY*LPALGETBUFFERPTRSOFT)(ALuint buffer, ALenum param, ALvoid **value);
typedef void (AL_APIENTRY*LPALGETBUFFER3PTRSOFT)(ALuint buffer, ALenum param, ALvoid **value1, ALvoid **value2, ALvoid **value3);
typedef void (AL_APIENTRY*LPALGETBUFFERPTRVSOFT)(ALuint buffer, ALenum param, ALvoid **values);
#endif
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};
/* 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(ALenum err{alGetError()})
throw std::runtime_error{"alGenBuffers failed"};
alGenSources(1, &mSource);
if(ALenum err{alGetError()})
{
alDeleteBuffers(1, &mBuffer);
throw std::runtime_error{"alGenSources failed"};
}
}
~StreamPlayer()
{
alDeleteSources(1, &mSource);
alDeleteBuffers(1, &mBuffer);
if(mSndfile)
sf_close(mSndfile);
}
void close()
{
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;
}
mFormat = AL_NONE;
if(mSfInfo.channels == 1)
mFormat = AL_FORMAT_MONO16;
else if(mSfInfo.channels == 2)
mFormat = AL_FORMAT_STEREO16;
else if(mSfInfo.channels == 3)
{
if(sf_command(mSndfile, SFC_WAVEX_GET_AMBISONIC, NULL, 0) == SF_AMBISONIC_B_FORMAT)
mFormat = AL_FORMAT_BFORMAT2D_16;
}
else if(mSfInfo.channels == 4)
{
if(sf_command(mSndfile, SFC_WAVEX_GET_AMBISONIC, NULL, 0) == SF_AMBISONIC_B_FORMAT)
mFormat = AL_FORMAT_BFORMAT3D_16;
}
if(!mFormat)
{
fprintf(stderr, "Unsupported channel count: %d\n", mSfInfo.channels);
sf_close(mSndfile);
mSndfile = nullptr;
return false;
}
/* Set a 1s ring buffer size. */
mBufferDataSize = static_cast<ALuint>(mSfInfo.samplerate*mSfInfo.channels) * sizeof(short);
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()
{
alBufferCallbackSOFT(mBuffer, mFormat, mSfInfo.samplerate, bufferCallbackC, this, 0);
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);
const size_t frame_size{static_cast<ALuint>(mSfInfo.channels) * sizeof(short)};
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) / frame_size
: (static_cast<ALuint>(pos) + mStartOffset/frame_size))
/ 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};
if(writable < frame_size) break;
sf_count_t num_frames{sf_readf_short(mSndfile,
reinterpret_cast<short*>(&mBufferData[woffset]),
static_cast<sf_count_t>(writable/frame_size))};
if(num_frames < 1) break;
read_bytes = static_cast<size_t>(num_frames) * frame_size;
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)};
if(writable < frame_size) break;
sf_count_t num_frames{sf_readf_short(mSndfile,
reinterpret_cast<short*>(&mBufferData[woffset]),
static_cast<sf_count_t>(writable/frame_size))};
if(num_frames < 1) break;
read_bytes = static_cast<size_t>(num_frames) * frame_size;
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_SOFTX_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;
}
+32 -8
View File
@@ -44,6 +44,8 @@
#include "common/alhelpers.h"
#include "win_main_utf8.h"
#ifndef M_PI
#define M_PI (3.14159265358979323846)
#endif
@@ -82,22 +84,25 @@ 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++)
data[i] += (ALfloat)(sin(i/smps_per_cycle * 2.0*M_PI) * g);
{
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)
static ALuint CreateWave(enum WaveType type, ALuint freq, ALuint srate, ALfloat gain)
{
ALuint seed = 22222;
ALint data_size;
ALuint data_size;
ALfloat *data;
ALuint buffer;
ALenum err;
ALuint i;
data_size = srate * sizeof(ALfloat);
data_size = (ALuint)(srate * sizeof(ALfloat));
data = calloc(1, data_size);
switch(type)
{
@@ -139,10 +144,16 @@ static ALuint CreateWave(enum WaveType type, ALuint freq, ALuint srate)
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, data_size, srate);
alBufferData(buffer, AL_FORMAT_MONO_FLOAT32, data, (ALsizei)data_size, (ALsizei)srate);
free(data);
/* Check if an error occured, and clean up if so. */
@@ -170,6 +181,7 @@ int main(int argc, char *argv[])
ALint tone_freq = 1000;
ALCint dev_rate;
ALenum state;
ALfloat gain = 1.0f;
int i;
argv++; argc--;
@@ -185,7 +197,8 @@ int main(int argc, char *argv[])
for(i = 0;i < argc;i++)
{
if(strcmp(argv[i], "-h") == 0 || strcmp(argv[i], "--help") == 0)
if(strcmp(argv[i], "-h") == 0 || strcmp(argv[i], "-?") == 0
|| strcmp(argv[i], "--help") == 0)
{
fprintf(stderr, "OpenAL Tone Generator\n"
"\n"
@@ -197,6 +210,7 @@ int main(int argc, char *argv[])
" --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
);
@@ -236,6 +250,16 @@ int main(int argc, char *argv[])
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++;
@@ -257,7 +281,7 @@ int main(int argc, char *argv[])
srate = dev_rate;
/* Load the sound into a buffer. */
buffer = CreateWave(wavetype, tone_freq, srate);
buffer = CreateWave(wavetype, (ALuint)tone_freq, (ALuint)srate, gain);
if(!buffer)
{
CloseAL();
@@ -271,7 +295,7 @@ int main(int argc, char *argv[])
/* Create the source to play the sound with. */
source = 0;
alGenSources(1, &source);
alSourcei(source, AL_BUFFER, buffer);
alSourcei(source, AL_BUFFER, (ALint)buffer);
assert(alGetError()==AL_NO_ERROR && "Failed to setup sound source");
/* Play the sound for a while. */
+83 -6
View File
@@ -28,15 +28,16 @@
* 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"
#include "alhelpers.h"
/* InitAL opens a device and sets up a context using default attributes, making
* the program ready to call OpenAL functions. */
@@ -107,10 +108,86 @@ const char *FormatName(ALenum format)
{
switch(format)
{
case AL_FORMAT_MONO8: return "Mono, U8";
case AL_FORMAT_MONO16: return "Mono, S16";
case AL_FORMAT_STEREO8: return "Stereo, U8";
case AL_FORMAT_STEREO16: return "Stereo, S16";
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_STEREO8: return "Stereo, U8";
case AL_FORMAT_STEREO16: return "Stereo, S16";
case AL_FORMAT_STEREO_FLOAT32: return "Stereo, Float32";
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_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";
}
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
+7 -7
View File
@@ -1,15 +1,11 @@
#ifndef ALHELPERS_H
#define ALHELPERS_H
#include "AL/alc.h"
#include "AL/al.h"
#include "AL/alext.h"
#include "threads.h"
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
#endif
/* Some helper functions to get the name from the format enums. */
const char *FormatName(ALenum type);
@@ -18,8 +14,12 @@ const char *FormatName(ALenum type);
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);
#ifdef __cplusplus
}
#endif /* __cplusplus */
} // extern "C"
#endif
#endif /* ALHELPERS_H */