update OpenAL-Soft to 1.24.3.

This commit is contained in:
Sasha Szpakowski
2025-05-03 12:51:37 -03:00
parent 375c6f88cd
commit 5e4f3241ac
322 changed files with 54386 additions and 12885 deletions
+257 -271
View File
@@ -1,27 +1,38 @@
#include "config.h"
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <algorithm>
#include <array>
#include <cstddef>
#include <cstdlib>
#include <cstring>
#include <cstdio>
#include <mutex>
#include <optional>
#include <string_view>
#include <tuple>
#include <unordered_map>
#include "AL/alc.h"
#include "alstring.h"
#include "almalloc.h"
#include "router.h"
#include "strutils.h"
#define DECL(x) { #x, reinterpret_cast<void*>(x) }
namespace {
using namespace std::string_view_literals;
std::once_flag InitOnce;
void LoadDrivers() { std::call_once(InitOnce, []{ LoadDriverList(); }); }
struct FuncExportEntry {
const char *funcName;
void *address;
};
static const std::array<FuncExportEntry,128> alcFunctions{{
#define DECL(x) FuncExportEntry{ #x, reinterpret_cast<void*>(x) }
const std::array alcFunctions{
DECL(alcCreateContext),
DECL(alcMakeContextCurrent),
DECL(alcProcessContext),
@@ -154,15 +165,15 @@ static const std::array<FuncExportEntry,128> alcFunctions{{
DECL(alGetAuxiliaryEffectSlotfv),
DECL(alGetAuxiliaryEffectSloti),
DECL(alGetAuxiliaryEffectSlotiv),
}};
};
#undef DECL
#define DECL(x) { #x, (x) }
struct EnumExportEntry {
const ALCchar *enumName;
ALCenum value;
};
static const std::array<EnumExportEntry,92> alcEnumerations{{
#define DECL(x) EnumExportEntry{ #x, (x) }
const std::array alcEnumerations{
DECL(ALC_INVALID),
DECL(ALC_FALSE),
DECL(ALC_TRUE),
@@ -268,92 +279,108 @@ static const std::array<EnumExportEntry,92> alcEnumerations{{
DECL(AL_LINEAR_DISTANCE_CLAMPED),
DECL(AL_EXPONENT_DISTANCE),
DECL(AL_EXPONENT_DISTANCE_CLAMPED),
}};
};
#undef DECL
static const ALCchar alcNoError[] = "No Error";
static const ALCchar alcErrInvalidDevice[] = "Invalid Device";
static const ALCchar alcErrInvalidContext[] = "Invalid Context";
static const ALCchar alcErrInvalidEnum[] = "Invalid Enum";
static const ALCchar alcErrInvalidValue[] = "Invalid Value";
static const ALCchar alcErrOutOfMemory[] = "Out of Memory";
static const ALCchar alcExtensionList[] =
"ALC_ENUMERATE_ALL_EXT ALC_ENUMERATION_EXT ALC_EXT_CAPTURE "
"ALC_EXT_thread_local_context";
[[nodiscard]] constexpr auto GetNoErrorString() noexcept { return "No Error"; }
[[nodiscard]] constexpr auto GetInvalidDeviceString() noexcept { return "Invalid Device"; }
[[nodiscard]] constexpr auto GetInvalidContextString() noexcept { return "Invalid Context"; }
[[nodiscard]] constexpr auto GetInvalidEnumString() noexcept { return "Invalid Enum"; }
[[nodiscard]] constexpr auto GetInvalidValueString() noexcept { return "Invalid Value"; }
[[nodiscard]] constexpr auto GetOutOfMemoryString() noexcept { return "Out of Memory"; }
static const ALCint alcMajorVersion = 1;
static const ALCint alcMinorVersion = 1;
[[nodiscard]] constexpr auto GetExtensionList() noexcept -> std::string_view
{
return "ALC_ENUMERATE_ALL_EXT ALC_ENUMERATION_EXT ALC_EXT_CAPTURE "
"ALC_EXT_thread_local_context"sv;
}
constexpr ALCint alcMajorVersion = 1;
constexpr ALCint alcMinorVersion = 1;
static std::recursive_mutex EnumerationLock;
static std::mutex ContextSwitchLock;
std::recursive_mutex EnumerationLock;
std::mutex ContextSwitchLock;
static std::atomic<ALCenum> LastError{ALC_NO_ERROR};
static PtrIntMap DeviceIfaceMap;
static PtrIntMap ContextIfaceMap;
std::atomic<ALCenum> LastError{ALC_NO_ERROR};
std::unordered_map<ALCdevice*,ALCuint> DeviceIfaceMap;
std::unordered_map<ALCcontext*,ALCuint> ContextIfaceMap;
template<typename T, typename U, typename V>
auto maybe_get(std::unordered_map<T,U> &list, V&& key) -> std::optional<U>
{
auto iter = list.find(std::forward<V>(key));
if(iter != list.end()) return iter->second;
return std::nullopt;
}
typedef struct EnumeratedList {
struct EnumeratedList {
std::vector<ALCchar> Names;
std::vector<ALCint> Indicies;
std::vector<ALCuint> Indicies;
void clear()
{
Names.clear();
Indicies.clear();
}
} EnumeratedList;
static EnumeratedList DevicesList;
static EnumeratedList AllDevicesList;
static EnumeratedList CaptureDevicesList;
static void AppendDeviceList(EnumeratedList *list, const ALCchar *names, ALint idx)
void AppendDeviceList(const ALCchar *names, ALCuint idx);
[[nodiscard]]
auto GetDriverIndexForName(const std::string_view name) const -> std::optional<ALCuint>;
};
EnumeratedList DevicesList;
EnumeratedList AllDevicesList;
EnumeratedList CaptureDevicesList;
void EnumeratedList::AppendDeviceList(const ALCchar* names, ALCuint idx)
{
const ALCchar *name_end = names;
if(!name_end) return;
ALCsizei count = 0;
size_t count{0};
while(*name_end)
{
TRACE("Enumerated \"%s\", driver %d\n", name_end, idx);
TRACE("Enumerated \"{}\", driver {}", name_end, idx);
++count;
name_end += strlen(name_end)+1;
name_end += strlen(name_end)+1; /* NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic) */
}
if(names == name_end)
return;
list->Names.reserve(list->Names.size() + (name_end - names) + 1);
list->Names.insert(list->Names.cend(), names, name_end);
Names.reserve(Names.size() + static_cast<size_t>(name_end - names) + 1);
Names.insert(Names.cend(), names, name_end);
list->Indicies.reserve(list->Indicies.size() + count);
list->Indicies.insert(list->Indicies.cend(), count, idx);
Indicies.reserve(Indicies.size() + count);
Indicies.insert(Indicies.cend(), count, idx);
}
static ALint GetDriverIndexForName(const EnumeratedList *list, const ALCchar *name)
auto EnumeratedList::GetDriverIndexForName(const std::string_view name) const -> std::optional<ALCuint>
{
const ALCchar *devnames = list->Names.data();
const ALCint *index = list->Indicies.data();
auto devnames = Names.cbegin();
auto index = Indicies.cbegin();
while(devnames && *devnames)
while(devnames != Names.cend() && *devnames)
{
if(strcmp(name, devnames) == 0)
return *index;
devnames += strlen(devnames)+1;
index++;
const auto devname = std::string_view{al::to_address(devnames)};
if(name == devname) return *index;
devnames += ptrdiff_t(devname.size()+1);
++index;
}
return -1;
return std::nullopt;
}
static void InitCtxFuncs(DriverIface &iface)
void InitCtxFuncs(DriverIface &iface)
{
ALCdevice *device{iface.alcGetContextsDevice(iface.alcGetCurrentContext())};
#define LOAD_PROC(x) do { \
iface.x = reinterpret_cast<decltype(iface.x)>(iface.alGetProcAddress(#x));\
if(!iface.x) \
ERR("Failed to find entry point for %s in %ls\n", #x, \
iface.Name.c_str()); \
ERR("Failed to find entry point for {} in {}", #x, \
wstr_to_utf8(iface.Name)); \
} while(0)
if(iface.alcIsExtensionPresent(device, "ALC_EXT_EFX"))
{
@@ -394,65 +421,69 @@ static void InitCtxFuncs(DriverIface &iface)
#undef LOAD_PROC
}
} /* namespace */
ALC_API ALCdevice* ALC_APIENTRY alcOpenDevice(const ALCchar *devicename) noexcept
{
ALCdevice *device = nullptr;
ALint idx = 0;
LoadDrivers();
ALCdevice *device{nullptr};
std::optional<ALCuint> idx;
/* Prior to the enumeration extension, apps would hardcode these names as a
* quality hint for the wrapper driver. Ignore them since there's no sane
* way to map them.
*/
if(devicename && (devicename[0] == '\0' ||
strcmp(devicename, "DirectSound3D") == 0 ||
strcmp(devicename, "DirectSound") == 0 ||
strcmp(devicename, "MMSYSTEM") == 0))
devicename = nullptr;
if(devicename)
if(devicename && *devicename != '\0' && devicename != "DirectSound3D"sv
&& devicename != "DirectSound"sv && devicename != "MMSYSTEM"sv)
{
{
std::lock_guard<std::recursive_mutex> enumlock{EnumerationLock};
if(DevicesList.Names.empty())
std::ignore = alcGetString(nullptr, ALC_DEVICE_SPECIFIER);
idx = GetDriverIndexForName(&DevicesList, devicename);
if(idx < 0)
idx = DevicesList.GetDriverIndexForName(devicename);
if(!idx)
{
if(AllDevicesList.Names.empty())
std::ignore = alcGetString(nullptr, ALC_ALL_DEVICES_SPECIFIER);
idx = GetDriverIndexForName(&AllDevicesList, devicename);
idx = AllDevicesList.GetDriverIndexForName(devicename);
}
}
if(idx < 0)
if(!idx)
{
LastError.store(ALC_INVALID_VALUE);
TRACE("Failed to find driver for name \"%s\"\n", devicename);
TRACE("Failed to find driver for name \"{}\"", devicename);
return nullptr;
}
TRACE("Found driver %d for name \"%s\"\n", idx, devicename);
device = DriverList[idx]->alcOpenDevice(devicename);
TRACE("Found driver {} for name \"{}\"", *idx, devicename);
device = DriverList[*idx]->alcOpenDevice(devicename);
}
else
{
ALCuint drvidx{0};
for(const auto &drv : DriverList)
{
if(drv->ALCVer >= MAKE_ALC_VER(1, 1)
if(drv->ALCVer >= MakeALCVer(1, 1)
|| drv->alcIsExtensionPresent(nullptr, "ALC_ENUMERATION_EXT"))
{
TRACE("Using default device from driver %d\n", idx);
TRACE("Using default device from driver {}", drvidx);
device = drv->alcOpenDevice(nullptr);
idx = drvidx;
break;
}
++idx;
++drvidx;
}
}
if(device)
{
if(DeviceIfaceMap.insert(device, idx) != ALC_NO_ERROR)
{
DriverList[idx]->alcCloseDevice(device);
try {
DeviceIfaceMap.emplace(device, idx.value());
}
catch(...) {
DriverList[idx.value()]->alcCloseDevice(device);
device = nullptr;
}
}
@@ -462,36 +493,36 @@ ALC_API ALCdevice* ALC_APIENTRY alcOpenDevice(const ALCchar *devicename) noexcep
ALC_API ALCboolean ALC_APIENTRY alcCloseDevice(ALCdevice *device) noexcept
{
ALint idx;
if(!device || (idx=DeviceIfaceMap.lookupByKey(device)) < 0)
if(const auto idx = maybe_get(DeviceIfaceMap, device))
{
LastError.store(ALC_INVALID_DEVICE);
return ALC_FALSE;
if(!DriverList[*idx]->alcCloseDevice(device))
return ALC_FALSE;
DeviceIfaceMap.erase(device);
return ALC_TRUE;
}
if(!DriverList[idx]->alcCloseDevice(device))
return ALC_FALSE;
DeviceIfaceMap.removeByKey(device);
return ALC_TRUE;
LastError.store(ALC_INVALID_DEVICE);
return ALC_FALSE;
}
ALC_API ALCcontext* ALC_APIENTRY alcCreateContext(ALCdevice *device, const ALCint *attrlist) noexcept
{
ALCcontext *context;
ALint idx;
if(!device || (idx=DeviceIfaceMap.lookupByKey(device)) < 0)
const auto idx = maybe_get(DeviceIfaceMap, device);
if(!idx)
{
LastError.store(ALC_INVALID_DEVICE);
return nullptr;
}
context = DriverList[idx]->alcCreateContext(device, attrlist);
ALCcontext *context{DriverList[*idx]->alcCreateContext(device, attrlist)};
if(context)
{
if(ContextIfaceMap.insert(context, idx) != ALC_NO_ERROR)
{
DriverList[idx]->alcDestroyContext(context);
try {
ContextIfaceMap.emplace(context, *idx);
}
catch(...) {
DriverList[*idx]->alcDestroyContext(context);
context = nullptr;
}
}
@@ -501,41 +532,40 @@ ALC_API ALCcontext* ALC_APIENTRY alcCreateContext(ALCdevice *device, const ALCin
ALC_API ALCboolean ALC_APIENTRY alcMakeContextCurrent(ALCcontext *context) noexcept
{
ALint idx = -1;
std::lock_guard<std::mutex> ctxlock{ContextSwitchLock};
std::optional<ALCuint> idx;
if(context)
{
idx = ContextIfaceMap.lookupByKey(context);
if(idx < 0)
idx = maybe_get(ContextIfaceMap, context);
if(!idx)
{
LastError.store(ALC_INVALID_CONTEXT);
return ALC_FALSE;
}
if(!DriverList[idx]->alcMakeContextCurrent(context))
if(!DriverList[*idx]->alcMakeContextCurrent(context))
return ALC_FALSE;
auto do_init = [idx]() { InitCtxFuncs(*DriverList[idx]); };
std::call_once(DriverList[idx]->InitOnceCtx, do_init);
std::call_once(DriverList[*idx]->InitOnceCtx, [idx]{ InitCtxFuncs(*DriverList[*idx]); });
}
/* Unset the context from the old driver if it's different from the new
* current one.
*/
if(idx < 0)
if(!idx)
{
DriverIface *oldiface = GetThreadDriver();
DriverIface *oldiface{GetThreadDriver()};
if(oldiface) oldiface->alcSetThreadContext(nullptr);
oldiface = CurrentCtxDriver.exchange(nullptr);
if(oldiface) oldiface->alcMakeContextCurrent(nullptr);
}
else
{
DriverIface *oldiface = GetThreadDriver();
if(oldiface && oldiface != DriverList[idx].get())
DriverIface *oldiface{GetThreadDriver()};
if(oldiface && oldiface != DriverList[*idx].get())
oldiface->alcSetThreadContext(nullptr);
oldiface = CurrentCtxDriver.exchange(DriverList[idx].get());
if(oldiface && oldiface != DriverList[idx].get())
oldiface = CurrentCtxDriver.exchange(DriverList[*idx].get());
if(oldiface && oldiface != DriverList[*idx].get())
oldiface->alcMakeContextCurrent(nullptr);
}
SetThreadDriver(nullptr);
@@ -545,55 +575,43 @@ ALC_API ALCboolean ALC_APIENTRY alcMakeContextCurrent(ALCcontext *context) noexc
ALC_API void ALC_APIENTRY alcProcessContext(ALCcontext *context) noexcept
{
if(context)
{
ALint idx = ContextIfaceMap.lookupByKey(context);
if(idx >= 0)
return DriverList[idx]->alcProcessContext(context);
}
if(const auto idx = maybe_get(ContextIfaceMap, context))
return DriverList[*idx]->alcProcessContext(context);
LastError.store(ALC_INVALID_CONTEXT);
}
ALC_API void ALC_APIENTRY alcSuspendContext(ALCcontext *context) noexcept
{
if(context)
{
ALint idx = ContextIfaceMap.lookupByKey(context);
if(idx >= 0)
return DriverList[idx]->alcSuspendContext(context);
}
if(const auto idx = maybe_get(ContextIfaceMap, context))
return DriverList[*idx]->alcSuspendContext(context);
LastError.store(ALC_INVALID_CONTEXT);
}
ALC_API void ALC_APIENTRY alcDestroyContext(ALCcontext *context) noexcept
{
ALint idx;
if(!context || (idx=ContextIfaceMap.lookupByKey(context)) < 0)
if(const auto idx = maybe_get(ContextIfaceMap, context))
{
LastError.store(ALC_INVALID_CONTEXT);
DriverList[*idx]->alcDestroyContext(context);
ContextIfaceMap.erase(context);
return;
}
DriverList[idx]->alcDestroyContext(context);
ContextIfaceMap.removeByKey(context);
LastError.store(ALC_INVALID_CONTEXT);
}
ALC_API ALCcontext* ALC_APIENTRY alcGetCurrentContext() noexcept
{
DriverIface *iface = GetThreadDriver();
DriverIface *iface{GetThreadDriver()};
if(!iface) iface = CurrentCtxDriver.load();
return iface ? iface->alcGetCurrentContext() : nullptr;
}
ALC_API ALCdevice* ALC_APIENTRY alcGetContextsDevice(ALCcontext *context) noexcept
{
if(context)
{
ALint idx = ContextIfaceMap.lookupByKey(context);
if(idx >= 0)
return DriverList[idx]->alcGetContextsDevice(context);
}
if(const auto idx = maybe_get(ContextIfaceMap, context))
return DriverList[*idx]->alcGetContextsDevice(context);
LastError.store(ALC_INVALID_CONTEXT);
return nullptr;
}
@@ -603,41 +621,34 @@ ALC_API ALCenum ALC_APIENTRY alcGetError(ALCdevice *device) noexcept
{
if(device)
{
ALint idx = DeviceIfaceMap.lookupByKey(device);
if(idx < 0) return ALC_INVALID_DEVICE;
return DriverList[idx]->alcGetError(device);
if(const auto idx = maybe_get(DeviceIfaceMap, device))
return DriverList[*idx]->alcGetError(device);
return ALC_INVALID_DEVICE;
}
return LastError.exchange(ALC_NO_ERROR);
}
ALC_API ALCboolean ALC_APIENTRY alcIsExtensionPresent(ALCdevice *device, const ALCchar *extname) noexcept
{
const char *ptr;
size_t len;
if(device)
{
ALint idx = DeviceIfaceMap.lookupByKey(device);
if(idx < 0)
{
LastError.store(ALC_INVALID_DEVICE);
return ALC_FALSE;
}
return DriverList[idx]->alcIsExtensionPresent(device, extname);
if(const auto idx = maybe_get(DeviceIfaceMap, device))
return DriverList[*idx]->alcIsExtensionPresent(device, extname);
LastError.store(ALC_INVALID_DEVICE);
return ALC_FALSE;
}
len = strlen(extname);
ptr = alcExtensionList;
while(ptr && *ptr)
const auto tofind = std::string_view{extname};
const auto extlist = GetExtensionList();
auto matchpos = extlist.find(tofind);
while(matchpos != std::string_view::npos)
{
if(al::strncasecmp(ptr, extname, len) == 0 && (ptr[len] == '\0' || isspace(ptr[len])))
const auto endpos = matchpos + tofind.size();
if((matchpos == 0 || std::isspace(extlist[matchpos-1]))
&& (endpos == extlist.size() || std::isspace(extlist[endpos])))
return ALC_TRUE;
if((ptr=strchr(ptr, ' ')) != nullptr)
{
do {
++ptr;
} while(isspace(*ptr));
}
matchpos = extlist.find(tofind, matchpos+1);
}
return ALC_FALSE;
}
@@ -646,13 +657,11 @@ ALC_API void* ALC_APIENTRY alcGetProcAddress(ALCdevice *device, const ALCchar *f
{
if(device)
{
ALint idx = DeviceIfaceMap.lookupByKey(device);
if(idx < 0)
{
LastError.store(ALC_INVALID_DEVICE);
return nullptr;
}
return DriverList[idx]->alcGetProcAddress(device, funcname);
if(const auto idx = maybe_get(DeviceIfaceMap, device))
return DriverList[*idx]->alcGetProcAddress(device, funcname);
LastError.store(ALC_INVALID_DEVICE);
return nullptr;
}
auto iter = std::find_if(alcFunctions.cbegin(), alcFunctions.cend(),
@@ -666,13 +675,11 @@ ALC_API ALCenum ALC_APIENTRY alcGetEnumValue(ALCdevice *device, const ALCchar *e
{
if(device)
{
ALint idx = DeviceIfaceMap.lookupByKey(device);
if(idx < 0)
{
LastError.store(ALC_INVALID_DEVICE);
return 0;
}
return DriverList[idx]->alcGetEnumValue(device, enumname);
if(const auto idx = maybe_get(DeviceIfaceMap, device))
return DriverList[*idx]->alcGetEnumValue(device, enumname);
LastError.store(ALC_INVALID_DEVICE);
return 0;
}
auto iter = std::find_if(alcEnumerations.cbegin(), alcEnumerations.cend(),
@@ -684,46 +691,38 @@ ALC_API ALCenum ALC_APIENTRY alcGetEnumValue(ALCdevice *device, const ALCchar *e
ALC_API const ALCchar* ALC_APIENTRY alcGetString(ALCdevice *device, ALCenum param) noexcept
{
LoadDrivers();
if(device)
{
ALint idx = DeviceIfaceMap.lookupByKey(device);
if(idx < 0)
{
LastError.store(ALC_INVALID_DEVICE);
return nullptr;
}
return DriverList[idx]->alcGetString(device, param);
if(const auto idx = maybe_get(DeviceIfaceMap, device))
return DriverList[*idx]->alcGetString(device, param);
LastError.store(ALC_INVALID_DEVICE);
return nullptr;
}
switch(param)
{
case ALC_NO_ERROR:
return alcNoError;
case ALC_INVALID_ENUM:
return alcErrInvalidEnum;
case ALC_INVALID_VALUE:
return alcErrInvalidValue;
case ALC_INVALID_DEVICE:
return alcErrInvalidDevice;
case ALC_INVALID_CONTEXT:
return alcErrInvalidContext;
case ALC_OUT_OF_MEMORY:
return alcErrOutOfMemory;
case ALC_EXTENSIONS:
return alcExtensionList;
case ALC_NO_ERROR: return GetNoErrorString();
case ALC_INVALID_ENUM: return GetInvalidEnumString();
case ALC_INVALID_VALUE: return GetInvalidValueString();
case ALC_INVALID_DEVICE: return GetInvalidDeviceString();
case ALC_INVALID_CONTEXT: return GetInvalidContextString();
case ALC_OUT_OF_MEMORY: return GetOutOfMemoryString();
case ALC_EXTENSIONS: return GetExtensionList().data();
case ALC_DEVICE_SPECIFIER:
{
std::lock_guard<std::recursive_mutex> enumlock{EnumerationLock};
DevicesList.clear();
ALint idx{0};
ALCuint idx{0};
for(const auto &drv : DriverList)
{
/* Only enumerate names from drivers that support it. */
if(drv->ALCVer >= MAKE_ALC_VER(1, 1)
if(drv->ALCVer >= MakeALCVer(1, 1)
|| drv->alcIsExtensionPresent(nullptr, "ALC_ENUMERATION_EXT"))
AppendDeviceList(&DevicesList,
drv->alcGetString(nullptr, ALC_DEVICE_SPECIFIER), idx);
DevicesList.AppendDeviceList(drv->alcGetString(nullptr,ALC_DEVICE_SPECIFIER), idx);
++idx;
}
/* Ensure the list is double-null termianted. */
@@ -737,18 +736,18 @@ ALC_API const ALCchar* ALC_APIENTRY alcGetString(ALCdevice *device, ALCenum para
{
std::lock_guard<std::recursive_mutex> enumlock{EnumerationLock};
AllDevicesList.clear();
ALint idx{0};
ALCuint idx{0};
for(const auto &drv : DriverList)
{
/* If the driver doesn't support ALC_ENUMERATE_ALL_EXT, substitute
* standard enumeration.
*/
if(drv->alcIsExtensionPresent(nullptr, "ALC_ENUMERATE_ALL_EXT"))
AppendDeviceList(&AllDevicesList,
AllDevicesList.AppendDeviceList(
drv->alcGetString(nullptr, ALC_ALL_DEVICES_SPECIFIER), idx);
else if(drv->ALCVer >= MAKE_ALC_VER(1, 1)
else if(drv->ALCVer >= MakeALCVer(1, 1)
|| drv->alcIsExtensionPresent(nullptr, "ALC_ENUMERATION_EXT"))
AppendDeviceList(&AllDevicesList,
AllDevicesList.AppendDeviceList(
drv->alcGetString(nullptr, ALC_DEVICE_SPECIFIER), idx);
++idx;
}
@@ -763,12 +762,12 @@ ALC_API const ALCchar* ALC_APIENTRY alcGetString(ALCdevice *device, ALCenum para
{
std::lock_guard<std::recursive_mutex> enumlock{EnumerationLock};
CaptureDevicesList.clear();
ALint idx{0};
ALCuint idx{0};
for(const auto &drv : DriverList)
{
if(drv->ALCVer >= MAKE_ALC_VER(1, 1)
if(drv->ALCVer >= MakeALCVer(1, 1)
|| drv->alcIsExtensionPresent(nullptr, "ALC_EXT_CAPTURE"))
AppendDeviceList(&CaptureDevicesList,
CaptureDevicesList.AppendDeviceList(
drv->alcGetString(nullptr, ALC_CAPTURE_DEVICE_SPECIFIER), idx);
++idx;
}
@@ -783,7 +782,7 @@ ALC_API const ALCchar* ALC_APIENTRY alcGetString(ALCdevice *device, ALCenum para
{
for(const auto &drv : DriverList)
{
if(drv->ALCVer >= MAKE_ALC_VER(1, 1)
if(drv->ALCVer >= MakeALCVer(1, 1)
|| drv->alcIsExtensionPresent(nullptr, "ALC_ENUMERATION_EXT"))
return drv->alcGetString(nullptr, ALC_DEFAULT_DEVICE_SPECIFIER);
}
@@ -804,7 +803,7 @@ ALC_API const ALCchar* ALC_APIENTRY alcGetString(ALCdevice *device, ALCenum para
{
for(const auto &drv : DriverList)
{
if(drv->ALCVer >= MAKE_ALC_VER(1, 1)
if(drv->ALCVer >= MakeALCVer(1, 1)
|| drv->alcIsExtensionPresent(nullptr, "ALC_EXT_CAPTURE"))
return drv->alcGetString(nullptr, ALC_CAPTURE_DEFAULT_DEVICE_SPECIFIER);
}
@@ -822,13 +821,11 @@ ALC_API void ALC_APIENTRY alcGetIntegerv(ALCdevice *device, ALCenum param, ALCsi
{
if(device)
{
ALint idx = DeviceIfaceMap.lookupByKey(device);
if(idx < 0)
{
LastError.store(ALC_INVALID_DEVICE);
return;
}
return DriverList[idx]->alcGetIntegerv(device, param, size, values);
if(const auto idx = maybe_get(DeviceIfaceMap, device))
return DriverList[*idx]->alcGetIntegerv(device, param, size, values);
LastError.store(ALC_INVALID_DEVICE);
return;
}
if(size <= 0 || values == nullptr)
@@ -842,14 +839,15 @@ ALC_API void ALC_APIENTRY alcGetIntegerv(ALCdevice *device, ALCenum param, ALCsi
case ALC_MAJOR_VERSION:
if(size >= 1)
{
values[0] = alcMajorVersion;
*values = alcMajorVersion;
return;
}
/*fall-through*/
LastError.store(ALC_INVALID_VALUE);
return;
case ALC_MINOR_VERSION:
if(size >= 1)
{
values[0] = alcMinorVersion;
*values = alcMinorVersion;
return;
}
LastError.store(ALC_INVALID_VALUE);
@@ -873,51 +871,56 @@ ALC_API void ALC_APIENTRY alcGetIntegerv(ALCdevice *device, ALCenum param, ALCsi
}
ALC_API ALCdevice* ALC_APIENTRY alcCaptureOpenDevice(const ALCchar *devicename, ALCuint frequency, ALCenum format, ALCsizei buffersize) noexcept
ALC_API ALCdevice* ALC_APIENTRY alcCaptureOpenDevice(const ALCchar *devicename, ALCuint frequency,
ALCenum format, ALCsizei buffersize) noexcept
{
ALCdevice *device = nullptr;
ALint idx = 0;
LoadDrivers();
if(devicename && devicename[0] == '\0')
devicename = nullptr;
if(devicename)
ALCdevice *device{nullptr};
std::optional<ALCuint> idx;
if(devicename && *devicename != '\0')
{
{
std::lock_guard<std::recursive_mutex> enumlock{EnumerationLock};
if(CaptureDevicesList.Names.empty())
std::ignore = alcGetString(nullptr, ALC_CAPTURE_DEVICE_SPECIFIER);
idx = GetDriverIndexForName(&CaptureDevicesList, devicename);
idx = CaptureDevicesList.GetDriverIndexForName(devicename);
}
if(idx < 0)
if(!idx)
{
LastError.store(ALC_INVALID_VALUE);
TRACE("Failed to find driver for name \"%s\"\n", devicename);
TRACE("Failed to find driver for name \"{}\"", devicename);
return nullptr;
}
TRACE("Found driver %d for name \"%s\"\n", idx, devicename);
device = DriverList[idx]->alcCaptureOpenDevice(devicename, frequency, format, buffersize);
TRACE("Found driver {} for name \"{}\"", *idx, devicename);
device = DriverList[*idx]->alcCaptureOpenDevice(devicename, frequency, format, buffersize);
}
else
{
ALCuint drvidx{0};
for(const auto &drv : DriverList)
{
if(drv->ALCVer >= MAKE_ALC_VER(1, 1)
if(drv->ALCVer >= MakeALCVer(1, 1)
|| drv->alcIsExtensionPresent(nullptr, "ALC_EXT_CAPTURE"))
{
TRACE("Using default capture device from driver %d\n", idx);
TRACE("Using default capture device from driver {}", drvidx);
device = drv->alcCaptureOpenDevice(nullptr, frequency, format, buffersize);
idx = drvidx;
break;
}
++idx;
++drvidx;
}
}
if(device)
{
if(DeviceIfaceMap.insert(device, idx) != ALC_NO_ERROR)
{
DriverList[idx]->alcCaptureCloseDevice(device);
try {
DeviceIfaceMap.emplace(device, idx.value());
}
catch(...) {
DriverList[idx.value()]->alcCaptureCloseDevice(device);
device = nullptr;
}
}
@@ -927,84 +930,67 @@ ALC_API ALCdevice* ALC_APIENTRY alcCaptureOpenDevice(const ALCchar *devicename,
ALC_API ALCboolean ALC_APIENTRY alcCaptureCloseDevice(ALCdevice *device) noexcept
{
ALint idx;
if(!device || (idx=DeviceIfaceMap.lookupByKey(device)) < 0)
if(const auto idx = maybe_get(DeviceIfaceMap, device))
{
LastError.store(ALC_INVALID_DEVICE);
return ALC_FALSE;
if(!DriverList[*idx]->alcCaptureCloseDevice(device))
return ALC_FALSE;
DeviceIfaceMap.erase(device);
return ALC_TRUE;
}
if(!DriverList[idx]->alcCaptureCloseDevice(device))
return ALC_FALSE;
DeviceIfaceMap.removeByKey(device);
return ALC_TRUE;
LastError.store(ALC_INVALID_DEVICE);
return ALC_FALSE;
}
ALC_API void ALC_APIENTRY alcCaptureStart(ALCdevice *device) noexcept
{
if(device)
{
ALint idx = DeviceIfaceMap.lookupByKey(device);
if(idx >= 0)
return DriverList[idx]->alcCaptureStart(device);
}
if(const auto idx = maybe_get(DeviceIfaceMap, device))
return DriverList[*idx]->alcCaptureStart(device);
LastError.store(ALC_INVALID_DEVICE);
}
ALC_API void ALC_APIENTRY alcCaptureStop(ALCdevice *device) noexcept
{
if(device)
{
ALint idx = DeviceIfaceMap.lookupByKey(device);
if(idx >= 0)
return DriverList[idx]->alcCaptureStop(device);
}
if(const auto idx = maybe_get(DeviceIfaceMap, device))
return DriverList[*idx]->alcCaptureStop(device);
LastError.store(ALC_INVALID_DEVICE);
}
ALC_API void ALC_APIENTRY alcCaptureSamples(ALCdevice *device, ALCvoid *buffer, ALCsizei samples) noexcept
{
if(device)
{
ALint idx = DeviceIfaceMap.lookupByKey(device);
if(idx >= 0)
return DriverList[idx]->alcCaptureSamples(device, buffer, samples);
}
if(const auto idx = maybe_get(DeviceIfaceMap, device))
return DriverList[*idx]->alcCaptureSamples(device, buffer, samples);
LastError.store(ALC_INVALID_DEVICE);
}
ALC_API ALCboolean ALC_APIENTRY alcSetThreadContext(ALCcontext *context) noexcept
{
ALCenum err = ALC_INVALID_CONTEXT;
ALint idx;
if(!context)
{
DriverIface *oldiface = GetThreadDriver();
DriverIface *oldiface{GetThreadDriver()};
if(oldiface && !oldiface->alcSetThreadContext(nullptr))
return ALC_FALSE;
SetThreadDriver(nullptr);
return ALC_TRUE;
}
idx = ContextIfaceMap.lookupByKey(context);
if(idx >= 0)
ALCenum err{ALC_INVALID_CONTEXT};
if(const auto idx = maybe_get(ContextIfaceMap, context))
{
if(DriverList[idx]->alcSetThreadContext(context))
if(DriverList[*idx]->alcSetThreadContext(context))
{
auto do_init = [idx]() { InitCtxFuncs(*DriverList[idx]); };
std::call_once(DriverList[idx]->InitOnceCtx, do_init);
std::call_once(DriverList[*idx]->InitOnceCtx, [idx]{InitCtxFuncs(*DriverList[*idx]);});
DriverIface *oldiface = GetThreadDriver();
if(oldiface != DriverList[idx].get())
DriverIface *oldiface{GetThreadDriver()};
if(oldiface != DriverList[*idx].get())
{
SetThreadDriver(DriverList[idx].get());
SetThreadDriver(DriverList[*idx].get());
if(oldiface) oldiface->alcSetThreadContext(nullptr);
}
return ALC_TRUE;
}
err = DriverList[idx]->alcGetError(nullptr);
err = DriverList[*idx]->alcGetError(nullptr);
}
LastError.store(err);
return ALC_FALSE;
@@ -1012,7 +998,7 @@ ALC_API ALCboolean ALC_APIENTRY alcSetThreadContext(ALCcontext *context) noexcep
ALC_API ALCcontext* ALC_APIENTRY alcGetThreadContext() noexcept
{
DriverIface *iface = GetThreadDriver();
if(iface) return iface->alcGetThreadContext();
if(DriverIface *iface{GetThreadDriver()})
return iface->alcGetThreadContext();
return nullptr;
}
+270 -259
View File
@@ -4,105 +4,94 @@
#include "router.h"
#include <algorithm>
#include <array>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include <string_view>
#include <vector>
#include "AL/alc.h"
#include "AL/al.h"
#include "almalloc.h"
#include "albit.h"
#include "alstring.h"
#include "opthelpers.h"
#include "strutils.h"
#include "version.h"
enum LogLevel LogLevel = LogLevel_Error;
FILE *LogFile;
eLogLevel LogLevel{eLogLevel::Error};
gsl::owner<std::FILE*> LogFile;
static void LoadDriverList();
namespace {
std::vector<std::wstring> gAcceptList;
std::vector<std::wstring> gRejectList;
BOOL APIENTRY DllMain(HINSTANCE, DWORD reason, void*)
{
switch(reason)
{
case DLL_PROCESS_ATTACH:
LogFile = stderr;
if(auto logfname = al::getenv("ALROUTER_LOGFILE"))
{
FILE *f = fopen(logfname->c_str(), "w");
if(f == nullptr)
ERR("Could not open log file: %s\n", logfname->c_str());
else
LogFile = f;
}
if(auto loglev = al::getenv("ALROUTER_LOGLEVEL"))
{
char *end = nullptr;
long l = strtol(loglev->c_str(), &end, 0);
if(!end || *end != '\0')
ERR("Invalid log level value: %s\n", loglev->c_str());
else if(l < LogLevel_None || l > LogLevel_Trace)
ERR("Log level out of range: %s\n", loglev->c_str());
else
LogLevel = static_cast<enum LogLevel>(l);
}
TRACE("Initializing router v0.1-%s %s\n", ALSOFT_GIT_COMMIT_HASH, ALSOFT_GIT_BRANCH);
LoadDriverList();
break;
case DLL_THREAD_ATTACH:
break;
case DLL_THREAD_DETACH:
break;
case DLL_PROCESS_DETACH:
DriverList.clear();
if(LogFile && LogFile != stderr)
fclose(LogFile);
LogFile = nullptr;
break;
}
return TRUE;
}
static void AddModule(HMODULE module, const WCHAR *name)
void AddModule(HMODULE module, const std::wstring_view name)
{
for(auto &drv : DriverList)
{
if(drv->Module == module)
{
TRACE("Skipping already-loaded module %p\n", decltype(std::declval<void*>()){module});
TRACE("Skipping already-loaded module {}", decltype(std::declval<void*>()){module});
FreeLibrary(module);
return;
}
if(drv->Name == name)
{
TRACE("Skipping similarly-named module %ls\n", name);
TRACE("Skipping similarly-named module {}", wstr_to_utf8(name));
FreeLibrary(module);
return;
}
}
if(!gAcceptList.empty())
{
auto iter = std::find_if(gAcceptList.cbegin(), gAcceptList.cend(),
[name](const std::wstring_view accept)
{ return al::case_compare(name, accept) == 0; });
if(iter == gAcceptList.cend())
{
TRACE("{} not found in ALROUTER_ACCEPT, skipping", wstr_to_utf8(name));
FreeLibrary(module);
return;
}
}
if(!gRejectList.empty())
{
auto iter = std::find_if(gRejectList.cbegin(), gRejectList.cend(),
[name](const std::wstring_view accept)
{ return al::case_compare(name, accept) == 0; });
if(iter != gRejectList.cend())
{
TRACE("{} found in ALROUTER_REJECT, skipping", wstr_to_utf8(name));
FreeLibrary(module);
return;
}
}
DriverList.emplace_back(std::make_unique<DriverIface>(name, module));
DriverIface &newdrv = *DriverList.back();
DriverIface &newdrv = *DriverList.emplace_back(std::make_unique<DriverIface>(name, module));
/* Load required functions. */
int err = 0;
#define LOAD_PROC(x) do { \
newdrv.x = reinterpret_cast<decltype(newdrv.x)>(reinterpret_cast<void*>( \
GetProcAddress(module, #x))); \
if(!newdrv.x) \
{ \
ERR("Failed to find entry point for %s in %ls\n", #x, name); \
err = 1; \
} \
} while(0)
bool loadok{true};
auto do_load = [module,name](auto &func, const char *fname) -> bool
{
using func_t = std::remove_reference_t<decltype(func)>;
auto ptr = GetProcAddress(module, fname);
if(!ptr)
{
ERR("Failed to find entry point for {} in {}", fname, wstr_to_utf8(name));
return false;
}
func = al::bit_cast<func_t>(ptr);
return true;
};
#define LOAD_PROC(x) loadok &= do_load(newdrv.x, #x)
LOAD_PROC(alcCreateContext);
LOAD_PROC(alcMakeContextCurrent);
LOAD_PROC(alcProcessContext);
@@ -185,262 +174,284 @@ static void AddModule(HMODULE module, const WCHAR *name)
LOAD_PROC(alDopplerVelocity);
LOAD_PROC(alSpeedOfSound);
LOAD_PROC(alDistanceModel);
if(!err)
#undef LOAD_PROC
if(loadok)
{
ALCint alc_ver[2] = { 0, 0 };
std::array<ALCint,2> alc_ver{0, 0};
newdrv.alcGetIntegerv(nullptr, ALC_MAJOR_VERSION, 1, &alc_ver[0]);
newdrv.alcGetIntegerv(nullptr, ALC_MINOR_VERSION, 1, &alc_ver[1]);
if(newdrv.alcGetError(nullptr) == ALC_NO_ERROR)
newdrv.ALCVer = MAKE_ALC_VER(alc_ver[0], alc_ver[1]);
newdrv.ALCVer = MakeALCVer(alc_ver[0], alc_ver[1]);
else
{
WARN("Failed to query ALC version for %ls, assuming 1.0\n", name);
newdrv.ALCVer = MAKE_ALC_VER(1, 0);
WARN("Failed to query ALC version for {}, assuming 1.0", wstr_to_utf8(name));
newdrv.ALCVer = MakeALCVer(1, 0);
}
auto do_load2 = [module,name](auto &func, const char *fname) -> void
{
using func_t = std::remove_reference_t<decltype(func)>;
auto ptr = GetProcAddress(module, fname);
if(!ptr)
WARN("Failed to find optional entry point for {} in {}", fname,
wstr_to_utf8(name));
else
func = al::bit_cast<func_t>(ptr);
};
#define LOAD_PROC(x) do_load2(newdrv.x, #x)
LOAD_PROC(alBufferf);
LOAD_PROC(alBuffer3f);
LOAD_PROC(alBufferfv);
LOAD_PROC(alBufferi);
LOAD_PROC(alBuffer3i);
LOAD_PROC(alBufferiv);
LOAD_PROC(alGetBufferf);
LOAD_PROC(alGetBuffer3f);
LOAD_PROC(alGetBufferfv);
LOAD_PROC(alGetBufferi);
LOAD_PROC(alGetBuffer3i);
LOAD_PROC(alGetBufferiv);
#undef LOAD_PROC
#define LOAD_PROC(x) do { \
newdrv.x = reinterpret_cast<decltype(newdrv.x)>(reinterpret_cast<void*>( \
GetProcAddress(module, #x))); \
if(!newdrv.x) \
{ \
WARN("Failed to find optional entry point for %s in %ls\n", #x, name); \
} \
} while(0)
LOAD_PROC(alBufferf);
LOAD_PROC(alBuffer3f);
LOAD_PROC(alBufferfv);
LOAD_PROC(alBufferi);
LOAD_PROC(alBuffer3i);
LOAD_PROC(alBufferiv);
LOAD_PROC(alGetBufferf);
LOAD_PROC(alGetBuffer3f);
LOAD_PROC(alGetBufferfv);
LOAD_PROC(alGetBufferi);
LOAD_PROC(alGetBuffer3i);
LOAD_PROC(alGetBufferiv);
#undef LOAD_PROC
#define LOAD_PROC(x) do { \
newdrv.x = reinterpret_cast<decltype(newdrv.x)>( \
newdrv.alcGetProcAddress(nullptr, #x)); \
if(!newdrv.x) \
{ \
ERR("Failed to find entry point for %s in %ls\n", #x, name); \
err = 1; \
} \
} while(0)
auto do_load3 = [name,&newdrv](auto &func, const char *fname) -> bool
{
using func_t = std::remove_reference_t<decltype(func)>;
auto ptr = newdrv.alcGetProcAddress(nullptr, fname);
if(!ptr)
{
ERR("Failed to find entry point for {} in {}", fname, wstr_to_utf8(name));
return false;
}
func = reinterpret_cast<func_t>(ptr);
return true;
};
#define LOAD_PROC(x) loadok &= do_load3(newdrv.x, #x)
if(newdrv.alcIsExtensionPresent(nullptr, "ALC_EXT_thread_local_context"))
{
LOAD_PROC(alcSetThreadContext);
LOAD_PROC(alcGetThreadContext);
}
#undef LOAD_PROC
}
if(err)
if(!loadok)
{
DriverList.pop_back();
return;
}
TRACE("Loaded module %p, %ls, ALC %d.%d\n", decltype(std::declval<void*>()){module}, name,
newdrv.ALCVer>>8, newdrv.ALCVer&255);
#undef LOAD_PROC
TRACE("Loaded module {}, {}, ALC {}.{}", decltype(std::declval<void*>()){module},
wstr_to_utf8(name), newdrv.ALCVer>>8, newdrv.ALCVer&255);
}
static void SearchDrivers(WCHAR *path)
void SearchDrivers(const std::wstring_view path)
{
WIN32_FIND_DATAW fdata;
TRACE("Searching for drivers in %ls...\n", path);
std::wstring srchPath = path;
TRACE("Searching for drivers in {}...", wstr_to_utf8(path));
std::wstring srchPath{path};
srchPath += L"\\*oal.dll";
HANDLE srchHdl = FindFirstFileW(srchPath.c_str(), &fdata);
if(srchHdl != INVALID_HANDLE_VALUE)
{
do {
HMODULE mod;
WIN32_FIND_DATAW fdata{};
HANDLE srchHdl{FindFirstFileW(srchPath.c_str(), &fdata)};
if(srchHdl == INVALID_HANDLE_VALUE) return;
srchPath = path;
srchPath += L"\\";
srchPath += fdata.cFileName;
TRACE("Found %ls\n", srchPath.c_str());
do {
srchPath = path;
srchPath += L"\\";
srchPath += std::data(fdata.cFileName);
TRACE("Found {}", wstr_to_utf8(srchPath));
mod = LoadLibraryW(srchPath.c_str());
if(!mod)
WARN("Could not load %ls\n", srchPath.c_str());
else
AddModule(mod, fdata.cFileName);
} while(FindNextFileW(srchHdl, &fdata));
FindClose(srchHdl);
}
HMODULE mod{LoadLibraryW(srchPath.c_str())};
if(!mod)
WARN("Could not load {}", wstr_to_utf8(srchPath));
else
AddModule(mod, std::data(fdata.cFileName));
} while(FindNextFileW(srchHdl, &fdata));
FindClose(srchHdl);
}
static WCHAR *strrchrW(WCHAR *str, WCHAR ch)
bool GetLoadedModuleDirectory(const WCHAR *name, std::wstring *moddir)
{
WCHAR *res = nullptr;
while(str && *str != '\0')
{
if(*str == ch)
res = str;
++str;
}
return res;
}
static int GetLoadedModuleDirectory(const WCHAR *name, WCHAR *moddir, DWORD length)
{
HMODULE module = nullptr;
WCHAR *sep0, *sep1;
HMODULE module{nullptr};
if(name)
{
module = GetModuleHandleW(name);
if(!module) return 0;
if(!module) return false;
}
if(GetModuleFileNameW(module, moddir, length) == 0)
return 0;
moddir->assign(256, '\0');
DWORD res{GetModuleFileNameW(module, moddir->data(), static_cast<DWORD>(moddir->size()))};
if(res >= moddir->size())
{
do {
moddir->append(256, '\0');
res = GetModuleFileNameW(module, moddir->data(), static_cast<DWORD>(moddir->size()));
} while(res >= moddir->size());
}
moddir->resize(res);
sep0 = strrchrW(moddir, '/');
if(sep0) sep1 = strrchrW(sep0+1, '\\');
else sep1 = strrchrW(moddir, '\\');
auto sep0 = moddir->rfind('/');
auto sep1 = moddir->rfind('\\');
if(sep0 < moddir->size() && sep1 < moddir->size())
moddir->resize(std::max(sep0, sep1));
else if(sep0 < moddir->size())
moddir->resize(sep0);
else if(sep1 < moddir->size())
moddir->resize(sep1);
else
moddir->resize(0);
if(sep1) *sep1 = '\0';
else if(sep0) *sep0 = '\0';
else *moddir = '\0';
return 1;
return !moddir->empty();
}
} // namespace
void LoadDriverList()
{
WCHAR dll_path[MAX_PATH+1] = L"";
WCHAR cwd_path[MAX_PATH+1] = L"";
WCHAR proc_path[MAX_PATH+1] = L"";
WCHAR sys_path[MAX_PATH+1] = L"";
TRACE("Initializing router v0.1-{} {}", ALSOFT_GIT_COMMIT_HASH, ALSOFT_GIT_BRANCH);
if(GetLoadedModuleDirectory(L"OpenAL32.dll", dll_path, MAX_PATH))
TRACE("Got DLL path %ls\n", dll_path);
if(auto list = al::getenv(L"ALROUTER_ACCEPT"))
{
std::wstring_view namelist{*list};
while(!namelist.empty())
{
auto seppos = namelist.find(',');
if(seppos > 0)
gAcceptList.emplace_back(namelist.substr(0, seppos));
if(seppos < namelist.size())
namelist.remove_prefix(seppos+1);
else
namelist.remove_prefix(namelist.size());
}
}
if(auto list = al::getenv(L"ALROUTER_REJECT"))
{
std::wstring_view namelist{*list};
while(!namelist.empty())
{
auto seppos = namelist.find(',');
if(seppos > 0)
gRejectList.emplace_back(namelist.substr(0, seppos));
if(seppos < namelist.size())
namelist.remove_prefix(seppos+1);
else
namelist.remove_prefix(namelist.size());
}
}
GetCurrentDirectoryW(MAX_PATH, cwd_path);
auto len = wcslen(cwd_path);
if(len > 0 && (cwd_path[len-1] == '\\' || cwd_path[len-1] == '/'))
cwd_path[len-1] = '\0';
TRACE("Got current working directory %ls\n", cwd_path);
std::wstring dll_path;
if(GetLoadedModuleDirectory(L"OpenAL32.dll", &dll_path))
TRACE("Got DLL path {}", wstr_to_utf8(dll_path));
if(GetLoadedModuleDirectory(nullptr, proc_path, MAX_PATH))
TRACE("Got proc path %ls\n", proc_path);
std::wstring cwd_path;
if(DWORD pathlen{GetCurrentDirectoryW(0, nullptr)})
{
do {
cwd_path.resize(pathlen);
pathlen = GetCurrentDirectoryW(pathlen, cwd_path.data());
} while(pathlen >= cwd_path.size());
cwd_path.resize(pathlen);
}
if(!cwd_path.empty() && (cwd_path.back() == '\\' || cwd_path.back() == '/'))
cwd_path.pop_back();
if(!cwd_path.empty())
TRACE("Got current working directory {}", wstr_to_utf8(cwd_path));
GetSystemDirectoryW(sys_path, MAX_PATH);
len = wcslen(sys_path);
if(len > 0 && (sys_path[len-1] == '\\' || sys_path[len-1] == '/'))
sys_path[len-1] = '\0';
TRACE("Got system path %ls\n", sys_path);
std::wstring proc_path;
if(GetLoadedModuleDirectory(nullptr, &proc_path))
TRACE("Got proc path {}", wstr_to_utf8(proc_path));
std::wstring sys_path;
if(UINT pathlen{GetSystemDirectoryW(nullptr, 0)})
{
do {
sys_path.resize(pathlen);
pathlen = GetSystemDirectoryW(sys_path.data(), pathlen);
} while(pathlen >= sys_path.size());
sys_path.resize(pathlen);
}
if(!sys_path.empty() && (sys_path.back() == '\\' || sys_path.back() == '/'))
sys_path.pop_back();
if(!sys_path.empty())
TRACE("Got system path {}", wstr_to_utf8(sys_path));
/* Don't search the DLL's path if it is the same as the current working
* directory, app's path, or system path (don't want to do duplicate
* searches, or increase the priority of the app or system path).
*/
if(dll_path[0] &&
(!cwd_path[0] || wcscmp(dll_path, cwd_path) != 0) &&
(!proc_path[0] || wcscmp(dll_path, proc_path) != 0) &&
(!sys_path[0] || wcscmp(dll_path, sys_path) != 0))
if(!dll_path.empty() && (cwd_path.empty() || dll_path != cwd_path)
&& (proc_path.empty() || dll_path != proc_path)
&& (sys_path.empty() || dll_path != sys_path))
SearchDrivers(dll_path);
if(cwd_path[0] &&
(!proc_path[0] || wcscmp(cwd_path, proc_path) != 0) &&
(!sys_path[0] || wcscmp(cwd_path, sys_path) != 0))
if(!cwd_path.empty() && (proc_path.empty() || cwd_path != proc_path)
&& (sys_path.empty() || cwd_path != sys_path))
SearchDrivers(cwd_path);
if(proc_path[0] && (!sys_path[0] || wcscmp(proc_path, sys_path) != 0))
if(!proc_path.empty() && (sys_path.empty() || proc_path != sys_path))
SearchDrivers(proc_path);
if(sys_path[0])
if(!sys_path.empty())
SearchDrivers(sys_path);
}
PtrIntMap::~PtrIntMap()
{
std::lock_guard<std::mutex> maplock{mLock};
free(mKeys);
mKeys = nullptr;
mValues = nullptr;
mSize = 0;
mCapacity = 0;
}
ALenum PtrIntMap::insert(void *key, int value)
{
std::lock_guard<std::mutex> maplock{mLock};
auto iter = std::lower_bound(mKeys, mKeys+mSize, key);
auto pos = static_cast<ALsizei>(std::distance(mKeys, iter));
if(pos == mSize || mKeys[pos] != key)
/* Sort drivers that can enumerate device names to the front. */
static constexpr auto is_enumerable = [](DriverIfacePtr &drv)
{
if(mSize == mCapacity)
{
void **newkeys{nullptr};
ALsizei newcap{mCapacity ? (mCapacity<<1) : 4};
if(newcap > mCapacity)
newkeys = static_cast<void**>(
calloc(newcap, sizeof(mKeys[0])+sizeof(mValues[0])));
if(!newkeys)
return AL_OUT_OF_MEMORY;
auto newvalues = reinterpret_cast<int*>(&newkeys[newcap]);
return drv->ALCVer >= MakeALCVer(1, 1)
|| drv->alcIsExtensionPresent(nullptr, "ALC_ENUMERATE_ALL_EXT")
|| drv->alcIsExtensionPresent(nullptr, "ALC_ENUMERATION_EXT");
};
std::stable_partition(DriverList.begin(), DriverList.end(), is_enumerable);
if(mKeys)
{
std::copy_n(mKeys, mSize, newkeys);
std::copy_n(mValues, mSize, newvalues);
}
free(mKeys);
mKeys = newkeys;
mValues = newvalues;
mCapacity = newcap;
}
if(pos < mSize)
{
std::copy_backward(mKeys+pos, mKeys+mSize, mKeys+mSize+1);
std::copy_backward(mValues+pos, mValues+mSize, mValues+mSize+1);
}
mSize++;
}
mKeys[pos] = key;
mValues[pos] = value;
return AL_NO_ERROR;
/* HACK: rapture3d_oal.dll isn't likely to work if it's one distributed for
* specific games licensed to use it. It will enumerate a Rapture3D device
* but fail to open. This isn't much of a problem, the device just won't
* work for users not allowed to use it. But if it's the first in the list
* where it gets used for the default device, the default device will fail
* to open. Move it down so it's not used for the default device.
*/
if(DriverList.size() > 1
&& al::case_compare(DriverList.front()->Name, L"rapture3d_oal.dll") == 0)
std::swap(*DriverList.begin(), *(DriverList.begin()+1));
}
int PtrIntMap::removeByKey(void *key)
BOOL APIENTRY DllMain(HINSTANCE, DWORD reason, void*)
{
int ret = -1;
std::lock_guard<std::mutex> maplock{mLock};
auto iter = std::lower_bound(mKeys, mKeys+mSize, key);
auto pos = static_cast<ALsizei>(std::distance(mKeys, iter));
if(pos < mSize && mKeys[pos] == key)
switch(reason)
{
ret = mValues[pos];
if(pos+1 < mSize)
case DLL_PROCESS_ATTACH:
if(auto logfname = al::getenv(L"ALROUTER_LOGFILE"))
{
std::copy(mKeys+pos+1, mKeys+mSize, mKeys+pos);
std::copy(mValues+pos+1, mValues+mSize, mValues+pos);
gsl::owner<std::FILE*> f{_wfopen(logfname->c_str(), L"w")};
if(f == nullptr)
ERR("Could not open log file: {}", wstr_to_utf8(*logfname));
else
LogFile = f;
}
mSize--;
if(auto loglev = al::getenv("ALROUTER_LOGLEVEL"))
{
char *end = nullptr;
long l{strtol(loglev->c_str(), &end, 0)};
if(!end || *end != '\0')
ERR("Invalid log level value: {}", *loglev);
else if(l < al::to_underlying(eLogLevel::None)
|| l > al::to_underlying(eLogLevel::Trace))
ERR("Log level out of range: {}", *loglev);
else
LogLevel = static_cast<eLogLevel>(l);
}
break;
case DLL_THREAD_ATTACH:
break;
case DLL_THREAD_DETACH:
break;
case DLL_PROCESS_DETACH:
DriverList.clear();
if(LogFile)
fclose(LogFile);
LogFile = nullptr;
break;
}
return ret;
}
int PtrIntMap::lookupByKey(void *key)
{
int ret = -1;
std::lock_guard<std::mutex> maplock{mLock};
auto iter = std::lower_bound(mKeys, mKeys+mSize, key);
auto pos = static_cast<ALsizei>(std::distance(mKeys, iter));
if(pos < mSize && mKeys[pos] == key)
ret = mValues[pos];
return ret;
return TRUE;
}
+50 -63
View File
@@ -5,9 +5,8 @@
#include <windows.h>
#include <winnt.h>
#include <stdio.h>
#include <atomic>
#include <cstdio>
#include <memory>
#include <mutex>
#include <string>
@@ -18,15 +17,13 @@
#include "AL/al.h"
#include "AL/alext.h"
#include "almalloc.h"
#include "fmt/core.h"
#define MAKE_ALC_VER(major, minor) (((major)<<8) | (minor))
constexpr auto MakeALCVer(int major, int minor) noexcept -> int { return (major<<8) | minor; }
struct DriverIface {
std::wstring Name;
HMODULE Module{nullptr};
int ALCVer{0};
std::once_flag InitOnceCtx{};
LPALCCREATECONTEXT alcCreateContext{nullptr};
LPALCMAKECONTEXTCURRENT alcMakeContextCurrent{nullptr};
LPALCPROCESSCONTEXT alcProcessContext{nullptr};
@@ -160,16 +157,19 @@ struct DriverIface {
LPALGETAUXILIARYEFFECTSLOTI alGetAuxiliaryEffectSloti{nullptr};
LPALGETAUXILIARYEFFECTSLOTIV alGetAuxiliaryEffectSlotiv{nullptr};
std::wstring Name;
HMODULE Module{nullptr};
int ALCVer{0};
std::once_flag InitOnceCtx;
template<typename T>
DriverIface(T&& name, HMODULE mod)
: Name(std::forward<T>(name)), Module(mod)
{ }
~DriverIface()
{
if(Module)
FreeLibrary(Module);
Module = nullptr;
}
DriverIface(T&& name, HMODULE mod) : Name(std::forward<T>(name)), Module(mod) { }
~DriverIface() { if(Module) FreeLibrary(Module); }
DriverIface(const DriverIface&) = delete;
DriverIface(DriverIface&&) = delete;
DriverIface& operator=(const DriverIface&) = delete;
DriverIface& operator=(DriverIface&&) = delete;
};
using DriverIfacePtr = std::unique_ptr<DriverIface>;
@@ -182,54 +182,41 @@ inline DriverIface *GetThreadDriver() noexcept { return ThreadCtxDriver; }
inline void SetThreadDriver(DriverIface *driver) noexcept { ThreadCtxDriver = driver; }
class PtrIntMap {
void **mKeys{nullptr};
/* Shares memory with keys. */
int *mValues{nullptr};
ALsizei mSize{0};
ALsizei mCapacity{0};
std::mutex mLock;
public:
PtrIntMap() = default;
~PtrIntMap();
ALenum insert(void *key, int value);
int removeByKey(void *key);
int lookupByKey(void *key);
enum class eLogLevel {
None = 0,
Error = 1,
Warn = 2,
Trace = 3,
};
extern eLogLevel LogLevel;
extern gsl::owner<std::FILE*> LogFile;
#define TRACE(...) do { \
if(LogLevel >= eLogLevel::Trace) \
{ \
std::FILE *file{LogFile ? LogFile : stderr}; \
fmt::println(file, "AL Router (II): " __VA_ARGS__); \
fflush(file); \
} \
} while(0)
#define WARN(...) do { \
if(LogLevel >= eLogLevel::Warn) \
{ \
std::FILE *file{LogFile ? LogFile : stderr}; \
fmt::println(file, "AL Router (WW): " __VA_ARGS__); \
fflush(file); \
} \
} while(0)
#define ERR(...) do { \
if(LogLevel >= eLogLevel::Error) \
{ \
std::FILE *file{LogFile ? LogFile : stderr}; \
fmt::println(file, "AL Router (EE): " __VA_ARGS__); \
fflush(file); \
} \
} while(0)
enum LogLevel {
LogLevel_None = 0,
LogLevel_Error = 1,
LogLevel_Warn = 2,
LogLevel_Trace = 3,
};
extern enum LogLevel LogLevel;
extern FILE *LogFile;
#define TRACE(...) do { \
if(LogLevel >= LogLevel_Trace) \
{ \
fprintf(LogFile, "AL Router (II): " __VA_ARGS__); \
fflush(LogFile); \
} \
} while(0)
#define WARN(...) do { \
if(LogLevel >= LogLevel_Warn) \
{ \
fprintf(LogFile, "AL Router (WW): " __VA_ARGS__); \
fflush(LogFile); \
} \
} while(0)
#define ERR(...) do { \
if(LogLevel >= LogLevel_Error) \
{ \
fprintf(LogFile, "AL Router (EE): " __VA_ARGS__); \
fflush(LogFile); \
} \
} while(0)
void LoadDriverList();
#endif /* ROUTER_ROUTER_H */