update openal

This commit is contained in:
AzaezelX 2024-06-30 14:35:57 -05:00
parent 62f3b93ff9
commit 6721a6b021
287 changed files with 33851 additions and 27325 deletions

View file

@ -22,7 +22,7 @@
* THE SOFTWARE.
*/
/* This file contains an example for applying convolution reverb to a source. */
/* This file contains an example for applying convolution to a source. */
#include <assert.h>
#include <inttypes.h>
@ -38,10 +38,12 @@
#include "common/alhelpers.h"
#include "win_main_utf8.h"
#ifndef AL_SOFT_convolution_reverb
#define AL_SOFT_convolution_reverb
#define AL_EFFECT_CONVOLUTION_REVERB_SOFT 0xA000
#ifndef AL_SOFT_convolution_effect
#define AL_SOFT_convolution_effect
#define AL_EFFECT_CONVOLUTION_SOFT 0xA000
#endif
@ -88,11 +90,11 @@ 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
enum { NumBuffers = 4 };
enum { BufferSamples = 8192 };
typedef struct StreamPlayer {
ALuint buffers[NUM_BUFFERS];
ALuint buffers[NumBuffers];
ALuint source;
SNDFILE *sndfile;
@ -109,7 +111,7 @@ static StreamPlayer *NewPlayer(void)
player = calloc(1, sizeof(*player));
assert(player != NULL);
alGenBuffers(NUM_BUFFERS, player->buffers);
alGenBuffers(NumBuffers, player->buffers);
assert(alGetError() == AL_NO_ERROR && "Could not create buffers");
alGenSources(1, &player->source);
@ -138,11 +140,11 @@ static void DeletePlayer(StreamPlayer *player)
ClosePlayerFile(player);
alDeleteSources(1, &player->source);
alDeleteBuffers(NUM_BUFFERS, player->buffers);
alDeleteBuffers(NumBuffers, player->buffers);
if(alGetError() != AL_NO_ERROR)
fprintf(stderr, "Failed to delete object IDs\n");
memset(player, 0, sizeof(*player));
memset(player, 0, sizeof(*player)); /* NOLINT(clang-analyzer-security.insecureAPI.*) */
free(player);
}
@ -184,7 +186,7 @@ static int OpenPlayerFile(StreamPlayer *player, const char *filename)
return 0;
}
frame_size = (size_t)(BUFFER_SAMPLES * player->sfinfo.channels) * sizeof(float);
frame_size = (size_t)(BufferSamples * player->sfinfo.channels) * sizeof(float);
player->membuf = malloc(frame_size);
return 1;
@ -197,9 +199,9 @@ static int StartPlayer(StreamPlayer *player)
alSourceRewind(player->source);
alSourcei(player->source, AL_BUFFER, 0);
for(i = 0;i < NUM_BUFFERS;i++)
for(i = 0;i < NumBuffers;i++)
{
sf_count_t slen = sf_readf_float(player->sndfile, player->membuf, BUFFER_SAMPLES);
sf_count_t slen = sf_readf_float(player->sndfile, player->membuf, BufferSamples);
if(slen < 1) break;
slen *= player->sfinfo.channels * (sf_count_t)sizeof(float);
@ -243,7 +245,7 @@ static int UpdatePlayer(StreamPlayer *player)
alSourceUnqueueBuffers(player->source, 1, &bufid);
processed--;
slen = sf_readf_float(player->sndfile, player->membuf, BUFFER_SAMPLES);
slen = sf_readf_float(player->sndfile, player->membuf, BufferSamples);
if(slen > 0)
{
slen *= player->sfinfo.channels * (sf_count_t)sizeof(float);
@ -278,21 +280,21 @@ static int UpdatePlayer(StreamPlayer *player)
}
/* CreateEffect creates a new OpenAL effect object with a convolution reverb
* type, and returns the new effect ID.
/* CreateEffect creates a new OpenAL effect object with a convolution type, and
* returns the new effect ID.
*/
static ALuint CreateEffect(void)
{
ALuint effect = 0;
ALenum err;
printf("Using Convolution Reverb\n");
printf("Using Convolution\n");
/* Create the effect object and set the convolution reverb effect type. */
/* Create the effect object and set the convolution effect type. */
alGenEffects(1, &effect);
alEffecti(effect, AL_EFFECT_TYPE, AL_EFFECT_CONVOLUTION_REVERB_SOFT);
alEffecti(effect, AL_EFFECT_TYPE, AL_EFFECT_CONVOLUTION_SOFT);
/* Check if an error occured, and clean up if so. */
/* Check if an error occurred, and clean up if so. */
err = alGetError();
if(err != AL_NO_ERROR)
{
@ -359,10 +361,10 @@ static ALuint LoadSound(const char *filename)
}
namepart = strrchr(filename, '/');
if(namepart || (namepart=strrchr(filename, '\\')))
namepart++;
else
namepart = filename;
if(!namepart) namepart = strrchr(filename, '\\');
if(!namepart) namepart = filename;
else namepart++;
printf("Loading: %s (%s, %dhz, %" PRId64 " samples / %.2f seconds)\n", namepart,
FormatName(format), sfinfo.samplerate, sfinfo.frames,
(double)sfinfo.frames / sfinfo.samplerate);
@ -391,7 +393,7 @@ static ALuint LoadSound(const char *filename)
free(membuf);
sf_close(sndfile);
/* Check if an error occured, and clean up if so. */
/* Check if an error occurred, and clean up if so. */
err = alGetError();
if(err != AL_NO_ERROR)
{
@ -423,10 +425,10 @@ int main(int argc, char **argv)
if(InitAL(&argv, &argc) != 0)
return 1;
if(!alIsExtensionPresent("AL_SOFTX_convolution_reverb"))
if(!alIsExtensionPresent("AL_SOFTX_convolution_effect"))
{
CloseAL();
fprintf(stderr, "Error: Convolution revern not supported\n");
fprintf(stderr, "Error: Convolution effect not supported\n");
return 1;
}
@ -500,11 +502,11 @@ int main(int argc, char **argv)
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.
* effects to access it as needed. In this case, convolution 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
@ -555,10 +557,9 @@ int main(int argc, char **argv)
continue;
namepart = strrchr(argv[i], '/');
if(namepart || (namepart=strrchr(argv[i], '\\')))
namepart++;
else
namepart = argv[i];
if(!namepart) namepart = strrchr(argv[i], '\\');
if(!namepart) namepart = argv[i];
else namepart++;
printf("Playing: %s (%s, %dhz)\n", namepart, FormatName(player->format),
player->sfinfo.samplerate);

View file

@ -0,0 +1,472 @@
/*
* OpenAL Direct Context Example
*
* Copyright (c) 2024 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 with the Direct API
* extension.
*/
#include <algorithm>
#include <cassert>
#include <cstddef>
#include <cstdio>
#include <iostream>
#include <limits>
#include <memory>
#include <string>
#include <string_view>
#include <vector>
#include "sndfile.h"
#include "AL/al.h"
#include "AL/alc.h"
#include "AL/alext.h"
#include "alspan.h"
#include "common/alhelpers.h"
#include "win_main_utf8.h"
namespace {
/* On Windows when using Creative's router, we need to override the ALC
* functions and access the driver functions directly. This isn't needed when
* not using the router, or on other OSs.
*/
LPALCOPENDEVICE p_alcOpenDevice{alcOpenDevice};
LPALCCLOSEDEVICE p_alcCloseDevice{alcCloseDevice};
LPALCISEXTENSIONPRESENT p_alcIsExtensionPresent{alcIsExtensionPresent};
LPALCCREATECONTEXT p_alcCreateContext{alcCreateContext};
LPALCDESTROYCONTEXT p_alcDestroyContext{alcDestroyContext};
LPALCGETPROCADDRESS p_alcGetProcAddress{alcGetProcAddress};
LPALGETSTRINGDIRECT alGetStringDirect{};
LPALGETERRORDIRECT alGetErrorDirect{};
LPALISEXTENSIONPRESENTDIRECT alIsExtensionPresentDirect{};
LPALGENBUFFERSDIRECT alGenBuffersDirect{};
LPALDELETEBUFFERSDIRECT alDeleteBuffersDirect{};
LPALISBUFFERDIRECT alIsBufferDirect{};
LPALBUFFERIDIRECT alBufferiDirect{};
LPALBUFFERDATADIRECT alBufferDataDirect{};
LPALGENSOURCESDIRECT alGenSourcesDirect{};
LPALDELETESOURCESDIRECT alDeleteSourcesDirect{};
LPALSOURCEIDIRECT alSourceiDirect{};
LPALGETSOURCEIDIRECT alGetSourceiDirect{};
LPALGETSOURCEFDIRECT alGetSourcefDirect{};
LPALSOURCEPLAYDIRECT alSourcePlayDirect{};
struct SndFileDeleter {
void operator()(SNDFILE *sndfile) { sf_close(sndfile); }
};
using SndFilePtr = std::unique_ptr<SNDFILE,SndFileDeleter>;
enum class FormatType {
Int16,
Float,
IMA4,
MSADPCM
};
/* LoadBuffer loads the named audio file into an OpenAL buffer object, and
* returns the new buffer ID.
*/
ALuint LoadSound(ALCcontext *context, const std::string_view filename)
{
/* Open the audio file and check that it's usable. */
SF_INFO sfinfo{};
SndFilePtr sndfile{sf_open(std::string{filename}.c_str(), SFM_READ, &sfinfo)};
if(!sndfile)
{
std::cerr<< "Could not open audio in "<<filename<<": "<<sf_strerror(sndfile.get())<<"\n";
return 0;
}
if(sfinfo.frames < 1)
{
std::cerr<< "Bad sample count in "<<filename<<" ("<<sfinfo.frames<<")\n";
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.
*/
FormatType sample_format{FormatType::Int16};
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(alIsExtensionPresentDirect(context, "AL_EXT_FLOAT32"))
sample_format = FormatType::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
&& alIsExtensionPresentDirect(context, "AL_EXT_IMA4")
&& alIsExtensionPresentDirect(context, "AL_SOFT_block_alignment"))
sample_format = FormatType::IMA4;
break;
case SF_FORMAT_MS_ADPCM:
if(sfinfo.channels <= 2 && (sfinfo.format&SF_FORMAT_TYPEMASK) == SF_FORMAT_WAV
&& alIsExtensionPresentDirect(context, "AL_SOFT_MSADPCM")
&& alIsExtensionPresentDirect(context, "AL_SOFT_block_alignment"))
sample_format = FormatType::MSADPCM;
break;
}
ALint byteblockalign{0}, splblockalign{0};
if(sample_format == FormatType::IMA4 || sample_format == FormatType::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, nullptr};
SF_CHUNK_ITERATOR *iter{sf_get_chunk_iterator(sndfile.get(), &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 = FormatType::Int16;
else
{
auto fmtbuf = std::vector<ALubyte>(inf.datalen, ALubyte{0});
inf.data = fmtbuf.data();
if(sf_get_chunk_data(iter, &inf) != SF_ERR_NO_ERROR)
sample_format = FormatType::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 == FormatType::IMA4)
{
splblockalign = (byteblockalign/sfinfo.channels - 4)/4*8 + 1;
if(splblockalign < 1
|| ((splblockalign-1)/2 + 4)*sfinfo.channels != byteblockalign)
sample_format = FormatType::Int16;
}
else if(sample_format == FormatType::MSADPCM)
{
splblockalign = (byteblockalign/sfinfo.channels - 7)*2 + 2;
if(splblockalign < 2
|| ((splblockalign-2)/2 + 7)*sfinfo.channels != byteblockalign)
sample_format = FormatType::Int16;
}
else
sample_format = FormatType::Int16;
}
}
}
if(sample_format == FormatType::Int16)
{
splblockalign = 1;
byteblockalign = sfinfo.channels * 2;
}
else if(sample_format == FormatType::Float)
{
splblockalign = 1;
byteblockalign = sfinfo.channels * 4;
}
/* Figure out the OpenAL format from the file and desired sample type. */
ALenum format{AL_NONE};
if(sfinfo.channels == 1)
{
if(sample_format == FormatType::Int16)
format = AL_FORMAT_MONO16;
else if(sample_format == FormatType::Float)
format = AL_FORMAT_MONO_FLOAT32;
else if(sample_format == FormatType::IMA4)
format = AL_FORMAT_MONO_IMA4;
else if(sample_format == FormatType::MSADPCM)
format = AL_FORMAT_MONO_MSADPCM_SOFT;
}
else if(sfinfo.channels == 2)
{
if(sample_format == FormatType::Int16)
format = AL_FORMAT_STEREO16;
else if(sample_format == FormatType::Float)
format = AL_FORMAT_STEREO_FLOAT32;
else if(sample_format == FormatType::IMA4)
format = AL_FORMAT_STEREO_IMA4;
else if(sample_format == FormatType::MSADPCM)
format = AL_FORMAT_STEREO_MSADPCM_SOFT;
}
else if(sfinfo.channels == 3)
{
if(sf_command(sndfile.get(), SFC_WAVEX_GET_AMBISONIC, nullptr, 0) == SF_AMBISONIC_B_FORMAT)
{
if(sample_format == FormatType::Int16)
format = AL_FORMAT_BFORMAT2D_16;
else if(sample_format == FormatType::Float)
format = AL_FORMAT_BFORMAT2D_FLOAT32;
}
}
else if(sfinfo.channels == 4)
{
if(sf_command(sndfile.get(), SFC_WAVEX_GET_AMBISONIC, nullptr, 0) == SF_AMBISONIC_B_FORMAT)
{
if(sample_format == FormatType::Int16)
format = AL_FORMAT_BFORMAT3D_16;
else if(sample_format == FormatType::Float)
format = AL_FORMAT_BFORMAT3D_FLOAT32;
}
}
if(!format)
{
std::cerr<< "Unsupported channel count: "<<sfinfo.channels<<"\n";
return 0;
}
if(sfinfo.frames/splblockalign > sf_count_t{std::numeric_limits<int>::max()}/byteblockalign)
{
std::cerr<< "Too many sample frames in "<<filename<<" ("<<sfinfo.frames<<")\n";
return 0;
}
/* Decode the whole audio file to a buffer. */
auto membuf = std::vector<std::byte>(static_cast<size_t>(sfinfo.frames / splblockalign
* byteblockalign));
sf_count_t num_frames{};
if(sample_format == FormatType::Int16)
num_frames = sf_readf_short(sndfile.get(), reinterpret_cast<short*>(membuf.data()),
sfinfo.frames);
else if(sample_format == FormatType::Float)
num_frames = sf_readf_float(sndfile.get(), reinterpret_cast<float*>(membuf.data()),
sfinfo.frames);
else
{
const sf_count_t count{sfinfo.frames / splblockalign * byteblockalign};
num_frames = sf_read_raw(sndfile.get(), membuf.data(), count);
if(num_frames > 0)
num_frames = num_frames / byteblockalign * splblockalign;
}
if(num_frames < 1)
{
std::cerr<< "Failed to read samples in "<<filename<<" ("<<num_frames<<")\n";
return 0;
}
const auto num_bytes = static_cast<ALsizei>(num_frames / splblockalign * byteblockalign);
std::cout<< "Loading: "<<filename<<" ("<<FormatName(format)<<", "<<sfinfo.samplerate<<"hz)\n"
<<std::flush;
ALuint buffer{};
alGenBuffersDirect(context, 1, &buffer);
if(splblockalign > 1)
alBufferiDirect(context, buffer, AL_UNPACK_BLOCK_ALIGNMENT_SOFT, splblockalign);
alBufferDataDirect(context, buffer, format, membuf.data(), num_bytes, sfinfo.samplerate);
/* Check if an error occurred, and clean up if so. */
if(ALenum err{alGetErrorDirect(context)}; err != AL_NO_ERROR)
{
std::cerr<< "OpenAL Error: "<<alGetStringDirect(context, err)<<"\n";
if(buffer && alIsBufferDirect(context, buffer))
alDeleteBuffersDirect(context, 1, &buffer);
return 0;
}
return buffer;
}
int main(al::span<std::string_view> args)
{
/* Print out usage if no arguments were specified */
if(args.size() < 2)
{
std::cerr<< "Usage: "<<args[0]<<" [-device <name>] <filename>\n";
return 1;
}
/* Initialize OpenAL. */
args = args.subspan(1);
ALCdevice *device{};
if(args.size() > 1 && args[0] == "-device")
{
device = p_alcOpenDevice(std::string{args[1]}.c_str());
if(!device)
std::cerr<< "Failed to open \""<<args[1]<<"\", trying default\n";
args = args.subspan(2);
}
if(!device)
device = p_alcOpenDevice(nullptr);
if(!device)
{
std::cerr<< "Could not open a device!\n";
return 1;
}
if(!p_alcIsExtensionPresent(device, "ALC_EXT_direct_context"))
{
std::cerr<< "ALC_EXT_direct_context not supported on device\n";
p_alcCloseDevice(device);
return 1;
}
/* On Windows with Creative's router, the device needs to be bootstrapped
* to use it through the driver directly. Otherwise the Direct functions
* aren't able to recognize the router's ALCcontexts. To handle this, we
* use the router's alcOpenDevice, alcGetProcAddress, and alcCloseDevice
* functions to open the device with the router, get the device driver's
* alcGetProcAddress2 function, and close the device with the router. Then
* call alcGetProcAddress2 with the null device handle to get the driver's
* functions. Afterward, we can open the device back up using the driver
* functions directly and continue on.
*
* Note that this will allow using other devices from the same driver just
* fine, but switching to a device on another driver will require using the
* original functions from the router (and require re-bootstrapping to use
* that driver's functions, if applicable). If controlling multiple devices
* with Direct functions from separate drivers simultaneously is desired, a
* good strategy may be to associate the driver's ALC and Direct functions
* with the ALCdevice and ALCcontext handles created from them.
*
* This is all unnecessary when not using Creative's router, including on
* non-Windows OSs or when using OpenAL Soft's router, where the original
* ALC functions can be used as normal.
*/
{
const std::string devname{alcGetString(device, ALC_ALL_DEVICES_SPECIFIER)};
auto p_alcGetProcAddress2 = reinterpret_cast<LPALCGETPROCADDRESS2>(
p_alcGetProcAddress(device, "alcGetProcAddress2"));
p_alcCloseDevice(device);
/* Load the driver-specific ALC functions we'll be using. */
#define LOAD_PROC(N) p_##N = reinterpret_cast<decltype(p_##N)>(p_alcGetProcAddress2(nullptr, #N))
LOAD_PROC(alcOpenDevice);
LOAD_PROC(alcCloseDevice);
LOAD_PROC(alcIsExtensionPresent);
LOAD_PROC(alcGetProcAddress);
LOAD_PROC(alcCreateContext);
LOAD_PROC(alcDestroyContext);
LOAD_PROC(alcGetProcAddress);
#undef LOAD_PROC
device = p_alcOpenDevice(devname.c_str());
assert(device != nullptr);
}
/* Load the Direct API functions we're using. */
#define LOAD_PROC(N) N = reinterpret_cast<decltype(N)>(p_alcGetProcAddress(device, #N))
LOAD_PROC(alGetStringDirect);
LOAD_PROC(alGetErrorDirect);
LOAD_PROC(alIsExtensionPresentDirect);
LOAD_PROC(alGenBuffersDirect);
LOAD_PROC(alDeleteBuffersDirect);
LOAD_PROC(alIsBufferDirect);
LOAD_PROC(alBufferiDirect);
LOAD_PROC(alBufferDataDirect);
LOAD_PROC(alGenSourcesDirect);
LOAD_PROC(alDeleteSourcesDirect);
LOAD_PROC(alSourceiDirect);
LOAD_PROC(alGetSourceiDirect);
LOAD_PROC(alGetSourcefDirect);
LOAD_PROC(alSourcePlayDirect);
#undef LOAD_PROC
/* Create the context. It doesn't need to be set as current to use with the
* Direct API functions.
*/
ALCcontext *context{p_alcCreateContext(device, nullptr)};
if(!context)
{
p_alcCloseDevice(device);
std::cerr<< "Could not create a context!\n";
return 1;
}
/* Load the sound into a buffer. */
const ALuint buffer{LoadSound(context, args[0])};
if(!buffer)
{
p_alcDestroyContext(context);
p_alcCloseDevice(device);
return 1;
}
/* Create the source to play the sound with. */
ALuint source{0};
alGenSourcesDirect(context, 1, &source);
alSourceiDirect(context, source, AL_BUFFER, static_cast<ALint>(buffer));
assert(alGetErrorDirect(context)==AL_NO_ERROR && "Failed to setup sound source");
/* Play the sound until it finishes. */
alSourcePlayDirect(context, source);
ALenum state{};
do {
al_nssleep(10000000);
alGetSourceiDirect(context, source, AL_SOURCE_STATE, &state);
/* Get the source offset. */
ALfloat offset{};
alGetSourcefDirect(context, source, AL_SEC_OFFSET, &offset);
printf("\rOffset: %f ", offset);
fflush(stdout);
} while(alGetErrorDirect(context) == AL_NO_ERROR && state == AL_PLAYING);
printf("\n");
/* All done. Delete resources, and close down OpenAL. */
alDeleteSourcesDirect(context, 1, &source);
alDeleteBuffersDirect(context, 1, &buffer);
p_alcDestroyContext(context);
p_alcCloseDevice(device);
return 0;
}
} // namespace
int main(int argc, char **argv)
{
assert(argc >= 0);
auto args = std::vector<std::string_view>(static_cast<unsigned int>(argc));
std::copy_n(argv, args.size(), args.begin());
return main(al::span{args});
}

File diff suppressed because it is too large Load diff

View file

@ -40,6 +40,8 @@
#include "common/alhelpers.h"
#include "win_main_utf8.h"
#ifndef M_PI
#define M_PI (3.14159265358979323846)
@ -121,7 +123,7 @@ static ALuint LoadSound(const char *filename)
free(membuf);
sf_close(sndfile);
/* Check if an error occured, and clean up if so. */
/* Check if an error occurred, and clean up if so. */
err = alGetError();
if(err != AL_NO_ERROR)
{

View file

@ -37,6 +37,8 @@
#include "common/alhelpers.h"
#include "win_main_utf8.h"
static LPALSOURCEDSOFT alSourcedSOFT;
static LPALSOURCE3DSOFT alSource3dSOFT;
@ -124,7 +126,7 @@ static ALuint LoadSound(const char *filename)
free(membuf);
sf_close(sndfile);
/* Check if an error occured, and clean up if so. */
/* Check if an error occurred, and clean up if so. */
err = alGetError();
if(err != AL_NO_ERROR)
{

View file

@ -29,6 +29,7 @@
#include <assert.h>
#include <math.h>
#include <stdio.h>
#include <string.h>
#define SDL_MAIN_HANDLED
#include "SDL.h"
@ -118,7 +119,7 @@ static ALuint CreateSineWave(void)
alGenBuffers(1, &buffer);
alBufferData(buffer, AL_FORMAT_MONO16, data, sizeof(data), 44100);
/* Check if an error occured, and clean up if so. */
/* Check if an error occurred, and clean up if so. */
err = alGetError();
if(err != AL_NO_ERROR)
{

View file

@ -47,6 +47,8 @@
#include "common/alhelpers.h"
#include "win_main_utf8.h"
#ifndef M_PI
#define M_PI 3.14159265358979323846
@ -106,7 +108,8 @@ static int LoadEffect(ALuint effect, const EFXEAXREVERBPROPERTIES *reverb)
* the needed panning vectors).
*/
alEffecti(effect, AL_EFFECT_TYPE, AL_EFFECT_EAXREVERB);
if((err=alGetError()) != AL_NO_ERROR)
err = alGetError();
if(err != AL_NO_ERROR)
{
fprintf(stderr, "Failed to set EAX Reverb: %s (0x%04x)\n", alGetString(err), err);
return 0;
@ -137,8 +140,9 @@ static int LoadEffect(ALuint effect, const EFXEAXREVERBPROPERTIES *reverb)
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)
/* Check if an error occurred, and return failure if so. */
err = alGetError();
if(err != AL_NO_ERROR)
{
fprintf(stderr, "Error setting up reverb: %s\n", alGetString(err));
return 0;
@ -210,7 +214,7 @@ static ALuint LoadSound(const char *filename)
free(membuf);
sf_close(sndfile);
/* Check if an error occured, and clean up if so. */
/* Check if an error occurred, and clean up if so. */
err = alGetError();
if(err != AL_NO_ERROR)
{
@ -493,7 +497,7 @@ int main(int argc, char **argv)
}
if(argc < 1)
{
fprintf(stderr, "No filename spacified.\n");
fprintf(stderr, "No filename specified.\n");
CloseAL();
return 1;
}

View file

@ -37,6 +37,8 @@
#include "common/alhelpers.h"
#include "win_main_utf8.h"
enum FormatType {
Int16,
@ -266,7 +268,7 @@ static ALuint LoadSound(const char *filename)
free(membuf);
sf_close(sndfile);
/* Check if an error occured, and clean up if so. */
/* Check if an error occurred, and clean up if so. */
err = alGetError();
if(err != AL_NO_ERROR)
{

View file

@ -139,7 +139,7 @@ int main(int argc, char **argv)
char *end;
if(strcmp(argv[0], "--") == 0)
break;
else if(strcmp(argv[0], "--channels") == 0 || strcmp(argv[0], "-c") == 0)
if(strcmp(argv[0], "--channels") == 0 || strcmp(argv[0], "-c") == 0)
{
if(argc < 2)
{

View file

@ -40,6 +40,8 @@
#include "common/alhelpers.h"
#include "win_main_utf8.h"
/* Effect object functions */
static LPALGENEFFECTS alGenEffects;
@ -75,16 +77,17 @@ static ALuint LoadEffect(const EFXEAXREVERBPROPERTIES *reverb)
ALuint effect = 0;
ALenum err;
/* Clear error state. */
alGetError();
/* Create the effect object and check if we can do EAX reverb. */
alGenEffects(1, &effect);
if(alGetEnumValue("AL_EFFECT_EAXREVERB") != 0)
alEffecti(effect, AL_EFFECT_TYPE, AL_EFFECT_EAXREVERB);
err = alGetError();
if(err == AL_NO_ERROR)
{
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);
@ -114,7 +117,8 @@ static ALuint LoadEffect(const EFXEAXREVERBPROPERTIES *reverb)
printf("Using Standard Reverb\n");
/* No EAX Reverb. Set the standard reverb effect type then load the
* available reverb properties. */
* available reverb properties.
*/
alEffecti(effect, AL_EFFECT_TYPE, AL_EFFECT_REVERB);
alEffectf(effect, AL_REVERB_DENSITY, reverb->flDensity);
@ -132,7 +136,7 @@ static ALuint LoadEffect(const EFXEAXREVERBPROPERTIES *reverb)
alEffecti(effect, AL_REVERB_DECAY_HFLIMIT, reverb->iDecayHFLimit);
}
/* Check if an error occured, and clean up if so. */
/* Check if an error occurred, and clean up if so. */
err = alGetError();
if(err != AL_NO_ERROR)
{
@ -219,7 +223,7 @@ static ALuint LoadSound(const char *filename)
free(membuf);
sf_close(sndfile);
/* Check if an error occured, and clean up if so. */
/* Check if an error occurred, and clean up if so. */
err = alGetError();
if(err != AL_NO_ERROR)
{

View file

@ -37,13 +37,15 @@
#include "common/alhelpers.h"
#include "win_main_utf8.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
enum { NumBuffers = 4 };
enum { BufferMillisec = 200 };
typedef enum SampleType {
Int16, Float, IMA4, MSADPCM
@ -51,7 +53,7 @@ typedef enum SampleType {
typedef struct StreamPlayer {
/* These are the buffers and source to play out through OpenAL with. */
ALuint buffers[NUM_BUFFERS];
ALuint buffers[NumBuffers];
ALuint source;
/* Handle for the audio file */
@ -88,7 +90,7 @@ static StreamPlayer *NewPlayer(void)
assert(player != NULL);
/* Generate the buffers and source */
alGenBuffers(NUM_BUFFERS, player->buffers);
alGenBuffers(NumBuffers, player->buffers);
assert(alGetError() == AL_NO_ERROR && "Could not create buffers");
alGenSources(1, &player->source);
@ -111,11 +113,11 @@ static void DeletePlayer(StreamPlayer *player)
ClosePlayerFile(player);
alDeleteSources(1, &player->source);
alDeleteBuffers(NUM_BUFFERS, player->buffers);
alDeleteBuffers(NumBuffers, player->buffers);
if(alGetError() != AL_NO_ERROR)
fprintf(stderr, "Failed to delete object IDs\n");
memset(player, 0, sizeof(*player));
memset(player, 0, sizeof(*player)); /* NOLINT(clang-analyzer-security.insecureAPI.*) */
free(player);
}
@ -291,8 +293,8 @@ static int OpenPlayerFile(StreamPlayer *player, const char *filename)
}
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));
player->block_count = player->block_count * BufferMillisec / 1000;
player->membuf = malloc((size_t)player->block_count * (size_t)player->byteblockalign);
return 1;
}
@ -310,7 +312,7 @@ static void ClosePlayerFile(StreamPlayer *player)
if(player->sampleblockalign > 1)
{
ALsizei i;
for(i = 0;i < NUM_BUFFERS;i++)
for(i = 0;i < NumBuffers;i++)
alBufferi(player->buffers[i], AL_UNPACK_BLOCK_ALIGNMENT_SOFT, 0);
player->sampleblockalign = 0;
player->byteblockalign = 0;
@ -328,7 +330,7 @@ static int StartPlayer(StreamPlayer *player)
alSourcei(player->source, AL_BUFFER, 0);
/* Fill the buffer queue */
for(i = 0;i < NUM_BUFFERS;i++)
for(i = 0;i < NumBuffers;i++)
{
sf_count_t slen;
@ -336,21 +338,21 @@ static int StartPlayer(StreamPlayer *player)
if(player->sample_type == Int16)
{
slen = sf_readf_short(player->sndfile, player->membuf,
player->block_count * player->sampleblockalign);
(sf_count_t)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);
(sf_count_t)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);
(sf_count_t)player->block_count * player->byteblockalign);
if(slen > 0) slen -= slen%player->byteblockalign;
if(slen < 1) break;
}
@ -407,19 +409,19 @@ static int UpdatePlayer(StreamPlayer *player)
if(player->sample_type == Int16)
{
slen = sf_readf_short(player->sndfile, player->membuf,
player->block_count * player->sampleblockalign);
(sf_count_t)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);
(sf_count_t)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);
(sf_count_t)player->block_count * player->byteblockalign);
if(slen > 0) slen -= slen%player->byteblockalign;
}
@ -486,10 +488,9 @@ int main(int argc, char **argv)
/* Get the name portion, without the path, for display. */
namepart = strrchr(argv[i], '/');
if(namepart || (namepart=strrchr(argv[i], '\\')))
namepart++;
else
namepart = argv[i];
if(!namepart) namepart = strrchr(argv[i], '\\');
if(!namepart) namepart = argv[i];
else namepart++;
printf("Playing: %s (%s, %dhz)\n", namepart, FormatName(player->format),
player->sfinfo.samplerate);

View file

@ -24,15 +24,19 @@
/* This file contains a streaming audio player using a callback buffer. */
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <algorithm>
#include <atomic>
#include <cassert>
#include <chrono>
#include <cstddef>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <memory>
#include <stdexcept>
#include <string>
#include <string_view>
#include <thread>
#include <vector>
@ -42,8 +46,12 @@
#include "AL/alc.h"
#include "AL/alext.h"
#include "alspan.h"
#include "alstring.h"
#include "common/alhelpers.h"
#include "win_main_utf8.h"
namespace {
@ -56,8 +64,7 @@ struct StreamPlayer {
/* A lockless ring-buffer (supports single-provider, single-consumer
* operation).
*/
std::unique_ptr<ALbyte[]> mBufferData;
size_t mBufferDataSize{0};
std::vector<std::byte> mBufferData;
std::atomic<size_t> mReadPos{0};
std::atomic<size_t> mWritePos{0};
size_t mSamplesPerBlock{1};
@ -78,7 +85,7 @@ struct StreamPlayer {
size_t mDecoderOffset{0};
/* The format of the callback samples. */
ALenum mFormat;
ALenum mFormat{};
StreamPlayer()
{
@ -114,15 +121,16 @@ struct StreamPlayer {
}
}
bool open(const char *filename)
bool open(const std::string &filename)
{
close();
/* Open the file and figure out the OpenAL format. */
mSndfile = sf_open(filename, SFM_READ, &mSfInfo);
mSndfile = sf_open(filename.c_str(), SFM_READ, &mSfInfo);
if(!mSndfile)
{
fprintf(stderr, "Could not open audio in %s: %s\n", filename, sf_strerror(mSndfile));
fprintf(stderr, "Could not open audio in %s: %s\n", filename.c_str(),
sf_strerror(mSndfile));
return false;
}
@ -166,8 +174,8 @@ struct StreamPlayer {
mSampleFormat = SampleType::Int16;
else
{
auto fmtbuf = std::make_unique<ALubyte[]>(inf.datalen);
inf.data = fmtbuf.get();
auto fmtbuf = std::vector<ALubyte>(inf.datalen);
inf.data = fmtbuf.data();
if(sf_get_chunk_data(iter, &inf) != SF_ERR_NO_ERROR)
mSampleFormat = SampleType::Int16;
else
@ -194,12 +202,12 @@ struct StreamPlayer {
if(mSampleFormat == SampleType::Int16)
{
mSamplesPerBlock = 1;
mBytesPerBlock = static_cast<size_t>(mSfInfo.channels * 2);
mBytesPerBlock = static_cast<size_t>(mSfInfo.channels) * 2;
}
else if(mSampleFormat == SampleType::Float)
{
mSamplesPerBlock = 1;
mBytesPerBlock = static_cast<size_t>(mSfInfo.channels * 4);
mBytesPerBlock = static_cast<size_t>(mSfInfo.channels) * 4;
}
else
{
@ -232,7 +240,7 @@ struct StreamPlayer {
}
else if(mSfInfo.channels == 3)
{
if(sf_command(mSndfile, SFC_WAVEX_GET_AMBISONIC, NULL, 0) == SF_AMBISONIC_B_FORMAT)
if(sf_command(mSndfile, SFC_WAVEX_GET_AMBISONIC, nullptr, 0) == SF_AMBISONIC_B_FORMAT)
{
if(mSampleFormat == SampleType::Int16)
mFormat = AL_FORMAT_BFORMAT2D_16;
@ -242,7 +250,7 @@ struct StreamPlayer {
}
else if(mSfInfo.channels == 4)
{
if(sf_command(mSndfile, SFC_WAVEX_GET_AMBISONIC, NULL, 0) == SF_AMBISONIC_B_FORMAT)
if(sf_command(mSndfile, SFC_WAVEX_GET_AMBISONIC, nullptr, 0) == SF_AMBISONIC_B_FORMAT)
{
if(mSampleFormat == SampleType::Int16)
mFormat = AL_FORMAT_BFORMAT3D_16;
@ -262,8 +270,7 @@ struct StreamPlayer {
/* 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]);
mBufferData.resize(static_cast<ALuint>(numblocks * mBytesPerBlock));
mReadPos.store(0, std::memory_order_relaxed);
mWritePos.store(0, std::memory_order_relaxed);
mDecoderOffset = 0;
@ -276,10 +283,11 @@ struct StreamPlayer {
* 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)
static ALsizei AL_APIENTRY bufferCallbackC(void *userptr, void *data, ALsizei size) noexcept
{ return static_cast<StreamPlayer*>(userptr)->bufferCallback(data, size); }
ALsizei bufferCallback(void *data, ALsizei size)
ALsizei bufferCallback(void *data, ALsizei size) noexcept
{
auto dst = al::span{static_cast<std::byte*>(data), static_cast<ALuint>(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
@ -290,7 +298,7 @@ struct StreamPlayer {
ALsizei got{0};
size_t roffset{mReadPos.load(std::memory_order_acquire)};
while(got < size)
while(!dst.empty())
{
/* If the write offset == read offset, there's nothing left in the
* ring-buffer. Break from the loop and give what has been written.
@ -303,19 +311,19 @@ struct StreamPlayer {
* 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));
size_t todo{((woffset < roffset) ? mBufferData.size() : woffset) - roffset};
todo = std::min(todo, dst.size());
/* 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;
std::copy_n(mBufferData.cbegin()+ptrdiff_t(roffset), todo, dst.begin());
dst = dst.subspan(todo);
got += static_cast<ALsizei>(todo);
roffset += todo;
if(roffset == mBufferDataSize)
if(roffset == mBufferData.size())
roffset = 0;
}
/* Finally, store the updated read offset, and return how many bytes
@ -351,7 +359,7 @@ struct StreamPlayer {
if(state != AL_INITIAL)
{
const size_t roffset{mReadPos.load(std::memory_order_relaxed)};
const size_t readable{((woffset >= roffset) ? woffset : (mBufferDataSize+woffset)) -
const size_t readable{((woffset >= roffset) ? woffset : (mBufferData.size()+woffset)) -
roffset};
/* For a stopped (underrun) source, the current playback offset is
* the current decoder offset excluding the readable buffered data.
@ -362,7 +370,7 @@ struct StreamPlayer {
? (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);
printf("\r%3zus (%3zu%% full)", curtime, readable * 100 / mBufferData.size());
}
else
fputs("Starting...", stdout);
@ -415,8 +423,8 @@ struct StreamPlayer {
* data can fit, and calculate how much can go in front before
* wrapping.
*/
const size_t writable{(!roffset ? mBufferDataSize-woffset-1 :
(mBufferDataSize-woffset)) / mBytesPerBlock};
const size_t writable{(!roffset ? mBufferData.size()-woffset-1 :
(mBufferData.size()-woffset)) / mBytesPerBlock};
if(!writable) break;
if(mSampleFormat == SampleType::Int16)
@ -444,7 +452,7 @@ struct StreamPlayer {
}
woffset += read_bytes;
if(woffset == mBufferDataSize)
if(woffset == mBufferData.size())
woffset = 0;
}
mWritePos.store(woffset, std::memory_order_release);
@ -459,7 +467,7 @@ struct StreamPlayer {
* what's available.
*/
const size_t roffset{mReadPos.load(std::memory_order_relaxed)};
const size_t readable{((woffset >= roffset) ? woffset : (mBufferDataSize+woffset)) -
const size_t readable{((woffset >= roffset) ? woffset : (mBufferData.size()+woffset)) -
roffset};
if(readable == 0)
return false;
@ -476,29 +484,28 @@ struct StreamPlayer {
}
};
} // namespace
int main(int argc, char **argv)
int main(al::span<std::string_view> args)
{
/* A simple RAII container for OpenAL startup and shutdown. */
struct AudioManager {
AudioManager(char ***argv_, int *argc_)
AudioManager(al::span<std::string_view> &args_)
{
if(InitAL(argv_, argc_) != 0)
if(InitAL(args_) != 0)
throw std::runtime_error{"Failed to initialize OpenAL"};
}
~AudioManager() { CloseAL(); }
};
/* Print out usage if no arguments were specified */
if(argc < 2)
if(args.size() < 2)
{
fprintf(stderr, "Usage: %s [-device <name>] <filenames...>\n", argv[0]);
fprintf(stderr, "Usage: %.*s [-device <name>] <filenames...>\n", al::sizei(args[0]),
args[0].data());
return 1;
}
argv++; argc--;
AudioManager almgr{&argv, &argc};
args = args.subspan(1);
AudioManager almgr{args};
if(!alIsExtensionPresent("AL_SOFT_callback_buffer"))
{
@ -512,23 +519,23 @@ int main(int argc, char **argv)
ALCint refresh{25};
alcGetIntegerv(alcGetContextsDevice(alcGetCurrentContext()), ALC_REFRESH, 1, &refresh);
std::unique_ptr<StreamPlayer> player{new StreamPlayer{}};
auto player = std::make_unique<StreamPlayer>();
/* Play each file listed on the command line */
for(int i{0};i < argc;++i)
for(size_t i{0};i < args.size();++i)
{
if(!player->open(argv[i]))
if(!player->open(std::string{args[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];
auto namepart = args[i];
if(auto sep = namepart.rfind('/'); sep < namepart.size())
namepart = namepart.substr(sep+1);
else if(sep = namepart.rfind('\\'); sep < namepart.size())
namepart = namepart.substr(sep+1);
printf("Playing: %s (%s, %dhz)\n", namepart, FormatName(player->mFormat),
player->mSfInfo.samplerate);
printf("Playing: %.*s (%s, %dhz)\n", al::sizei(namepart), namepart.data(),
FormatName(player->mFormat), player->mSfInfo.samplerate);
fflush(stdout);
if(!player->prepare())
@ -549,3 +556,13 @@ int main(int argc, char **argv)
return 0;
}
} // namespace
int main(int argc, char **argv)
{
assert(argc >= 0);
auto args = std::vector<std::string_view>(static_cast<unsigned int>(argc));
std::copy_n(argv, args.size(), args.begin());
return main(al::span{args});
}

View file

@ -79,63 +79,72 @@ static inline ALuint dither_rng(ALuint *seed)
return *seed;
}
static void ApplySin(ALfloat *data, ALdouble g, ALuint srate, ALuint freq)
static void ApplySin(ALfloat *data, ALuint length, ALdouble g, ALuint srate, ALuint freq)
{
ALdouble smps_per_cycle = (ALdouble)srate / freq;
ALdouble cycles_per_sample = (ALdouble)freq / srate;
ALuint i;
for(i = 0;i < srate;i++)
for(i = 0;i < length;i++)
{
ALdouble ival;
data[i] += (ALfloat)(sin(modf(i/smps_per_cycle, &ival) * 2.0*M_PI) * g);
data[i] += (ALfloat)(sin(modf(i*cycles_per_sample, &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)
static ALuint CreateWave(enum WaveType type, ALuint seconds, ALuint freq, ALuint srate,
ALfloat gain)
{
ALuint seed = 22222;
ALuint num_samples;
ALuint data_size;
ALfloat *data;
ALuint buffer;
ALenum err;
ALuint i;
data_size = (ALuint)(srate * sizeof(ALfloat));
if(seconds > INT_MAX / srate / sizeof(ALfloat))
{
fprintf(stderr, "Too many seconds: %u * %u * %zu > %d\n", seconds, srate, sizeof(ALfloat),
INT_MAX);
return 0;
}
num_samples = seconds * srate;
data_size = (ALuint)(num_samples * sizeof(ALfloat));
data = calloc(1, data_size);
switch(type)
{
case WT_Sine:
ApplySin(data, 1.0, srate, freq);
ApplySin(data, num_samples, 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);
ApplySin(data, num_samples, 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);
ApplySin(data, num_samples, 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);
ApplySin(data, num_samples, 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).
* instead just a non-0 sample. This can be useful to test (other
* than resampling, the ALSOFT_DEFAULT_REVERB environment variable
* can test the reverb response).
*/
for(i = 0;i < srate;i++)
data[i] = (i%(srate/freq)) ? 0.0f : 1.0f;
data[0] = 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++)
for(i = 0;i < num_samples;i++)
{
ALuint rng0 = dither_rng(&seed);
ALuint rng1 = dither_rng(&seed);
@ -146,7 +155,7 @@ static ALuint CreateWave(enum WaveType type, ALuint freq, ALuint srate, ALfloat
if(gain != 1.0f)
{
for(i = 0;i < srate;i++)
for(i = 0;i < num_samples;i++)
data[i] *= gain;
}
@ -156,7 +165,7 @@ static ALuint CreateWave(enum WaveType type, ALuint freq, ALuint srate, ALfloat
alBufferData(buffer, AL_FORMAT_MONO_FLOAT32, data, (ALsizei)data_size, (ALsizei)srate);
free(data);
/* Check if an error occured, and clean up if so. */
/* Check if an error occurred, and clean up if so. */
err = alGetError();
if(err != AL_NO_ERROR)
{
@ -175,8 +184,8 @@ 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 last_pos;
ALint seconds = 4;
ALint srate = -1;
ALint tone_freq = 1000;
ALCint dev_rate;
@ -217,10 +226,13 @@ int main(int argc, char *argv[])
CloseAL();
return 1;
}
else if(i+1 < argc && strcmp(argv[i], "-t") == 0)
if(i+1 < argc && strcmp(argv[i], "-t") == 0)
{
i++;
max_loops = atoi(argv[i]) - 1;
seconds = atoi(argv[i]);
if(seconds <= 0)
seconds = 4;
}
else if(i+1 < argc && (strcmp(argv[i], "--waveform") == 0 || strcmp(argv[i], "-w") == 0))
{
@ -281,7 +293,7 @@ int main(int argc, char *argv[])
srate = dev_rate;
/* Load the sound into a buffer. */
buffer = CreateWave(wavetype, (ALuint)tone_freq, (ALuint)srate, gain);
buffer = CreateWave(wavetype, (ALuint)seconds, (ALuint)tone_freq, (ALuint)srate, gain);
if(!buffer)
{
CloseAL();
@ -289,7 +301,7 @@ int main(int argc, char *argv[])
}
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":"");
tone_freq, GetWaveTypeName(wavetype), srate, dev_rate, seconds, (seconds!=1)?"s":"");
fflush(stdout);
/* Create the source to play the sound with. */
@ -299,21 +311,18 @@ int main(int argc, char *argv[])
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);
last_pos = -1;
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)
alGetSourcei(source, AL_SAMPLE_OFFSET, &pos);
pos /= srate;
if(pos > last_pos)
{
++num_loops;
if(num_loops >= max_loops)
alSourcei(source, AL_LOOPING, AL_FALSE);
printf("%d...\n", max_loops - num_loops + 1);
printf("%d...\n", seconds - pos);
fflush(stdout);
}
last_pos = pos;

View file

@ -2,13 +2,14 @@
#define ALHELPERS_H
#include "AL/al.h"
#include "AL/alc.h"
#ifdef __cplusplus
extern "C" {
#endif
/* Some helper functions to get the name from the format enums. */
const char *FormatName(ALenum type);
const char *FormatName(ALenum format);
/* Easy device init/deinit functions. InitAL returns 0 on success. */
int InitAL(char ***argv, int *argc);
@ -33,6 +34,54 @@ void al_nssleep(unsigned long nsec);
#ifdef __cplusplus
} // extern "C"
#include <cstdio>
#include <iostream>
#include <string>
#include <string_view>
#include "alspan.h"
int InitAL(al::span<std::string_view> &args)
{
ALCdevice *device{};
/* Open and initialize a device */
if(args.size() > 1 && args[0] == "-device")
{
device = alcOpenDevice(std::string{args[1]}.c_str());
if(!device)
std::cerr<< "Failed to open \""<<args[1]<<"\", trying default\n";
args = args.subspan(2);
}
if(!device)
device = alcOpenDevice(nullptr);
if(!device)
{
std::fprintf(stderr, "Could not open a device!\n");
return 1;
}
ALCcontext *ctx{alcCreateContext(device, nullptr)};
if(!ctx || alcMakeContextCurrent(ctx) == ALC_FALSE)
{
if(ctx)
alcDestroyContext(ctx);
alcCloseDevice(device);
std::fprintf(stderr, "Could not set a context!\n");
return 1;
}
const ALCchar *name{};
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);
std::printf("Opened \"%s\"\n", name);
return 0;
}
#endif
#endif /* ALHELPERS_H */