update openal-soft to 1.24.3

keeping the alt 87514151c4 (diff-73a8dc1ce58605f6c5ea53548454c3bae516ec5132a29c9d7ff7edf9730c75be)
This commit is contained in:
AzaezelX 2025-09-03 11:09:27 -05:00
parent 12db0500e8
commit ba32094b7b
276 changed files with 49304 additions and 8712 deletions

View file

@ -0,0 +1,311 @@
/*
* OpenAL Debug 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 using the debug extension. */
#include <algorithm>
#include <array>
#include <cassert>
#include <cstdio>
#include <memory>
#include <string>
#include <string_view>
#include <vector>
#include "AL/al.h"
#include "AL/alc.h"
#include "AL/alext.h"
#include "alnumeric.h"
#include "alspan.h"
#include "fmt/core.h"
#include "win_main_utf8.h"
namespace {
using namespace std::string_view_literals;
struct DeviceCloser {
void operator()(ALCdevice *device) const noexcept { alcCloseDevice(device); }
};
using DevicePtr = std::unique_ptr<ALCdevice,DeviceCloser>;
struct ContextDestroyer {
void operator()(ALCcontext *context) const noexcept { alcDestroyContext(context); }
};
using ContextPtr = std::unique_ptr<ALCcontext,ContextDestroyer>;
constexpr auto GetDebugSourceName(ALenum source) noexcept -> std::string_view
{
switch(source)
{
case AL_DEBUG_SOURCE_API_EXT: return "API"sv;
case AL_DEBUG_SOURCE_AUDIO_SYSTEM_EXT: return "Audio System"sv;
case AL_DEBUG_SOURCE_THIRD_PARTY_EXT: return "Third Party"sv;
case AL_DEBUG_SOURCE_APPLICATION_EXT: return "Application"sv;
case AL_DEBUG_SOURCE_OTHER_EXT: return "Other"sv;
}
return "<invalid source>"sv;
}
constexpr auto GetDebugTypeName(ALenum type) noexcept -> std::string_view
{
switch(type)
{
case AL_DEBUG_TYPE_ERROR_EXT: return "Error"sv;
case AL_DEBUG_TYPE_DEPRECATED_BEHAVIOR_EXT: return "Deprecated Behavior"sv;
case AL_DEBUG_TYPE_UNDEFINED_BEHAVIOR_EXT: return "Undefined Behavior"sv;
case AL_DEBUG_TYPE_PORTABILITY_EXT: return "Portability"sv;
case AL_DEBUG_TYPE_PERFORMANCE_EXT: return "Performance"sv;
case AL_DEBUG_TYPE_MARKER_EXT: return "Marker"sv;
case AL_DEBUG_TYPE_PUSH_GROUP_EXT: return "Push Group"sv;
case AL_DEBUG_TYPE_POP_GROUP_EXT: return "Pop Group"sv;
case AL_DEBUG_TYPE_OTHER_EXT: return "Other"sv;
}
return "<invalid type>"sv;
}
constexpr auto GetDebugSeverityName(ALenum severity) noexcept -> std::string_view
{
switch(severity)
{
case AL_DEBUG_SEVERITY_HIGH_EXT: return "High"sv;
case AL_DEBUG_SEVERITY_MEDIUM_EXT: return "Medium"sv;
case AL_DEBUG_SEVERITY_LOW_EXT: return "Low"sv;
case AL_DEBUG_SEVERITY_NOTIFICATION_EXT: return "Notification"sv;
}
return "<invalid severity>"sv;
}
auto alDebugMessageCallbackEXT = LPALDEBUGMESSAGECALLBACKEXT{};
auto alDebugMessageInsertEXT = LPALDEBUGMESSAGEINSERTEXT{};
auto alDebugMessageControlEXT = LPALDEBUGMESSAGECONTROLEXT{};
auto alPushDebugGroupEXT = LPALPUSHDEBUGGROUPEXT{};
auto alPopDebugGroupEXT = LPALPOPDEBUGGROUPEXT{};
auto alGetDebugMessageLogEXT = LPALGETDEBUGMESSAGELOGEXT{};
auto alObjectLabelEXT = LPALOBJECTLABELEXT{};
auto alGetObjectLabelEXT = LPALGETOBJECTLABELEXT{};
auto alGetPointerEXT = LPALGETPOINTEREXT{};
auto alGetPointervEXT = LPALGETPOINTERVEXT{};
int main(al::span<std::string_view> args)
{
/* Print out usage if -h was specified */
if(args.size() > 1 && (args[1] == "-h" || args[1] == "--help"))
{
fmt::println(stderr, "Usage: {} [-device <name>] [-nodebug]", args[0]);
return 1;
}
/* Initialize OpenAL. */
args = args.subspan(1);
auto device = DevicePtr{};
if(args.size() > 1 && args[0] == "-device")
{
device = DevicePtr{alcOpenDevice(std::string{args[1]}.c_str())};
if(!device)
fmt::println(stderr, "Failed to open \"{}\", trying default", args[1]);
args = args.subspan(2);
}
if(!device)
device = DevicePtr{alcOpenDevice(nullptr)};
if(!device)
{
fmt::println(stderr, "Could not open a device!");
return 1;
}
if(!alcIsExtensionPresent(device.get(), "ALC_EXT_debug"))
{
fmt::println(stderr, "ALC_EXT_debug not supported on device");
return 1;
}
/* Load the Debug API functions we're using. */
#define LOAD_PROC(N) N = reinterpret_cast<decltype(N)>(alcGetProcAddress(device.get(), #N))
LOAD_PROC(alDebugMessageCallbackEXT);
LOAD_PROC(alDebugMessageInsertEXT);
LOAD_PROC(alDebugMessageControlEXT);
LOAD_PROC(alPushDebugGroupEXT);
LOAD_PROC(alPopDebugGroupEXT);
LOAD_PROC(alGetDebugMessageLogEXT);
LOAD_PROC(alObjectLabelEXT);
LOAD_PROC(alGetObjectLabelEXT);
LOAD_PROC(alGetPointerEXT);
LOAD_PROC(alGetPointervEXT);
#undef LOAD_PROC
/* Create a debug context and set it as current. If -nodebug was specified,
* create a non-debug context (to see how debug messages react).
*/
auto flags = ALCint{ALC_CONTEXT_DEBUG_BIT_EXT};
if(!args.empty() && args[0] == "-nodebug")
flags &= ~ALC_CONTEXT_DEBUG_BIT_EXT;
const auto attribs = std::array<ALCint,3>{{
ALC_CONTEXT_FLAGS_EXT, flags,
0 /* end-of-list */
}};
auto context = ContextPtr{alcCreateContext(device.get(), attribs.data())};
if(!context || alcMakeContextCurrent(context.get()) == ALC_FALSE)
{
fmt::println(stderr, "Could not create and set a context!");
return 1;
}
/* Enable low-severity debug messages, which are disabled by default. */
alDebugMessageControlEXT(AL_DONT_CARE_EXT, AL_DONT_CARE_EXT, AL_DEBUG_SEVERITY_LOW_EXT, 0,
nullptr, AL_TRUE);
fmt::println("Context flags: {:#010x}", as_unsigned(alGetInteger(AL_CONTEXT_FLAGS_EXT)));
/* A debug context has debug output enabled by default. But in case this
* isn't a debug context, explicitly enable it (probably won't get much, if
* anything, in that case).
*/
fmt::println("Default debug state is: {}",
alIsEnabled(AL_DEBUG_OUTPUT_EXT) ? "enabled"sv : "disabled"sv);
alEnable(AL_DEBUG_OUTPUT_EXT);
/* The max debug message length property will allow us to define message
* storage of sufficient length. This includes space for the null
* terminator.
*/
const auto maxloglength = alGetInteger(AL_MAX_DEBUG_MESSAGE_LENGTH_EXT);
fmt::println("Max debug message length: {}", maxloglength);
fmt::println("");
/* Doppler Velocity is deprecated since AL 1.1, so this should generate a
* deprecation debug message. We'll first handle debug messages through the
* message log, meaning we'll query for and read it afterward.
*/
fmt::println("Calling alDopplerVelocity(0.5f)...");
alDopplerVelocity(0.5f);
for(auto numlogs = alGetInteger(AL_DEBUG_LOGGED_MESSAGES_EXT);numlogs > 0;--numlogs)
{
auto message = std::vector<char>(static_cast<ALuint>(maxloglength), '\0');
auto source = ALenum{};
auto type = ALenum{};
auto id = ALuint{};
auto severity = ALenum{};
auto msglength = ALsizei{};
/* Getting the message removes it from the log. */
const auto read = alGetDebugMessageLogEXT(1, maxloglength, &source, &type, &id, &severity,
&msglength, message.data());
if(read != 1)
{
fmt::println(stderr, "Read {} debug messages, expected to read 1", read);
break;
}
/* The message lengths returned by alGetDebugMessageLogEXT include the
* null terminator, so subtract one for the string_view length. If we
* read more than one message at a time, the length could be used as
* the offset to the next message.
*/
const auto msgstr = std::string_view{message.data(),
static_cast<ALuint>(msglength ? msglength-1 : 0)};
fmt::println("Got message from log:\n"
" Source: {}\n"
" Type: {}\n"
" ID: {}\n"
" Severity: {}\n"
" Message: \"{}\"", GetDebugSourceName(source), GetDebugTypeName(type), id,
GetDebugSeverityName(severity), msgstr);
}
fmt::println("");
/* Now set up a callback function. This lets us print the debug messages as
* they happen without having to explicitly query and get them.
*/
static constexpr auto debug_callback = [](ALenum source, ALenum type, ALuint id,
ALenum severity, ALsizei length, const ALchar *message, void *userParam [[maybe_unused]])
noexcept -> void
{
/* The message length provided to the callback does not include the
* null terminator.
*/
const auto msgstr = std::string_view{message, static_cast<ALuint>(length)};
fmt::println("Got message from callback:\n"
" Source: {}\n"
" Type: {}\n"
" ID: {}\n"
" Severity: {}\n"
" Message: \"{}\"", GetDebugSourceName(source), GetDebugTypeName(type), id,
GetDebugSeverityName(severity), msgstr);
};
alDebugMessageCallbackEXT(debug_callback, nullptr);
if(const auto numlogs = alGetInteger(AL_DEBUG_LOGGED_MESSAGES_EXT))
fmt::println(stderr, "{} left over logged message{}!", numlogs, (numlogs==1)?"":"s");
/* This should also generate a deprecation debug message, which will now go
* through the callback.
*/
fmt::println("Calling alGetInteger(AL_DOPPLER_VELOCITY)...");
auto dv [[maybe_unused]] = alGetInteger(AL_DOPPLER_VELOCITY);
fmt::println("");
/* These functions are notoriously unreliable for their behavior, they will
* likely generate portability debug messages.
*/
fmt::println("Calling alcSuspendContext and alcProcessContext...");
alcSuspendContext(context.get());
alcProcessContext(context.get());
fputs("\n", stdout);
fmt::println("Pushing a debug group, making some invalid calls, and popping the debug group...");
alPushDebugGroupEXT(AL_DEBUG_SOURCE_APPLICATION_EXT, 0, -1, "Error test group");
alSpeedOfSound(0.0f);
/* Can't set the label of the null buffer. */
alObjectLabelEXT(AL_BUFFER, 0, -1, "The null buffer");
alPopDebugGroupEXT();
fmt::println("");
/* All done, insert a custom message and unset the callback. The context
* and device will clean themselves up.
*/
alDebugMessageInsertEXT(AL_DEBUG_SOURCE_APPLICATION_EXT, AL_DEBUG_TYPE_MARKER_EXT, 0,
AL_DEBUG_SEVERITY_NOTIFICATION_EXT, -1, "End of run, cleaning up");
alDebugMessageCallbackEXT(nullptr, nullptr);
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

@ -30,7 +30,6 @@
#include <cassert>
#include <cstddef>
#include <cstdio>
#include <iostream>
#include <limits>
#include <memory>
#include <string>
@ -45,6 +44,7 @@
#include "alspan.h"
#include "common/alhelpers.h"
#include "fmt/core.h"
#include "win_main_utf8.h"
@ -102,12 +102,13 @@ ALuint LoadSound(ALCcontext *context, const std::string_view filename)
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";
fmt::println(stderr, "Could not open audio in {}: {}", filename,
sf_strerror(sndfile.get()));
return 0;
}
if(sfinfo.frames < 1)
{
std::cerr<< "Bad sample count in "<<filename<<" ("<<sfinfo.frames<<")\n";
fmt::println(stderr, "Bad sample count in {} ({})", filename, sfinfo.frames);
return 0;
}
@ -255,13 +256,13 @@ ALuint LoadSound(ALCcontext *context, const std::string_view filename)
}
if(!format)
{
std::cerr<< "Unsupported channel count: "<<sfinfo.channels<<"\n";
fmt::println(stderr, "Unsupported channel count: {}", sfinfo.channels);
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";
fmt::println(stderr, "Too many sample frames in {} ({})", filename, sfinfo.frames);
return 0;
}
@ -285,14 +286,13 @@ ALuint LoadSound(ALCcontext *context, const std::string_view filename)
}
if(num_frames < 1)
{
std::cerr<< "Failed to read samples in "<<filename<<" ("<<num_frames<<")\n";
fmt::println(stderr, "Failed to read samples in {} ({})", filename, num_frames);
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;
fmt::println("Loading: {} ({}, {}hz)", filename, FormatName(format), sfinfo.samplerate);
ALuint buffer{};
alGenBuffersDirect(context, 1, &buffer);
@ -303,7 +303,7 @@ ALuint LoadSound(ALCcontext *context, const std::string_view filename)
/* 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";
fmt::println(stderr, "OpenAL Error: {}", alGetStringDirect(context, err));
if(buffer && alIsBufferDirect(context, buffer))
alDeleteBuffersDirect(context, 1, &buffer);
return 0;
@ -318,7 +318,7 @@ 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";
fmt::println(stderr, "Usage: {} [-device <name>] <filename>", args[0]);
return 1;
}
@ -330,20 +330,20 @@ int main(al::span<std::string_view> args)
{
device = p_alcOpenDevice(std::string{args[1]}.c_str());
if(!device)
std::cerr<< "Failed to open \""<<args[1]<<"\", trying default\n";
fmt::println(stderr, "Failed to open \"{}\", trying default", args[1]);
args = args.subspan(2);
}
if(!device)
device = p_alcOpenDevice(nullptr);
if(!device)
{
std::cerr<< "Could not open a device!\n";
fmt::println(stderr, "Could not open a device!");
return 1;
}
if(!p_alcIsExtensionPresent(device, "ALC_EXT_direct_context"))
{
std::cerr<< "ALC_EXT_direct_context not supported on device\n";
fmt::println(stderr, "ALC_EXT_direct_context not supported on device");
p_alcCloseDevice(device);
return 1;
}
@ -417,7 +417,7 @@ int main(al::span<std::string_view> args)
if(!context)
{
p_alcCloseDevice(device);
std::cerr<< "Could not create a context!\n";
fmt::println(stderr, "Could not create a context!");
return 1;
}
@ -446,10 +446,10 @@ int main(al::span<std::string_view> args)
/* Get the source offset. */
ALfloat offset{};
alGetSourcefDirect(context, source, AL_SEC_OFFSET, &offset);
printf("\rOffset: %f ", offset);
fmt::print(" \rOffset: {:.02f}", offset);
fflush(stdout);
} while(alGetErrorDirect(context) == AL_NO_ERROR && state == AL_PLAYING);
printf("\n");
fmt::println("");
/* All done. Delete resources, and close down OpenAL. */
alDeleteSourcesDirect(context, 1, &source);

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -29,13 +29,14 @@
#include <assert.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SDL_MAIN_HANDLED
#include "SDL.h"
#include "SDL_audio.h"
#include "SDL_error.h"
#include "SDL_stdinc.h"
#include "SDL3/SDL_audio.h"
#include "SDL3/SDL_error.h"
#include "SDL3/SDL_main.h"
#include "SDL3/SDL_stdinc.h"
#include "AL/al.h"
#include "AL/alc.h"
@ -43,13 +44,6 @@
#include "common/alhelpers.h"
#ifndef SDL_AUDIO_MASK_BITSIZE
#define SDL_AUDIO_MASK_BITSIZE (0xFF)
#endif
#ifndef SDL_AUDIO_BITSIZE
#define SDL_AUDIO_BITSIZE(x) (x & SDL_AUDIO_MASK_BITSIZE)
#endif
#ifndef M_PI
#define M_PI (3.14159265358979323846)
#endif
@ -59,6 +53,8 @@ typedef struct {
ALCcontext *Context;
ALCsizei FrameSize;
void *Buffer;
int BufferSize;
} PlaybackInfo;
static LPALCLOOPBACKOPENDEVICESOFT alcLoopbackOpenDeviceSOFT;
@ -66,10 +62,26 @@ static LPALCISRENDERFORMATSUPPORTEDSOFT alcIsRenderFormatSupportedSOFT;
static LPALCRENDERSAMPLESSOFT alcRenderSamplesSOFT;
void SDLCALL RenderSDLSamples(void *userdata, Uint8 *stream, int len)
void SDLCALL RenderSDLSamples(void *userdata, SDL_AudioStream *stream, int additional_amount,
int total_amount)
{
PlaybackInfo *playback = (PlaybackInfo*)userdata;
alcRenderSamplesSOFT(playback->Device, stream, len/playback->FrameSize);
if(additional_amount < 0)
additional_amount = total_amount;
if(additional_amount <= 0)
return;
if(additional_amount > playback->BufferSize)
{
free(playback->Buffer);
playback->Buffer = malloc((unsigned int)additional_amount);
playback->BufferSize = additional_amount;
}
alcRenderSamplesSOFT(playback->Device, playback->Buffer,
additional_amount/playback->FrameSize);
SDL_PutAudioStreamData(stream, playback->Buffer, additional_amount);
}
@ -135,8 +147,9 @@ static ALuint CreateSineWave(void)
int main(int argc, char *argv[])
{
PlaybackInfo playback = { NULL, NULL, 0 };
SDL_AudioSpec desired, obtained;
PlaybackInfo playback = { NULL, NULL, 0, NULL, 0 };
SDL_AudioStream *stream = NULL;
SDL_AudioSpec obtained;
ALuint source, buffer;
ALCint attrs[16];
ALenum state;
@ -159,25 +172,25 @@ int main(int argc, char *argv[])
LOAD_PROC(LPALCRENDERSAMPLESSOFT, alcRenderSamplesSOFT);
#undef LOAD_PROC
if(SDL_Init(SDL_INIT_AUDIO) == -1)
if(!SDL_Init(SDL_INIT_AUDIO))
{
fprintf(stderr, "Failed to init SDL audio: %s\n", SDL_GetError());
return 1;
}
/* Set up SDL audio with our requested format and callback. */
desired.channels = 2;
desired.format = AUDIO_S16SYS;
desired.freq = 44100;
desired.padding = 0;
desired.samples = 4096;
desired.callback = RenderSDLSamples;
desired.userdata = &playback;
if(SDL_OpenAudio(&desired, &obtained) != 0)
/* Set up SDL audio with our callback, and get the stream format. */
stream = SDL_OpenAudioDeviceStream(SDL_AUDIO_DEVICE_DEFAULT_PLAYBACK, NULL, RenderSDLSamples,
&playback);
if(!stream)
{
SDL_Quit();
fprintf(stderr, "Failed to open SDL audio: %s\n", SDL_GetError());
return 1;
goto error;
}
if(!SDL_GetAudioStreamFormat(stream, &obtained, NULL))
{
fprintf(stderr, "Failed to query SDL audio format: %s\n", SDL_GetError());
goto error;
}
/* Set up our OpenAL attributes based on what we got from SDL. */
@ -186,6 +199,14 @@ int main(int argc, char *argv[])
attrs[1] = ALC_MONO_SOFT;
else if(obtained.channels == 2)
attrs[1] = ALC_STEREO_SOFT;
else if(obtained.channels == 4)
attrs[1] = ALC_QUAD_SOFT;
else if(obtained.channels == 6)
attrs[1] = ALC_5POINT1_SOFT;
else if(obtained.channels == 7)
attrs[1] = ALC_6POINT1_SOFT;
else if(obtained.channels == 8)
attrs[1] = ALC_7POINT1_SOFT;
else
{
fprintf(stderr, "Unhandled SDL channel count: %d\n", obtained.channels);
@ -193,17 +214,15 @@ int main(int argc, char *argv[])
}
attrs[2] = ALC_FORMAT_TYPE_SOFT;
if(obtained.format == AUDIO_U8)
if(obtained.format == SDL_AUDIO_U8)
attrs[3] = ALC_UNSIGNED_BYTE_SOFT;
else if(obtained.format == AUDIO_S8)
else if(obtained.format == SDL_AUDIO_S8)
attrs[3] = ALC_BYTE_SOFT;
else if(obtained.format == AUDIO_U16SYS)
attrs[3] = ALC_UNSIGNED_SHORT_SOFT;
else if(obtained.format == AUDIO_S16SYS)
else if(obtained.format == SDL_AUDIO_S16)
attrs[3] = ALC_SHORT_SOFT;
else if(obtained.format == AUDIO_S32SYS)
else if(obtained.format == SDL_AUDIO_S32)
attrs[3] = ALC_INT_SOFT;
else if(obtained.format == AUDIO_F32SYS)
else if(obtained.format == SDL_AUDIO_F32)
attrs[3] = ALC_FLOAT_SOFT;
else
{
@ -216,7 +235,7 @@ int main(int argc, char *argv[])
attrs[6] = 0; /* end of list */
playback.FrameSize = obtained.channels * SDL_AUDIO_BITSIZE(obtained.format) / 8;
playback.FrameSize = obtained.channels * (int)SDL_AUDIO_BITSIZE(obtained.format) / 8;
/* Initialize OpenAL loopback device, using our format attributes. */
playback.Device = alcLoopbackOpenDeviceSOFT(NULL);
@ -229,7 +248,7 @@ int main(int argc, char *argv[])
if(alcIsRenderFormatSupportedSOFT(playback.Device, attrs[5], attrs[1], attrs[3]) == ALC_FALSE)
{
fprintf(stderr, "Render format not supported: %s, %s, %dhz\n",
ChannelsName(attrs[1]), TypeName(attrs[3]), attrs[5]);
ChannelsName(attrs[1]), TypeName(attrs[3]), attrs[5]);
goto error;
}
playback.Context = alcCreateContext(playback.Device, attrs);
@ -239,20 +258,18 @@ int main(int argc, char *argv[])
goto error;
}
printf("Got render format from SDL stream: %s, %s, %dhz\n", ChannelsName(attrs[1]),
TypeName(attrs[3]), attrs[5]);
/* Start SDL playing. Our callback (thus alcRenderSamplesSOFT) will now
* start being called regularly to update the AL playback state. */
SDL_PauseAudio(0);
* start being called regularly to update the AL playback state.
*/
SDL_ResumeAudioStreamDevice(stream);
/* Load the sound into a buffer. */
buffer = CreateSineWave();
if(!buffer)
{
SDL_CloseAudio();
alcDestroyContext(playback.Context);
alcCloseDevice(playback.Device);
SDL_Quit();
return 1;
}
goto error;
/* Create the source to play the sound with. */
source = 0;
@ -272,23 +289,25 @@ int main(int argc, char *argv[])
alDeleteBuffers(1, &buffer);
/* Stop SDL playing. */
SDL_PauseAudio(1);
SDL_PauseAudioStreamDevice(stream);
/* Close up OpenAL and SDL. */
SDL_CloseAudio();
SDL_DestroyAudioStream(stream);
alcDestroyContext(playback.Context);
alcCloseDevice(playback.Device);
SDL_Quit();
SDL_QuitSubSystem(SDL_INIT_AUDIO);
return 0;
error:
SDL_CloseAudio();
if(stream)
SDL_DestroyAudioStream(stream);
if(playback.Context)
alcDestroyContext(playback.Context);
if(playback.Device)
alcCloseDevice(playback.Device);
SDL_Quit();
SDL_QuitSubSystem(SDL_INIT_AUDIO);
return 1;
}

View file

@ -46,9 +46,10 @@
#include "AL/alc.h"
#include "AL/alext.h"
#include "alnumeric.h"
#include "alspan.h"
#include "alstring.h"
#include "common/alhelpers.h"
#include "fmt/core.h"
#include "win_main_utf8.h"
@ -129,7 +130,7 @@ struct StreamPlayer {
mSndfile = sf_open(filename.c_str(), SFM_READ, &mSfInfo);
if(!mSndfile)
{
fprintf(stderr, "Could not open audio in %s: %s\n", filename.c_str(),
fmt::println(stderr, "Could not open audio in {}: {}", filename,
sf_strerror(mSndfile));
return false;
}
@ -260,7 +261,7 @@ struct StreamPlayer {
}
if(!mFormat)
{
fprintf(stderr, "Unsupported channel count: %d\n", mSfInfo.channels);
fmt::println(stderr, "Unsupported channel count: {}", mSfInfo.channels);
sf_close(mSndfile);
mSndfile = nullptr;
@ -287,7 +288,9 @@ struct StreamPlayer {
{ return static_cast<StreamPlayer*>(userptr)->bufferCallback(data, size); }
ALsizei bufferCallback(void *data, ALsizei size) noexcept
{
auto dst = al::span{static_cast<std::byte*>(data), static_cast<ALuint>(size)};
const auto output = al::span{static_cast<std::byte*>(data), static_cast<ALuint>(size)};
auto dst = output.begin();
/* 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
@ -295,10 +298,9 @@ struct StreamPlayer {
* 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(!dst.empty())
while(const auto remaining = static_cast<size_t>(std::distance(dst, output.end())))
{
/* If the write offset == read offset, there's nothing left in the
* ring-buffer. Break from the loop and give what has been written.
@ -312,15 +314,14 @@ struct StreamPlayer {
* amount to copy given how much is remaining to write.
*/
size_t todo{((woffset < roffset) ? mBufferData.size() : woffset) - roffset};
todo = std::min(todo, dst.size());
todo = std::min(todo, remaining);
/* Copy from the ring buffer to the provided output buffer. Wrap
* the resulting read offset if it reached the end of the ring-
* buffer.
*/
std::copy_n(mBufferData.cbegin()+ptrdiff_t(roffset), todo, dst.begin());
dst = dst.subspan(todo);
got += static_cast<ALsizei>(todo);
const auto input = al::span{mBufferData}.subspan(roffset, todo);
dst = std::copy_n(input.begin(), input.size(), dst);
roffset += todo;
if(roffset == mBufferData.size())
@ -331,7 +332,7 @@ struct StreamPlayer {
*/
mReadPos.store(roffset, std::memory_order_release);
return got;
return static_cast<ALsizei>(std::distance(output.begin(), dst));
}
bool prepare()
@ -342,7 +343,8 @@ struct StreamPlayer {
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);
fmt::println(stderr, "Failed to set callback: {} ({:#x})", alGetString(err),
as_unsigned(err));
return false;
}
return true;
@ -366,95 +368,72 @@ struct StreamPlayer {
* 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)
const auto curtime = ((state == AL_STOPPED)
? (mDecoderOffset-readable) / mBytesPerBlock * mSamplesPerBlock
: (static_cast<ALuint>(pos) + mStartOffset/mBytesPerBlock*mSamplesPerBlock))
/ static_cast<ALuint>(mSfInfo.samplerate)};
printf("\r%3zus (%3zu%% full)", curtime, readable * 100 / mBufferData.size());
: (size_t{static_cast<ALuint>(pos)} + mStartOffset))
/ static_cast<ALuint>(mSfInfo.samplerate);
fmt::print("\r {}m{:02}s ({:3}% full)", curtime/60, curtime%60,
readable * 100 / mBufferData.size());
}
else
fputs("Starting...", stdout);
fmt::println("Starting...");
fflush(stdout);
while(!sf_error(mSndfile))
{
size_t read_bytes;
const size_t roffset{mReadPos.load(std::memory_order_relaxed)};
if(roffset > woffset)
const auto roffset = mReadPos.load(std::memory_order_relaxed);
auto get_writable = [this,roffset,woffset]() noexcept -> size_t
{
/* Note that the ring buffer's writable space is one byte less
* than the available area because the write offset ending up
* at the read offset would be interpreted as being empty
* instead of full.
*/
const size_t writable{(roffset-woffset-1) / mBytesPerBlock};
if(!writable) break;
if(mSampleFormat == SampleType::Int16)
if(roffset > woffset)
{
sf_count_t num_frames{sf_readf_short(mSndfile,
reinterpret_cast<short*>(&mBufferData[woffset]),
static_cast<sf_count_t>(writable*mSamplesPerBlock))};
if(num_frames < 1) break;
read_bytes = static_cast<size_t>(num_frames) * mBytesPerBlock;
}
else if(mSampleFormat == SampleType::Float)
{
sf_count_t num_frames{sf_readf_float(mSndfile,
reinterpret_cast<float*>(&mBufferData[woffset]),
static_cast<sf_count_t>(writable*mSamplesPerBlock))};
if(num_frames < 1) break;
read_bytes = static_cast<size_t>(num_frames) * mBytesPerBlock;
}
else
{
sf_count_t numbytes{sf_read_raw(mSndfile, &mBufferData[woffset],
static_cast<sf_count_t>(writable*mBytesPerBlock))};
if(numbytes < 1) break;
read_bytes = static_cast<size_t>(numbytes);
/* 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.
*/
return roffset - woffset - 1;
}
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 ? mBufferData.size()-woffset-1 :
(mBufferData.size()-woffset)) / mBytesPerBlock};
if(!writable) break;
return mBufferData.size() - (!roffset ? woffset+1 : woffset);
};
if(mSampleFormat == SampleType::Int16)
{
sf_count_t num_frames{sf_readf_short(mSndfile,
reinterpret_cast<short*>(&mBufferData[woffset]),
static_cast<sf_count_t>(writable*mSamplesPerBlock))};
if(num_frames < 1) break;
read_bytes = static_cast<size_t>(num_frames) * mBytesPerBlock;
}
else if(mSampleFormat == SampleType::Float)
{
sf_count_t num_frames{sf_readf_float(mSndfile,
reinterpret_cast<float*>(&mBufferData[woffset]),
static_cast<sf_count_t>(writable*mSamplesPerBlock))};
if(num_frames < 1) break;
read_bytes = static_cast<size_t>(num_frames) * mBytesPerBlock;
}
else
{
sf_count_t numbytes{sf_read_raw(mSndfile, &mBufferData[woffset],
static_cast<sf_count_t>(writable*mBytesPerBlock))};
if(numbytes < 1) break;
read_bytes = static_cast<size_t>(numbytes);
}
const auto writable = get_writable() / mBytesPerBlock;
if(!writable) break;
woffset += read_bytes;
if(woffset == mBufferData.size())
woffset = 0;
auto read_bytes = size_t{};
if(mSampleFormat == SampleType::Int16)
{
const auto num_frames = sf_readf_short(mSndfile,
reinterpret_cast<short*>(&mBufferData[woffset]),
static_cast<sf_count_t>(writable*mSamplesPerBlock));
if(num_frames < 1) break;
read_bytes = static_cast<size_t>(num_frames) * mBytesPerBlock;
}
else if(mSampleFormat == SampleType::Float)
{
const auto num_frames = sf_readf_float(mSndfile,
reinterpret_cast<float*>(&mBufferData[woffset]),
static_cast<sf_count_t>(writable*mSamplesPerBlock));
if(num_frames < 1) break;
read_bytes = static_cast<size_t>(num_frames) * mBytesPerBlock;
}
else
{
const auto numbytes = sf_read_raw(mSndfile, &mBufferData[woffset],
static_cast<sf_count_t>(writable*mBytesPerBlock));
if(numbytes < 1) break;
read_bytes = static_cast<size_t>(numbytes);
}
woffset += read_bytes;
if(woffset == mBufferData.size())
woffset = 0;
mWritePos.store(woffset, std::memory_order_release);
mDecoderOffset += read_bytes;
}
@ -466,16 +445,16 @@ struct StreamPlayer {
* 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 : (mBufferData.size()+woffset)) -
roffset};
const auto roffset = mReadPos.load(std::memory_order_relaxed);
const auto readable = ((woffset < roffset) ? mBufferData.size()+woffset : 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;
mStartOffset = (mDecoderOffset-readable) / mBytesPerBlock * mSamplesPerBlock;
alSourcePlay(mSource);
if(alGetError() != AL_NO_ERROR)
return false;
@ -486,30 +465,28 @@ struct StreamPlayer {
int main(al::span<std::string_view> args)
{
/* A simple RAII container for OpenAL startup and shutdown. */
struct AudioManager {
AudioManager(al::span<std::string_view> &args_)
{
if(InitAL(args_) != 0)
throw std::runtime_error{"Failed to initialize OpenAL"};
}
~AudioManager() { CloseAL(); }
};
/* Print out usage if no arguments were specified */
if(args.size() < 2)
{
fprintf(stderr, "Usage: %.*s [-device <name>] <filenames...>\n", al::sizei(args[0]),
args[0].data());
fmt::println(stderr, "Usage: {} [-device <name>] <filenames...>", args[0]);
return 1;
}
args = args.subspan(1);
AudioManager almgr{args};
if(InitAL(args) != 0)
throw std::runtime_error{"Failed to initialize OpenAL"};
/* A simple RAII container for automating OpenAL shutdown. */
struct AudioManager {
AudioManager() = default;
AudioManager(const AudioManager&) = delete;
auto operator=(const AudioManager&) -> AudioManager& = delete;
~AudioManager() { CloseAL(); }
};
AudioManager almgr;
if(!alIsExtensionPresent("AL_SOFT_callback_buffer"))
{
fprintf(stderr, "AL_SOFT_callback_buffer extension not available\n");
fmt::println(stderr, "AL_SOFT_callback_buffer extension not available");
return 1;
}
@ -528,14 +505,11 @@ int main(al::span<std::string_view> args)
continue;
/* Get the name portion, without the path, for display. */
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);
const auto fpos = std::max(args[i].rfind('/')+1, args[i].rfind('\\')+1);
const auto namepart = args[i].substr(fpos);
printf("Playing: %.*s (%s, %dhz)\n", al::sizei(namepart), namepart.data(),
FormatName(player->mFormat), player->mSfInfo.samplerate);
fmt::println("Playing: {} ({}, {}hz)", namepart, FormatName(player->mFormat),
player->mSfInfo.samplerate);
fflush(stdout);
if(!player->prepare())
@ -552,7 +526,7 @@ int main(al::span<std::string_view> args)
player->close();
}
/* All done. */
printf("Done.\n");
fmt::println("Done.");
return 0;
}

View file

@ -185,9 +185,9 @@ int main(int argc, char *argv[])
const char *appname = argv[0];
ALuint source, buffer;
ALint last_pos;
ALint seconds = 4;
ALuint seconds = 4;
ALint srate = -1;
ALint tone_freq = 1000;
ALuint tone_freq = 1000;
ALCint dev_rate;
ALenum state;
ALfloat gain = 1.0f;
@ -229,9 +229,10 @@ int main(int argc, char *argv[])
if(i+1 < argc && strcmp(argv[i], "-t") == 0)
{
char *endptr = NULL;
i++;
seconds = atoi(argv[i]);
if(seconds <= 0)
seconds = (ALuint)strtoul(argv[i], &endptr, 0);
if(!endptr || *endptr != '\0' || seconds <= 0)
seconds = 4;
}
else if(i+1 < argc && (strcmp(argv[i], "--waveform") == 0 || strcmp(argv[i], "-w") == 0))
@ -254,9 +255,10 @@ int main(int argc, char *argv[])
}
else if(i+1 < argc && (strcmp(argv[i], "--freq") == 0 || strcmp(argv[i], "-f") == 0))
{
char *endptr = NULL;
i++;
tone_freq = atoi(argv[i]);
if(tone_freq < 1)
tone_freq = (ALuint)strtoul(argv[i], &endptr, 0);
if(!endptr || *endptr != '\0' || tone_freq < 1)
{
fprintf(stderr, "Invalid tone frequency: %s (min: 1hz)\n", argv[i]);
tone_freq = 1;
@ -264,9 +266,10 @@ int main(int argc, char *argv[])
}
else if(i+1 < argc && (strcmp(argv[i], "--gain") == 0 || strcmp(argv[i], "-g") == 0))
{
char *endptr = NULL;
i++;
gain = (ALfloat)atof(argv[i]);
if(gain < 0.0f || gain > 1.0f)
gain = strtof(argv[i], &endptr);
if(!endptr || *endptr != '\0' || gain < 0.0f || gain > 1.0f)
{
fprintf(stderr, "Invalid gain: %s (min: 0.0, max 1.0)\n", argv[i]);
gain = 1.0f;
@ -274,9 +277,10 @@ int main(int argc, char *argv[])
}
else if(i+1 < argc && (strcmp(argv[i], "--srate") == 0 || strcmp(argv[i], "-s") == 0))
{
char *endptr = NULL;
i++;
srate = atoi(argv[i]);
if(srate < 40)
srate = (ALint)strtol(argv[i], &endptr, 0);
if(!endptr || *endptr != '\0' || srate < 40)
{
fprintf(stderr, "Invalid sample rate: %s (min: 40hz)\n", argv[i]);
srate = 40;
@ -293,15 +297,15 @@ int main(int argc, char *argv[])
srate = dev_rate;
/* Load the sound into a buffer. */
buffer = CreateWave(wavetype, (ALuint)seconds, (ALuint)tone_freq, (ALuint)srate, gain);
buffer = CreateWave(wavetype, seconds, tone_freq, (ALuint)srate, gain);
if(!buffer)
{
CloseAL();
return 1;
}
printf("Playing %dhz %s-wave tone with %dhz sample rate and %dhz output, for %d second%s...\n",
tone_freq, GetWaveTypeName(wavetype), srate, dev_rate, seconds, (seconds!=1)?"s":"");
printf("Playing %uhz %s-wave tone with %dhz sample rate and %dhz output, for %u second%s...\n",
tone_freq, GetWaveTypeName(wavetype), srate, dev_rate, seconds, (seconds!=1)?"s":"");
fflush(stdout);
/* Create the source to play the sound with. */
@ -322,7 +326,7 @@ int main(int argc, char *argv[])
if(pos > last_pos)
{
printf("%d...\n", seconds - pos);
printf("%u...\n", seconds - (ALuint)pos);
fflush(stdout);
}
last_pos = pos;

View file

@ -24,7 +24,7 @@ void al_nssleep(unsigned long nsec);
* still needs to use a normal cast and live with the warning (C++ is fine with
* a regular reinterpret_cast).
*/
#if __STDC_VERSION__ >= 199901L
#if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L
#define FUNCTION_CAST(T, ptr) (union{void *p; T f;}){ptr}.f
#elif defined(__cplusplus)
#define FUNCTION_CAST(T, ptr) reinterpret_cast<T>(ptr)
@ -36,11 +36,11 @@ void al_nssleep(unsigned long nsec);
} // extern "C"
#include <cstdio>
#include <iostream>
#include <string>
#include <string_view>
#include "alspan.h"
#include "fmt/core.h"
int InitAL(al::span<std::string_view> &args)
{
@ -51,14 +51,14 @@ int InitAL(al::span<std::string_view> &args)
{
device = alcOpenDevice(std::string{args[1]}.c_str());
if(!device)
std::cerr<< "Failed to open \""<<args[1]<<"\", trying default\n";
fmt::println(stderr, "Failed to open \"{}\", trying default", args[1]);
args = args.subspan(2);
}
if(!device)
device = alcOpenDevice(nullptr);
if(!device)
{
std::fprintf(stderr, "Could not open a device!\n");
fmt::println(stderr, "Could not open a device!");
return 1;
}
@ -68,7 +68,7 @@ int InitAL(al::span<std::string_view> &args)
if(ctx)
alcDestroyContext(ctx);
alcCloseDevice(device);
std::fprintf(stderr, "Could not set a context!\n");
fmt::println(stderr, "Could not set a context!");
return 1;
}
@ -77,7 +77,7 @@ int InitAL(al::span<std::string_view> &args)
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);
fmt::println("Opened \"{}\"", name);
return 0;
}