mirror of
https://github.com/love2d/megasource.git
synced 2026-08-18 19:54:37 +02:00
update OpenAL-Soft to 1.24.3.
This commit is contained in:
@@ -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});
|
||||
}
|
||||
@@ -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 <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 "fmt/core.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)
|
||||
{
|
||||
fmt::println(stderr, "Could not open audio in {}: {}", filename,
|
||||
sf_strerror(sndfile.get()));
|
||||
return 0;
|
||||
}
|
||||
if(sfinfo.frames < 1)
|
||||
{
|
||||
fmt::println(stderr, "Bad sample count in {} ({})", filename, sfinfo.frames);
|
||||
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)
|
||||
{
|
||||
fmt::println(stderr, "Unsupported channel count: {}", sfinfo.channels);
|
||||
return 0;
|
||||
}
|
||||
|
||||
if(sfinfo.frames/splblockalign > sf_count_t{std::numeric_limits<int>::max()}/byteblockalign)
|
||||
{
|
||||
fmt::println(stderr, "Too many sample frames in {} ({})", filename, sfinfo.frames);
|
||||
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)
|
||||
{
|
||||
fmt::println(stderr, "Failed to read samples in {} ({})", filename, num_frames);
|
||||
return 0;
|
||||
}
|
||||
|
||||
const auto num_bytes = static_cast<ALsizei>(num_frames / splblockalign * byteblockalign);
|
||||
|
||||
fmt::println("Loading: {} ({}, {}hz)", filename, FormatName(format), sfinfo.samplerate);
|
||||
|
||||
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)
|
||||
{
|
||||
fmt::println(stderr, "OpenAL Error: {}", alGetStringDirect(context, err));
|
||||
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)
|
||||
{
|
||||
fmt::println(stderr, "Usage: {} [-device <name>] <filename>", args[0]);
|
||||
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)
|
||||
fmt::println(stderr, "Failed to open \"{}\", trying default", args[1]);
|
||||
args = args.subspan(2);
|
||||
}
|
||||
if(!device)
|
||||
device = p_alcOpenDevice(nullptr);
|
||||
if(!device)
|
||||
{
|
||||
fmt::println(stderr, "Could not open a device!");
|
||||
return 1;
|
||||
}
|
||||
|
||||
if(!p_alcIsExtensionPresent(device, "ALC_EXT_direct_context"))
|
||||
{
|
||||
fmt::println(stderr, "ALC_EXT_direct_context not supported on device");
|
||||
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);
|
||||
fmt::println(stderr, "Could not create a context!");
|
||||
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);
|
||||
fmt::print(" \rOffset: {:.02f}", offset);
|
||||
fflush(stdout);
|
||||
} while(alGetErrorDirect(context) == AL_NO_ERROR && state == AL_PLAYING);
|
||||
fmt::println("");
|
||||
|
||||
/* 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
File diff suppressed because it is too large
Load Diff
@@ -29,12 +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"
|
||||
@@ -42,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
|
||||
@@ -58,6 +53,8 @@ typedef struct {
|
||||
ALCcontext *Context;
|
||||
|
||||
ALCsizei FrameSize;
|
||||
void *Buffer;
|
||||
int BufferSize;
|
||||
} PlaybackInfo;
|
||||
|
||||
static LPALCLOOPBACKOPENDEVICESOFT alcLoopbackOpenDeviceSOFT;
|
||||
@@ -65,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);
|
||||
}
|
||||
|
||||
|
||||
@@ -134,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;
|
||||
@@ -158,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. */
|
||||
@@ -185,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);
|
||||
@@ -192,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
|
||||
{
|
||||
@@ -215,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);
|
||||
@@ -228,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);
|
||||
@@ -238,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;
|
||||
@@ -271,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;
|
||||
}
|
||||
|
||||
@@ -77,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);
|
||||
@@ -116,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);
|
||||
|
||||
@@ -25,14 +25,18 @@
|
||||
/* This file contains a streaming audio player using a callback buffer. */
|
||||
|
||||
|
||||
#include <algorithm>
|
||||
#include <atomic>
|
||||
#include <cassert>
|
||||
#include <chrono>
|
||||
#include <cstring>
|
||||
#include <cstddef>
|
||||
#include <cstdlib>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <memory>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
@@ -42,7 +46,10 @@
|
||||
#include "AL/alc.h"
|
||||
#include "AL/alext.h"
|
||||
|
||||
#include "alnumeric.h"
|
||||
#include "alspan.h"
|
||||
#include "common/alhelpers.h"
|
||||
#include "fmt/core.h"
|
||||
|
||||
#include "win_main_utf8.h"
|
||||
|
||||
@@ -58,7 +65,7 @@ struct StreamPlayer {
|
||||
/* A lockless ring-buffer (supports single-provider, single-consumer
|
||||
* operation).
|
||||
*/
|
||||
std::vector<ALbyte> mBufferData;
|
||||
std::vector<std::byte> mBufferData;
|
||||
std::atomic<size_t> mReadPos{0};
|
||||
std::atomic<size_t> mWritePos{0};
|
||||
size_t mSamplesPerBlock{1};
|
||||
@@ -115,15 +122,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));
|
||||
fmt::println(stderr, "Could not open audio in {}: {}", filename,
|
||||
sf_strerror(mSndfile));
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -253,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;
|
||||
|
||||
@@ -280,6 +288,9 @@ struct StreamPlayer {
|
||||
{ return static_cast<StreamPlayer*>(userptr)->bufferCallback(data, size); }
|
||||
ALsizei bufferCallback(void *data, ALsizei size) noexcept
|
||||
{
|
||||
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
|
||||
@@ -287,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(got < size)
|
||||
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.
|
||||
@@ -304,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<size_t>(todo, static_cast<ALuint>(size-got));
|
||||
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.
|
||||
*/
|
||||
memcpy(data, &mBufferData[roffset], todo);
|
||||
data = static_cast<ALbyte*>(data) + 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())
|
||||
@@ -323,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()
|
||||
@@ -334,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;
|
||||
@@ -358,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;
|
||||
}
|
||||
@@ -458,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;
|
||||
@@ -476,33 +463,30 @@ 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_)
|
||||
{
|
||||
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)
|
||||
if(args.size() < 2)
|
||||
{
|
||||
fprintf(stderr, "Usage: %s [-device <name>] <filenames...>\n", argv[0]);
|
||||
fmt::println(stderr, "Usage: {} [-device <name>] <filenames...>", args[0]);
|
||||
return 1;
|
||||
}
|
||||
args = args.subspan(1);
|
||||
|
||||
argv++; argc--;
|
||||
AudioManager almgr{&argv, &argc};
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -512,23 +496,19 @@ 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], '\\');
|
||||
if(namepart)
|
||||
++namepart;
|
||||
else
|
||||
namepart = argv[i];
|
||||
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", namepart, FormatName(player->mFormat),
|
||||
fmt::println("Playing: {} ({}, {}hz)", namepart, FormatName(player->mFormat),
|
||||
player->mSfInfo.samplerate);
|
||||
fflush(stdout);
|
||||
|
||||
@@ -546,7 +526,17 @@ int main(int argc, char **argv)
|
||||
player->close();
|
||||
}
|
||||
/* All done. */
|
||||
printf("Done.\n");
|
||||
fmt::println("Done.");
|
||||
|
||||
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});
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
#define ALHELPERS_H
|
||||
|
||||
#include "AL/al.h"
|
||||
#include "AL/alc.h"
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
@@ -23,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)
|
||||
@@ -33,6 +34,54 @@ void al_nssleep(unsigned long nsec);
|
||||
|
||||
#ifdef __cplusplus
|
||||
} // extern "C"
|
||||
|
||||
#include <cstdio>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
|
||||
#include "alspan.h"
|
||||
#include "fmt/core.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)
|
||||
fmt::println(stderr, "Failed to open \"{}\", trying default", args[1]);
|
||||
args = args.subspan(2);
|
||||
}
|
||||
if(!device)
|
||||
device = alcOpenDevice(nullptr);
|
||||
if(!device)
|
||||
{
|
||||
fmt::println(stderr, "Could not open a device!");
|
||||
return 1;
|
||||
}
|
||||
|
||||
ALCcontext *ctx{alcCreateContext(device, nullptr)};
|
||||
if(!ctx || alcMakeContextCurrent(ctx) == ALC_FALSE)
|
||||
{
|
||||
if(ctx)
|
||||
alcDestroyContext(ctx);
|
||||
alcCloseDevice(device);
|
||||
fmt::println(stderr, "Could not set a context!");
|
||||
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);
|
||||
fmt::println("Opened \"{}\"", name);
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
#endif /* ALHELPERS_H */
|
||||
|
||||
Reference in New Issue
Block a user