aboutsummaryrefslogtreecommitdiffstats
path: root/al
diff options
context:
space:
mode:
Diffstat (limited to 'al')
-rw-r--r--al/alAuxEffectSlot.cpp808
-rw-r--r--al/alAuxEffectSlot.h103
-rw-r--r--al/alBuffer.cpp1408
-rw-r--r--al/alBuffer.h121
-rw-r--r--al/alEffect.cpp742
-rw-r--r--al/alEffect.h61
-rw-r--r--al/alError.cpp118
-rw-r--r--al/alError.h24
-rw-r--r--al/alExtension.cpp80
-rw-r--r--al/alFilter.cpp665
-rw-r--r--al/alFilter.h56
-rw-r--r--al/alListener.cpp454
-rw-r--r--al/alListener.h58
-rw-r--r--al/alSource.cpp3638
-rw-r--r--al/alSource.h131
-rw-r--r--al/alState.cpp859
-rw-r--r--al/event.cpp216
17 files changed, 9542 insertions, 0 deletions
diff --git a/al/alAuxEffectSlot.cpp b/al/alAuxEffectSlot.cpp
new file mode 100644
index 00000000..42966bf2
--- /dev/null
+++ b/al/alAuxEffectSlot.cpp
@@ -0,0 +1,808 @@
+/**
+ * OpenAL cross platform audio library
+ * Copyright (C) 1999-2007 by authors.
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library; if not, write to the
+ * Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ * Or go to http://www.gnu.org/copyleft/lgpl.html
+ */
+
+#include "config.h"
+
+#include "alAuxEffectSlot.h"
+
+#include <algorithm>
+#include <cstdint>
+#include <iterator>
+#include <memory>
+#include <mutex>
+#include <thread>
+
+#include "AL/al.h"
+#include "AL/alc.h"
+
+#include "alEffect.h"
+#include "alError.h"
+#include "alcmain.h"
+#include "alcontext.h"
+#include "alexcpt.h"
+#include "almalloc.h"
+#include "alnumeric.h"
+#include "alspan.h"
+#include "alu.h"
+#include "fpu_modes.h"
+#include "inprogext.h"
+#include "logging.h"
+#include "opthelpers.h"
+
+
+namespace {
+
+inline ALeffectslot *LookupEffectSlot(ALCcontext *context, ALuint id) noexcept
+{
+ ALuint lidx = (id-1) >> 6;
+ ALsizei slidx = (id-1) & 0x3f;
+
+ if(UNLIKELY(lidx >= context->EffectSlotList.size()))
+ return nullptr;
+ EffectSlotSubList &sublist{context->EffectSlotList[lidx]};
+ if(UNLIKELY(sublist.FreeMask & (1_u64 << slidx)))
+ return nullptr;
+ return sublist.EffectSlots + slidx;
+}
+
+inline ALeffect *LookupEffect(ALCdevice *device, ALuint id) noexcept
+{
+ ALuint lidx = (id-1) >> 6;
+ ALsizei slidx = (id-1) & 0x3f;
+
+ if(UNLIKELY(lidx >= device->EffectList.size()))
+ return nullptr;
+ EffectSubList &sublist = device->EffectList[lidx];
+ if(UNLIKELY(sublist.FreeMask & (1_u64 << slidx)))
+ return nullptr;
+ return sublist.Effects + slidx;
+}
+
+
+void AddActiveEffectSlots(const ALuint *slotids, ALsizei count, ALCcontext *context)
+{
+ if(count < 1) return;
+ ALeffectslotArray *curarray{context->ActiveAuxSlots.load(std::memory_order_acquire)};
+ size_t newcount{curarray->size() + count};
+
+ /* Insert the new effect slots into the head of the array, followed by the
+ * existing ones.
+ */
+ ALeffectslotArray *newarray = ALeffectslot::CreatePtrArray(newcount);
+ auto slotiter = std::transform(slotids, slotids+count, newarray->begin(),
+ [context](ALuint id) noexcept -> ALeffectslot*
+ { return LookupEffectSlot(context, id); }
+ );
+ std::copy(curarray->begin(), curarray->end(), slotiter);
+
+ /* Remove any duplicates (first instance of each will be kept). */
+ auto last = newarray->end();
+ for(auto start=newarray->begin()+1;;)
+ {
+ last = std::remove(start, last, *(start-1));
+ if(start == last) break;
+ ++start;
+ }
+ newcount = static_cast<size_t>(std::distance(newarray->begin(), last));
+
+ /* Reallocate newarray if the new size ended up smaller from duplicate
+ * removal.
+ */
+ if(UNLIKELY(newcount < newarray->size()))
+ {
+ curarray = newarray;
+ newarray = ALeffectslot::CreatePtrArray(newcount);
+ std::copy_n(curarray->begin(), newcount, newarray->begin());
+ delete curarray;
+ curarray = nullptr;
+ }
+
+ curarray = context->ActiveAuxSlots.exchange(newarray, std::memory_order_acq_rel);
+ ALCdevice *device{context->Device};
+ while((device->MixCount.load(std::memory_order_acquire)&1))
+ std::this_thread::yield();
+ delete curarray;
+}
+
+void RemoveActiveEffectSlots(const ALuint *slotids, ALsizei count, ALCcontext *context)
+{
+ if(count < 1) return;
+ ALeffectslotArray *curarray{context->ActiveAuxSlots.load(std::memory_order_acquire)};
+
+ /* Don't shrink the allocated array size since we don't know how many (if
+ * any) of the effect slots to remove are in the array.
+ */
+ ALeffectslotArray *newarray = ALeffectslot::CreatePtrArray(curarray->size());
+
+ /* Copy each element in curarray to newarray whose ID is not in slotids. */
+ const ALuint *slotids_end{slotids + count};
+ auto slotiter = std::copy_if(curarray->begin(), curarray->end(), newarray->begin(),
+ [slotids, slotids_end](const ALeffectslot *slot) -> bool
+ { return std::find(slotids, slotids_end, slot->id) == slotids_end; }
+ );
+
+ /* Reallocate with the new size. */
+ auto newsize = static_cast<size_t>(std::distance(newarray->begin(), slotiter));
+ if(LIKELY(newsize != newarray->size()))
+ {
+ curarray = newarray;
+ newarray = ALeffectslot::CreatePtrArray(newsize);
+ std::copy_n(curarray->begin(), newsize, newarray->begin());
+
+ delete curarray;
+ curarray = nullptr;
+ }
+
+ curarray = context->ActiveAuxSlots.exchange(newarray, std::memory_order_acq_rel);
+ ALCdevice *device{context->Device};
+ while((device->MixCount.load(std::memory_order_acquire)&1))
+ std::this_thread::yield();
+ delete curarray;
+}
+
+
+ALeffectslot *AllocEffectSlot(ALCcontext *context)
+{
+ ALCdevice *device{context->Device};
+ std::lock_guard<std::mutex> _{context->EffectSlotLock};
+ if(context->NumEffectSlots >= device->AuxiliaryEffectSlotMax)
+ {
+ alSetError(context, AL_OUT_OF_MEMORY, "Exceeding %u effect slot limit",
+ device->AuxiliaryEffectSlotMax);
+ return nullptr;
+ }
+ auto sublist = std::find_if(context->EffectSlotList.begin(), context->EffectSlotList.end(),
+ [](const EffectSlotSubList &entry) noexcept -> bool
+ { return entry.FreeMask != 0; }
+ );
+ auto lidx = static_cast<ALsizei>(std::distance(context->EffectSlotList.begin(), sublist));
+ ALeffectslot *slot;
+ ALsizei slidx;
+ if(LIKELY(sublist != context->EffectSlotList.end()))
+ {
+ slidx = CTZ64(sublist->FreeMask);
+ slot = sublist->EffectSlots + slidx;
+ }
+ else
+ {
+ /* Don't allocate so many list entries that the 32-bit ID could
+ * overflow...
+ */
+ if(UNLIKELY(context->EffectSlotList.size() >= 1<<25))
+ {
+ alSetError(context, AL_OUT_OF_MEMORY, "Too many effect slots allocated");
+ return nullptr;
+ }
+ context->EffectSlotList.emplace_back();
+ sublist = context->EffectSlotList.end() - 1;
+
+ sublist->FreeMask = ~0_u64;
+ sublist->EffectSlots = static_cast<ALeffectslot*>(al_calloc(16, sizeof(ALeffectslot)*64));
+ if(UNLIKELY(!sublist->EffectSlots))
+ {
+ context->EffectSlotList.pop_back();
+ alSetError(context, AL_OUT_OF_MEMORY, "Failed to allocate effect slot batch");
+ return nullptr;
+ }
+
+ slidx = 0;
+ slot = sublist->EffectSlots + slidx;
+ }
+
+ slot = new (slot) ALeffectslot{};
+ ALenum err{InitEffectSlot(slot)};
+ if(err != AL_NO_ERROR)
+ {
+ al::destroy_at(slot);
+ alSetError(context, err, "Effect slot object initialization failed");
+ return nullptr;
+ }
+ aluInitEffectPanning(slot, device);
+
+ /* Add 1 to avoid source ID 0. */
+ slot->id = ((lidx<<6) | slidx) + 1;
+
+ context->NumEffectSlots += 1;
+ sublist->FreeMask &= ~(1_u64 << slidx);
+
+ return slot;
+}
+
+void FreeEffectSlot(ALCcontext *context, ALeffectslot *slot)
+{
+ ALuint id = slot->id - 1;
+ ALsizei lidx = id >> 6;
+ ALsizei slidx = id & 0x3f;
+
+ al::destroy_at(slot);
+
+ context->EffectSlotList[lidx].FreeMask |= 1_u64 << slidx;
+ context->NumEffectSlots--;
+}
+
+
+#define DO_UPDATEPROPS() do { \
+ if(!context->DeferUpdates.load(std::memory_order_acquire)) \
+ UpdateEffectSlotProps(slot, context.get()); \
+ else \
+ slot->PropsClean.clear(std::memory_order_release); \
+} while(0)
+
+} // namespace
+
+ALeffectslotArray *ALeffectslot::CreatePtrArray(size_t count) noexcept
+{
+ /* Allocate space for twice as many pointers, so the mixer has scratch
+ * space to store a sorted list during mixing.
+ */
+ void *ptr{al_calloc(alignof(ALeffectslotArray), ALeffectslotArray::Sizeof(count*2))};
+ return new (ptr) ALeffectslotArray{count};
+}
+
+
+AL_API ALvoid AL_APIENTRY alGenAuxiliaryEffectSlots(ALsizei n, ALuint *effectslots)
+START_API_FUNC
+{
+ ContextRef context{GetContextRef()};
+ if(UNLIKELY(!context)) return;
+
+ if(n < 0)
+ SETERR_RETURN(context.get(), AL_INVALID_VALUE,, "Generating %d effect slots", n);
+ if(n == 0) return;
+
+ if(n == 1)
+ {
+ ALeffectslot *slot{AllocEffectSlot(context.get())};
+ if(!slot) return;
+ effectslots[0] = slot->id;
+ }
+ else
+ {
+ auto tempids = al::vector<ALuint>(n);
+ auto alloc_end = std::find_if_not(tempids.begin(), tempids.end(),
+ [&context](ALuint &id) -> bool
+ {
+ ALeffectslot *slot{AllocEffectSlot(context.get())};
+ if(!slot) return false;
+ id = slot->id;
+ return true;
+ }
+ );
+ if(alloc_end != tempids.end())
+ {
+ auto count = static_cast<ALsizei>(std::distance(tempids.begin(), alloc_end));
+ alDeleteAuxiliaryEffectSlots(count, tempids.data());
+ return;
+ }
+
+ std::copy(tempids.cbegin(), tempids.cend(), effectslots);
+ }
+
+ std::unique_lock<std::mutex> slotlock{context->EffectSlotLock};
+ AddActiveEffectSlots(effectslots, n, context.get());
+}
+END_API_FUNC
+
+AL_API ALvoid AL_APIENTRY alDeleteAuxiliaryEffectSlots(ALsizei n, const ALuint *effectslots)
+START_API_FUNC
+{
+ ContextRef context{GetContextRef()};
+ if(UNLIKELY(!context)) return;
+
+ if(n < 0)
+ SETERR_RETURN(context.get(), AL_INVALID_VALUE,, "Deleting %d effect slots", n);
+ if(n == 0) return;
+
+ std::lock_guard<std::mutex> _{context->EffectSlotLock};
+ auto effectslots_end = effectslots + n;
+ auto bad_slot = std::find_if(effectslots, effectslots_end,
+ [&context](ALuint id) -> bool
+ {
+ ALeffectslot *slot{LookupEffectSlot(context.get(), id)};
+ if(!slot)
+ {
+ alSetError(context.get(), AL_INVALID_NAME, "Invalid effect slot ID %u", id);
+ return true;
+ }
+ if(ReadRef(&slot->ref) != 0)
+ {
+ alSetError(context.get(), AL_INVALID_NAME, "Deleting in-use effect slot %u", id);
+ return true;
+ }
+ return false;
+ }
+ );
+ if(bad_slot != effectslots_end)
+ return;
+
+ // All effectslots are valid, remove and delete them
+ RemoveActiveEffectSlots(effectslots, n, context.get());
+ std::for_each(effectslots, effectslots_end,
+ [&context](ALuint sid) -> void
+ {
+ ALeffectslot *slot{LookupEffectSlot(context.get(), sid)};
+ if(slot) FreeEffectSlot(context.get(), slot);
+ }
+ );
+}
+END_API_FUNC
+
+AL_API ALboolean AL_APIENTRY alIsAuxiliaryEffectSlot(ALuint effectslot)
+START_API_FUNC
+{
+ ContextRef context{GetContextRef()};
+ if(LIKELY(context))
+ {
+ std::lock_guard<std::mutex> _{context->EffectSlotLock};
+ if(LookupEffectSlot(context.get(), effectslot) != nullptr)
+ return AL_TRUE;
+ }
+ return AL_FALSE;
+}
+END_API_FUNC
+
+
+AL_API ALvoid AL_APIENTRY alAuxiliaryEffectSloti(ALuint effectslot, ALenum param, ALint value)
+START_API_FUNC
+{
+ ContextRef context{GetContextRef()};
+ if(UNLIKELY(!context)) return;
+
+ std::lock_guard<std::mutex> _{context->PropLock};
+ std::lock_guard<std::mutex> __{context->EffectSlotLock};
+ ALeffectslot *slot = LookupEffectSlot(context.get(), effectslot);
+ if(UNLIKELY(!slot))
+ SETERR_RETURN(context.get(), AL_INVALID_NAME,, "Invalid effect slot ID %u", effectslot);
+
+ ALeffectslot *target{};
+ ALCdevice *device{};
+ ALenum err{};
+ switch(param)
+ {
+ case AL_EFFECTSLOT_EFFECT:
+ device = context->Device;
+
+ { std::lock_guard<std::mutex> ___{device->EffectLock};
+ ALeffect *effect{value ? LookupEffect(device, value) : nullptr};
+ if(!(value == 0 || effect != nullptr))
+ SETERR_RETURN(context.get(), AL_INVALID_VALUE,, "Invalid effect ID %u", value);
+ err = InitializeEffect(context.get(), slot, effect);
+ }
+ if(err != AL_NO_ERROR)
+ {
+ alSetError(context.get(), err, "Effect initialization failed");
+ return;
+ }
+ break;
+
+ case AL_EFFECTSLOT_AUXILIARY_SEND_AUTO:
+ if(!(value == AL_TRUE || value == AL_FALSE))
+ SETERR_RETURN(context.get(), AL_INVALID_VALUE,,
+ "Effect slot auxiliary send auto out of range");
+ slot->AuxSendAuto = value;
+ break;
+
+ case AL_EFFECTSLOT_TARGET_SOFT:
+ target = (value ? LookupEffectSlot(context.get(), value) : nullptr);
+ if(value && !target)
+ SETERR_RETURN(context.get(), AL_INVALID_VALUE,, "Invalid effect slot target ID");
+ if(target)
+ {
+ ALeffectslot *checker{target};
+ while(checker && checker != slot)
+ checker = checker->Target;
+ if(checker)
+ SETERR_RETURN(context.get(), AL_INVALID_OPERATION,,
+ "Setting target of effect slot ID %u to %u creates circular chain", slot->id,
+ target->id);
+ }
+
+ if(ALeffectslot *oldtarget{slot->Target})
+ {
+ /* We must force an update if there was an existing effect slot
+ * target, in case it's about to be deleted.
+ */
+ if(target) IncrementRef(&target->ref);
+ DecrementRef(&oldtarget->ref);
+ slot->Target = target;
+ UpdateEffectSlotProps(slot, context.get());
+ return;
+ }
+
+ if(target) IncrementRef(&target->ref);
+ slot->Target = target;
+ break;
+
+ default:
+ SETERR_RETURN(context.get(), AL_INVALID_ENUM,,
+ "Invalid effect slot integer property 0x%04x", param);
+ }
+ DO_UPDATEPROPS();
+}
+END_API_FUNC
+
+AL_API ALvoid AL_APIENTRY alAuxiliaryEffectSlotiv(ALuint effectslot, ALenum param, const ALint *values)
+START_API_FUNC
+{
+ switch(param)
+ {
+ case AL_EFFECTSLOT_EFFECT:
+ case AL_EFFECTSLOT_AUXILIARY_SEND_AUTO:
+ case AL_EFFECTSLOT_TARGET_SOFT:
+ alAuxiliaryEffectSloti(effectslot, param, values[0]);
+ return;
+ }
+
+ ContextRef context{GetContextRef()};
+ if(UNLIKELY(!context)) return;
+
+ std::lock_guard<std::mutex> _{context->EffectSlotLock};
+ ALeffectslot *slot = LookupEffectSlot(context.get(), effectslot);
+ if(UNLIKELY(!slot))
+ SETERR_RETURN(context.get(), AL_INVALID_NAME,, "Invalid effect slot ID %u", effectslot);
+
+ switch(param)
+ {
+ default:
+ SETERR_RETURN(context.get(), AL_INVALID_ENUM,,
+ "Invalid effect slot integer-vector property 0x%04x", param);
+ }
+}
+END_API_FUNC
+
+AL_API ALvoid AL_APIENTRY alAuxiliaryEffectSlotf(ALuint effectslot, ALenum param, ALfloat value)
+START_API_FUNC
+{
+ ContextRef context{GetContextRef()};
+ if(UNLIKELY(!context)) return;
+
+ std::lock_guard<std::mutex> _{context->PropLock};
+ std::lock_guard<std::mutex> __{context->EffectSlotLock};
+ ALeffectslot *slot = LookupEffectSlot(context.get(), effectslot);
+ if(UNLIKELY(!slot))
+ SETERR_RETURN(context.get(), AL_INVALID_NAME,, "Invalid effect slot ID %u", effectslot);
+
+ switch(param)
+ {
+ case AL_EFFECTSLOT_GAIN:
+ if(!(value >= 0.0f && value <= 1.0f))
+ SETERR_RETURN(context.get(), AL_INVALID_VALUE,, "Effect slot gain out of range");
+ slot->Gain = value;
+ break;
+
+ default:
+ SETERR_RETURN(context.get(), AL_INVALID_ENUM,, "Invalid effect slot float property 0x%04x",
+ param);
+ }
+ DO_UPDATEPROPS();
+}
+END_API_FUNC
+
+AL_API ALvoid AL_APIENTRY alAuxiliaryEffectSlotfv(ALuint effectslot, ALenum param, const ALfloat *values)
+START_API_FUNC
+{
+ switch(param)
+ {
+ case AL_EFFECTSLOT_GAIN:
+ alAuxiliaryEffectSlotf(effectslot, param, values[0]);
+ return;
+ }
+
+ ContextRef context{GetContextRef()};
+ if(UNLIKELY(!context)) return;
+
+ std::lock_guard<std::mutex> _{context->EffectSlotLock};
+ ALeffectslot *slot = LookupEffectSlot(context.get(), effectslot);
+ if(UNLIKELY(!slot))
+ SETERR_RETURN(context.get(), AL_INVALID_NAME,, "Invalid effect slot ID %u", effectslot);
+
+ switch(param)
+ {
+ default:
+ SETERR_RETURN(context.get(), AL_INVALID_ENUM,,
+ "Invalid effect slot float-vector property 0x%04x", param);
+ }
+}
+END_API_FUNC
+
+
+AL_API ALvoid AL_APIENTRY alGetAuxiliaryEffectSloti(ALuint effectslot, ALenum param, ALint *value)
+START_API_FUNC
+{
+ ContextRef context{GetContextRef()};
+ if(UNLIKELY(!context)) return;
+
+ std::lock_guard<std::mutex> _{context->EffectSlotLock};
+ ALeffectslot *slot = LookupEffectSlot(context.get(), effectslot);
+ if(UNLIKELY(!slot))
+ SETERR_RETURN(context.get(), AL_INVALID_NAME,, "Invalid effect slot ID %u", effectslot);
+
+ switch(param)
+ {
+ case AL_EFFECTSLOT_AUXILIARY_SEND_AUTO:
+ *value = slot->AuxSendAuto;
+ break;
+
+ case AL_EFFECTSLOT_TARGET_SOFT:
+ *value = slot->Target ? slot->Target->id : 0;
+ break;
+
+ default:
+ SETERR_RETURN(context.get(), AL_INVALID_ENUM,,
+ "Invalid effect slot integer property 0x%04x", param);
+ }
+}
+END_API_FUNC
+
+AL_API ALvoid AL_APIENTRY alGetAuxiliaryEffectSlotiv(ALuint effectslot, ALenum param, ALint *values)
+START_API_FUNC
+{
+ switch(param)
+ {
+ case AL_EFFECTSLOT_EFFECT:
+ case AL_EFFECTSLOT_AUXILIARY_SEND_AUTO:
+ case AL_EFFECTSLOT_TARGET_SOFT:
+ alGetAuxiliaryEffectSloti(effectslot, param, values);
+ return;
+ }
+
+ ContextRef context{GetContextRef()};
+ if(UNLIKELY(!context)) return;
+
+ std::lock_guard<std::mutex> _{context->EffectSlotLock};
+ ALeffectslot *slot = LookupEffectSlot(context.get(), effectslot);
+ if(UNLIKELY(!slot))
+ SETERR_RETURN(context.get(), AL_INVALID_NAME,, "Invalid effect slot ID %u", effectslot);
+
+ switch(param)
+ {
+ default:
+ SETERR_RETURN(context.get(), AL_INVALID_ENUM,,
+ "Invalid effect slot integer-vector property 0x%04x", param);
+ }
+}
+END_API_FUNC
+
+AL_API ALvoid AL_APIENTRY alGetAuxiliaryEffectSlotf(ALuint effectslot, ALenum param, ALfloat *value)
+START_API_FUNC
+{
+ ContextRef context{GetContextRef()};
+ if(UNLIKELY(!context)) return;
+
+ std::lock_guard<std::mutex> _{context->EffectSlotLock};
+ ALeffectslot *slot = LookupEffectSlot(context.get(), effectslot);
+ if(UNLIKELY(!slot))
+ SETERR_RETURN(context.get(), AL_INVALID_NAME,, "Invalid effect slot ID %u", effectslot);
+
+ switch(param)
+ {
+ case AL_EFFECTSLOT_GAIN:
+ *value = slot->Gain;
+ break;
+
+ default:
+ SETERR_RETURN(context.get(), AL_INVALID_ENUM,,
+ "Invalid effect slot float property 0x%04x", param);
+ }
+}
+END_API_FUNC
+
+AL_API ALvoid AL_APIENTRY alGetAuxiliaryEffectSlotfv(ALuint effectslot, ALenum param, ALfloat *values)
+START_API_FUNC
+{
+ switch(param)
+ {
+ case AL_EFFECTSLOT_GAIN:
+ alGetAuxiliaryEffectSlotf(effectslot, param, values);
+ return;
+ }
+
+ ContextRef context{GetContextRef()};
+ if(UNLIKELY(!context)) return;
+
+ std::lock_guard<std::mutex> _{context->EffectSlotLock};
+ ALeffectslot *slot = LookupEffectSlot(context.get(), effectslot);
+ if(UNLIKELY(!slot))
+ SETERR_RETURN(context.get(), AL_INVALID_NAME,, "Invalid effect slot ID %u", effectslot);
+
+ switch(param)
+ {
+ default:
+ SETERR_RETURN(context.get(), AL_INVALID_ENUM,,
+ "Invalid effect slot float-vector property 0x%04x", param);
+ }
+}
+END_API_FUNC
+
+
+ALenum InitializeEffect(ALCcontext *Context, ALeffectslot *EffectSlot, ALeffect *effect)
+{
+ ALenum newtype{effect ? effect->type : AL_EFFECT_NULL};
+ if(newtype != EffectSlot->Effect.Type)
+ {
+ EffectStateFactory *factory{getFactoryByType(newtype)};
+ if(!factory)
+ {
+ ERR("Failed to find factory for effect type 0x%04x\n", newtype);
+ return AL_INVALID_ENUM;
+ }
+ EffectState *State{factory->create()};
+ if(!State) return AL_OUT_OF_MEMORY;
+
+ FPUCtl mixer_mode{};
+ ALCdevice *Device{Context->Device};
+ std::unique_lock<std::mutex> statelock{Device->StateLock};
+ State->mOutTarget = Device->Dry.Buffer;
+ if(State->deviceUpdate(Device) == AL_FALSE)
+ {
+ statelock.unlock();
+ mixer_mode.leave();
+ State->DecRef();
+ return AL_OUT_OF_MEMORY;
+ }
+ mixer_mode.leave();
+
+ if(!effect)
+ {
+ EffectSlot->Effect.Type = AL_EFFECT_NULL;
+ EffectSlot->Effect.Props = EffectProps {};
+ }
+ else
+ {
+ EffectSlot->Effect.Type = effect->type;
+ EffectSlot->Effect.Props = effect->Props;
+ }
+
+ EffectSlot->Effect.State->DecRef();
+ EffectSlot->Effect.State = State;
+ }
+ else if(effect)
+ EffectSlot->Effect.Props = effect->Props;
+
+ /* Remove state references from old effect slot property updates. */
+ ALeffectslotProps *props{Context->FreeEffectslotProps.load()};
+ while(props)
+ {
+ if(props->State)
+ props->State->DecRef();
+ props->State = nullptr;
+ props = props->next.load(std::memory_order_relaxed);
+ }
+
+ return AL_NO_ERROR;
+}
+
+
+void EffectState::IncRef() noexcept
+{
+ auto ref = IncrementRef(&mRef);
+ TRACEREF("EffectState %p increasing refcount to %u\n", this, ref);
+}
+
+void EffectState::DecRef() noexcept
+{
+ auto ref = DecrementRef(&mRef);
+ TRACEREF("EffectState %p decreasing refcount to %u\n", this, ref);
+ if(ref == 0) delete this;
+}
+
+
+ALenum InitEffectSlot(ALeffectslot *slot)
+{
+ EffectStateFactory *factory{getFactoryByType(slot->Effect.Type)};
+ if(!factory) return AL_INVALID_VALUE;
+ slot->Effect.State = factory->create();
+ if(!slot->Effect.State) return AL_OUT_OF_MEMORY;
+
+ slot->Effect.State->IncRef();
+ slot->Params.mEffectState = slot->Effect.State;
+ return AL_NO_ERROR;
+}
+
+ALeffectslot::~ALeffectslot()
+{
+ if(Target)
+ DecrementRef(&Target->ref);
+ Target = nullptr;
+
+ ALeffectslotProps *props{Update.load()};
+ if(props)
+ {
+ if(props->State) props->State->DecRef();
+ TRACE("Freed unapplied AuxiliaryEffectSlot update %p\n", props);
+ al_free(props);
+ }
+
+ if(Effect.State)
+ Effect.State->DecRef();
+ if(Params.mEffectState)
+ Params.mEffectState->DecRef();
+}
+
+void UpdateEffectSlotProps(ALeffectslot *slot, ALCcontext *context)
+{
+ /* Get an unused property container, or allocate a new one as needed. */
+ ALeffectslotProps *props{context->FreeEffectslotProps.load(std::memory_order_relaxed)};
+ if(!props)
+ props = static_cast<ALeffectslotProps*>(al_calloc(16, sizeof(*props)));
+ else
+ {
+ ALeffectslotProps *next;
+ do {
+ next = props->next.load(std::memory_order_relaxed);
+ } while(context->FreeEffectslotProps.compare_exchange_weak(props, next,
+ std::memory_order_seq_cst, std::memory_order_acquire) == 0);
+ }
+
+ /* Copy in current property values. */
+ props->Gain = slot->Gain;
+ props->AuxSendAuto = slot->AuxSendAuto;
+ props->Target = slot->Target;
+
+ props->Type = slot->Effect.Type;
+ props->Props = slot->Effect.Props;
+ /* Swap out any stale effect state object there may be in the container, to
+ * delete it.
+ */
+ EffectState *oldstate{props->State};
+ slot->Effect.State->IncRef();
+ props->State = slot->Effect.State;
+
+ /* Set the new container for updating internal parameters. */
+ props = slot->Update.exchange(props, std::memory_order_acq_rel);
+ if(props)
+ {
+ /* If there was an unused update container, put it back in the
+ * freelist.
+ */
+ if(props->State)
+ props->State->DecRef();
+ props->State = nullptr;
+ AtomicReplaceHead(context->FreeEffectslotProps, props);
+ }
+
+ if(oldstate)
+ oldstate->DecRef();
+}
+
+void UpdateAllEffectSlotProps(ALCcontext *context)
+{
+ std::lock_guard<std::mutex> _{context->EffectSlotLock};
+ ALeffectslotArray *auxslots{context->ActiveAuxSlots.load(std::memory_order_acquire)};
+ for(ALeffectslot *slot : *auxslots)
+ {
+ if(!slot->PropsClean.test_and_set(std::memory_order_acq_rel))
+ UpdateEffectSlotProps(slot, context);
+ }
+}
+
+EffectSlotSubList::~EffectSlotSubList()
+{
+ uint64_t usemask{~FreeMask};
+ while(usemask)
+ {
+ ALsizei idx{CTZ64(usemask)};
+ al::destroy_at(EffectSlots+idx);
+ usemask &= ~(1_u64 << idx);
+ }
+ FreeMask = ~usemask;
+ al_free(EffectSlots);
+ EffectSlots = nullptr;
+}
diff --git a/al/alAuxEffectSlot.h b/al/alAuxEffectSlot.h
new file mode 100644
index 00000000..369638a0
--- /dev/null
+++ b/al/alAuxEffectSlot.h
@@ -0,0 +1,103 @@
+#ifndef AL_AUXEFFECTSLOT_H
+#define AL_AUXEFFECTSLOT_H
+
+#include <atomic>
+#include <cstddef>
+
+#include "AL/al.h"
+#include "AL/alc.h"
+#include "AL/efx.h"
+
+#include "alcmain.h"
+#include "almalloc.h"
+#include "atomic.h"
+#include "effects/base.h"
+#include "vector.h"
+
+struct ALeffect;
+struct ALeffectslot;
+
+
+using ALeffectslotArray = al::FlexArray<ALeffectslot*>;
+
+
+struct ALeffectslotProps {
+ ALfloat Gain;
+ ALboolean AuxSendAuto;
+ ALeffectslot *Target;
+
+ ALenum Type;
+ EffectProps Props;
+
+ EffectState *State;
+
+ std::atomic<ALeffectslotProps*> next;
+};
+
+
+struct ALeffectslot {
+ ALfloat Gain{1.0f};
+ ALboolean AuxSendAuto{AL_TRUE};
+ ALeffectslot *Target{nullptr};
+
+ struct {
+ ALenum Type{AL_EFFECT_NULL};
+ EffectProps Props{};
+
+ EffectState *State{nullptr};
+ } Effect;
+
+ std::atomic_flag PropsClean;
+
+ RefCount ref{0u};
+
+ std::atomic<ALeffectslotProps*> Update{nullptr};
+
+ struct {
+ ALfloat Gain{1.0f};
+ ALboolean AuxSendAuto{AL_TRUE};
+ ALeffectslot *Target{nullptr};
+
+ ALenum EffectType{AL_EFFECT_NULL};
+ EffectProps mEffectProps{};
+ EffectState *mEffectState{nullptr};
+
+ ALfloat RoomRolloff{0.0f}; /* Added to the source's room rolloff, not multiplied. */
+ ALfloat DecayTime{0.0f};
+ ALfloat DecayLFRatio{0.0f};
+ ALfloat DecayHFRatio{0.0f};
+ ALboolean DecayHFLimit{AL_FALSE};
+ ALfloat AirAbsorptionGainHF{1.0f};
+ } Params;
+
+ /* Self ID */
+ ALuint id{};
+
+ /* Mixing buffer used by the Wet mix. */
+ al::vector<FloatBufferLine, 16> MixBuffer;
+
+ /* Wet buffer configuration is ACN channel order with N3D scaling.
+ * Consequently, effects that only want to work with mono input can use
+ * channel 0 by itself. Effects that want multichannel can process the
+ * ambisonics signal and make a B-Format source pan.
+ */
+ MixParams Wet;
+
+ ALeffectslot() { PropsClean.test_and_set(std::memory_order_relaxed); }
+ ALeffectslot(const ALeffectslot&) = delete;
+ ALeffectslot& operator=(const ALeffectslot&) = delete;
+ ~ALeffectslot();
+
+ static ALeffectslotArray *CreatePtrArray(size_t count) noexcept;
+
+ DEF_PLACE_NEWDEL()
+};
+
+ALenum InitEffectSlot(ALeffectslot *slot);
+void UpdateEffectSlotProps(ALeffectslot *slot, ALCcontext *context);
+void UpdateAllEffectSlotProps(ALCcontext *context);
+
+
+ALenum InitializeEffect(ALCcontext *Context, ALeffectslot *EffectSlot, ALeffect *effect);
+
+#endif
diff --git a/al/alBuffer.cpp b/al/alBuffer.cpp
new file mode 100644
index 00000000..505b9dab
--- /dev/null
+++ b/al/alBuffer.cpp
@@ -0,0 +1,1408 @@
+/**
+ * OpenAL cross platform audio library
+ * Copyright (C) 1999-2007 by authors.
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library; if not, write to the
+ * Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ * Or go to http://www.gnu.org/copyleft/lgpl.html
+ */
+
+#include "config.h"
+
+#include "alBuffer.h"
+
+#include <algorithm>
+#include <array>
+#include <atomic>
+#include <cassert>
+#include <cstdint>
+#include <cstdlib>
+#include <cstring>
+#include <iterator>
+#include <limits>
+#include <memory>
+#include <mutex>
+#include <new>
+#include <utility>
+
+#include "AL/al.h"
+#include "AL/alc.h"
+#include "AL/alext.h"
+
+#include "alError.h"
+#include "albyte.h"
+#include "alcmain.h"
+#include "alcontext.h"
+#include "alexcpt.h"
+#include "almalloc.h"
+#include "alnumeric.h"
+#include "aloptional.h"
+#include "atomic.h"
+#include "inprogext.h"
+#include "opthelpers.h"
+
+
+namespace {
+
+/* IMA ADPCM Stepsize table */
+constexpr int IMAStep_size[89] = {
+ 7, 8, 9, 10, 11, 12, 13, 14, 16, 17, 19,
+ 21, 23, 25, 28, 31, 34, 37, 41, 45, 50, 55,
+ 60, 66, 73, 80, 88, 97, 107, 118, 130, 143, 157,
+ 173, 190, 209, 230, 253, 279, 307, 337, 371, 408, 449,
+ 494, 544, 598, 658, 724, 796, 876, 963, 1060, 1166, 1282,
+ 1411, 1552, 1707, 1878, 2066, 2272, 2499, 2749, 3024, 3327, 3660,
+ 4026, 4428, 4871, 5358, 5894, 6484, 7132, 7845, 8630, 9493,10442,
+ 11487,12635,13899,15289,16818,18500,20350,22358,24633,27086,29794,
+ 32767
+};
+
+/* IMA4 ADPCM Codeword decode table */
+constexpr int IMA4Codeword[16] = {
+ 1, 3, 5, 7, 9, 11, 13, 15,
+ -1,-3,-5,-7,-9,-11,-13,-15,
+};
+
+/* IMA4 ADPCM Step index adjust decode table */
+constexpr int IMA4Index_adjust[16] = {
+ -1,-1,-1,-1, 2, 4, 6, 8,
+ -1,-1,-1,-1, 2, 4, 6, 8
+};
+
+
+/* MSADPCM Adaption table */
+constexpr int MSADPCMAdaption[16] = {
+ 230, 230, 230, 230, 307, 409, 512, 614,
+ 768, 614, 512, 409, 307, 230, 230, 230
+};
+
+/* MSADPCM Adaption Coefficient tables */
+constexpr int MSADPCMAdaptionCoeff[7][2] = {
+ { 256, 0 },
+ { 512, -256 },
+ { 0, 0 },
+ { 192, 64 },
+ { 240, 0 },
+ { 460, -208 },
+ { 392, -232 }
+};
+
+
+void DecodeIMA4Block(ALshort *dst, const al::byte *src, ALint numchans, ALsizei align)
+{
+ ALint sample[MAX_INPUT_CHANNELS]{};
+ ALint index[MAX_INPUT_CHANNELS]{};
+ ALuint code[MAX_INPUT_CHANNELS]{};
+
+ for(int c{0};c < numchans;c++)
+ {
+ sample[c] = al::to_integer<int>(src[0]) | (al::to_integer<int>(src[1])<<8);
+ sample[c] = (sample[c]^0x8000) - 32768;
+ src += 2;
+ index[c] = al::to_integer<int>(src[0]) | (al::to_integer<int>(src[1])<<8);
+ index[c] = clampi((index[c]^0x8000) - 32768, 0, 88);
+ src += 2;
+
+ *(dst++) = sample[c];
+ }
+
+ for(int i{1};i < align;i++)
+ {
+ if((i&7) == 1)
+ {
+ for(int c{0};c < numchans;c++)
+ {
+ code[c] = al::to_integer<ALuint>(src[0]) | (al::to_integer<ALuint>(src[1])<< 8) |
+ (al::to_integer<ALuint>(src[2])<<16) | (al::to_integer<ALuint>(src[3])<<24);
+ src += 4;
+ }
+ }
+
+ for(int c{0};c < numchans;c++)
+ {
+ const ALuint nibble{code[c]&0xf};
+ code[c] >>= 4;
+
+ sample[c] += IMA4Codeword[nibble] * IMAStep_size[index[c]] / 8;
+ sample[c] = clampi(sample[c], -32768, 32767);
+
+ index[c] += IMA4Index_adjust[nibble];
+ index[c] = clampi(index[c], 0, 88);
+
+ *(dst++) = sample[c];
+ }
+ }
+}
+
+void DecodeMSADPCMBlock(ALshort *dst, const al::byte *src, ALint numchans, ALsizei align)
+{
+ ALubyte blockpred[MAX_INPUT_CHANNELS]{};
+ ALint delta[MAX_INPUT_CHANNELS]{};
+ ALshort samples[MAX_INPUT_CHANNELS][2]{};
+
+ for(int c{0};c < numchans;c++)
+ {
+ blockpred[c] = minu(al::to_integer<ALubyte>(src[0]), 6);
+ ++src;
+ }
+ for(int c{0};c < numchans;c++)
+ {
+ delta[c] = al::to_integer<int>(src[0]) | (al::to_integer<int>(src[1])<<8);
+ delta[c] = (delta[c]^0x8000) - 32768;
+ src += 2;
+ }
+ for(int c{0};c < numchans;c++)
+ {
+ samples[c][0] = al::to_integer<short>(src[0]) | (al::to_integer<short>(src[1])<<8);
+ samples[c][0] = (samples[c][0]^0x8000) - 32768;
+ src += 2;
+ }
+ for(int c{0};c < numchans;c++)
+ {
+ samples[c][1] = al::to_integer<short>(src[0]) | (al::to_integer<short>(src[1])<<8);
+ samples[c][1] = (samples[c][1]^0x8000) - 32768;
+ src += 2;
+ }
+
+ /* Second sample is written first. */
+ for(int c{0};c < numchans;c++)
+ *(dst++) = samples[c][1];
+ for(int c{0};c < numchans;c++)
+ *(dst++) = samples[c][0];
+
+ int num{0};
+ for(int i{2};i < align;i++)
+ {
+ for(int c{0};c < numchans;c++)
+ {
+ /* Read the nibble (first is in the upper bits). */
+ al::byte nibble;
+ if(!(num++ & 1))
+ nibble = *src >> 4;
+ else
+ nibble = *(src++) & 0x0f;
+
+ ALint pred{(samples[c][0]*MSADPCMAdaptionCoeff[blockpred[c]][0] +
+ samples[c][1]*MSADPCMAdaptionCoeff[blockpred[c]][1]) / 256};
+ pred += (al::to_integer<int>(nibble^0x08) - 0x08) * delta[c];
+ pred = clampi(pred, -32768, 32767);
+
+ samples[c][1] = samples[c][0];
+ samples[c][0] = pred;
+
+ delta[c] = (MSADPCMAdaption[al::to_integer<ALubyte>(nibble)] * delta[c]) / 256;
+ delta[c] = maxi(16, delta[c]);
+
+ *(dst++) = pred;
+ }
+ }
+}
+
+void Convert_ALshort_ALima4(ALshort *dst, const al::byte *src, ALsizei numchans, ALsizei len,
+ ALsizei align)
+{
+ const ALsizei byte_align{((align-1)/2 + 4) * numchans};
+
+ len /= align;
+ while(len--)
+ {
+ DecodeIMA4Block(dst, src, numchans, align);
+ src += byte_align;
+ dst += align*numchans;
+ }
+}
+
+void Convert_ALshort_ALmsadpcm(ALshort *dst, const al::byte *src, ALsizei numchans, ALsizei len,
+ ALsizei align)
+{
+ const ALsizei byte_align{((align-2)/2 + 7) * numchans};
+
+ len /= align;
+ while(len--)
+ {
+ DecodeMSADPCMBlock(dst, src, numchans, align);
+ src += byte_align;
+ dst += align*numchans;
+ }
+}
+
+
+constexpr ALbitfieldSOFT INVALID_STORAGE_MASK{~unsigned(AL_MAP_READ_BIT_SOFT |
+ AL_MAP_WRITE_BIT_SOFT | AL_MAP_PERSISTENT_BIT_SOFT | AL_PRESERVE_DATA_BIT_SOFT)};
+constexpr ALbitfieldSOFT MAP_READ_WRITE_FLAGS{AL_MAP_READ_BIT_SOFT | AL_MAP_WRITE_BIT_SOFT};
+constexpr ALbitfieldSOFT INVALID_MAP_FLAGS{~unsigned(AL_MAP_READ_BIT_SOFT | AL_MAP_WRITE_BIT_SOFT |
+ AL_MAP_PERSISTENT_BIT_SOFT)};
+
+
+ALbuffer *AllocBuffer(ALCcontext *context)
+{
+ ALCdevice *device{context->Device};
+ std::lock_guard<std::mutex> _{device->BufferLock};
+ auto sublist = std::find_if(device->BufferList.begin(), device->BufferList.end(),
+ [](const BufferSubList &entry) noexcept -> bool
+ { return entry.FreeMask != 0; }
+ );
+
+ auto lidx = static_cast<ALsizei>(std::distance(device->BufferList.begin(), sublist));
+ ALbuffer *buffer{nullptr};
+ ALsizei slidx{0};
+ if(LIKELY(sublist != device->BufferList.end()))
+ {
+ slidx = CTZ64(sublist->FreeMask);
+ buffer = sublist->Buffers + slidx;
+ }
+ else
+ {
+ /* Don't allocate so many list entries that the 32-bit ID could
+ * overflow...
+ */
+ if(UNLIKELY(device->BufferList.size() >= 1<<25))
+ {
+ alSetError(context, AL_OUT_OF_MEMORY, "Too many buffers allocated");
+ return nullptr;
+ }
+ device->BufferList.emplace_back();
+ sublist = device->BufferList.end() - 1;
+ sublist->FreeMask = ~0_u64;
+ sublist->Buffers = reinterpret_cast<ALbuffer*>(al_calloc(16, sizeof(ALbuffer)*64));
+ if(UNLIKELY(!sublist->Buffers))
+ {
+ device->BufferList.pop_back();
+ alSetError(context, AL_OUT_OF_MEMORY, "Failed to allocate buffer batch");
+ return nullptr;
+ }
+
+ slidx = 0;
+ buffer = sublist->Buffers + slidx;
+ }
+
+ buffer = new (buffer) ALbuffer{};
+ /* Add 1 to avoid buffer ID 0. */
+ buffer->id = ((lidx<<6) | slidx) + 1;
+
+ sublist->FreeMask &= ~(1_u64 << slidx);
+
+ return buffer;
+}
+
+void FreeBuffer(ALCdevice *device, ALbuffer *buffer)
+{
+ ALuint id{buffer->id - 1};
+ ALsizei lidx = id >> 6;
+ ALsizei slidx = id & 0x3f;
+
+ al::destroy_at(buffer);
+
+ device->BufferList[lidx].FreeMask |= 1_u64 << slidx;
+}
+
+inline ALbuffer *LookupBuffer(ALCdevice *device, ALuint id)
+{
+ ALuint lidx = (id-1) >> 6;
+ ALsizei slidx = (id-1) & 0x3f;
+
+ if(UNLIKELY(lidx >= device->BufferList.size()))
+ return nullptr;
+ BufferSubList &sublist = device->BufferList[lidx];
+ if(UNLIKELY(sublist.FreeMask & (1_u64 << slidx)))
+ return nullptr;
+ return sublist.Buffers + slidx;
+}
+
+
+ALsizei SanitizeAlignment(UserFmtType type, ALsizei align)
+{
+ if(align < 0)
+ return 0;
+
+ if(align == 0)
+ {
+ if(type == UserFmtIMA4)
+ {
+ /* Here is where things vary:
+ * nVidia and Apple use 64+1 sample frames per block -> block_size=36 bytes per channel
+ * Most PC sound software uses 2040+1 sample frames per block -> block_size=1024 bytes per channel
+ */
+ return 65;
+ }
+ if(type == UserFmtMSADPCM)
+ return 64;
+ return 1;
+ }
+
+ if(type == UserFmtIMA4)
+ {
+ /* IMA4 block alignment must be a multiple of 8, plus 1. */
+ if((align&7) == 1) return align;
+ return 0;
+ }
+ if(type == UserFmtMSADPCM)
+ {
+ /* MSADPCM block alignment must be a multiple of 2. */
+ if((align&1) == 0) return align;
+ return 0;
+ }
+
+ return align;
+}
+
+
+const ALchar *NameFromUserFmtType(UserFmtType type)
+{
+ switch(type)
+ {
+ case UserFmtUByte: return "Unsigned Byte";
+ case UserFmtShort: return "Signed Short";
+ case UserFmtFloat: return "Float32";
+ case UserFmtDouble: return "Float64";
+ case UserFmtMulaw: return "muLaw";
+ case UserFmtAlaw: return "aLaw";
+ case UserFmtIMA4: return "IMA4 ADPCM";
+ case UserFmtMSADPCM: return "MSADPCM";
+ }
+ return "<internal type error>";
+}
+
+/*
+ * LoadData
+ *
+ * Loads the specified data into the buffer, using the specified format.
+ */
+void LoadData(ALCcontext *context, ALbuffer *ALBuf, ALuint freq, ALsizei size, UserFmtChannels SrcChannels, UserFmtType SrcType, const al::byte *SrcData, ALbitfieldSOFT access)
+{
+ if(UNLIKELY(ReadRef(&ALBuf->ref) != 0 || ALBuf->MappedAccess != 0))
+ SETERR_RETURN(context, AL_INVALID_OPERATION,, "Modifying storage for in-use buffer %u",
+ ALBuf->id);
+
+ /* Currently no channel configurations need to be converted. */
+ FmtChannels DstChannels{FmtMono};
+ switch(SrcChannels)
+ {
+ case UserFmtMono: DstChannels = FmtMono; break;
+ case UserFmtStereo: DstChannels = FmtStereo; break;
+ case UserFmtRear: DstChannels = FmtRear; break;
+ case UserFmtQuad: DstChannels = FmtQuad; break;
+ case UserFmtX51: DstChannels = FmtX51; break;
+ case UserFmtX61: DstChannels = FmtX61; break;
+ case UserFmtX71: DstChannels = FmtX71; break;
+ case UserFmtBFormat2D: DstChannels = FmtBFormat2D; break;
+ case UserFmtBFormat3D: DstChannels = FmtBFormat3D; break;
+ }
+ if (UNLIKELY(static_cast<long>(SrcChannels) !=
+ static_cast<long>(DstChannels)))
+ SETERR_RETURN(context, AL_INVALID_ENUM, , "Invalid format");
+
+ /* IMA4 and MSADPCM convert to 16-bit short. */
+ FmtType DstType{FmtUByte};
+ switch(SrcType)
+ {
+ case UserFmtUByte: DstType = FmtUByte; break;
+ case UserFmtShort: DstType = FmtShort; break;
+ case UserFmtFloat: DstType = FmtFloat; break;
+ case UserFmtDouble: DstType = FmtDouble; break;
+ case UserFmtAlaw: DstType = FmtAlaw; break;
+ case UserFmtMulaw: DstType = FmtMulaw; break;
+ case UserFmtIMA4: DstType = FmtShort; break;
+ case UserFmtMSADPCM: DstType = FmtShort; break;
+ }
+
+ /* TODO: Currently we can only map samples when they're not converted. To
+ * allow it would need some kind of double-buffering to hold onto a copy of
+ * the original data.
+ */
+ if((access&MAP_READ_WRITE_FLAGS))
+ {
+ if (UNLIKELY(static_cast<long>(SrcType) != static_cast<long>(DstType)))
+ SETERR_RETURN(context, AL_INVALID_VALUE, ,
+ "%s samples cannot be mapped",
+ NameFromUserFmtType(SrcType));
+ }
+
+ const ALsizei unpackalign{ALBuf->UnpackAlign.load()};
+ const ALsizei align{SanitizeAlignment(SrcType, unpackalign)};
+ if(UNLIKELY(align < 1))
+ SETERR_RETURN(context, AL_INVALID_VALUE,, "Invalid unpack alignment %d for %s samples",
+ unpackalign, NameFromUserFmtType(SrcType));
+
+ if((access&AL_PRESERVE_DATA_BIT_SOFT))
+ {
+ /* Can only preserve data with the same format and alignment. */
+ if(UNLIKELY(ALBuf->mFmtChannels != DstChannels || ALBuf->OriginalType != SrcType))
+ SETERR_RETURN(context, AL_INVALID_VALUE,, "Preserving data of mismatched format");
+ if(UNLIKELY(ALBuf->OriginalAlign != align))
+ SETERR_RETURN(context, AL_INVALID_VALUE,, "Preserving data of mismatched alignment");
+ }
+
+ /* Convert the input/source size in bytes to sample frames using the unpack
+ * block alignment.
+ */
+ const ALsizei SrcByteAlign{
+ (SrcType == UserFmtIMA4) ? ((align-1)/2 + 4) * ChannelsFromUserFmt(SrcChannels) :
+ (SrcType == UserFmtMSADPCM) ? ((align-2)/2 + 7) * ChannelsFromUserFmt(SrcChannels) :
+ (align * FrameSizeFromUserFmt(SrcChannels, SrcType))
+ };
+ if(UNLIKELY((size%SrcByteAlign) != 0))
+ SETERR_RETURN(context, AL_INVALID_VALUE,,
+ "Data size %d is not a multiple of frame size %d (%d unpack alignment)",
+ size, SrcByteAlign, align);
+
+ if(UNLIKELY(size/SrcByteAlign > std::numeric_limits<ALsizei>::max()/align))
+ SETERR_RETURN(context, AL_OUT_OF_MEMORY,,
+ "Buffer size overflow, %d blocks x %d samples per block", size/SrcByteAlign, align);
+ const ALsizei frames{size / SrcByteAlign * align};
+
+ /* Convert the sample frames to the number of bytes needed for internal
+ * storage.
+ */
+ ALsizei NumChannels{ChannelsFromFmt(DstChannels)};
+ ALsizei FrameSize{NumChannels * BytesFromFmt(DstType)};
+ if(UNLIKELY(frames > std::numeric_limits<ALsizei>::max()/FrameSize))
+ SETERR_RETURN(context, AL_OUT_OF_MEMORY,,
+ "Buffer size overflow, %d frames x %d bytes per frame", frames, FrameSize);
+ size_t newsize{static_cast<size_t>(frames) * FrameSize};
+
+ /* Round up to the next 16-byte multiple. This could reallocate only when
+ * increasing or the new size is less than half the current, but then the
+ * buffer's AL_SIZE would not be very reliable for accounting buffer memory
+ * usage, and reporting the real size could cause problems for apps that
+ * use AL_SIZE to try to get the buffer's play length.
+ */
+ newsize = RoundUp(newsize, 16);
+ if(newsize != ALBuf->mData.size())
+ {
+ auto newdata = al::vector<al::byte,16>(newsize, al::byte{});
+ if((access&AL_PRESERVE_DATA_BIT_SOFT))
+ {
+ const size_t tocopy{minz(newdata.size(), ALBuf->mData.size())};
+ std::copy_n(ALBuf->mData.begin(), tocopy, newdata.begin());
+ }
+ ALBuf->mData = std::move(newdata);
+ }
+
+ if(SrcType == UserFmtIMA4)
+ {
+ assert(DstType == FmtShort);
+ if(SrcData != nullptr && !ALBuf->mData.empty())
+ Convert_ALshort_ALima4(reinterpret_cast<ALshort*>(ALBuf->mData.data()),
+ SrcData, NumChannels, frames, align);
+ ALBuf->OriginalAlign = align;
+ }
+ else if(SrcType == UserFmtMSADPCM)
+ {
+ assert(DstType == FmtShort);
+ if(SrcData != nullptr && !ALBuf->mData.empty())
+ Convert_ALshort_ALmsadpcm(reinterpret_cast<ALshort*>(ALBuf->mData.data()),
+ SrcData, NumChannels, frames, align);
+ ALBuf->OriginalAlign = align;
+ }
+ else
+ {
+ assert(static_cast<long>(SrcType) == static_cast<long>(DstType));
+ if(SrcData != nullptr && !ALBuf->mData.empty())
+ std::copy_n(SrcData, frames*FrameSize, ALBuf->mData.begin());
+ ALBuf->OriginalAlign = 1;
+ }
+ ALBuf->OriginalSize = size;
+ ALBuf->OriginalType = SrcType;
+
+ ALBuf->Frequency = freq;
+ ALBuf->mFmtChannels = DstChannels;
+ ALBuf->mFmtType = DstType;
+ ALBuf->Access = access;
+
+ ALBuf->SampleLen = frames;
+ ALBuf->LoopStart = 0;
+ ALBuf->LoopEnd = ALBuf->SampleLen;
+}
+
+struct DecompResult { UserFmtChannels channels; UserFmtType type; };
+al::optional<DecompResult> DecomposeUserFormat(ALenum format)
+{
+ struct FormatMap {
+ ALenum format;
+ UserFmtChannels channels;
+ UserFmtType type;
+ };
+ static constexpr std::array<FormatMap,46> UserFmtList{{
+ { AL_FORMAT_MONO8, UserFmtMono, UserFmtUByte },
+ { AL_FORMAT_MONO16, UserFmtMono, UserFmtShort },
+ { AL_FORMAT_MONO_FLOAT32, UserFmtMono, UserFmtFloat },
+ { AL_FORMAT_MONO_DOUBLE_EXT, UserFmtMono, UserFmtDouble },
+ { AL_FORMAT_MONO_IMA4, UserFmtMono, UserFmtIMA4 },
+ { AL_FORMAT_MONO_MSADPCM_SOFT, UserFmtMono, UserFmtMSADPCM },
+ { AL_FORMAT_MONO_MULAW, UserFmtMono, UserFmtMulaw },
+ { AL_FORMAT_MONO_ALAW_EXT, UserFmtMono, UserFmtAlaw },
+
+ { AL_FORMAT_STEREO8, UserFmtStereo, UserFmtUByte },
+ { AL_FORMAT_STEREO16, UserFmtStereo, UserFmtShort },
+ { AL_FORMAT_STEREO_FLOAT32, UserFmtStereo, UserFmtFloat },
+ { AL_FORMAT_STEREO_DOUBLE_EXT, UserFmtStereo, UserFmtDouble },
+ { AL_FORMAT_STEREO_IMA4, UserFmtStereo, UserFmtIMA4 },
+ { AL_FORMAT_STEREO_MSADPCM_SOFT, UserFmtStereo, UserFmtMSADPCM },
+ { AL_FORMAT_STEREO_MULAW, UserFmtStereo, UserFmtMulaw },
+ { AL_FORMAT_STEREO_ALAW_EXT, UserFmtStereo, UserFmtAlaw },
+
+ { AL_FORMAT_REAR8, UserFmtRear, UserFmtUByte },
+ { AL_FORMAT_REAR16, UserFmtRear, UserFmtShort },
+ { AL_FORMAT_REAR32, UserFmtRear, UserFmtFloat },
+ { AL_FORMAT_REAR_MULAW, UserFmtRear, UserFmtMulaw },
+
+ { AL_FORMAT_QUAD8_LOKI, UserFmtQuad, UserFmtUByte },
+ { AL_FORMAT_QUAD16_LOKI, UserFmtQuad, UserFmtShort },
+
+ { AL_FORMAT_QUAD8, UserFmtQuad, UserFmtUByte },
+ { AL_FORMAT_QUAD16, UserFmtQuad, UserFmtShort },
+ { AL_FORMAT_QUAD32, UserFmtQuad, UserFmtFloat },
+ { AL_FORMAT_QUAD_MULAW, UserFmtQuad, UserFmtMulaw },
+
+ { AL_FORMAT_51CHN8, UserFmtX51, UserFmtUByte },
+ { AL_FORMAT_51CHN16, UserFmtX51, UserFmtShort },
+ { AL_FORMAT_51CHN32, UserFmtX51, UserFmtFloat },
+ { AL_FORMAT_51CHN_MULAW, UserFmtX51, UserFmtMulaw },
+
+ { AL_FORMAT_61CHN8, UserFmtX61, UserFmtUByte },
+ { AL_FORMAT_61CHN16, UserFmtX61, UserFmtShort },
+ { AL_FORMAT_61CHN32, UserFmtX61, UserFmtFloat },
+ { AL_FORMAT_61CHN_MULAW, UserFmtX61, UserFmtMulaw },
+
+ { AL_FORMAT_71CHN8, UserFmtX71, UserFmtUByte },
+ { AL_FORMAT_71CHN16, UserFmtX71, UserFmtShort },
+ { AL_FORMAT_71CHN32, UserFmtX71, UserFmtFloat },
+ { AL_FORMAT_71CHN_MULAW, UserFmtX71, UserFmtMulaw },
+
+ { AL_FORMAT_BFORMAT2D_8, UserFmtBFormat2D, UserFmtUByte },
+ { AL_FORMAT_BFORMAT2D_16, UserFmtBFormat2D, UserFmtShort },
+ { AL_FORMAT_BFORMAT2D_FLOAT32, UserFmtBFormat2D, UserFmtFloat },
+ { AL_FORMAT_BFORMAT2D_MULAW, UserFmtBFormat2D, UserFmtMulaw },
+
+ { AL_FORMAT_BFORMAT3D_8, UserFmtBFormat3D, UserFmtUByte },
+ { AL_FORMAT_BFORMAT3D_16, UserFmtBFormat3D, UserFmtShort },
+ { AL_FORMAT_BFORMAT3D_FLOAT32, UserFmtBFormat3D, UserFmtFloat },
+ { AL_FORMAT_BFORMAT3D_MULAW, UserFmtBFormat3D, UserFmtMulaw },
+ }};
+
+ for(const auto &fmt : UserFmtList)
+ {
+ if(fmt.format == format)
+ return al::make_optional(DecompResult{fmt.channels, fmt.type});
+ }
+ return al::nullopt;
+}
+
+} // namespace
+
+
+AL_API ALvoid AL_APIENTRY alGenBuffers(ALsizei n, ALuint *buffers)
+START_API_FUNC
+{
+ ContextRef context{GetContextRef()};
+ if(UNLIKELY(!context)) return;
+
+ if(UNLIKELY(n < 0))
+ {
+ alSetError(context.get(), AL_INVALID_VALUE, "Generating %d buffers", n);
+ return;
+ }
+
+ if(LIKELY(n == 1))
+ {
+ /* Special handling for the easy and normal case. */
+ ALbuffer *buffer = AllocBuffer(context.get());
+ if(buffer) buffers[0] = buffer->id;
+ }
+ else if(n > 1)
+ {
+ /* Store the allocated buffer IDs in a separate local list, to avoid
+ * modifying the user storage in case of failure.
+ */
+ al::vector<ALuint> ids;
+ ids.reserve(n);
+ do {
+ ALbuffer *buffer = AllocBuffer(context.get());
+ if(!buffer)
+ {
+ alDeleteBuffers(static_cast<ALsizei>(ids.size()), ids.data());
+ return;
+ }
+
+ ids.emplace_back(buffer->id);
+ } while(--n);
+ std::copy(ids.begin(), ids.end(), buffers);
+ }
+}
+END_API_FUNC
+
+AL_API ALvoid AL_APIENTRY alDeleteBuffers(ALsizei n, const ALuint *buffers)
+START_API_FUNC
+{
+ ContextRef context{GetContextRef()};
+ if(UNLIKELY(!context)) return;
+
+ if(UNLIKELY(n < 0))
+ {
+ alSetError(context.get(), AL_INVALID_VALUE, "Deleting %d buffers", n);
+ return;
+ }
+ if(UNLIKELY(n == 0))
+ return;
+
+ ALCdevice *device = context->Device;
+ std::lock_guard<std::mutex> _{device->BufferLock};
+
+ /* First try to find any buffers that are invalid or in-use. */
+ const ALuint *buffers_end = buffers + n;
+ auto invbuf = std::find_if(buffers, buffers_end,
+ [device, &context](ALuint bid) -> bool
+ {
+ if(!bid) return false;
+ ALbuffer *ALBuf = LookupBuffer(device, bid);
+ if(UNLIKELY(!ALBuf))
+ {
+ alSetError(context.get(), AL_INVALID_NAME, "Invalid buffer ID %u", bid);
+ return true;
+ }
+ if(UNLIKELY(ReadRef(&ALBuf->ref) != 0))
+ {
+ alSetError(context.get(), AL_INVALID_OPERATION, "Deleting in-use buffer %u", bid);
+ return true;
+ }
+ return false;
+ }
+ );
+ if(LIKELY(invbuf == buffers_end))
+ {
+ /* All good. Delete non-0 buffer IDs. */
+ std::for_each(buffers, buffers_end,
+ [device](ALuint bid) -> void
+ {
+ ALbuffer *buffer{bid ? LookupBuffer(device, bid) : nullptr};
+ if(buffer) FreeBuffer(device, buffer);
+ }
+ );
+ }
+}
+END_API_FUNC
+
+AL_API ALboolean AL_APIENTRY alIsBuffer(ALuint buffer)
+START_API_FUNC
+{
+ ContextRef context{GetContextRef()};
+ if(LIKELY(context))
+ {
+ ALCdevice *device = context->Device;
+ std::lock_guard<std::mutex> _{device->BufferLock};
+ if(!buffer || LookupBuffer(device, buffer))
+ return AL_TRUE;
+ }
+ return AL_FALSE;
+}
+END_API_FUNC
+
+
+AL_API ALvoid AL_APIENTRY alBufferData(ALuint buffer, ALenum format, const ALvoid *data, ALsizei size, ALsizei freq)
+START_API_FUNC
+{ alBufferStorageSOFT(buffer, format, data, size, freq, 0); }
+END_API_FUNC
+
+AL_API void AL_APIENTRY alBufferStorageSOFT(ALuint buffer, ALenum format, const ALvoid *data, ALsizei size, ALsizei freq, ALbitfieldSOFT flags)
+START_API_FUNC
+{
+ ContextRef context{GetContextRef()};
+ if(UNLIKELY(!context)) return;
+
+ ALCdevice *device = context->Device;
+ std::lock_guard<std::mutex> _{device->BufferLock};
+
+ ALbuffer *albuf = LookupBuffer(device, buffer);
+ if(UNLIKELY(!albuf))
+ alSetError(context.get(), AL_INVALID_NAME, "Invalid buffer ID %u", buffer);
+ else if(UNLIKELY(size < 0))
+ alSetError(context.get(), AL_INVALID_VALUE, "Negative storage size %d", size);
+ else if(UNLIKELY(freq < 1))
+ alSetError(context.get(), AL_INVALID_VALUE, "Invalid sample rate %d", freq);
+ else if(UNLIKELY((flags&INVALID_STORAGE_MASK) != 0))
+ alSetError(context.get(), AL_INVALID_VALUE, "Invalid storage flags 0x%x",
+ flags&INVALID_STORAGE_MASK);
+ else if(UNLIKELY((flags&AL_MAP_PERSISTENT_BIT_SOFT) && !(flags&MAP_READ_WRITE_FLAGS)))
+ alSetError(context.get(), AL_INVALID_VALUE,
+ "Declaring persistently mapped storage without read or write access");
+ else
+ {
+ auto usrfmt = DecomposeUserFormat(format);
+ if(UNLIKELY(!usrfmt))
+ alSetError(context.get(), AL_INVALID_ENUM, "Invalid format 0x%04x", format);
+ else
+ LoadData(context.get(), albuf, freq, size, usrfmt->channels, usrfmt->type,
+ static_cast<const al::byte*>(data), flags);
+ }
+}
+END_API_FUNC
+
+AL_API void* AL_APIENTRY alMapBufferSOFT(ALuint buffer, ALsizei offset, ALsizei length, ALbitfieldSOFT access)
+START_API_FUNC
+{
+ ContextRef context{GetContextRef()};
+ if(UNLIKELY(!context)) return nullptr;
+
+ ALCdevice *device = context->Device;
+ std::lock_guard<std::mutex> _{device->BufferLock};
+
+ ALbuffer *albuf = LookupBuffer(device, buffer);
+ if(UNLIKELY(!albuf))
+ alSetError(context.get(), AL_INVALID_NAME, "Invalid buffer ID %u", buffer);
+ else if(UNLIKELY((access&INVALID_MAP_FLAGS) != 0))
+ alSetError(context.get(), AL_INVALID_VALUE, "Invalid map flags 0x%x", access&INVALID_MAP_FLAGS);
+ else if(UNLIKELY(!(access&MAP_READ_WRITE_FLAGS)))
+ alSetError(context.get(), AL_INVALID_VALUE, "Mapping buffer %u without read or write access",
+ buffer);
+ else
+ {
+ ALbitfieldSOFT unavailable = (albuf->Access^access) & access;
+ if(UNLIKELY(ReadRef(&albuf->ref) != 0 && !(access&AL_MAP_PERSISTENT_BIT_SOFT)))
+ alSetError(context.get(), AL_INVALID_OPERATION,
+ "Mapping in-use buffer %u without persistent mapping", buffer);
+ else if(UNLIKELY(albuf->MappedAccess != 0))
+ alSetError(context.get(), AL_INVALID_OPERATION, "Mapping already-mapped buffer %u", buffer);
+ else if(UNLIKELY((unavailable&AL_MAP_READ_BIT_SOFT)))
+ alSetError(context.get(), AL_INVALID_VALUE,
+ "Mapping buffer %u for reading without read access", buffer);
+ else if(UNLIKELY((unavailable&AL_MAP_WRITE_BIT_SOFT)))
+ alSetError(context.get(), AL_INVALID_VALUE,
+ "Mapping buffer %u for writing without write access", buffer);
+ else if(UNLIKELY((unavailable&AL_MAP_PERSISTENT_BIT_SOFT)))
+ alSetError(context.get(), AL_INVALID_VALUE,
+ "Mapping buffer %u persistently without persistent access", buffer);
+ else if(UNLIKELY(offset < 0 || offset >= albuf->OriginalSize ||
+ length <= 0 || length > albuf->OriginalSize - offset))
+ alSetError(context.get(), AL_INVALID_VALUE, "Mapping invalid range %d+%d for buffer %u",
+ offset, length, buffer);
+ else
+ {
+ void *retval = albuf->mData.data() + offset;
+ albuf->MappedAccess = access;
+ albuf->MappedOffset = offset;
+ albuf->MappedSize = length;
+ return retval;
+ }
+ }
+
+ return nullptr;
+}
+END_API_FUNC
+
+AL_API void AL_APIENTRY alUnmapBufferSOFT(ALuint buffer)
+START_API_FUNC
+{
+ ContextRef context{GetContextRef()};
+ if(UNLIKELY(!context)) return;
+
+ ALCdevice *device = context->Device;
+ std::lock_guard<std::mutex> _{device->BufferLock};
+
+ ALbuffer *albuf = LookupBuffer(device, buffer);
+ if(UNLIKELY(!albuf))
+ alSetError(context.get(), AL_INVALID_NAME, "Invalid buffer ID %u", buffer);
+ else if(albuf->MappedAccess == 0)
+ alSetError(context.get(), AL_INVALID_OPERATION, "Unmapping unmapped buffer %u", buffer);
+ else
+ {
+ albuf->MappedAccess = 0;
+ albuf->MappedOffset = 0;
+ albuf->MappedSize = 0;
+ }
+}
+END_API_FUNC
+
+AL_API void AL_APIENTRY alFlushMappedBufferSOFT(ALuint buffer, ALsizei offset, ALsizei length)
+START_API_FUNC
+{
+ ContextRef context{GetContextRef()};
+ if(UNLIKELY(!context)) return;
+
+ ALCdevice *device = context->Device;
+ std::lock_guard<std::mutex> _{device->BufferLock};
+
+ ALbuffer *albuf = LookupBuffer(device, buffer);
+ if(UNLIKELY(!albuf))
+ alSetError(context.get(), AL_INVALID_NAME, "Invalid buffer ID %u", buffer);
+ else if(UNLIKELY(!(albuf->MappedAccess&AL_MAP_WRITE_BIT_SOFT)))
+ alSetError(context.get(), AL_INVALID_OPERATION,
+ "Flushing buffer %u while not mapped for writing", buffer);
+ else if(UNLIKELY(offset < albuf->MappedOffset ||
+ offset >= albuf->MappedOffset+albuf->MappedSize ||
+ length <= 0 || length > albuf->MappedOffset+albuf->MappedSize-offset))
+ alSetError(context.get(), AL_INVALID_VALUE, "Flushing invalid range %d+%d on buffer %u",
+ offset, length, buffer);
+ else
+ {
+ /* FIXME: Need to use some method of double-buffering for the mixer and
+ * app to hold separate memory, which can be safely transfered
+ * asynchronously. Currently we just say the app shouldn't write where
+ * OpenAL's reading, and hope for the best...
+ */
+ std::atomic_thread_fence(std::memory_order_seq_cst);
+ }
+}
+END_API_FUNC
+
+AL_API ALvoid AL_APIENTRY alBufferSubDataSOFT(ALuint buffer, ALenum format, const ALvoid *data, ALsizei offset, ALsizei length)
+START_API_FUNC
+{
+ ContextRef context{GetContextRef()};
+ if(UNLIKELY(!context)) return;
+
+ ALCdevice *device = context->Device;
+ std::lock_guard<std::mutex> _{device->BufferLock};
+
+ ALbuffer *albuf = LookupBuffer(device, buffer);
+ if(UNLIKELY(!albuf))
+ {
+ alSetError(context.get(), AL_INVALID_NAME, "Invalid buffer ID %u", buffer);
+ return;
+ }
+
+ auto usrfmt = DecomposeUserFormat(format);
+ if(UNLIKELY(!usrfmt))
+ {
+ alSetError(context.get(), AL_INVALID_ENUM, "Invalid format 0x%04x", format);
+ return;
+ }
+
+ ALsizei unpack_align{albuf->UnpackAlign.load()};
+ ALsizei align{SanitizeAlignment(usrfmt->type, unpack_align)};
+ if(UNLIKELY(align < 1))
+ alSetError(context.get(), AL_INVALID_VALUE, "Invalid unpack alignment %d", unpack_align);
+ else if(UNLIKELY(long{usrfmt->channels} != long{albuf->mFmtChannels} ||
+ usrfmt->type != albuf->OriginalType))
+ alSetError(context.get(), AL_INVALID_ENUM,
+ "Unpacking data with mismatched format");
+ else if(UNLIKELY(align != albuf->OriginalAlign))
+ alSetError(context.get(), AL_INVALID_VALUE,
+ "Unpacking data with alignment %u does not match original alignment %u",
+ align, albuf->OriginalAlign);
+ else if(UNLIKELY(albuf->MappedAccess != 0))
+ alSetError(context.get(), AL_INVALID_OPERATION, "Unpacking data into mapped buffer %u",
+ buffer);
+ else
+ {
+ ALsizei num_chans{ChannelsFromFmt(albuf->mFmtChannels)};
+ ALsizei frame_size{num_chans * BytesFromFmt(albuf->mFmtType)};
+ ALsizei byte_align{
+ (albuf->OriginalType == UserFmtIMA4) ? ((align-1)/2 + 4) * num_chans :
+ (albuf->OriginalType == UserFmtMSADPCM) ? ((align-2)/2 + 7) * num_chans :
+ (align * frame_size)
+ };
+
+ if(UNLIKELY(offset < 0 || length < 0 || offset > albuf->OriginalSize ||
+ length > albuf->OriginalSize-offset))
+ alSetError(context.get(), AL_INVALID_VALUE, "Invalid data sub-range %d+%d on buffer %u",
+ offset, length, buffer);
+ else if(UNLIKELY((offset%byte_align) != 0))
+ alSetError(context.get(), AL_INVALID_VALUE,
+ "Sub-range offset %d is not a multiple of frame size %d (%d unpack alignment)",
+ offset, byte_align, align);
+ else if(UNLIKELY((length%byte_align) != 0))
+ alSetError(context.get(), AL_INVALID_VALUE,
+ "Sub-range length %d is not a multiple of frame size %d (%d unpack alignment)",
+ length, byte_align, align);
+ else
+ {
+ /* offset -> byte offset, length -> sample count */
+ offset = offset/byte_align * align * frame_size;
+ length = length/byte_align * align;
+
+ void *dst = albuf->mData.data() + offset;
+ if(usrfmt->type == UserFmtIMA4 && albuf->mFmtType == FmtShort)
+ Convert_ALshort_ALima4(static_cast<ALshort*>(dst),
+ static_cast<const al::byte*>(data), num_chans, length, align);
+ else if(usrfmt->type == UserFmtMSADPCM && albuf->mFmtType == FmtShort)
+ Convert_ALshort_ALmsadpcm(static_cast<ALshort*>(dst),
+ static_cast<const al::byte*>(data), num_chans, length, align);
+ else
+ {
+ assert(long{usrfmt->type} == static_cast<long>(albuf->mFmtType));
+ memcpy(dst, data, length * frame_size);
+ }
+ }
+ }
+}
+END_API_FUNC
+
+
+AL_API void AL_APIENTRY alBufferSamplesSOFT(ALuint /*buffer*/, ALuint /*samplerate*/,
+ ALenum /*internalformat*/, ALsizei /*samples*/, ALenum /*channels*/, ALenum /*type*/,
+ const ALvoid* /*data*/)
+START_API_FUNC
+{
+ ContextRef context{GetContextRef()};
+ if(UNLIKELY(!context)) return;
+
+ alSetError(context.get(), AL_INVALID_OPERATION, "alBufferSamplesSOFT not supported");
+}
+END_API_FUNC
+
+AL_API void AL_APIENTRY alBufferSubSamplesSOFT(ALuint /*buffer*/, ALsizei /*offset*/,
+ ALsizei /*samples*/, ALenum /*channels*/, ALenum /*type*/, const ALvoid* /*data*/)
+START_API_FUNC
+{
+ ContextRef context{GetContextRef()};
+ if(UNLIKELY(!context)) return;
+
+ alSetError(context.get(), AL_INVALID_OPERATION, "alBufferSubSamplesSOFT not supported");
+}
+END_API_FUNC
+
+AL_API void AL_APIENTRY alGetBufferSamplesSOFT(ALuint /*buffer*/, ALsizei /*offset*/,
+ ALsizei /*samples*/, ALenum /*channels*/, ALenum /*type*/, ALvoid* /*data*/)
+START_API_FUNC
+{
+ ContextRef context{GetContextRef()};
+ if(UNLIKELY(!context)) return;
+
+ alSetError(context.get(), AL_INVALID_OPERATION, "alGetBufferSamplesSOFT not supported");
+}
+END_API_FUNC
+
+AL_API ALboolean AL_APIENTRY alIsBufferFormatSupportedSOFT(ALenum /*format*/)
+START_API_FUNC
+{
+ ContextRef context{GetContextRef()};
+ if(!context) return AL_FALSE;
+
+ alSetError(context.get(), AL_INVALID_OPERATION, "alIsBufferFormatSupportedSOFT not supported");
+ return AL_FALSE;
+}
+END_API_FUNC
+
+
+AL_API void AL_APIENTRY alBufferf(ALuint buffer, ALenum param, ALfloat /*value*/)
+START_API_FUNC
+{
+ ContextRef context{GetContextRef()};
+ if(UNLIKELY(!context)) return;
+
+ ALCdevice *device = context->Device;
+ std::lock_guard<std::mutex> _{device->BufferLock};
+
+ if(UNLIKELY(LookupBuffer(device, buffer) == nullptr))
+ alSetError(context.get(), AL_INVALID_NAME, "Invalid buffer ID %u", buffer);
+ else switch(param)
+ {
+ default:
+ alSetError(context.get(), AL_INVALID_ENUM, "Invalid buffer float property 0x%04x", param);
+ }
+}
+END_API_FUNC
+
+AL_API void AL_APIENTRY alBuffer3f(ALuint buffer, ALenum param,
+ ALfloat /*value1*/, ALfloat /*value2*/, ALfloat /*value3*/)
+START_API_FUNC
+{
+ ContextRef context{GetContextRef()};
+ if(UNLIKELY(!context)) return;
+
+ ALCdevice *device = context->Device;
+ std::lock_guard<std::mutex> _{device->BufferLock};
+
+ if(UNLIKELY(LookupBuffer(device, buffer) == nullptr))
+ alSetError(context.get(), AL_INVALID_NAME, "Invalid buffer ID %u", buffer);
+ else switch(param)
+ {
+ default:
+ alSetError(context.get(), AL_INVALID_ENUM, "Invalid buffer 3-float property 0x%04x", param);
+ }
+}
+END_API_FUNC
+
+AL_API void AL_APIENTRY alBufferfv(ALuint buffer, ALenum param, const ALfloat *values)
+START_API_FUNC
+{
+ ContextRef context{GetContextRef()};
+ if(UNLIKELY(!context)) return;
+
+ ALCdevice *device = context->Device;
+ std::lock_guard<std::mutex> _{device->BufferLock};
+
+ if(UNLIKELY(LookupBuffer(device, buffer) == nullptr))
+ alSetError(context.get(), AL_INVALID_NAME, "Invalid buffer ID %u", buffer);
+ else if(UNLIKELY(!values))
+ alSetError(context.get(), AL_INVALID_VALUE, "NULL pointer");
+ else switch(param)
+ {
+ default:
+ alSetError(context.get(), AL_INVALID_ENUM, "Invalid buffer float-vector property 0x%04x", param);
+ }
+}
+END_API_FUNC
+
+
+AL_API void AL_APIENTRY alBufferi(ALuint buffer, ALenum param, ALint value)
+START_API_FUNC
+{
+ ContextRef context{GetContextRef()};
+ if(UNLIKELY(!context)) return;
+
+ ALCdevice *device = context->Device;
+ std::lock_guard<std::mutex> _{device->BufferLock};
+
+ ALbuffer *albuf = LookupBuffer(device, buffer);
+ if(UNLIKELY(!albuf))
+ alSetError(context.get(), AL_INVALID_NAME, "Invalid buffer ID %u", buffer);
+ else switch(param)
+ {
+ case AL_UNPACK_BLOCK_ALIGNMENT_SOFT:
+ if(UNLIKELY(value < 0))
+ alSetError(context.get(), AL_INVALID_VALUE, "Invalid unpack block alignment %d", value);
+ else
+ albuf->UnpackAlign.store(value);
+ break;
+
+ case AL_PACK_BLOCK_ALIGNMENT_SOFT:
+ if(UNLIKELY(value < 0))
+ alSetError(context.get(), AL_INVALID_VALUE, "Invalid pack block alignment %d", value);
+ else
+ albuf->PackAlign.store(value);
+ break;
+
+ default:
+ alSetError(context.get(), AL_INVALID_ENUM, "Invalid buffer integer property 0x%04x", param);
+ }
+}
+END_API_FUNC
+
+AL_API void AL_APIENTRY alBuffer3i(ALuint buffer, ALenum param,
+ ALint /*value1*/, ALint /*value2*/, ALint /*value3*/)
+START_API_FUNC
+{
+ ContextRef context{GetContextRef()};
+ if(UNLIKELY(!context)) return;
+
+ ALCdevice *device = context->Device;
+ std::lock_guard<std::mutex> _{device->BufferLock};
+
+ if(UNLIKELY(LookupBuffer(device, buffer) == nullptr))
+ alSetError(context.get(), AL_INVALID_NAME, "Invalid buffer ID %u", buffer);
+ else switch(param)
+ {
+ default:
+ alSetError(context.get(), AL_INVALID_ENUM, "Invalid buffer 3-integer property 0x%04x", param);
+ }
+}
+END_API_FUNC
+
+AL_API void AL_APIENTRY alBufferiv(ALuint buffer, ALenum param, const ALint *values)
+START_API_FUNC
+{
+ if(values)
+ {
+ switch(param)
+ {
+ case AL_UNPACK_BLOCK_ALIGNMENT_SOFT:
+ case AL_PACK_BLOCK_ALIGNMENT_SOFT:
+ alBufferi(buffer, param, values[0]);
+ return;
+ }
+ }
+
+ ContextRef context{GetContextRef()};
+ if(UNLIKELY(!context)) return;
+
+ ALCdevice *device = context->Device;
+ std::lock_guard<std::mutex> _{device->BufferLock};
+
+ ALbuffer *albuf = LookupBuffer(device, buffer);
+ if(UNLIKELY(!albuf))
+ alSetError(context.get(), AL_INVALID_NAME, "Invalid buffer ID %u", buffer);
+ else if(UNLIKELY(!values))
+ alSetError(context.get(), AL_INVALID_VALUE, "NULL pointer");
+ else switch(param)
+ {
+ case AL_LOOP_POINTS_SOFT:
+ if(UNLIKELY(ReadRef(&albuf->ref) != 0))
+ alSetError(context.get(), AL_INVALID_OPERATION, "Modifying in-use buffer %u's loop points",
+ buffer);
+ else if(UNLIKELY(values[0] >= values[1] || values[0] < 0 || values[1] > albuf->SampleLen))
+ alSetError(context.get(), AL_INVALID_VALUE, "Invalid loop point range %d -> %d o buffer %u",
+ values[0], values[1], buffer);
+ else
+ {
+ albuf->LoopStart = values[0];
+ albuf->LoopEnd = values[1];
+ }
+ break;
+
+ default:
+ alSetError(context.get(), AL_INVALID_ENUM, "Invalid buffer integer-vector property 0x%04x",
+ param);
+ }
+}
+END_API_FUNC
+
+
+AL_API ALvoid AL_APIENTRY alGetBufferf(ALuint buffer, ALenum param, ALfloat *value)
+START_API_FUNC
+{
+ ContextRef context{GetContextRef()};
+ if(UNLIKELY(!context)) return;
+
+ ALCdevice *device = context->Device;
+ std::lock_guard<std::mutex> _{device->BufferLock};
+
+ ALbuffer *albuf = LookupBuffer(device, buffer);
+ if(UNLIKELY(!albuf))
+ alSetError(context.get(), AL_INVALID_NAME, "Invalid buffer ID %u", buffer);
+ else if(UNLIKELY(!value))
+ alSetError(context.get(), AL_INVALID_VALUE, "NULL pointer");
+ else switch(param)
+ {
+ default:
+ alSetError(context.get(), AL_INVALID_ENUM, "Invalid buffer float property 0x%04x", param);
+ }
+}
+END_API_FUNC
+
+AL_API void AL_APIENTRY alGetBuffer3f(ALuint buffer, ALenum param, ALfloat *value1, ALfloat *value2, ALfloat *value3)
+START_API_FUNC
+{
+ ContextRef context{GetContextRef()};
+ if(UNLIKELY(!context)) return;
+
+ ALCdevice *device = context->Device;
+ std::lock_guard<std::mutex> _{device->BufferLock};
+
+ if(UNLIKELY(LookupBuffer(device, buffer) == nullptr))
+ alSetError(context.get(), AL_INVALID_NAME, "Invalid buffer ID %u", buffer);
+ else if(UNLIKELY(!value1 || !value2 || !value3))
+ alSetError(context.get(), AL_INVALID_VALUE, "NULL pointer");
+ else switch(param)
+ {
+ default:
+ alSetError(context.get(), AL_INVALID_ENUM, "Invalid buffer 3-float property 0x%04x", param);
+ }
+}
+END_API_FUNC
+
+AL_API void AL_APIENTRY alGetBufferfv(ALuint buffer, ALenum param, ALfloat *values)
+START_API_FUNC
+{
+ switch(param)
+ {
+ case AL_SEC_LENGTH_SOFT:
+ alGetBufferf(buffer, param, values);
+ return;
+ }
+
+ ContextRef context{GetContextRef()};
+ if(UNLIKELY(!context)) return;
+
+ ALCdevice *device = context->Device;
+ std::lock_guard<std::mutex> _{device->BufferLock};
+
+ if(UNLIKELY(LookupBuffer(device, buffer) == nullptr))
+ alSetError(context.get(), AL_INVALID_NAME, "Invalid buffer ID %u", buffer);
+ else if(UNLIKELY(!values))
+ alSetError(context.get(), AL_INVALID_VALUE, "NULL pointer");
+ else switch(param)
+ {
+ default:
+ alSetError(context.get(), AL_INVALID_ENUM, "Invalid buffer float-vector property 0x%04x", param);
+ }
+}
+END_API_FUNC
+
+
+AL_API ALvoid AL_APIENTRY alGetBufferi(ALuint buffer, ALenum param, ALint *value)
+START_API_FUNC
+{
+ ContextRef context{GetContextRef()};
+ if(UNLIKELY(!context)) return;
+
+ ALCdevice *device = context->Device;
+ std::lock_guard<std::mutex> _{device->BufferLock};
+ ALbuffer *albuf = LookupBuffer(device, buffer);
+ if(UNLIKELY(!albuf))
+ alSetError(context.get(), AL_INVALID_NAME, "Invalid buffer ID %u", buffer);
+ else if(UNLIKELY(!value))
+ alSetError(context.get(), AL_INVALID_VALUE, "NULL pointer");
+ else switch(param)
+ {
+ case AL_FREQUENCY:
+ *value = albuf->Frequency;
+ break;
+
+ case AL_BITS:
+ *value = BytesFromFmt(albuf->mFmtType) * 8;
+ break;
+
+ case AL_CHANNELS:
+ *value = ChannelsFromFmt(albuf->mFmtChannels);
+ break;
+
+ case AL_SIZE:
+ *value = albuf->SampleLen * FrameSizeFromFmt(albuf->mFmtChannels, albuf->mFmtType);
+ break;
+
+ case AL_UNPACK_BLOCK_ALIGNMENT_SOFT:
+ *value = albuf->UnpackAlign.load();
+ break;
+
+ case AL_PACK_BLOCK_ALIGNMENT_SOFT:
+ *value = albuf->PackAlign.load();
+ break;
+
+ default:
+ alSetError(context.get(), AL_INVALID_ENUM, "Invalid buffer integer property 0x%04x", param);
+ }
+}
+END_API_FUNC
+
+AL_API void AL_APIENTRY alGetBuffer3i(ALuint buffer, ALenum param, ALint *value1, ALint *value2, ALint *value3)
+START_API_FUNC
+{
+ ContextRef context{GetContextRef()};
+ if(UNLIKELY(!context)) return;
+
+ ALCdevice *device = context->Device;
+ std::lock_guard<std::mutex> _{device->BufferLock};
+ if(UNLIKELY(LookupBuffer(device, buffer) == nullptr))
+ alSetError(context.get(), AL_INVALID_NAME, "Invalid buffer ID %u", buffer);
+ else if(UNLIKELY(!value1 || !value2 || !value3))
+ alSetError(context.get(), AL_INVALID_VALUE, "NULL pointer");
+ else switch(param)
+ {
+ default:
+ alSetError(context.get(), AL_INVALID_ENUM, "Invalid buffer 3-integer property 0x%04x", param);
+ }
+}
+END_API_FUNC
+
+AL_API void AL_APIENTRY alGetBufferiv(ALuint buffer, ALenum param, ALint *values)
+START_API_FUNC
+{
+ switch(param)
+ {
+ case AL_FREQUENCY:
+ case AL_BITS:
+ case AL_CHANNELS:
+ case AL_SIZE:
+ case AL_INTERNAL_FORMAT_SOFT:
+ case AL_BYTE_LENGTH_SOFT:
+ case AL_SAMPLE_LENGTH_SOFT:
+ case AL_UNPACK_BLOCK_ALIGNMENT_SOFT:
+ case AL_PACK_BLOCK_ALIGNMENT_SOFT:
+ alGetBufferi(buffer, param, values);
+ return;
+ }
+
+ ContextRef context{GetContextRef()};
+ if(UNLIKELY(!context)) return;
+
+ ALCdevice *device = context->Device;
+ std::lock_guard<std::mutex> _{device->BufferLock};
+ ALbuffer *albuf = LookupBuffer(device, buffer);
+ if(UNLIKELY(!albuf))
+ alSetError(context.get(), AL_INVALID_NAME, "Invalid buffer ID %u", buffer);
+ else if(UNLIKELY(!values))
+ alSetError(context.get(), AL_INVALID_VALUE, "NULL pointer");
+ else switch(param)
+ {
+ case AL_LOOP_POINTS_SOFT:
+ values[0] = albuf->LoopStart;
+ values[1] = albuf->LoopEnd;
+ break;
+
+ default:
+ alSetError(context.get(), AL_INVALID_ENUM, "Invalid buffer integer-vector property 0x%04x",
+ param);
+ }
+}
+END_API_FUNC
+
+
+ALsizei BytesFromUserFmt(UserFmtType type)
+{
+ switch(type)
+ {
+ case UserFmtUByte: return sizeof(ALubyte);
+ case UserFmtShort: return sizeof(ALshort);
+ case UserFmtFloat: return sizeof(ALfloat);
+ case UserFmtDouble: return sizeof(ALdouble);
+ case UserFmtMulaw: return sizeof(ALubyte);
+ case UserFmtAlaw: return sizeof(ALubyte);
+ case UserFmtIMA4: break; /* not handled here */
+ case UserFmtMSADPCM: break; /* not handled here */
+ }
+ return 0;
+}
+ALsizei ChannelsFromUserFmt(UserFmtChannels chans)
+{
+ switch(chans)
+ {
+ case UserFmtMono: return 1;
+ case UserFmtStereo: return 2;
+ case UserFmtRear: return 2;
+ case UserFmtQuad: return 4;
+ case UserFmtX51: return 6;
+ case UserFmtX61: return 7;
+ case UserFmtX71: return 8;
+ case UserFmtBFormat2D: return 3;
+ case UserFmtBFormat3D: return 4;
+ }
+ return 0;
+}
+
+ALsizei BytesFromFmt(FmtType type)
+{
+ switch(type)
+ {
+ case FmtUByte: return sizeof(ALubyte);
+ case FmtShort: return sizeof(ALshort);
+ case FmtFloat: return sizeof(ALfloat);
+ case FmtDouble: return sizeof(ALdouble);
+ case FmtMulaw: return sizeof(ALubyte);
+ case FmtAlaw: return sizeof(ALubyte);
+ }
+ return 0;
+}
+ALsizei ChannelsFromFmt(FmtChannels chans)
+{
+ switch(chans)
+ {
+ case FmtMono: return 1;
+ case FmtStereo: return 2;
+ case FmtRear: return 2;
+ case FmtQuad: return 4;
+ case FmtX51: return 6;
+ case FmtX61: return 7;
+ case FmtX71: return 8;
+ case FmtBFormat2D: return 3;
+ case FmtBFormat3D: return 4;
+ }
+ return 0;
+}
+
+
+BufferSubList::~BufferSubList()
+{
+ uint64_t usemask{~FreeMask};
+ while(usemask)
+ {
+ ALsizei idx{CTZ64(usemask)};
+ al::destroy_at(Buffers+idx);
+ usemask &= ~(1_u64 << idx);
+ }
+ FreeMask = ~usemask;
+ al_free(Buffers);
+ Buffers = nullptr;
+}
diff --git a/al/alBuffer.h b/al/alBuffer.h
new file mode 100644
index 00000000..1d5873e5
--- /dev/null
+++ b/al/alBuffer.h
@@ -0,0 +1,121 @@
+#ifndef AL_BUFFER_H
+#define AL_BUFFER_H
+
+#include <atomic>
+
+#include "AL/al.h"
+
+#include "albyte.h"
+#include "almalloc.h"
+#include "atomic.h"
+#include "inprogext.h"
+#include "vector.h"
+
+
+/* User formats */
+enum UserFmtType : unsigned char {
+ UserFmtUByte,
+ UserFmtShort,
+ UserFmtFloat,
+ UserFmtDouble,
+ UserFmtMulaw,
+ UserFmtAlaw,
+ UserFmtIMA4,
+ UserFmtMSADPCM,
+};
+enum UserFmtChannels : unsigned char {
+ UserFmtMono,
+ UserFmtStereo,
+ UserFmtRear,
+ UserFmtQuad,
+ UserFmtX51, /* (WFX order) */
+ UserFmtX61, /* (WFX order) */
+ UserFmtX71, /* (WFX order) */
+ UserFmtBFormat2D, /* WXY */
+ UserFmtBFormat3D, /* WXYZ */
+};
+
+ALsizei BytesFromUserFmt(UserFmtType type);
+ALsizei ChannelsFromUserFmt(UserFmtChannels chans);
+inline ALsizei FrameSizeFromUserFmt(UserFmtChannels chans, UserFmtType type)
+{ return ChannelsFromUserFmt(chans) * BytesFromUserFmt(type); }
+
+
+/* Storable formats */
+enum FmtType : unsigned char {
+ FmtUByte = UserFmtUByte,
+ FmtShort = UserFmtShort,
+ FmtFloat = UserFmtFloat,
+ FmtDouble = UserFmtDouble,
+ FmtMulaw = UserFmtMulaw,
+ FmtAlaw = UserFmtAlaw,
+};
+enum FmtChannels : unsigned char {
+ FmtMono = UserFmtMono,
+ FmtStereo = UserFmtStereo,
+ FmtRear = UserFmtRear,
+ FmtQuad = UserFmtQuad,
+ FmtX51 = UserFmtX51,
+ FmtX61 = UserFmtX61,
+ FmtX71 = UserFmtX71,
+ FmtBFormat2D = UserFmtBFormat2D,
+ FmtBFormat3D = UserFmtBFormat3D,
+};
+#define MAX_INPUT_CHANNELS (8)
+
+/* DevFmtType traits, providing the type, etc given a DevFmtType. */
+template<FmtType T>
+struct FmtTypeTraits { };
+
+template<>
+struct FmtTypeTraits<FmtUByte> { using Type = ALubyte; };
+template<>
+struct FmtTypeTraits<FmtShort> { using Type = ALshort; };
+template<>
+struct FmtTypeTraits<FmtFloat> { using Type = ALfloat; };
+template<>
+struct FmtTypeTraits<FmtDouble> { using Type = ALdouble; };
+template<>
+struct FmtTypeTraits<FmtMulaw> { using Type = ALubyte; };
+template<>
+struct FmtTypeTraits<FmtAlaw> { using Type = ALubyte; };
+
+
+ALsizei BytesFromFmt(FmtType type);
+ALsizei ChannelsFromFmt(FmtChannels chans);
+inline ALsizei FrameSizeFromFmt(FmtChannels chans, FmtType type)
+{ return ChannelsFromFmt(chans) * BytesFromFmt(type); }
+
+
+struct ALbuffer {
+ al::vector<al::byte,16> mData;
+
+ ALsizei Frequency{0};
+ ALbitfieldSOFT Access{0u};
+ ALsizei SampleLen{0};
+
+ FmtChannels mFmtChannels{};
+ FmtType mFmtType{};
+
+ UserFmtType OriginalType{};
+ ALsizei OriginalSize{0};
+ ALsizei OriginalAlign{0};
+
+ ALsizei LoopStart{0};
+ ALsizei LoopEnd{0};
+
+ std::atomic<ALsizei> UnpackAlign{0};
+ std::atomic<ALsizei> PackAlign{0};
+
+ ALbitfieldSOFT MappedAccess{0u};
+ ALsizei MappedOffset{0};
+ ALsizei MappedSize{0};
+
+ /* Number of times buffer was attached to a source (deletion can only occur when 0) */
+ RefCount ref{0u};
+
+ /* Self ID */
+ ALuint id{0};
+};
+
+#endif
diff --git a/al/alEffect.cpp b/al/alEffect.cpp
new file mode 100644
index 00000000..4a75f69f
--- /dev/null
+++ b/al/alEffect.cpp
@@ -0,0 +1,742 @@
+/**
+ * OpenAL cross platform audio library
+ * Copyright (C) 1999-2007 by authors.
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library; if not, write to the
+ * Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ * Or go to http://www.gnu.org/copyleft/lgpl.html
+ */
+
+#include "config.h"
+
+#include "alEffect.h"
+
+#include <algorithm>
+#include <cstdint>
+#include <cstring>
+#include <iterator>
+#include <memory>
+#include <mutex>
+#include <new>
+#include <utility>
+
+#include "AL/al.h"
+#include "AL/alc.h"
+#include "AL/alext.h"
+#include "AL/efx-presets.h"
+#include "AL/efx.h"
+
+#include "alError.h"
+#include "alcmain.h"
+#include "alcontext.h"
+#include "alexcpt.h"
+#include "almalloc.h"
+#include "alnumeric.h"
+#include "effects/base.h"
+#include "logging.h"
+#include "opthelpers.h"
+#include "vector.h"
+
+
+const EffectList gEffectList[15]{
+ { "eaxreverb", EAXREVERB_EFFECT, AL_EFFECT_EAXREVERB },
+ { "reverb", REVERB_EFFECT, AL_EFFECT_REVERB },
+ { "autowah", AUTOWAH_EFFECT, AL_EFFECT_AUTOWAH },
+ { "chorus", CHORUS_EFFECT, AL_EFFECT_CHORUS },
+ { "compressor", COMPRESSOR_EFFECT, AL_EFFECT_COMPRESSOR },
+ { "distortion", DISTORTION_EFFECT, AL_EFFECT_DISTORTION },
+ { "echo", ECHO_EFFECT, AL_EFFECT_ECHO },
+ { "equalizer", EQUALIZER_EFFECT, AL_EFFECT_EQUALIZER },
+ { "flanger", FLANGER_EFFECT, AL_EFFECT_FLANGER },
+ { "fshifter", FSHIFTER_EFFECT, AL_EFFECT_FREQUENCY_SHIFTER },
+ { "modulator", MODULATOR_EFFECT, AL_EFFECT_RING_MODULATOR },
+ { "pshifter", PSHIFTER_EFFECT, AL_EFFECT_PITCH_SHIFTER },
+ { "vmorpher", VMORPHER_EFFECT, AL_EFFECT_VOCAL_MORPHER },
+ { "dedicated", DEDICATED_EFFECT, AL_EFFECT_DEDICATED_LOW_FREQUENCY_EFFECT },
+ { "dedicated", DEDICATED_EFFECT, AL_EFFECT_DEDICATED_DIALOGUE },
+};
+
+ALboolean DisabledEffects[MAX_EFFECTS];
+
+namespace {
+
+constexpr struct FactoryItem {
+ ALenum Type;
+ EffectStateFactory* (&GetFactory)(void);
+} FactoryList[] = {
+ { AL_EFFECT_NULL, NullStateFactory_getFactory },
+ { AL_EFFECT_EAXREVERB, ReverbStateFactory_getFactory },
+ { AL_EFFECT_REVERB, StdReverbStateFactory_getFactory },
+ { AL_EFFECT_AUTOWAH, AutowahStateFactory_getFactory },
+ { AL_EFFECT_CHORUS, ChorusStateFactory_getFactory },
+ { AL_EFFECT_COMPRESSOR, CompressorStateFactory_getFactory },
+ { AL_EFFECT_DISTORTION, DistortionStateFactory_getFactory },
+ { AL_EFFECT_ECHO, EchoStateFactory_getFactory },
+ { AL_EFFECT_EQUALIZER, EqualizerStateFactory_getFactory },
+ { AL_EFFECT_FLANGER, FlangerStateFactory_getFactory },
+ { AL_EFFECT_FREQUENCY_SHIFTER, FshifterStateFactory_getFactory },
+ { AL_EFFECT_RING_MODULATOR, ModulatorStateFactory_getFactory },
+ { AL_EFFECT_PITCH_SHIFTER, PshifterStateFactory_getFactory},
+ { AL_EFFECT_VOCAL_MORPHER, VmorpherStateFactory_getFactory},
+ { AL_EFFECT_DEDICATED_DIALOGUE, DedicatedStateFactory_getFactory },
+ { AL_EFFECT_DEDICATED_LOW_FREQUENCY_EFFECT, DedicatedStateFactory_getFactory }
+};
+
+
+template<typename... T>
+void ALeffect_setParami(ALeffect *effect, T&& ...args)
+{ effect->vtab->setParami(&effect->Props, std::forward<T>(args)...); }
+template<typename... T>
+void ALeffect_setParamiv(ALeffect *effect, T&& ...args)
+{ effect->vtab->setParamiv(&effect->Props, std::forward<T>(args)...); }
+template<typename... T>
+void ALeffect_setParamf(ALeffect *effect, T&& ...args)
+{ effect->vtab->setParamf(&effect->Props, std::forward<T>(args)...); }
+template<typename... T>
+void ALeffect_setParamfv(ALeffect *effect, T&& ...args)
+{ effect->vtab->setParamfv(&effect->Props, std::forward<T>(args)...); }
+
+template<typename... T>
+void ALeffect_getParami(const ALeffect *effect, T&& ...args)
+{ effect->vtab->getParami(&effect->Props, std::forward<T>(args)...); }
+template<typename... T>
+void ALeffect_getParamiv(const ALeffect *effect, T&& ...args)
+{ effect->vtab->getParamiv(&effect->Props, std::forward<T>(args)...); }
+template<typename... T>
+void ALeffect_getParamf(const ALeffect *effect, T&& ...args)
+{ effect->vtab->getParamf(&effect->Props, std::forward<T>(args)...); }
+template<typename... T>
+void ALeffect_getParamfv(const ALeffect *effect, T&& ...args)
+{ effect->vtab->getParamfv(&effect->Props, std::forward<T>(args)...); }
+
+
+void InitEffectParams(ALeffect *effect, ALenum type)
+{
+ EffectStateFactory *factory = getFactoryByType(type);
+ if(factory)
+ {
+ effect->Props = factory->getDefaultProps();
+ effect->vtab = factory->getEffectVtable();
+ }
+ else
+ {
+ effect->Props = EffectProps {};
+ effect->vtab = nullptr;
+ }
+ effect->type = type;
+}
+
+ALeffect *AllocEffect(ALCcontext *context)
+{
+ ALCdevice *device{context->Device};
+ std::lock_guard<std::mutex> _{device->EffectLock};
+ auto sublist = std::find_if(device->EffectList.begin(), device->EffectList.end(),
+ [](const EffectSubList &entry) noexcept -> bool
+ { return entry.FreeMask != 0; }
+ );
+
+ auto lidx = static_cast<ALsizei>(std::distance(device->EffectList.begin(), sublist));
+ ALeffect *effect{nullptr};
+ ALsizei slidx{0};
+ if(LIKELY(sublist != device->EffectList.end()))
+ {
+ slidx = CTZ64(sublist->FreeMask);
+ effect = sublist->Effects + slidx;
+ }
+ else
+ {
+ /* Don't allocate so many list entries that the 32-bit ID could
+ * overflow...
+ */
+ if(UNLIKELY(device->EffectList.size() >= 1<<25))
+ {
+ alSetError(context, AL_OUT_OF_MEMORY, "Too many effects allocated");
+ return nullptr;
+ }
+ device->EffectList.emplace_back();
+ sublist = device->EffectList.end() - 1;
+ sublist->FreeMask = ~0_u64;
+ sublist->Effects = static_cast<ALeffect*>(al_calloc(16, sizeof(ALeffect)*64));
+ if(UNLIKELY(!sublist->Effects))
+ {
+ device->EffectList.pop_back();
+ alSetError(context, AL_OUT_OF_MEMORY, "Failed to allocate effect batch");
+ return nullptr;
+ }
+
+ slidx = 0;
+ effect = sublist->Effects + slidx;
+ }
+
+ effect = new (effect) ALeffect{};
+ InitEffectParams(effect, AL_EFFECT_NULL);
+
+ /* Add 1 to avoid effect ID 0. */
+ effect->id = ((lidx<<6) | slidx) + 1;
+
+ sublist->FreeMask &= ~(1_u64 << slidx);
+
+ return effect;
+}
+
+void FreeEffect(ALCdevice *device, ALeffect *effect)
+{
+ ALuint id = effect->id - 1;
+ ALsizei lidx = id >> 6;
+ ALsizei slidx = id & 0x3f;
+
+ al::destroy_at(effect);
+
+ device->EffectList[lidx].FreeMask |= 1_u64 << slidx;
+}
+
+inline ALeffect *LookupEffect(ALCdevice *device, ALuint id)
+{
+ ALuint lidx = (id-1) >> 6;
+ ALsizei slidx = (id-1) & 0x3f;
+
+ if(UNLIKELY(lidx >= device->EffectList.size()))
+ return nullptr;
+ EffectSubList &sublist = device->EffectList[lidx];
+ if(UNLIKELY(sublist.FreeMask & (1_u64 << slidx)))
+ return nullptr;
+ return sublist.Effects + slidx;
+}
+
+} // namespace
+
+AL_API ALvoid AL_APIENTRY alGenEffects(ALsizei n, ALuint *effects)
+START_API_FUNC
+{
+ ContextRef context{GetContextRef()};
+ if(UNLIKELY(!context)) return;
+
+ if(UNLIKELY(n < 0))
+ {
+ alSetError(context.get(), AL_INVALID_VALUE, "Generating %d effects", n);
+ return;
+ }
+
+ if(LIKELY(n == 1))
+ {
+ /* Special handling for the easy and normal case. */
+ ALeffect *effect = AllocEffect(context.get());
+ if(effect) effects[0] = effect->id;
+ }
+ else if(n > 1)
+ {
+ /* Store the allocated buffer IDs in a separate local list, to avoid
+ * modifying the user storage in case of failure.
+ */
+ al::vector<ALuint> ids;
+ ids.reserve(n);
+ do {
+ ALeffect *effect = AllocEffect(context.get());
+ if(!effect)
+ {
+ alDeleteEffects(static_cast<ALsizei>(ids.size()), ids.data());
+ return;
+ }
+
+ ids.emplace_back(effect->id);
+ } while(--n);
+ std::copy(ids.begin(), ids.end(), effects);
+ }
+}
+END_API_FUNC
+
+AL_API ALvoid AL_APIENTRY alDeleteEffects(ALsizei n, const ALuint *effects)
+START_API_FUNC
+{
+ ContextRef context{GetContextRef()};
+ if(UNLIKELY(!context)) return;
+
+ if(UNLIKELY(n < 0))
+ {
+ alSetError(context.get(), AL_INVALID_VALUE, "Deleting %d effects", n);
+ return;
+ }
+ if(UNLIKELY(n == 0))
+ return;
+
+ ALCdevice *device{context->Device};
+ std::lock_guard<std::mutex> _{device->EffectLock};
+
+ /* First try to find any effects that are invalid. */
+ const ALuint *effects_end = effects + n;
+ auto inveffect = std::find_if(effects, effects_end,
+ [device, &context](ALuint eid) -> bool
+ {
+ if(!eid) return false;
+ ALeffect *effect{LookupEffect(device, eid)};
+ if(UNLIKELY(!effect))
+ {
+ alSetError(context.get(), AL_INVALID_NAME, "Invalid effect ID %u", eid);
+ return true;
+ }
+ return false;
+ }
+ );
+ if(LIKELY(inveffect == effects_end))
+ {
+ /* All good. Delete non-0 effect IDs. */
+ std::for_each(effects, effects_end,
+ [device](ALuint eid) -> void
+ {
+ ALeffect *effect{eid ? LookupEffect(device, eid) : nullptr};
+ if(effect) FreeEffect(device, effect);
+ }
+ );
+ }
+}
+END_API_FUNC
+
+AL_API ALboolean AL_APIENTRY alIsEffect(ALuint effect)
+START_API_FUNC
+{
+ ContextRef context{GetContextRef()};
+ if(LIKELY(context))
+ {
+ ALCdevice *device{context->Device};
+ std::lock_guard<std::mutex> _{device->EffectLock};
+ if(!effect || LookupEffect(device, effect))
+ return AL_TRUE;
+ }
+ return AL_FALSE;
+}
+END_API_FUNC
+
+AL_API ALvoid AL_APIENTRY alEffecti(ALuint effect, ALenum param, ALint value)
+START_API_FUNC
+{
+ ContextRef context{GetContextRef()};
+ if(UNLIKELY(!context)) return;
+
+ ALCdevice *device{context->Device};
+ std::lock_guard<std::mutex> _{device->EffectLock};
+
+ ALeffect *aleffect{LookupEffect(device, effect)};
+ if(UNLIKELY(!aleffect))
+ alSetError(context.get(), AL_INVALID_NAME, "Invalid effect ID %u", effect);
+ else
+ {
+ if(param == AL_EFFECT_TYPE)
+ {
+ ALboolean isOk{value == AL_EFFECT_NULL};
+ if(!isOk)
+ {
+ for(const EffectList &effectitem : gEffectList)
+ {
+ if(value == effectitem.val && !DisabledEffects[effectitem.type])
+ {
+ isOk = AL_TRUE;
+ break;
+ }
+ }
+ }
+
+ if(isOk)
+ InitEffectParams(aleffect, value);
+ else
+ alSetError(context.get(), AL_INVALID_VALUE, "Effect type 0x%04x not supported", value);
+ }
+ else
+ {
+ /* Call the appropriate handler */
+ ALeffect_setParami(aleffect, context.get(), param, value);
+ }
+ }
+}
+END_API_FUNC
+
+AL_API ALvoid AL_APIENTRY alEffectiv(ALuint effect, ALenum param, const ALint *values)
+START_API_FUNC
+{
+ switch(param)
+ {
+ case AL_EFFECT_TYPE:
+ alEffecti(effect, param, values[0]);
+ return;
+ }
+
+ ContextRef context{GetContextRef()};
+ if(UNLIKELY(!context)) return;
+
+ ALCdevice *device{context->Device};
+ std::lock_guard<std::mutex> _{device->EffectLock};
+
+ ALeffect *aleffect{LookupEffect(device, effect)};
+ if(UNLIKELY(!aleffect))
+ alSetError(context.get(), AL_INVALID_NAME, "Invalid effect ID %u", effect);
+ else
+ {
+ /* Call the appropriate handler */
+ ALeffect_setParamiv(aleffect, context.get(), param, values);
+ }
+}
+END_API_FUNC
+
+AL_API ALvoid AL_APIENTRY alEffectf(ALuint effect, ALenum param, ALfloat value)
+START_API_FUNC
+{
+ ContextRef context{GetContextRef()};
+ if(UNLIKELY(!context)) return;
+
+ ALCdevice *device{context->Device};
+ std::lock_guard<std::mutex> _{device->EffectLock};
+
+ ALeffect *aleffect{LookupEffect(device, effect)};
+ if(UNLIKELY(!aleffect))
+ alSetError(context.get(), AL_INVALID_NAME, "Invalid effect ID %u", effect);
+ else
+ {
+ /* Call the appropriate handler */
+ ALeffect_setParamf(aleffect, context.get(), param, value);
+ }
+}
+END_API_FUNC
+
+AL_API ALvoid AL_APIENTRY alEffectfv(ALuint effect, ALenum param, const ALfloat *values)
+START_API_FUNC
+{
+ ContextRef context{GetContextRef()};
+ if(UNLIKELY(!context)) return;
+
+ ALCdevice *device{context->Device};
+ std::lock_guard<std::mutex> _{device->EffectLock};
+
+ ALeffect *aleffect{LookupEffect(device, effect)};
+ if(UNLIKELY(!aleffect))
+ alSetError(context.get(), AL_INVALID_NAME, "Invalid effect ID %u", effect);
+ else
+ {
+ /* Call the appropriate handler */
+ ALeffect_setParamfv(aleffect, context.get(), param, values);
+ }
+}
+END_API_FUNC
+
+AL_API ALvoid AL_APIENTRY alGetEffecti(ALuint effect, ALenum param, ALint *value)
+START_API_FUNC
+{
+ ContextRef context{GetContextRef()};
+ if(UNLIKELY(!context)) return;
+
+ ALCdevice *device{context->Device};
+ std::lock_guard<std::mutex> _{device->EffectLock};
+
+ const ALeffect *aleffect{LookupEffect(device, effect)};
+ if(UNLIKELY(!aleffect))
+ alSetError(context.get(), AL_INVALID_NAME, "Invalid effect ID %u", effect);
+ else
+ {
+ if(param == AL_EFFECT_TYPE)
+ *value = aleffect->type;
+ else
+ {
+ /* Call the appropriate handler */
+ ALeffect_getParami(aleffect, context.get(), param, value);
+ }
+ }
+}
+END_API_FUNC
+
+AL_API ALvoid AL_APIENTRY alGetEffectiv(ALuint effect, ALenum param, ALint *values)
+START_API_FUNC
+{
+ switch(param)
+ {
+ case AL_EFFECT_TYPE:
+ alGetEffecti(effect, param, values);
+ return;
+ }
+
+ ContextRef context{GetContextRef()};
+ if(UNLIKELY(!context)) return;
+
+ ALCdevice *device{context->Device};
+ std::lock_guard<std::mutex> _{device->EffectLock};
+
+ const ALeffect *aleffect{LookupEffect(device, effect)};
+ if(UNLIKELY(!aleffect))
+ alSetError(context.get(), AL_INVALID_NAME, "Invalid effect ID %u", effect);
+ else
+ {
+ /* Call the appropriate handler */
+ ALeffect_getParamiv(aleffect, context.get(), param, values);
+ }
+}
+END_API_FUNC
+
+AL_API ALvoid AL_APIENTRY alGetEffectf(ALuint effect, ALenum param, ALfloat *value)
+START_API_FUNC
+{
+ ContextRef context{GetContextRef()};
+ if(UNLIKELY(!context)) return;
+
+ ALCdevice *device{context->Device};
+ std::lock_guard<std::mutex> _{device->EffectLock};
+
+ const ALeffect *aleffect{LookupEffect(device, effect)};
+ if(UNLIKELY(!aleffect))
+ alSetError(context.get(), AL_INVALID_NAME, "Invalid effect ID %u", effect);
+ else
+ {
+ /* Call the appropriate handler */
+ ALeffect_getParamf(aleffect, context.get(), param, value);
+ }
+}
+END_API_FUNC
+
+AL_API ALvoid AL_APIENTRY alGetEffectfv(ALuint effect, ALenum param, ALfloat *values)
+START_API_FUNC
+{
+ ContextRef context{GetContextRef()};
+ if(UNLIKELY(!context)) return;
+
+ ALCdevice *device{context->Device};
+ std::lock_guard<std::mutex> _{device->EffectLock};
+
+ const ALeffect *aleffect{LookupEffect(device, effect)};
+ if(UNLIKELY(!aleffect))
+ alSetError(context.get(), AL_INVALID_NAME, "Invalid effect ID %u", effect);
+ else
+ {
+ /* Call the appropriate handler */
+ ALeffect_getParamfv(aleffect, context.get(), param, values);
+ }
+}
+END_API_FUNC
+
+
+void InitEffect(ALeffect *effect)
+{
+ InitEffectParams(effect, AL_EFFECT_NULL);
+}
+
+EffectSubList::~EffectSubList()
+{
+ uint64_t usemask{~FreeMask};
+ while(usemask)
+ {
+ ALsizei idx = CTZ64(usemask);
+ al::destroy_at(Effects+idx);
+ usemask &= ~(1_u64 << idx);
+ }
+ FreeMask = ~usemask;
+ al_free(Effects);
+ Effects = nullptr;
+}
+
+
+EffectStateFactory *getFactoryByType(ALenum type)
+{
+ auto iter = std::find_if(std::begin(FactoryList), std::end(FactoryList),
+ [type](const FactoryItem &item) noexcept -> bool
+ { return item.Type == type; }
+ );
+ return (iter != std::end(FactoryList)) ? iter->GetFactory() : nullptr;
+}
+
+
+#define DECL(x) { #x, EFX_REVERB_PRESET_##x }
+static const struct {
+ const char name[32];
+ EFXEAXREVERBPROPERTIES props;
+} reverblist[] = {
+ DECL(GENERIC),
+ DECL(PADDEDCELL),
+ DECL(ROOM),
+ DECL(BATHROOM),
+ DECL(LIVINGROOM),
+ DECL(STONEROOM),
+ DECL(AUDITORIUM),
+ DECL(CONCERTHALL),
+ DECL(CAVE),
+ DECL(ARENA),
+ DECL(HANGAR),
+ DECL(CARPETEDHALLWAY),
+ DECL(HALLWAY),
+ DECL(STONECORRIDOR),
+ DECL(ALLEY),
+ DECL(FOREST),
+ DECL(CITY),
+ DECL(MOUNTAINS),
+ DECL(QUARRY),
+ DECL(PLAIN),
+ DECL(PARKINGLOT),
+ DECL(SEWERPIPE),
+ DECL(UNDERWATER),
+ DECL(DRUGGED),
+ DECL(DIZZY),
+ DECL(PSYCHOTIC),
+
+ DECL(CASTLE_SMALLROOM),
+ DECL(CASTLE_SHORTPASSAGE),
+ DECL(CASTLE_MEDIUMROOM),
+ DECL(CASTLE_LARGEROOM),
+ DECL(CASTLE_LONGPASSAGE),
+ DECL(CASTLE_HALL),
+ DECL(CASTLE_CUPBOARD),
+ DECL(CASTLE_COURTYARD),
+ DECL(CASTLE_ALCOVE),
+
+ DECL(FACTORY_SMALLROOM),
+ DECL(FACTORY_SHORTPASSAGE),
+ DECL(FACTORY_MEDIUMROOM),
+ DECL(FACTORY_LARGEROOM),
+ DECL(FACTORY_LONGPASSAGE),
+ DECL(FACTORY_HALL),
+ DECL(FACTORY_CUPBOARD),
+ DECL(FACTORY_COURTYARD),
+ DECL(FACTORY_ALCOVE),
+
+ DECL(ICEPALACE_SMALLROOM),
+ DECL(ICEPALACE_SHORTPASSAGE),
+ DECL(ICEPALACE_MEDIUMROOM),
+ DECL(ICEPALACE_LARGEROOM),
+ DECL(ICEPALACE_LONGPASSAGE),
+ DECL(ICEPALACE_HALL),
+ DECL(ICEPALACE_CUPBOARD),
+ DECL(ICEPALACE_COURTYARD),
+ DECL(ICEPALACE_ALCOVE),
+
+ DECL(SPACESTATION_SMALLROOM),
+ DECL(SPACESTATION_SHORTPASSAGE),
+ DECL(SPACESTATION_MEDIUMROOM),
+ DECL(SPACESTATION_LARGEROOM),
+ DECL(SPACESTATION_LONGPASSAGE),
+ DECL(SPACESTATION_HALL),
+ DECL(SPACESTATION_CUPBOARD),
+ DECL(SPACESTATION_ALCOVE),
+
+ DECL(WOODEN_SMALLROOM),
+ DECL(WOODEN_SHORTPASSAGE),
+ DECL(WOODEN_MEDIUMROOM),
+ DECL(WOODEN_LARGEROOM),
+ DECL(WOODEN_LONGPASSAGE),
+ DECL(WOODEN_HALL),
+ DECL(WOODEN_CUPBOARD),
+ DECL(WOODEN_COURTYARD),
+ DECL(WOODEN_ALCOVE),
+
+ DECL(SPORT_EMPTYSTADIUM),
+ DECL(SPORT_SQUASHCOURT),
+ DECL(SPORT_SMALLSWIMMINGPOOL),
+ DECL(SPORT_LARGESWIMMINGPOOL),
+ DECL(SPORT_GYMNASIUM),
+ DECL(SPORT_FULLSTADIUM),
+ DECL(SPORT_STADIUMTANNOY),
+
+ DECL(PREFAB_WORKSHOP),
+ DECL(PREFAB_SCHOOLROOM),
+ DECL(PREFAB_PRACTISEROOM),
+ DECL(PREFAB_OUTHOUSE),
+ DECL(PREFAB_CARAVAN),
+
+ DECL(DOME_TOMB),
+ DECL(PIPE_SMALL),
+ DECL(DOME_SAINTPAULS),
+ DECL(PIPE_LONGTHIN),
+ DECL(PIPE_LARGE),
+ DECL(PIPE_RESONANT),
+
+ DECL(OUTDOORS_BACKYARD),
+ DECL(OUTDOORS_ROLLINGPLAINS),
+ DECL(OUTDOORS_DEEPCANYON),
+ DECL(OUTDOORS_CREEK),
+ DECL(OUTDOORS_VALLEY),
+
+ DECL(MOOD_HEAVEN),
+ DECL(MOOD_HELL),
+ DECL(MOOD_MEMORY),
+
+ DECL(DRIVING_COMMENTATOR),
+ DECL(DRIVING_PITGARAGE),
+ DECL(DRIVING_INCAR_RACER),
+ DECL(DRIVING_INCAR_SPORTS),
+ DECL(DRIVING_INCAR_LUXURY),
+ DECL(DRIVING_FULLGRANDSTAND),
+ DECL(DRIVING_EMPTYGRANDSTAND),
+ DECL(DRIVING_TUNNEL),
+
+ DECL(CITY_STREETS),
+ DECL(CITY_SUBWAY),
+ DECL(CITY_MUSEUM),
+ DECL(CITY_LIBRARY),
+ DECL(CITY_UNDERPASS),
+ DECL(CITY_ABANDONED),
+
+ DECL(DUSTYROOM),
+ DECL(CHAPEL),
+ DECL(SMALLWATERROOM),
+};
+#undef DECL
+
+void LoadReverbPreset(const char *name, ALeffect *effect)
+{
+ if(strcasecmp(name, "NONE") == 0)
+ {
+ InitEffectParams(effect, AL_EFFECT_NULL);
+ TRACE("Loading reverb '%s'\n", "NONE");
+ return;
+ }
+
+ if(!DisabledEffects[EAXREVERB_EFFECT])
+ InitEffectParams(effect, AL_EFFECT_EAXREVERB);
+ else if(!DisabledEffects[REVERB_EFFECT])
+ InitEffectParams(effect, AL_EFFECT_REVERB);
+ else
+ InitEffectParams(effect, AL_EFFECT_NULL);
+ for(const auto &reverbitem : reverblist)
+ {
+ const EFXEAXREVERBPROPERTIES *props;
+
+ if(strcasecmp(name, reverbitem.name) != 0)
+ continue;
+
+ TRACE("Loading reverb '%s'\n", reverbitem.name);
+ props = &reverbitem.props;
+ effect->Props.Reverb.Density = props->flDensity;
+ effect->Props.Reverb.Diffusion = props->flDiffusion;
+ effect->Props.Reverb.Gain = props->flGain;
+ effect->Props.Reverb.GainHF = props->flGainHF;
+ effect->Props.Reverb.GainLF = props->flGainLF;
+ effect->Props.Reverb.DecayTime = props->flDecayTime;
+ effect->Props.Reverb.DecayHFRatio = props->flDecayHFRatio;
+ effect->Props.Reverb.DecayLFRatio = props->flDecayLFRatio;
+ effect->Props.Reverb.ReflectionsGain = props->flReflectionsGain;
+ effect->Props.Reverb.ReflectionsDelay = props->flReflectionsDelay;
+ effect->Props.Reverb.ReflectionsPan[0] = props->flReflectionsPan[0];
+ effect->Props.Reverb.ReflectionsPan[1] = props->flReflectionsPan[1];
+ effect->Props.Reverb.ReflectionsPan[2] = props->flReflectionsPan[2];
+ effect->Props.Reverb.LateReverbGain = props->flLateReverbGain;
+ effect->Props.Reverb.LateReverbDelay = props->flLateReverbDelay;
+ effect->Props.Reverb.LateReverbPan[0] = props->flLateReverbPan[0];
+ effect->Props.Reverb.LateReverbPan[1] = props->flLateReverbPan[1];
+ effect->Props.Reverb.LateReverbPan[2] = props->flLateReverbPan[2];
+ effect->Props.Reverb.EchoTime = props->flEchoTime;
+ effect->Props.Reverb.EchoDepth = props->flEchoDepth;
+ effect->Props.Reverb.ModulationTime = props->flModulationTime;
+ effect->Props.Reverb.ModulationDepth = props->flModulationDepth;
+ effect->Props.Reverb.AirAbsorptionGainHF = props->flAirAbsorptionGainHF;
+ effect->Props.Reverb.HFReference = props->flHFReference;
+ effect->Props.Reverb.LFReference = props->flLFReference;
+ effect->Props.Reverb.RoomRolloffFactor = props->flRoomRolloffFactor;
+ effect->Props.Reverb.DecayHFLimit = props->iDecayHFLimit;
+ return;
+ }
+
+ WARN("Reverb preset '%s' not found\n", name);
+}
diff --git a/al/alEffect.h b/al/alEffect.h
new file mode 100644
index 00000000..270b8e20
--- /dev/null
+++ b/al/alEffect.h
@@ -0,0 +1,61 @@
+#ifndef AL_EFFECT_H
+#define AL_EFFECT_H
+
+#include "AL/al.h"
+#include "AL/efx.h"
+
+#include "effects/base.h"
+
+
+enum {
+ EAXREVERB_EFFECT = 0,
+ REVERB_EFFECT,
+ AUTOWAH_EFFECT,
+ CHORUS_EFFECT,
+ COMPRESSOR_EFFECT,
+ DISTORTION_EFFECT,
+ ECHO_EFFECT,
+ EQUALIZER_EFFECT,
+ FLANGER_EFFECT,
+ FSHIFTER_EFFECT,
+ MODULATOR_EFFECT,
+ PSHIFTER_EFFECT,
+ VMORPHER_EFFECT,
+ DEDICATED_EFFECT,
+
+ MAX_EFFECTS
+};
+extern ALboolean DisabledEffects[MAX_EFFECTS];
+
+extern ALfloat ReverbBoost;
+
+struct EffectList {
+ const char name[16];
+ int type;
+ ALenum val;
+};
+extern const EffectList gEffectList[15];
+
+
+struct ALeffect {
+ // Effect type (AL_EFFECT_NULL, ...)
+ ALenum type{AL_EFFECT_NULL};
+
+ EffectProps Props{};
+
+ const EffectVtable *vtab{nullptr};
+
+ /* Self ID */
+ ALuint id{0u};
+};
+
+inline ALboolean IsReverbEffect(ALenum type)
+{ return type == AL_EFFECT_REVERB || type == AL_EFFECT_EAXREVERB; }
+
+EffectStateFactory *getFactoryByType(ALenum type);
+
+void InitEffect(ALeffect *effect);
+
+void LoadReverbPreset(const char *name, ALeffect *effect);
+
+#endif
diff --git a/al/alError.cpp b/al/alError.cpp
new file mode 100644
index 00000000..159aee52
--- /dev/null
+++ b/al/alError.cpp
@@ -0,0 +1,118 @@
+/**
+ * OpenAL cross platform audio library
+ * Copyright (C) 1999-2000 by authors.
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library; if not, write to the
+ * Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ * Or go to http://www.gnu.org/copyleft/lgpl.html
+ */
+
+#include "config.h"
+
+#include "alError.h"
+
+#ifdef _WIN32
+#define WIN32_LEAN_AND_MEAN
+#include <windows.h>
+#endif
+
+#include <atomic>
+#include <csignal>
+#include <cstdarg>
+#include <cstdio>
+#include <cstring>
+#include <mutex>
+
+#include "AL/al.h"
+#include "AL/alc.h"
+
+#include "alcmain.h"
+#include "alcontext.h"
+#include "alexcpt.h"
+#include "almalloc.h"
+#include "inprogext.h"
+#include "logging.h"
+#include "opthelpers.h"
+#include "vector.h"
+
+
+bool TrapALError{false};
+
+void alSetError(ALCcontext *context, ALenum errorCode, const char *msg, ...)
+{
+ auto message = al::vector<char>(256);
+
+ va_list args, args2;
+ va_start(args, msg);
+ va_copy(args2, args);
+ int msglen{std::vsnprintf(message.data(), message.size(), msg, args)};
+ if(msglen >= 0 && static_cast<size_t>(msglen) >= message.size())
+ {
+ message.resize(static_cast<size_t>(msglen) + 1u);
+ msglen = std::vsnprintf(message.data(), message.size(), msg, args2);
+ }
+ va_end(args2);
+ va_end(args);
+
+ if(msglen >= 0) msg = message.data();
+ else msg = "<internal error constructing message>";
+ msglen = static_cast<int>(strlen(msg));
+
+ WARN("Error generated on context %p, code 0x%04x, \"%s\"\n", context, errorCode, msg);
+ if(TrapALError)
+ {
+#ifdef _WIN32
+ /* DebugBreak will cause an exception if there is no debugger */
+ if(IsDebuggerPresent())
+ DebugBreak();
+#elif defined(SIGTRAP)
+ raise(SIGTRAP);
+#endif
+ }
+
+ ALenum curerr{AL_NO_ERROR};
+ context->LastError.compare_exchange_strong(curerr, errorCode);
+ if((context->EnabledEvts.load(std::memory_order_relaxed)&EventType_Error))
+ {
+ std::lock_guard<std::mutex> _{context->EventCbLock};
+ ALbitfieldSOFT enabledevts{context->EnabledEvts.load(std::memory_order_relaxed)};
+ if((enabledevts&EventType_Error) && context->EventCb)
+ (*context->EventCb)(AL_EVENT_TYPE_ERROR_SOFT, 0, errorCode, msglen, msg,
+ context->EventParam);
+ }
+}
+
+AL_API ALenum AL_APIENTRY alGetError(void)
+START_API_FUNC
+{
+ ContextRef context{GetContextRef()};
+ if(UNLIKELY(!context))
+ {
+ constexpr ALenum deferror{AL_INVALID_OPERATION};
+ WARN("Querying error state on null context (implicitly 0x%04x)\n", deferror);
+ if(TrapALError)
+ {
+#ifdef _WIN32
+ if(IsDebuggerPresent())
+ DebugBreak();
+#elif defined(SIGTRAP)
+ raise(SIGTRAP);
+#endif
+ }
+ return deferror;
+ }
+
+ return context->LastError.exchange(AL_NO_ERROR);
+}
+END_API_FUNC
diff --git a/al/alError.h b/al/alError.h
new file mode 100644
index 00000000..6408b60c
--- /dev/null
+++ b/al/alError.h
@@ -0,0 +1,24 @@
+#ifndef AL_ERROR_H
+#define AL_ERROR_H
+
+#include "AL/al.h"
+#include "AL/alc.h"
+
+#include "logging.h"
+
+
+extern bool TrapALError;
+
+void alSetError(ALCcontext *context, ALenum errorCode, const char *msg, ...) DECL_FORMAT(printf, 3, 4);
+
+#define SETERR_GOTO(ctx, err, lbl, ...) do { \
+ alSetError((ctx), (err), __VA_ARGS__); \
+ goto lbl; \
+} while(0)
+
+#define SETERR_RETURN(ctx, err, retval, ...) do { \
+ alSetError((ctx), (err), __VA_ARGS__); \
+ return retval; \
+} while(0)
+
+#endif
diff --git a/al/alExtension.cpp b/al/alExtension.cpp
new file mode 100644
index 00000000..80681090
--- /dev/null
+++ b/al/alExtension.cpp
@@ -0,0 +1,80 @@
+/**
+ * OpenAL cross platform audio library
+ * Copyright (C) 1999-2007 by authors.
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library; if not, write to the
+ * Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ * Or go to http://www.gnu.org/copyleft/lgpl.html
+ */
+
+#include "config.h"
+
+#include <cctype>
+#include <cstdlib>
+#include <cstring>
+
+#include "AL/al.h"
+#include "AL/alc.h"
+
+#include "alError.h"
+#include "alcontext.h"
+#include "alexcpt.h"
+#include "opthelpers.h"
+
+
+AL_API ALboolean AL_APIENTRY alIsExtensionPresent(const ALchar *extName)
+START_API_FUNC
+{
+ ContextRef context{GetContextRef()};
+ if(UNLIKELY(!context)) return AL_FALSE;
+
+ if(!extName)
+ SETERR_RETURN(context.get(), AL_INVALID_VALUE, AL_FALSE, "NULL pointer");
+
+ size_t len{strlen(extName)};
+ const char *ptr{context->ExtensionList};
+ while(ptr && *ptr)
+ {
+ if(strncasecmp(ptr, extName, len) == 0 &&
+ (ptr[len] == '\0' || isspace(ptr[len])))
+ return AL_TRUE;
+
+ if((ptr=strchr(ptr, ' ')) != nullptr)
+ {
+ do {
+ ++ptr;
+ } while(isspace(*ptr));
+ }
+ }
+
+ return AL_FALSE;
+}
+END_API_FUNC
+
+
+AL_API ALvoid* AL_APIENTRY alGetProcAddress(const ALchar *funcName)
+START_API_FUNC
+{
+ if(!funcName) return nullptr;
+ return alcGetProcAddress(nullptr, funcName);
+}
+END_API_FUNC
+
+AL_API ALenum AL_APIENTRY alGetEnumValue(const ALchar *enumName)
+START_API_FUNC
+{
+ if(!enumName) return static_cast<ALenum>(0);
+ return alcGetEnumValue(nullptr, enumName);
+}
+END_API_FUNC
diff --git a/al/alFilter.cpp b/al/alFilter.cpp
new file mode 100644
index 00000000..31fbaf21
--- /dev/null
+++ b/al/alFilter.cpp
@@ -0,0 +1,665 @@
+/**
+ * OpenAL cross platform audio library
+ * Copyright (C) 1999-2007 by authors.
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library; if not, write to the
+ * Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ * Or go to http://www.gnu.org/copyleft/lgpl.html
+ */
+
+#include "config.h"
+
+#include "alFilter.h"
+
+#include <algorithm>
+#include <cstdint>
+#include <iterator>
+#include <memory>
+#include <mutex>
+#include <new>
+
+#include "AL/efx.h"
+
+#include "alError.h"
+#include "alcmain.h"
+#include "alcontext.h"
+#include "alexcpt.h"
+#include "almalloc.h"
+#include "alnumeric.h"
+#include "opthelpers.h"
+#include "vector.h"
+
+
+namespace {
+
+#define FILTER_MIN_GAIN 0.0f
+#define FILTER_MAX_GAIN 4.0f /* +12dB */
+
+void ALlowpass_setParami(ALfilter*, ALCcontext *context, ALenum param, ALint)
+{ alSetError(context, AL_INVALID_ENUM, "Invalid low-pass integer property 0x%04x", param); }
+void ALlowpass_setParamiv(ALfilter*, ALCcontext *context, ALenum param, const ALint*)
+{ alSetError(context, AL_INVALID_ENUM, "Invalid low-pass integer-vector property 0x%04x", param); }
+void ALlowpass_setParamf(ALfilter *filter, ALCcontext *context, ALenum param, ALfloat val)
+{
+ switch(param)
+ {
+ case AL_LOWPASS_GAIN:
+ if(!(val >= FILTER_MIN_GAIN && val <= FILTER_MAX_GAIN))
+ SETERR_RETURN(context, AL_INVALID_VALUE,, "Low-pass gain %f out of range", val);
+ filter->Gain = val;
+ break;
+
+ case AL_LOWPASS_GAINHF:
+ if(!(val >= AL_LOWPASS_MIN_GAINHF && val <= AL_LOWPASS_MAX_GAINHF))
+ SETERR_RETURN(context, AL_INVALID_VALUE,, "Low-pass gainhf %f out of range", val);
+ filter->GainHF = val;
+ break;
+
+ default:
+ alSetError(context, AL_INVALID_ENUM, "Invalid low-pass float property 0x%04x", param);
+ }
+}
+void ALlowpass_setParamfv(ALfilter *filter, ALCcontext *context, ALenum param, const ALfloat *vals)
+{ ALlowpass_setParamf(filter, context, param, vals[0]); }
+
+void ALlowpass_getParami(ALfilter*, ALCcontext *context, ALenum param, ALint*)
+{ alSetError(context, AL_INVALID_ENUM, "Invalid low-pass integer property 0x%04x", param); }
+void ALlowpass_getParamiv(ALfilter*, ALCcontext *context, ALenum param, ALint*)
+{ alSetError(context, AL_INVALID_ENUM, "Invalid low-pass integer-vector property 0x%04x", param); }
+void ALlowpass_getParamf(ALfilter *filter, ALCcontext *context, ALenum param, ALfloat *val)
+{
+ switch(param)
+ {
+ case AL_LOWPASS_GAIN:
+ *val = filter->Gain;
+ break;
+
+ case AL_LOWPASS_GAINHF:
+ *val = filter->GainHF;
+ break;
+
+ default:
+ alSetError(context, AL_INVALID_ENUM, "Invalid low-pass float property 0x%04x", param);
+ }
+}
+void ALlowpass_getParamfv(ALfilter *filter, ALCcontext *context, ALenum param, ALfloat *vals)
+{ ALlowpass_getParamf(filter, context, param, vals); }
+
+DEFINE_ALFILTER_VTABLE(ALlowpass);
+
+
+void ALhighpass_setParami(ALfilter*, ALCcontext *context, ALenum param, ALint)
+{ alSetError(context, AL_INVALID_ENUM, "Invalid high-pass integer property 0x%04x", param); }
+void ALhighpass_setParamiv(ALfilter*, ALCcontext *context, ALenum param, const ALint*)
+{ alSetError(context, AL_INVALID_ENUM, "Invalid high-pass integer-vector property 0x%04x", param); }
+void ALhighpass_setParamf(ALfilter *filter, ALCcontext *context, ALenum param, ALfloat val)
+{
+ switch(param)
+ {
+ case AL_HIGHPASS_GAIN:
+ if(!(val >= FILTER_MIN_GAIN && val <= FILTER_MAX_GAIN))
+ SETERR_RETURN(context, AL_INVALID_VALUE,, "High-pass gain out of range");
+ filter->Gain = val;
+ break;
+
+ case AL_HIGHPASS_GAINLF:
+ if(!(val >= AL_HIGHPASS_MIN_GAINLF && val <= AL_HIGHPASS_MAX_GAINLF))
+ SETERR_RETURN(context, AL_INVALID_VALUE,, "High-pass gainlf out of range");
+ filter->GainLF = val;
+ break;
+
+ default:
+ alSetError(context, AL_INVALID_ENUM, "Invalid high-pass float property 0x%04x", param);
+ }
+}
+void ALhighpass_setParamfv(ALfilter *filter, ALCcontext *context, ALenum param, const ALfloat *vals)
+{ ALhighpass_setParamf(filter, context, param, vals[0]); }
+
+void ALhighpass_getParami(ALfilter*, ALCcontext *context, ALenum param, ALint*)
+{ alSetError(context, AL_INVALID_ENUM, "Invalid high-pass integer property 0x%04x", param); }
+void ALhighpass_getParamiv(ALfilter*, ALCcontext *context, ALenum param, ALint*)
+{ alSetError(context, AL_INVALID_ENUM, "Invalid high-pass integer-vector property 0x%04x", param); }
+void ALhighpass_getParamf(ALfilter *filter, ALCcontext *context, ALenum param, ALfloat *val)
+{
+ switch(param)
+ {
+ case AL_HIGHPASS_GAIN:
+ *val = filter->Gain;
+ break;
+
+ case AL_HIGHPASS_GAINLF:
+ *val = filter->GainLF;
+ break;
+
+ default:
+ alSetError(context, AL_INVALID_ENUM, "Invalid high-pass float property 0x%04x", param);
+ }
+}
+void ALhighpass_getParamfv(ALfilter *filter, ALCcontext *context, ALenum param, ALfloat *vals)
+{ ALhighpass_getParamf(filter, context, param, vals); }
+
+DEFINE_ALFILTER_VTABLE(ALhighpass);
+
+
+void ALbandpass_setParami(ALfilter*, ALCcontext *context, ALenum param, ALint)
+{ alSetError(context, AL_INVALID_ENUM, "Invalid band-pass integer property 0x%04x", param); }
+void ALbandpass_setParamiv(ALfilter*, ALCcontext *context, ALenum param, const ALint*)
+{ alSetError(context, AL_INVALID_ENUM, "Invalid band-pass integer-vector property 0x%04x", param); }
+void ALbandpass_setParamf(ALfilter *filter, ALCcontext *context, ALenum param, ALfloat val)
+{
+ switch(param)
+ {
+ case AL_BANDPASS_GAIN:
+ if(!(val >= FILTER_MIN_GAIN && val <= FILTER_MAX_GAIN))
+ SETERR_RETURN(context, AL_INVALID_VALUE,, "Band-pass gain out of range");
+ filter->Gain = val;
+ break;
+
+ case AL_BANDPASS_GAINHF:
+ if(!(val >= AL_BANDPASS_MIN_GAINHF && val <= AL_BANDPASS_MAX_GAINHF))
+ SETERR_RETURN(context, AL_INVALID_VALUE,, "Band-pass gainhf out of range");
+ filter->GainHF = val;
+ break;
+
+ case AL_BANDPASS_GAINLF:
+ if(!(val >= AL_BANDPASS_MIN_GAINLF && val <= AL_BANDPASS_MAX_GAINLF))
+ SETERR_RETURN(context, AL_INVALID_VALUE,, "Band-pass gainlf out of range");
+ filter->GainLF = val;
+ break;
+
+ default:
+ alSetError(context, AL_INVALID_ENUM, "Invalid band-pass float property 0x%04x", param);
+ }
+}
+void ALbandpass_setParamfv(ALfilter *filter, ALCcontext *context, ALenum param, const ALfloat *vals)
+{ ALbandpass_setParamf(filter, context, param, vals[0]); }
+
+void ALbandpass_getParami(ALfilter*, ALCcontext *context, ALenum param, ALint*)
+{ alSetError(context, AL_INVALID_ENUM, "Invalid band-pass integer property 0x%04x", param); }
+void ALbandpass_getParamiv(ALfilter*, ALCcontext *context, ALenum param, ALint*)
+{ alSetError(context, AL_INVALID_ENUM, "Invalid band-pass integer-vector property 0x%04x", param); }
+void ALbandpass_getParamf(ALfilter *filter, ALCcontext *context, ALenum param, ALfloat *val)
+{
+ switch(param)
+ {
+ case AL_BANDPASS_GAIN:
+ *val = filter->Gain;
+ break;
+
+ case AL_BANDPASS_GAINHF:
+ *val = filter->GainHF;
+ break;
+
+ case AL_BANDPASS_GAINLF:
+ *val = filter->GainLF;
+ break;
+
+ default:
+ alSetError(context, AL_INVALID_ENUM, "Invalid band-pass float property 0x%04x", param);
+ }
+}
+void ALbandpass_getParamfv(ALfilter *filter, ALCcontext *context, ALenum param, ALfloat *vals)
+{ ALbandpass_getParamf(filter, context, param, vals); }
+
+DEFINE_ALFILTER_VTABLE(ALbandpass);
+
+
+void ALnullfilter_setParami(ALfilter*, ALCcontext *context, ALenum param, ALint)
+{ alSetError(context, AL_INVALID_ENUM, "Invalid null filter property 0x%04x", param); }
+void ALnullfilter_setParamiv(ALfilter*, ALCcontext *context, ALenum param, const ALint*)
+{ alSetError(context, AL_INVALID_ENUM, "Invalid null filter property 0x%04x", param); }
+void ALnullfilter_setParamf(ALfilter*, ALCcontext *context, ALenum param, ALfloat)
+{ alSetError(context, AL_INVALID_ENUM, "Invalid null filter property 0x%04x", param); }
+void ALnullfilter_setParamfv(ALfilter*, ALCcontext *context, ALenum param, const ALfloat*)
+{ alSetError(context, AL_INVALID_ENUM, "Invalid null filter property 0x%04x", param); }
+
+void ALnullfilter_getParami(ALfilter*, ALCcontext *context, ALenum param, ALint*)
+{ alSetError(context, AL_INVALID_ENUM, "Invalid null filter property 0x%04x", param); }
+void ALnullfilter_getParamiv(ALfilter*, ALCcontext *context, ALenum param, ALint*)
+{ alSetError(context, AL_INVALID_ENUM, "Invalid null filter property 0x%04x", param); }
+void ALnullfilter_getParamf(ALfilter*, ALCcontext *context, ALenum param, ALfloat*)
+{ alSetError(context, AL_INVALID_ENUM, "Invalid null filter property 0x%04x", param); }
+void ALnullfilter_getParamfv(ALfilter*, ALCcontext *context, ALenum param, ALfloat*)
+{ alSetError(context, AL_INVALID_ENUM, "Invalid null filter property 0x%04x", param); }
+
+DEFINE_ALFILTER_VTABLE(ALnullfilter);
+
+
+void InitFilterParams(ALfilter *filter, ALenum type)
+{
+ if(type == AL_FILTER_LOWPASS)
+ {
+ filter->Gain = AL_LOWPASS_DEFAULT_GAIN;
+ filter->GainHF = AL_LOWPASS_DEFAULT_GAINHF;
+ filter->HFReference = LOWPASSFREQREF;
+ filter->GainLF = 1.0f;
+ filter->LFReference = HIGHPASSFREQREF;
+ filter->vtab = &ALlowpass_vtable;
+ }
+ else if(type == AL_FILTER_HIGHPASS)
+ {
+ filter->Gain = AL_HIGHPASS_DEFAULT_GAIN;
+ filter->GainHF = 1.0f;
+ filter->HFReference = LOWPASSFREQREF;
+ filter->GainLF = AL_HIGHPASS_DEFAULT_GAINLF;
+ filter->LFReference = HIGHPASSFREQREF;
+ filter->vtab = &ALhighpass_vtable;
+ }
+ else if(type == AL_FILTER_BANDPASS)
+ {
+ filter->Gain = AL_BANDPASS_DEFAULT_GAIN;
+ filter->GainHF = AL_BANDPASS_DEFAULT_GAINHF;
+ filter->HFReference = LOWPASSFREQREF;
+ filter->GainLF = AL_BANDPASS_DEFAULT_GAINLF;
+ filter->LFReference = HIGHPASSFREQREF;
+ filter->vtab = &ALbandpass_vtable;
+ }
+ else
+ {
+ filter->Gain = 1.0f;
+ filter->GainHF = 1.0f;
+ filter->HFReference = LOWPASSFREQREF;
+ filter->GainLF = 1.0f;
+ filter->LFReference = HIGHPASSFREQREF;
+ filter->vtab = &ALnullfilter_vtable;
+ }
+ filter->type = type;
+}
+
+ALfilter *AllocFilter(ALCcontext *context)
+{
+ ALCdevice *device{context->Device};
+ std::lock_guard<std::mutex> _{device->FilterLock};
+ auto sublist = std::find_if(device->FilterList.begin(), device->FilterList.end(),
+ [](const FilterSubList &entry) noexcept -> bool
+ { return entry.FreeMask != 0; }
+ );
+
+ auto lidx = static_cast<ALsizei>(std::distance(device->FilterList.begin(), sublist));
+ ALfilter *filter{nullptr};
+ ALsizei slidx{0};
+ if(LIKELY(sublist != device->FilterList.end()))
+ {
+ slidx = CTZ64(sublist->FreeMask);
+ filter = sublist->Filters + slidx;
+ }
+ else
+ {
+ /* Don't allocate so many list entries that the 32-bit ID could
+ * overflow...
+ */
+ if(UNLIKELY(device->FilterList.size() >= 1<<25))
+ {
+ alSetError(context, AL_OUT_OF_MEMORY, "Too many filters allocated");
+ return nullptr;
+ }
+ device->FilterList.emplace_back();
+ sublist = device->FilterList.end() - 1;
+ sublist->FreeMask = ~0_u64;
+ sublist->Filters = static_cast<ALfilter*>(al_calloc(16, sizeof(ALfilter)*64));
+ if(UNLIKELY(!sublist->Filters))
+ {
+ device->FilterList.pop_back();
+ alSetError(context, AL_OUT_OF_MEMORY, "Failed to allocate filter batch");
+ return nullptr;
+ }
+
+ slidx = 0;
+ filter = sublist->Filters + slidx;
+ }
+
+ filter = new (filter) ALfilter{};
+ InitFilterParams(filter, AL_FILTER_NULL);
+
+ /* Add 1 to avoid filter ID 0. */
+ filter->id = ((lidx<<6) | slidx) + 1;
+
+ sublist->FreeMask &= ~(1_u64 << slidx);
+
+ return filter;
+}
+
+void FreeFilter(ALCdevice *device, ALfilter *filter)
+{
+ ALuint id = filter->id - 1;
+ ALsizei lidx = id >> 6;
+ ALsizei slidx = id & 0x3f;
+
+ al::destroy_at(filter);
+
+ device->FilterList[lidx].FreeMask |= 1_u64 << slidx;
+}
+
+
+inline ALfilter *LookupFilter(ALCdevice *device, ALuint id)
+{
+ ALuint lidx = (id-1) >> 6;
+ ALsizei slidx = (id-1) & 0x3f;
+
+ if(UNLIKELY(lidx >= device->FilterList.size()))
+ return nullptr;
+ FilterSubList &sublist = device->FilterList[lidx];
+ if(UNLIKELY(sublist.FreeMask & (1_u64 << slidx)))
+ return nullptr;
+ return sublist.Filters + slidx;
+}
+
+} // namespace
+
+AL_API ALvoid AL_APIENTRY alGenFilters(ALsizei n, ALuint *filters)
+START_API_FUNC
+{
+ ContextRef context{GetContextRef()};
+ if(UNLIKELY(!context)) return;
+
+ if(UNLIKELY(n < 0))
+ {
+ alSetError(context.get(), AL_INVALID_VALUE, "Generating %d filters", n);
+ return;
+ }
+
+ if(LIKELY(n == 1))
+ {
+ /* Special handling for the easy and normal case. */
+ ALfilter *filter = AllocFilter(context.get());
+ if(filter) filters[0] = filter->id;
+ }
+ else if(n > 1)
+ {
+ /* Store the allocated buffer IDs in a separate local list, to avoid
+ * modifying the user storage in case of failure.
+ */
+ al::vector<ALuint> ids;
+ ids.reserve(n);
+ do {
+ ALfilter *filter = AllocFilter(context.get());
+ if(!filter)
+ {
+ alDeleteFilters(static_cast<ALsizei>(ids.size()), ids.data());
+ return;
+ }
+
+ ids.emplace_back(filter->id);
+ } while(--n);
+ std::copy(ids.begin(), ids.end(), filters);
+ }
+}
+END_API_FUNC
+
+AL_API ALvoid AL_APIENTRY alDeleteFilters(ALsizei n, const ALuint *filters)
+START_API_FUNC
+{
+ ContextRef context{GetContextRef()};
+ if(UNLIKELY(!context)) return;
+
+ if(UNLIKELY(n < 0))
+ {
+ alSetError(context.get(), AL_INVALID_VALUE, "Deleting %d filters", n);
+ return;
+ }
+ if(UNLIKELY(n == 0))
+ return;
+
+ ALCdevice *device{context->Device};
+ std::lock_guard<std::mutex> _{device->FilterLock};
+
+ /* First try to find any filters that are invalid. */
+ const ALuint *filters_end = filters + n;
+ auto invflt = std::find_if(filters, filters_end,
+ [device, &context](ALuint fid) -> bool
+ {
+ if(!fid) return false;
+ ALfilter *filter{LookupFilter(device, fid)};
+ if(UNLIKELY(!filter))
+ {
+ alSetError(context.get(), AL_INVALID_NAME, "Invalid filter ID %u", fid);
+ return true;
+ }
+ return false;
+ }
+ );
+ if(LIKELY(invflt == filters_end))
+ {
+ /* All good. Delete non-0 filter IDs. */
+ std::for_each(filters, filters_end,
+ [device](ALuint fid) -> void
+ {
+ ALfilter *filter{fid ? LookupFilter(device, fid) : nullptr};
+ if(filter) FreeFilter(device, filter);
+ }
+ );
+ }
+}
+END_API_FUNC
+
+AL_API ALboolean AL_APIENTRY alIsFilter(ALuint filter)
+START_API_FUNC
+{
+ ContextRef context{GetContextRef()};
+ if(LIKELY(context))
+ {
+ ALCdevice *device{context->Device};
+ std::lock_guard<std::mutex> _{device->FilterLock};
+ if(!filter || LookupFilter(device, filter))
+ return AL_TRUE;
+ }
+ return AL_FALSE;
+}
+END_API_FUNC
+
+
+AL_API ALvoid AL_APIENTRY alFilteri(ALuint filter, ALenum param, ALint value)
+START_API_FUNC
+{
+ ContextRef context{GetContextRef()};
+ if(UNLIKELY(!context)) return;
+
+ ALCdevice *device{context->Device};
+ std::lock_guard<std::mutex> _{device->FilterLock};
+
+ ALfilter *alfilt{LookupFilter(device, filter)};
+ if(UNLIKELY(!alfilt))
+ alSetError(context.get(), AL_INVALID_NAME, "Invalid filter ID %u", filter);
+ else
+ {
+ if(param == AL_FILTER_TYPE)
+ {
+ if(value == AL_FILTER_NULL || value == AL_FILTER_LOWPASS ||
+ value == AL_FILTER_HIGHPASS || value == AL_FILTER_BANDPASS)
+ InitFilterParams(alfilt, value);
+ else
+ alSetError(context.get(), AL_INVALID_VALUE, "Invalid filter type 0x%04x", value);
+ }
+ else
+ {
+ /* Call the appropriate handler */
+ ALfilter_setParami(alfilt, context.get(), param, value);
+ }
+ }
+}
+END_API_FUNC
+
+AL_API ALvoid AL_APIENTRY alFilteriv(ALuint filter, ALenum param, const ALint *values)
+START_API_FUNC
+{
+ switch(param)
+ {
+ case AL_FILTER_TYPE:
+ alFilteri(filter, param, values[0]);
+ return;
+ }
+
+ ContextRef context{GetContextRef()};
+ if(UNLIKELY(!context)) return;
+
+ ALCdevice *device{context->Device};
+ std::lock_guard<std::mutex> _{device->FilterLock};
+
+ ALfilter *alfilt{LookupFilter(device, filter)};
+ if(UNLIKELY(!alfilt))
+ alSetError(context.get(), AL_INVALID_NAME, "Invalid filter ID %u", filter);
+ else
+ {
+ /* Call the appropriate handler */
+ ALfilter_setParamiv(alfilt, context.get(), param, values);
+ }
+}
+END_API_FUNC
+
+AL_API ALvoid AL_APIENTRY alFilterf(ALuint filter, ALenum param, ALfloat value)
+START_API_FUNC
+{
+ ContextRef context{GetContextRef()};
+ if(UNLIKELY(!context)) return;
+
+ ALCdevice *device{context->Device};
+ std::lock_guard<std::mutex> _{device->FilterLock};
+
+ ALfilter *alfilt{LookupFilter(device, filter)};
+ if(UNLIKELY(!alfilt))
+ alSetError(context.get(), AL_INVALID_NAME, "Invalid filter ID %u", filter);
+ else
+ {
+ /* Call the appropriate handler */
+ ALfilter_setParamf(alfilt, context.get(), param, value);
+ }
+}
+END_API_FUNC
+
+AL_API ALvoid AL_APIENTRY alFilterfv(ALuint filter, ALenum param, const ALfloat *values)
+START_API_FUNC
+{
+ ContextRef context{GetContextRef()};
+ if(UNLIKELY(!context)) return;
+
+ ALCdevice *device{context->Device};
+ std::lock_guard<std::mutex> _{device->FilterLock};
+
+ ALfilter *alfilt{LookupFilter(device, filter)};
+ if(UNLIKELY(!alfilt))
+ alSetError(context.get(), AL_INVALID_NAME, "Invalid filter ID %u", filter);
+ else
+ {
+ /* Call the appropriate handler */
+ ALfilter_setParamfv(alfilt, context.get(), param, values);
+ }
+}
+END_API_FUNC
+
+AL_API ALvoid AL_APIENTRY alGetFilteri(ALuint filter, ALenum param, ALint *value)
+START_API_FUNC
+{
+ ContextRef context{GetContextRef()};
+ if(UNLIKELY(!context)) return;
+
+ ALCdevice *device{context->Device};
+ std::lock_guard<std::mutex> _{device->FilterLock};
+
+ ALfilter *alfilt{LookupFilter(device, filter)};
+ if(UNLIKELY(!alfilt))
+ alSetError(context.get(), AL_INVALID_NAME, "Invalid filter ID %u", filter);
+ else
+ {
+ if(param == AL_FILTER_TYPE)
+ *value = alfilt->type;
+ else
+ {
+ /* Call the appropriate handler */
+ ALfilter_getParami(alfilt, context.get(), param, value);
+ }
+ }
+}
+END_API_FUNC
+
+AL_API ALvoid AL_APIENTRY alGetFilteriv(ALuint filter, ALenum param, ALint *values)
+START_API_FUNC
+{
+ switch(param)
+ {
+ case AL_FILTER_TYPE:
+ alGetFilteri(filter, param, values);
+ return;
+ }
+
+ ContextRef context{GetContextRef()};
+ if(UNLIKELY(!context)) return;
+
+ ALCdevice *device{context->Device};
+ std::lock_guard<std::mutex> _{device->FilterLock};
+
+ ALfilter *alfilt{LookupFilter(device, filter)};
+ if(UNLIKELY(!alfilt))
+ alSetError(context.get(), AL_INVALID_NAME, "Invalid filter ID %u", filter);
+ else
+ {
+ /* Call the appropriate handler */
+ ALfilter_getParamiv(alfilt, context.get(), param, values);
+ }
+}
+END_API_FUNC
+
+AL_API ALvoid AL_APIENTRY alGetFilterf(ALuint filter, ALenum param, ALfloat *value)
+START_API_FUNC
+{
+ ContextRef context{GetContextRef()};
+ if(UNLIKELY(!context)) return;
+
+ ALCdevice *device{context->Device};
+ std::lock_guard<std::mutex> _{device->FilterLock};
+
+ ALfilter *alfilt{LookupFilter(device, filter)};
+ if(UNLIKELY(!alfilt))
+ alSetError(context.get(), AL_INVALID_NAME, "Invalid filter ID %u", filter);
+ else
+ {
+ /* Call the appropriate handler */
+ ALfilter_getParamf(alfilt, context.get(), param, value);
+ }
+}
+END_API_FUNC
+
+AL_API ALvoid AL_APIENTRY alGetFilterfv(ALuint filter, ALenum param, ALfloat *values)
+START_API_FUNC
+{
+ ContextRef context{GetContextRef()};
+ if(UNLIKELY(!context)) return;
+
+ ALCdevice *device{context->Device};
+ std::lock_guard<std::mutex> _{device->FilterLock};
+
+ ALfilter *alfilt{LookupFilter(device, filter)};
+ if(UNLIKELY(!alfilt))
+ alSetError(context.get(), AL_INVALID_NAME, "Invalid filter ID %u", filter);
+ else
+ {
+ /* Call the appropriate handler */
+ ALfilter_getParamfv(alfilt, context.get(), param, values);
+ }
+}
+END_API_FUNC
+
+
+FilterSubList::~FilterSubList()
+{
+ uint64_t usemask{~FreeMask};
+ while(usemask)
+ {
+ ALsizei idx = CTZ64(usemask);
+ al::destroy_at(Filters+idx);
+ usemask &= ~(1_u64 << idx);
+ }
+ FreeMask = ~usemask;
+ al_free(Filters);
+ Filters = nullptr;
+}
diff --git a/al/alFilter.h b/al/alFilter.h
new file mode 100644
index 00000000..db098d70
--- /dev/null
+++ b/al/alFilter.h
@@ -0,0 +1,56 @@
+#ifndef AL_FILTER_H
+#define AL_FILTER_H
+
+#include "AL/al.h"
+#include "AL/alc.h"
+
+
+#define LOWPASSFREQREF (5000.0f)
+#define HIGHPASSFREQREF (250.0f)
+
+
+struct ALfilter;
+
+struct ALfilterVtable {
+ void (*const setParami)(ALfilter *filter, ALCcontext *context, ALenum param, ALint val);
+ void (*const setParamiv)(ALfilter *filter, ALCcontext *context, ALenum param, const ALint *vals);
+ void (*const setParamf)(ALfilter *filter, ALCcontext *context, ALenum param, ALfloat val);
+ void (*const setParamfv)(ALfilter *filter, ALCcontext *context, ALenum param, const ALfloat *vals);
+
+ void (*const getParami)(ALfilter *filter, ALCcontext *context, ALenum param, ALint *val);
+ void (*const getParamiv)(ALfilter *filter, ALCcontext *context, ALenum param, ALint *vals);
+ void (*const getParamf)(ALfilter *filter, ALCcontext *context, ALenum param, ALfloat *val);
+ void (*const getParamfv)(ALfilter *filter, ALCcontext *context, ALenum param, ALfloat *vals);
+};
+
+#define DEFINE_ALFILTER_VTABLE(T) \
+const ALfilterVtable T##_vtable = { \
+ T##_setParami, T##_setParamiv, T##_setParamf, T##_setParamfv, \
+ T##_getParami, T##_getParamiv, T##_getParamf, T##_getParamfv, \
+}
+
+struct ALfilter {
+ // Filter type (AL_FILTER_NULL, ...)
+ ALenum type;
+
+ ALfloat Gain;
+ ALfloat GainHF;
+ ALfloat HFReference;
+ ALfloat GainLF;
+ ALfloat LFReference;
+
+ const ALfilterVtable *vtab;
+
+ /* Self ID */
+ ALuint id;
+};
+#define ALfilter_setParami(o, c, p, v) ((o)->vtab->setParami(o, c, p, v))
+#define ALfilter_setParamf(o, c, p, v) ((o)->vtab->setParamf(o, c, p, v))
+#define ALfilter_setParamiv(o, c, p, v) ((o)->vtab->setParamiv(o, c, p, v))
+#define ALfilter_setParamfv(o, c, p, v) ((o)->vtab->setParamfv(o, c, p, v))
+#define ALfilter_getParami(o, c, p, v) ((o)->vtab->getParami(o, c, p, v))
+#define ALfilter_getParamf(o, c, p, v) ((o)->vtab->getParamf(o, c, p, v))
+#define ALfilter_getParamiv(o, c, p, v) ((o)->vtab->getParamiv(o, c, p, v))
+#define ALfilter_getParamfv(o, c, p, v) ((o)->vtab->getParamfv(o, c, p, v))
+
+#endif
diff --git a/al/alListener.cpp b/al/alListener.cpp
new file mode 100644
index 00000000..d3bf3aaa
--- /dev/null
+++ b/al/alListener.cpp
@@ -0,0 +1,454 @@
+/**
+ * OpenAL cross platform audio library
+ * Copyright (C) 1999-2000 by authors.
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library; if not, write to the
+ * Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ * Or go to http://www.gnu.org/copyleft/lgpl.html
+ */
+
+#include "config.h"
+
+#include "alListener.h"
+
+#include <cmath>
+#include <mutex>
+
+#include "AL/efx.h"
+
+#include "alError.h"
+#include "alcontext.h"
+#include "alexcpt.h"
+#include "almalloc.h"
+#include "atomic.h"
+#include "opthelpers.h"
+
+
+#define DO_UPDATEPROPS() do { \
+ if(!context->DeferUpdates.load(std::memory_order_acquire)) \
+ UpdateListenerProps(context.get()); \
+ else \
+ listener.PropsClean.clear(std::memory_order_release); \
+} while(0)
+
+
+AL_API ALvoid AL_APIENTRY alListenerf(ALenum param, ALfloat value)
+START_API_FUNC
+{
+ ContextRef context{GetContextRef()};
+ if(UNLIKELY(!context)) return;
+
+ ALlistener &listener = context->Listener;
+ std::lock_guard<std::mutex> _{context->PropLock};
+ switch(param)
+ {
+ case AL_GAIN:
+ if(!(value >= 0.0f && std::isfinite(value)))
+ SETERR_RETURN(context.get(), AL_INVALID_VALUE,, "Listener gain out of range");
+ listener.Gain = value;
+ DO_UPDATEPROPS();
+ break;
+
+ case AL_METERS_PER_UNIT:
+ if(!(value >= AL_MIN_METERS_PER_UNIT && value <= AL_MAX_METERS_PER_UNIT))
+ SETERR_RETURN(context.get(), AL_INVALID_VALUE,,
+ "Listener meters per unit out of range");
+ context->MetersPerUnit = value;
+ if(!context->DeferUpdates.load(std::memory_order_acquire))
+ UpdateContextProps(context.get());
+ else
+ context->PropsClean.clear(std::memory_order_release);
+ break;
+
+ default:
+ alSetError(context.get(), AL_INVALID_ENUM, "Invalid listener float property");
+ }
+}
+END_API_FUNC
+
+AL_API ALvoid AL_APIENTRY alListener3f(ALenum param, ALfloat value1, ALfloat value2, ALfloat value3)
+START_API_FUNC
+{
+ ContextRef context{GetContextRef()};
+ if(UNLIKELY(!context)) return;
+
+ ALlistener &listener = context->Listener;
+ std::lock_guard<std::mutex> _{context->PropLock};
+ switch(param)
+ {
+ case AL_POSITION:
+ if(!(std::isfinite(value1) && std::isfinite(value2) && std::isfinite(value3)))
+ SETERR_RETURN(context.get(), AL_INVALID_VALUE,, "Listener position out of range");
+ listener.Position[0] = value1;
+ listener.Position[1] = value2;
+ listener.Position[2] = value3;
+ DO_UPDATEPROPS();
+ break;
+
+ case AL_VELOCITY:
+ if(!(std::isfinite(value1) && std::isfinite(value2) && std::isfinite(value3)))
+ SETERR_RETURN(context.get(), AL_INVALID_VALUE,, "Listener velocity out of range");
+ listener.Velocity[0] = value1;
+ listener.Velocity[1] = value2;
+ listener.Velocity[2] = value3;
+ DO_UPDATEPROPS();
+ break;
+
+ default:
+ alSetError(context.get(), AL_INVALID_ENUM, "Invalid listener 3-float property");
+ }
+}
+END_API_FUNC
+
+AL_API ALvoid AL_APIENTRY alListenerfv(ALenum param, const ALfloat *values)
+START_API_FUNC
+{
+ if(values)
+ {
+ switch(param)
+ {
+ case AL_GAIN:
+ case AL_METERS_PER_UNIT:
+ alListenerf(param, values[0]);
+ return;
+
+ case AL_POSITION:
+ case AL_VELOCITY:
+ alListener3f(param, values[0], values[1], values[2]);
+ return;
+ }
+ }
+
+ ContextRef context{GetContextRef()};
+ if(UNLIKELY(!context)) return;
+
+ ALlistener &listener = context->Listener;
+ std::lock_guard<std::mutex> _{context->PropLock};
+ if(!values) SETERR_RETURN(context.get(), AL_INVALID_VALUE,, "NULL pointer");
+ switch(param)
+ {
+ case AL_ORIENTATION:
+ if(!(std::isfinite(values[0]) && std::isfinite(values[1]) && std::isfinite(values[2]) &&
+ std::isfinite(values[3]) && std::isfinite(values[4]) && std::isfinite(values[5])))
+ SETERR_RETURN(context.get(), AL_INVALID_VALUE,, "Listener orientation out of range");
+ /* AT then UP */
+ listener.OrientAt[0] = values[0];
+ listener.OrientAt[1] = values[1];
+ listener.OrientAt[2] = values[2];
+ listener.OrientUp[0] = values[3];
+ listener.OrientUp[1] = values[4];
+ listener.OrientUp[2] = values[5];
+ DO_UPDATEPROPS();
+ break;
+
+ default:
+ alSetError(context.get(), AL_INVALID_ENUM, "Invalid listener float-vector property");
+ }
+}
+END_API_FUNC
+
+
+AL_API ALvoid AL_APIENTRY alListeneri(ALenum param, ALint /*value*/)
+START_API_FUNC
+{
+ ContextRef context{GetContextRef()};
+ if(UNLIKELY(!context)) return;
+
+ std::lock_guard<std::mutex> _{context->PropLock};
+ switch(param)
+ {
+ default:
+ alSetError(context.get(), AL_INVALID_ENUM, "Invalid listener integer property");
+ }
+}
+END_API_FUNC
+
+AL_API void AL_APIENTRY alListener3i(ALenum param, ALint value1, ALint value2, ALint value3)
+START_API_FUNC
+{
+ switch(param)
+ {
+ case AL_POSITION:
+ case AL_VELOCITY:
+ alListener3f(param, static_cast<ALfloat>(value1), static_cast<ALfloat>(value2), static_cast<ALfloat>(value3));
+ return;
+ }
+
+ ContextRef context{GetContextRef()};
+ if(UNLIKELY(!context)) return;
+
+ std::lock_guard<std::mutex> _{context->PropLock};
+ switch(param)
+ {
+ default:
+ alSetError(context.get(), AL_INVALID_ENUM, "Invalid listener 3-integer property");
+ }
+}
+END_API_FUNC
+
+AL_API void AL_APIENTRY alListeneriv(ALenum param, const ALint *values)
+START_API_FUNC
+{
+ if(values)
+ {
+ ALfloat fvals[6];
+ switch(param)
+ {
+ case AL_POSITION:
+ case AL_VELOCITY:
+ alListener3f(param, static_cast<ALfloat>(values[0]), static_cast<ALfloat>(values[1]), static_cast<ALfloat>(values[2]));
+ return;
+
+ case AL_ORIENTATION:
+ fvals[0] = static_cast<ALfloat>(values[0]);
+ fvals[1] = static_cast<ALfloat>(values[1]);
+ fvals[2] = static_cast<ALfloat>(values[2]);
+ fvals[3] = static_cast<ALfloat>(values[3]);
+ fvals[4] = static_cast<ALfloat>(values[4]);
+ fvals[5] = static_cast<ALfloat>(values[5]);
+ alListenerfv(param, fvals);
+ return;
+ }
+ }
+
+ ContextRef context{GetContextRef()};
+ if(UNLIKELY(!context)) return;
+
+ std::lock_guard<std::mutex> _{context->PropLock};
+ if(!values)
+ alSetError(context.get(), AL_INVALID_VALUE, "NULL pointer");
+ else switch(param)
+ {
+ default:
+ alSetError(context.get(), AL_INVALID_ENUM, "Invalid listener integer-vector property");
+ }
+}
+END_API_FUNC
+
+
+AL_API ALvoid AL_APIENTRY alGetListenerf(ALenum param, ALfloat *value)
+START_API_FUNC
+{
+ ContextRef context{GetContextRef()};
+ if(UNLIKELY(!context)) return;
+
+ ALlistener &listener = context->Listener;
+ std::lock_guard<std::mutex> _{context->PropLock};
+ if(!value)
+ alSetError(context.get(), AL_INVALID_VALUE, "NULL pointer");
+ else switch(param)
+ {
+ case AL_GAIN:
+ *value = listener.Gain;
+ break;
+
+ case AL_METERS_PER_UNIT:
+ *value = context->MetersPerUnit;
+ break;
+
+ default:
+ alSetError(context.get(), AL_INVALID_ENUM, "Invalid listener float property");
+ }
+}
+END_API_FUNC
+
+AL_API ALvoid AL_APIENTRY alGetListener3f(ALenum param, ALfloat *value1, ALfloat *value2, ALfloat *value3)
+START_API_FUNC
+{
+ ContextRef context{GetContextRef()};
+ if(UNLIKELY(!context)) return;
+
+ ALlistener &listener = context->Listener;
+ std::lock_guard<std::mutex> _{context->PropLock};
+ if(!value1 || !value2 || !value3)
+ alSetError(context.get(), AL_INVALID_VALUE, "NULL pointer");
+ else switch(param)
+ {
+ case AL_POSITION:
+ *value1 = listener.Position[0];
+ *value2 = listener.Position[1];
+ *value3 = listener.Position[2];
+ break;
+
+ case AL_VELOCITY:
+ *value1 = listener.Velocity[0];
+ *value2 = listener.Velocity[1];
+ *value3 = listener.Velocity[2];
+ break;
+
+ default:
+ alSetError(context.get(), AL_INVALID_ENUM, "Invalid listener 3-float property");
+ }
+}
+END_API_FUNC
+
+AL_API ALvoid AL_APIENTRY alGetListenerfv(ALenum param, ALfloat *values)
+START_API_FUNC
+{
+ switch(param)
+ {
+ case AL_GAIN:
+ case AL_METERS_PER_UNIT:
+ alGetListenerf(param, values);
+ return;
+
+ case AL_POSITION:
+ case AL_VELOCITY:
+ alGetListener3f(param, values+0, values+1, values+2);
+ return;
+ }
+
+ ContextRef context{GetContextRef()};
+ if(UNLIKELY(!context)) return;
+
+ ALlistener &listener = context->Listener;
+ std::lock_guard<std::mutex> _{context->PropLock};
+ if(!values)
+ alSetError(context.get(), AL_INVALID_VALUE, "NULL pointer");
+ else switch(param)
+ {
+ case AL_ORIENTATION:
+ // AT then UP
+ values[0] = listener.OrientAt[0];
+ values[1] = listener.OrientAt[1];
+ values[2] = listener.OrientAt[2];
+ values[3] = listener.OrientUp[0];
+ values[4] = listener.OrientUp[1];
+ values[5] = listener.OrientUp[2];
+ break;
+
+ default:
+ alSetError(context.get(), AL_INVALID_ENUM, "Invalid listener float-vector property");
+ }
+}
+END_API_FUNC
+
+
+AL_API ALvoid AL_APIENTRY alGetListeneri(ALenum param, ALint *value)
+START_API_FUNC
+{
+ ContextRef context{GetContextRef()};
+ if(UNLIKELY(!context)) return;
+
+ std::lock_guard<std::mutex> _{context->PropLock};
+ if(!value)
+ alSetError(context.get(), AL_INVALID_VALUE, "NULL pointer");
+ else switch(param)
+ {
+ default:
+ alSetError(context.get(), AL_INVALID_ENUM, "Invalid listener integer property");
+ }
+}
+END_API_FUNC
+
+AL_API void AL_APIENTRY alGetListener3i(ALenum param, ALint *value1, ALint *value2, ALint *value3)
+START_API_FUNC
+{
+ ContextRef context{GetContextRef()};
+ if(UNLIKELY(!context)) return;
+
+ ALlistener &listener = context->Listener;
+ std::lock_guard<std::mutex> _{context->PropLock};
+ if(!value1 || !value2 || !value3)
+ alSetError(context.get(), AL_INVALID_VALUE, "NULL pointer");
+ else switch(param)
+ {
+ case AL_POSITION:
+ *value1 = static_cast<ALint>(listener.Position[0]);
+ *value2 = static_cast<ALint>(listener.Position[1]);
+ *value3 = static_cast<ALint>(listener.Position[2]);
+ break;
+
+ case AL_VELOCITY:
+ *value1 = static_cast<ALint>(listener.Velocity[0]);
+ *value2 = static_cast<ALint>(listener.Velocity[1]);
+ *value3 = static_cast<ALint>(listener.Velocity[2]);
+ break;
+
+ default:
+ alSetError(context.get(), AL_INVALID_ENUM, "Invalid listener 3-integer property");
+ }
+}
+END_API_FUNC
+
+AL_API void AL_APIENTRY alGetListeneriv(ALenum param, ALint* values)
+START_API_FUNC
+{
+ switch(param)
+ {
+ case AL_POSITION:
+ case AL_VELOCITY:
+ alGetListener3i(param, values+0, values+1, values+2);
+ return;
+ }
+
+ ContextRef context{GetContextRef()};
+ if(UNLIKELY(!context)) return;
+
+ ALlistener &listener = context->Listener;
+ std::lock_guard<std::mutex> _{context->PropLock};
+ if(!values)
+ alSetError(context.get(), AL_INVALID_VALUE, "NULL pointer");
+ else switch(param)
+ {
+ case AL_ORIENTATION:
+ // AT then UP
+ values[0] = static_cast<ALint>(listener.OrientAt[0]);
+ values[1] = static_cast<ALint>(listener.OrientAt[1]);
+ values[2] = static_cast<ALint>(listener.OrientAt[2]);
+ values[3] = static_cast<ALint>(listener.OrientUp[0]);
+ values[4] = static_cast<ALint>(listener.OrientUp[1]);
+ values[5] = static_cast<ALint>(listener.OrientUp[2]);
+ break;
+
+ default:
+ alSetError(context.get(), AL_INVALID_ENUM, "Invalid listener integer-vector property");
+ }
+}
+END_API_FUNC
+
+
+void UpdateListenerProps(ALCcontext *context)
+{
+ /* Get an unused proprty container, or allocate a new one as needed. */
+ ALlistenerProps *props{context->FreeListenerProps.load(std::memory_order_acquire)};
+ if(!props)
+ props = static_cast<ALlistenerProps*>(al_calloc(16, sizeof(*props)));
+ else
+ {
+ ALlistenerProps *next;
+ do {
+ next = props->next.load(std::memory_order_relaxed);
+ } while(context->FreeListenerProps.compare_exchange_weak(props, next,
+ std::memory_order_seq_cst, std::memory_order_acquire) == 0);
+ }
+
+ /* Copy in current property values. */
+ ALlistener &listener = context->Listener;
+ props->Position = listener.Position;
+ props->Velocity = listener.Velocity;
+ props->OrientAt = listener.OrientAt;
+ props->OrientUp = listener.OrientUp;
+ props->Gain = listener.Gain;
+
+ /* Set the new container for updating internal parameters. */
+ props = listener.Update.exchange(props, std::memory_order_acq_rel);
+ if(props)
+ {
+ /* If there was an unused update container, put it back in the
+ * freelist.
+ */
+ AtomicReplaceHead(context->FreeListenerProps, props);
+ }
+}
diff --git a/al/alListener.h b/al/alListener.h
new file mode 100644
index 00000000..a71db9f8
--- /dev/null
+++ b/al/alListener.h
@@ -0,0 +1,58 @@
+#ifndef AL_LISTENER_H
+#define AL_LISTENER_H
+
+#include <array>
+#include <atomic>
+
+#include "AL/al.h"
+#include "AL/alc.h"
+
+#include "vecmat.h"
+
+enum class DistanceModel;
+
+
+struct ALlistenerProps {
+ std::array<ALfloat,3> Position;
+ std::array<ALfloat,3> Velocity;
+ std::array<ALfloat,3> OrientAt;
+ std::array<ALfloat,3> OrientUp;
+ ALfloat Gain;
+
+ std::atomic<ALlistenerProps*> next;
+};
+
+struct ALlistener {
+ std::array<ALfloat,3> Position{{0.0f, 0.0f, 0.0f}};
+ std::array<ALfloat,3> Velocity{{0.0f, 0.0f, 0.0f}};
+ std::array<ALfloat,3> OrientAt{{0.0f, 0.0f, -1.0f}};
+ std::array<ALfloat,3> OrientUp{{0.0f, 1.0f, 0.0f}};
+ ALfloat Gain{1.0f};
+
+ std::atomic_flag PropsClean;
+
+ /* Pointer to the most recent property values that are awaiting an update.
+ */
+ std::atomic<ALlistenerProps*> Update{nullptr};
+
+ struct {
+ alu::Matrix Matrix;
+ alu::Vector Velocity;
+
+ ALfloat Gain;
+ ALfloat MetersPerUnit;
+
+ ALfloat DopplerFactor;
+ ALfloat SpeedOfSound; /* in units per sec! */
+ ALfloat ReverbSpeedOfSound; /* in meters per sec! */
+
+ ALboolean SourceDistanceModel;
+ DistanceModel mDistanceModel;
+ } Params;
+
+ ALlistener() { PropsClean.test_and_set(std::memory_order_relaxed); }
+};
+
+void UpdateListenerProps(ALCcontext *context);
+
+#endif
diff --git a/al/alSource.cpp b/al/alSource.cpp
new file mode 100644
index 00000000..4af5cc47
--- /dev/null
+++ b/al/alSource.cpp
@@ -0,0 +1,3638 @@
+/**
+ * OpenAL cross platform audio library
+ * Copyright (C) 1999-2007 by authors.
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library; if not, write to the
+ * Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ * Or go to http://www.gnu.org/copyleft/lgpl.html
+ */
+
+#include "config.h"
+
+#include "alSource.h"
+
+#include <algorithm>
+#include <array>
+#include <atomic>
+#include <cassert>
+#include <chrono>
+#include <climits>
+#include <cmath>
+#include <cstdint>
+#include <functional>
+#include <iterator>
+#include <limits>
+#include <memory>
+#include <mutex>
+#include <new>
+#include <numeric>
+#include <thread>
+#include <utility>
+
+#include "AL/al.h"
+#include "AL/alc.h"
+#include "AL/alext.h"
+#include "AL/efx.h"
+
+#include "alAuxEffectSlot.h"
+#include "alBuffer.h"
+#include "alError.h"
+#include "alFilter.h"
+#include "alcmain.h"
+#include "alcontext.h"
+#include "alexcpt.h"
+#include "almalloc.h"
+#include "alnumeric.h"
+#include "alu.h"
+#include "ambidefs.h"
+#include "atomic.h"
+#include "backends/base.h"
+#include "bformatdec.h"
+#include "filters/nfc.h"
+#include "filters/splitter.h"
+#include "inprogext.h"
+#include "logging.h"
+#include "math_defs.h"
+#include "opthelpers.h"
+#include "ringbuffer.h"
+#include "threads.h"
+
+
+namespace {
+
+using namespace std::placeholders;
+
+inline ALvoice *GetSourceVoice(ALsource *source, ALCcontext *context)
+{
+ ALint idx{source->VoiceIdx};
+ if(idx >= 0 && static_cast<ALuint>(idx) < context->VoiceCount.load(std::memory_order_relaxed))
+ {
+ ALuint sid{source->id};
+ ALvoice &voice = (*context->Voices)[idx];
+ if(voice.mSourceID.load(std::memory_order_acquire) == sid)
+ return &voice;
+ }
+ source->VoiceIdx = -1;
+ return nullptr;
+}
+
+void UpdateSourceProps(const ALsource *source, ALvoice *voice, ALCcontext *context)
+{
+ /* Get an unused property container, or allocate a new one as needed. */
+ ALvoiceProps *props{context->FreeVoiceProps.load(std::memory_order_acquire)};
+ if(!props)
+ props = new ALvoiceProps{};
+ else
+ {
+ ALvoiceProps *next;
+ do {
+ next = props->next.load(std::memory_order_relaxed);
+ } while(context->FreeVoiceProps.compare_exchange_weak(props, next,
+ std::memory_order_acq_rel, std::memory_order_acquire) == 0);
+ }
+
+ /* Copy in current property values. */
+ props->Pitch = source->Pitch;
+ props->Gain = source->Gain;
+ props->OuterGain = source->OuterGain;
+ props->MinGain = source->MinGain;
+ props->MaxGain = source->MaxGain;
+ props->InnerAngle = source->InnerAngle;
+ props->OuterAngle = source->OuterAngle;
+ props->RefDistance = source->RefDistance;
+ props->MaxDistance = source->MaxDistance;
+ props->RolloffFactor = source->RolloffFactor;
+ props->Position = source->Position;
+ props->Velocity = source->Velocity;
+ props->Direction = source->Direction;
+ props->OrientAt = source->OrientAt;
+ props->OrientUp = source->OrientUp;
+ props->HeadRelative = source->HeadRelative;
+ props->mDistanceModel = source->mDistanceModel;
+ props->mResampler = source->mResampler;
+ props->DirectChannels = source->DirectChannels;
+ props->mSpatializeMode = source->mSpatialize;
+
+ props->DryGainHFAuto = source->DryGainHFAuto;
+ props->WetGainAuto = source->WetGainAuto;
+ props->WetGainHFAuto = source->WetGainHFAuto;
+ props->OuterGainHF = source->OuterGainHF;
+
+ props->AirAbsorptionFactor = source->AirAbsorptionFactor;
+ props->RoomRolloffFactor = source->RoomRolloffFactor;
+ props->DopplerFactor = source->DopplerFactor;
+
+ props->StereoPan = source->StereoPan;
+
+ props->Radius = source->Radius;
+
+ props->Direct.Gain = source->Direct.Gain;
+ props->Direct.GainHF = source->Direct.GainHF;
+ props->Direct.HFReference = source->Direct.HFReference;
+ props->Direct.GainLF = source->Direct.GainLF;
+ props->Direct.LFReference = source->Direct.LFReference;
+
+ auto copy_send = [](const ALsource::SendData &srcsend) noexcept -> ALvoicePropsBase::SendData
+ {
+ ALvoicePropsBase::SendData ret;
+ ret.Slot = srcsend.Slot;
+ ret.Gain = srcsend.Gain;
+ ret.GainHF = srcsend.GainHF;
+ ret.HFReference = srcsend.HFReference;
+ ret.GainLF = srcsend.GainLF;
+ ret.LFReference = srcsend.LFReference;
+ return ret;
+ };
+ std::transform(source->Send.cbegin(), source->Send.cend(), props->Send, copy_send);
+
+ /* Set the new container for updating internal parameters. */
+ props = voice->mUpdate.exchange(props, std::memory_order_acq_rel);
+ if(props)
+ {
+ /* If there was an unused update container, put it back in the
+ * freelist.
+ */
+ AtomicReplaceHead(context->FreeVoiceProps, props);
+ }
+}
+
+/* GetSourceSampleOffset
+ *
+ * Gets the current read offset for the given Source, in 32.32 fixed-point
+ * samples. The offset is relative to the start of the queue (not the start of
+ * the current buffer).
+ */
+int64_t GetSourceSampleOffset(ALsource *Source, ALCcontext *context, std::chrono::nanoseconds *clocktime)
+{
+ ALCdevice *device{context->Device};
+ const ALbufferlistitem *Current;
+ uint64_t readPos;
+ ALuint refcount;
+ ALvoice *voice;
+
+ do {
+ Current = nullptr;
+ readPos = 0;
+ while(((refcount=device->MixCount.load(std::memory_order_acquire))&1))
+ std::this_thread::yield();
+ *clocktime = GetDeviceClockTime(device);
+
+ voice = GetSourceVoice(Source, context);
+ if(voice)
+ {
+ Current = voice->mCurrentBuffer.load(std::memory_order_relaxed);
+
+ readPos = uint64_t{voice->mPosition.load(std::memory_order_relaxed)} << 32;
+ readPos |= int64_t{voice->mPositionFrac.load(std::memory_order_relaxed)} <<
+ (32-FRACTIONBITS);
+ }
+ std::atomic_thread_fence(std::memory_order_acquire);
+ } while(refcount != device->MixCount.load(std::memory_order_relaxed));
+
+ if(voice)
+ {
+ const ALbufferlistitem *BufferList{Source->queue};
+ while(BufferList && BufferList != Current)
+ {
+ readPos += int64_t{BufferList->max_samples} << 32;
+ BufferList = BufferList->next.load(std::memory_order_relaxed);
+ }
+ readPos = minu64(readPos, 0x7fffffffffffffff_u64);
+ }
+
+ return static_cast<int64_t>(readPos);
+}
+
+/* GetSourceSecOffset
+ *
+ * Gets the current read offset for the given Source, in seconds. The offset is
+ * relative to the start of the queue (not the start of the current buffer).
+ */
+ALdouble GetSourceSecOffset(ALsource *Source, ALCcontext *context, std::chrono::nanoseconds *clocktime)
+{
+ ALCdevice *device{context->Device};
+ const ALbufferlistitem *Current;
+ uint64_t readPos;
+ ALuint refcount;
+ ALvoice *voice;
+
+ do {
+ Current = nullptr;
+ readPos = 0;
+ while(((refcount=device->MixCount.load(std::memory_order_acquire))&1))
+ std::this_thread::yield();
+ *clocktime = GetDeviceClockTime(device);
+
+ voice = GetSourceVoice(Source, context);
+ if(voice)
+ {
+ Current = voice->mCurrentBuffer.load(std::memory_order_relaxed);
+
+ readPos = uint64_t{voice->mPosition.load(std::memory_order_relaxed)} << FRACTIONBITS;
+ readPos |= voice->mPositionFrac.load(std::memory_order_relaxed);
+ }
+ std::atomic_thread_fence(std::memory_order_acquire);
+ } while(refcount != device->MixCount.load(std::memory_order_relaxed));
+
+ ALdouble offset{0.0};
+ if(voice)
+ {
+ const ALbufferlistitem *BufferList{Source->queue};
+ const ALbuffer *BufferFmt{nullptr};
+ while(BufferList && BufferList != Current)
+ {
+ for(ALsizei i{0};!BufferFmt && i < BufferList->num_buffers;++i)
+ BufferFmt = BufferList->buffers[i];
+ readPos += int64_t{BufferList->max_samples} << FRACTIONBITS;
+ BufferList = BufferList->next.load(std::memory_order_relaxed);
+ }
+
+ while(BufferList && !BufferFmt)
+ {
+ for(ALsizei i{0};!BufferFmt && i < BufferList->num_buffers;++i)
+ BufferFmt = BufferList->buffers[i];
+ BufferList = BufferList->next.load(std::memory_order_relaxed);
+ }
+ assert(BufferFmt != nullptr);
+
+ offset = static_cast<ALdouble>(readPos) / static_cast<ALdouble>FRACTIONONE /
+ static_cast<ALdouble>(BufferFmt->Frequency);
+ }
+
+ return offset;
+}
+
+/* GetSourceOffset
+ *
+ * Gets the current read offset for the given Source, in the appropriate format
+ * (Bytes, Samples or Seconds). The offset is relative to the start of the
+ * queue (not the start of the current buffer).
+ */
+ALdouble GetSourceOffset(ALsource *Source, ALenum name, ALCcontext *context)
+{
+ ALCdevice *device{context->Device};
+ const ALbufferlistitem *Current;
+ ALuint readPos;
+ ALsizei readPosFrac;
+ ALuint refcount;
+ ALvoice *voice;
+
+ do {
+ Current = nullptr;
+ readPos = readPosFrac = 0;
+ while(((refcount=device->MixCount.load(std::memory_order_acquire))&1))
+ std::this_thread::yield();
+ voice = GetSourceVoice(Source, context);
+ if(voice)
+ {
+ Current = voice->mCurrentBuffer.load(std::memory_order_relaxed);
+
+ readPos = voice->mPosition.load(std::memory_order_relaxed);
+ readPosFrac = voice->mPositionFrac.load(std::memory_order_relaxed);
+ }
+ std::atomic_thread_fence(std::memory_order_acquire);
+ } while(refcount != device->MixCount.load(std::memory_order_relaxed));
+
+ ALdouble offset{0.0};
+ if(voice)
+ {
+ const ALbufferlistitem *BufferList{Source->queue};
+ const ALbuffer *BufferFmt{nullptr};
+ ALboolean readFin{AL_FALSE};
+ ALuint totalBufferLen{0u};
+
+ while(BufferList)
+ {
+ for(ALsizei i{0};!BufferFmt && i < BufferList->num_buffers;++i)
+ BufferFmt = BufferList->buffers[i];
+
+ readFin |= (BufferList == Current);
+ totalBufferLen += BufferList->max_samples;
+ if(!readFin) readPos += BufferList->max_samples;
+
+ BufferList = BufferList->next.load(std::memory_order_relaxed);
+ }
+ assert(BufferFmt != nullptr);
+
+ if(Source->Looping)
+ readPos %= totalBufferLen;
+ else
+ {
+ /* Wrap back to 0 */
+ if(readPos >= totalBufferLen)
+ readPos = readPosFrac = 0;
+ }
+
+ offset = 0.0;
+ switch(name)
+ {
+ case AL_SEC_OFFSET:
+ offset = (readPos + static_cast<ALdouble>(readPosFrac)/FRACTIONONE) / BufferFmt->Frequency;
+ break;
+
+ case AL_SAMPLE_OFFSET:
+ offset = readPos + static_cast<ALdouble>(readPosFrac)/FRACTIONONE;
+ break;
+
+ case AL_BYTE_OFFSET:
+ if(BufferFmt->OriginalType == UserFmtIMA4)
+ {
+ ALsizei align = (BufferFmt->OriginalAlign-1)/2 + 4;
+ ALuint BlockSize = align * ChannelsFromFmt(BufferFmt->mFmtChannels);
+ ALuint FrameBlockSize = BufferFmt->OriginalAlign;
+
+ /* Round down to nearest ADPCM block */
+ offset = static_cast<ALdouble>(readPos / FrameBlockSize * BlockSize);
+ }
+ else if(BufferFmt->OriginalType == UserFmtMSADPCM)
+ {
+ ALsizei align = (BufferFmt->OriginalAlign-2)/2 + 7;
+ ALuint BlockSize = align * ChannelsFromFmt(BufferFmt->mFmtChannels);
+ ALuint FrameBlockSize = BufferFmt->OriginalAlign;
+
+ /* Round down to nearest ADPCM block */
+ offset = static_cast<ALdouble>(readPos / FrameBlockSize * BlockSize);
+ }
+ else
+ {
+ const ALsizei FrameSize{FrameSizeFromFmt(BufferFmt->mFmtChannels,
+ BufferFmt->mFmtType)};
+ offset = static_cast<ALdouble>(readPos * FrameSize);
+ }
+ break;
+ }
+ }
+
+ return offset;
+}
+
+
+/* GetSampleOffset
+ *
+ * Retrieves the sample offset into the Source's queue (from the Sample, Byte
+ * or Second offset supplied by the application). This takes into account the
+ * fact that the buffer format may have been modifed since.
+ */
+ALboolean GetSampleOffset(ALsource *Source, ALuint *offset, ALsizei *frac)
+{
+ const ALbuffer *BufferFmt{nullptr};
+ const ALbufferlistitem *BufferList;
+
+ /* Find the first valid Buffer in the Queue */
+ BufferList = Source->queue;
+ while(BufferList)
+ {
+ for(ALsizei i{0};i < BufferList->num_buffers && !BufferFmt;i++)
+ BufferFmt = BufferList->buffers[i];
+ if(BufferFmt) break;
+ BufferList = BufferList->next.load(std::memory_order_relaxed);
+ }
+ if(!BufferFmt)
+ {
+ Source->OffsetType = AL_NONE;
+ Source->Offset = 0.0;
+ return AL_FALSE;
+ }
+
+ ALdouble dbloff, dblfrac;
+ switch(Source->OffsetType)
+ {
+ case AL_BYTE_OFFSET:
+ /* Determine the ByteOffset (and ensure it is block aligned) */
+ *offset = static_cast<ALuint>(Source->Offset);
+ if(BufferFmt->OriginalType == UserFmtIMA4)
+ {
+ ALsizei align = (BufferFmt->OriginalAlign-1)/2 + 4;
+ *offset /= align * ChannelsFromFmt(BufferFmt->mFmtChannels);
+ *offset *= BufferFmt->OriginalAlign;
+ }
+ else if(BufferFmt->OriginalType == UserFmtMSADPCM)
+ {
+ ALsizei align = (BufferFmt->OriginalAlign-2)/2 + 7;
+ *offset /= align * ChannelsFromFmt(BufferFmt->mFmtChannels);
+ *offset *= BufferFmt->OriginalAlign;
+ }
+ else
+ *offset /= FrameSizeFromFmt(BufferFmt->mFmtChannels, BufferFmt->mFmtType);
+ *frac = 0;
+ break;
+
+ case AL_SAMPLE_OFFSET:
+ dblfrac = modf(Source->Offset, &dbloff);
+ *offset = static_cast<ALuint>(mind(dbloff, std::numeric_limits<unsigned int>::max()));
+ *frac = static_cast<ALsizei>(mind(dblfrac*FRACTIONONE, FRACTIONONE-1.0));
+ break;
+
+ case AL_SEC_OFFSET:
+ dblfrac = modf(Source->Offset*BufferFmt->Frequency, &dbloff);
+ *offset = static_cast<ALuint>(mind(dbloff, std::numeric_limits<unsigned int>::max()));
+ *frac = static_cast<ALsizei>(mind(dblfrac*FRACTIONONE, FRACTIONONE-1.0));
+ break;
+ }
+ Source->OffsetType = AL_NONE;
+ Source->Offset = 0.0;
+
+ return AL_TRUE;
+}
+
+/* ApplyOffset
+ *
+ * Apply the stored playback offset to the Source. This function will update
+ * the number of buffers "played" given the stored offset.
+ */
+ALboolean ApplyOffset(ALsource *Source, ALvoice *voice)
+{
+ /* Get sample frame offset */
+ ALuint offset{0u};
+ ALsizei frac{0};
+ if(!GetSampleOffset(Source, &offset, &frac))
+ return AL_FALSE;
+
+ ALuint totalBufferLen{0u};
+ ALbufferlistitem *BufferList{Source->queue};
+ while(BufferList && totalBufferLen <= offset)
+ {
+ if(static_cast<ALuint>(BufferList->max_samples) > offset-totalBufferLen)
+ {
+ /* Offset is in this buffer */
+ voice->mPosition.store(offset - totalBufferLen, std::memory_order_relaxed);
+ voice->mPositionFrac.store(frac, std::memory_order_relaxed);
+ voice->mCurrentBuffer.store(BufferList, std::memory_order_release);
+ return AL_TRUE;
+ }
+ totalBufferLen += BufferList->max_samples;
+
+ BufferList = BufferList->next.load(std::memory_order_relaxed);
+ }
+
+ /* Offset is out of range of the queue */
+ return AL_FALSE;
+}
+
+
+ALsource *AllocSource(ALCcontext *context)
+{
+ ALCdevice *device{context->Device};
+ std::lock_guard<std::mutex> _{context->SourceLock};
+ if(context->NumSources >= device->SourcesMax)
+ {
+ alSetError(context, AL_OUT_OF_MEMORY, "Exceeding %u source limit", device->SourcesMax);
+ return nullptr;
+ }
+ auto sublist = std::find_if(context->SourceList.begin(), context->SourceList.end(),
+ [](const SourceSubList &entry) noexcept -> bool
+ { return entry.FreeMask != 0; }
+ );
+ auto lidx = static_cast<ALsizei>(std::distance(context->SourceList.begin(), sublist));
+ ALsource *source;
+ ALsizei slidx;
+ if(LIKELY(sublist != context->SourceList.end()))
+ {
+ slidx = CTZ64(sublist->FreeMask);
+ source = sublist->Sources + slidx;
+ }
+ else
+ {
+ /* Don't allocate so many list entries that the 32-bit ID could
+ * overflow...
+ */
+ if(UNLIKELY(context->SourceList.size() >= 1<<25))
+ {
+ alSetError(context, AL_OUT_OF_MEMORY, "Too many sources allocated");
+ return nullptr;
+ }
+ context->SourceList.emplace_back();
+ sublist = context->SourceList.end() - 1;
+
+ sublist->FreeMask = ~0_u64;
+ sublist->Sources = static_cast<ALsource*>(al_calloc(16, sizeof(ALsource)*64));
+ if(UNLIKELY(!sublist->Sources))
+ {
+ context->SourceList.pop_back();
+ alSetError(context, AL_OUT_OF_MEMORY, "Failed to allocate source batch");
+ return nullptr;
+ }
+
+ slidx = 0;
+ source = sublist->Sources + slidx;
+ }
+
+ source = new (source) ALsource{device->NumAuxSends};
+
+ /* Add 1 to avoid source ID 0. */
+ source->id = ((lidx<<6) | slidx) + 1;
+
+ context->NumSources += 1;
+ sublist->FreeMask &= ~(1_u64 << slidx);
+
+ return source;
+}
+
+void FreeSource(ALCcontext *context, ALsource *source)
+{
+ ALuint id = source->id - 1;
+ ALsizei lidx = id >> 6;
+ ALsizei slidx = id & 0x3f;
+
+ ALCdevice *device{context->Device};
+ BackendUniqueLock backlock{*device->Backend};
+ if(ALvoice *voice{GetSourceVoice(source, context)})
+ {
+ voice->mCurrentBuffer.store(nullptr, std::memory_order_relaxed);
+ voice->mLoopBuffer.store(nullptr, std::memory_order_relaxed);
+ voice->mSourceID.store(0u, std::memory_order_relaxed);
+ std::atomic_thread_fence(std::memory_order_release);
+ /* Don't set the voice to stopping if it was already stopped or
+ * stopping.
+ */
+ ALvoice::State oldvstate{ALvoice::Playing};
+ voice->mPlayState.compare_exchange_strong(oldvstate, ALvoice::Stopping,
+ std::memory_order_acq_rel, std::memory_order_acquire);
+ }
+ backlock.unlock();
+
+ al::destroy_at(source);
+
+ context->SourceList[lidx].FreeMask |= 1_u64 << slidx;
+ context->NumSources--;
+}
+
+
+inline ALsource *LookupSource(ALCcontext *context, ALuint id) noexcept
+{
+ ALuint lidx = (id-1) >> 6;
+ ALsizei slidx = (id-1) & 0x3f;
+
+ if(UNLIKELY(lidx >= context->SourceList.size()))
+ return nullptr;
+ SourceSubList &sublist{context->SourceList[lidx]};
+ if(UNLIKELY(sublist.FreeMask & (1_u64 << slidx)))
+ return nullptr;
+ return sublist.Sources + slidx;
+}
+
+inline ALbuffer *LookupBuffer(ALCdevice *device, ALuint id) noexcept
+{
+ ALuint lidx = (id-1) >> 6;
+ ALsizei slidx = (id-1) & 0x3f;
+
+ if(UNLIKELY(lidx >= device->BufferList.size()))
+ return nullptr;
+ BufferSubList &sublist = device->BufferList[lidx];
+ if(UNLIKELY(sublist.FreeMask & (1_u64 << slidx)))
+ return nullptr;
+ return sublist.Buffers + slidx;
+}
+
+inline ALfilter *LookupFilter(ALCdevice *device, ALuint id) noexcept
+{
+ ALuint lidx = (id-1) >> 6;
+ ALsizei slidx = (id-1) & 0x3f;
+
+ if(UNLIKELY(lidx >= device->FilterList.size()))
+ return nullptr;
+ FilterSubList &sublist = device->FilterList[lidx];
+ if(UNLIKELY(sublist.FreeMask & (1_u64 << slidx)))
+ return nullptr;
+ return sublist.Filters + slidx;
+}
+
+inline ALeffectslot *LookupEffectSlot(ALCcontext *context, ALuint id) noexcept
+{
+ ALuint lidx = (id-1) >> 6;
+ ALsizei slidx = (id-1) & 0x3f;
+
+ if(UNLIKELY(lidx >= context->EffectSlotList.size()))
+ return nullptr;
+ EffectSlotSubList &sublist{context->EffectSlotList[lidx]};
+ if(UNLIKELY(sublist.FreeMask & (1_u64 << slidx)))
+ return nullptr;
+ return sublist.EffectSlots + slidx;
+}
+
+
+enum SourceProp : ALenum {
+ srcPitch = AL_PITCH,
+ srcGain = AL_GAIN,
+ srcMinGain = AL_MIN_GAIN,
+ srcMaxGain = AL_MAX_GAIN,
+ srcMaxDistance = AL_MAX_DISTANCE,
+ srcRolloffFactor = AL_ROLLOFF_FACTOR,
+ srcDopplerFactor = AL_DOPPLER_FACTOR,
+ srcConeOuterGain = AL_CONE_OUTER_GAIN,
+ srcSecOffset = AL_SEC_OFFSET,
+ srcSampleOffset = AL_SAMPLE_OFFSET,
+ srcByteOffset = AL_BYTE_OFFSET,
+ srcConeInnerAngle = AL_CONE_INNER_ANGLE,
+ srcConeOuterAngle = AL_CONE_OUTER_ANGLE,
+ srcRefDistance = AL_REFERENCE_DISTANCE,
+
+ srcPosition = AL_POSITION,
+ srcVelocity = AL_VELOCITY,
+ srcDirection = AL_DIRECTION,
+
+ srcSourceRelative = AL_SOURCE_RELATIVE,
+ srcLooping = AL_LOOPING,
+ srcBuffer = AL_BUFFER,
+ srcSourceState = AL_SOURCE_STATE,
+ srcBuffersQueued = AL_BUFFERS_QUEUED,
+ srcBuffersProcessed = AL_BUFFERS_PROCESSED,
+ srcSourceType = AL_SOURCE_TYPE,
+
+ /* ALC_EXT_EFX */
+ srcConeOuterGainHF = AL_CONE_OUTER_GAINHF,
+ srcAirAbsorptionFactor = AL_AIR_ABSORPTION_FACTOR,
+ srcRoomRolloffFactor = AL_ROOM_ROLLOFF_FACTOR,
+ srcDirectFilterGainHFAuto = AL_DIRECT_FILTER_GAINHF_AUTO,
+ srcAuxSendFilterGainAuto = AL_AUXILIARY_SEND_FILTER_GAIN_AUTO,
+ srcAuxSendFilterGainHFAuto = AL_AUXILIARY_SEND_FILTER_GAINHF_AUTO,
+ srcDirectFilter = AL_DIRECT_FILTER,
+ srcAuxSendFilter = AL_AUXILIARY_SEND_FILTER,
+
+ /* AL_SOFT_direct_channels */
+ srcDirectChannelsSOFT = AL_DIRECT_CHANNELS_SOFT,
+
+ /* AL_EXT_source_distance_model */
+ srcDistanceModel = AL_DISTANCE_MODEL,
+
+ /* AL_SOFT_source_latency */
+ srcSampleOffsetLatencySOFT = AL_SAMPLE_OFFSET_LATENCY_SOFT,
+ srcSecOffsetLatencySOFT = AL_SEC_OFFSET_LATENCY_SOFT,
+
+ /* AL_EXT_STEREO_ANGLES */
+ srcAngles = AL_STEREO_ANGLES,
+
+ /* AL_EXT_SOURCE_RADIUS */
+ srcRadius = AL_SOURCE_RADIUS,
+
+ /* AL_EXT_BFORMAT */
+ srcOrientation = AL_ORIENTATION,
+
+ /* AL_SOFT_source_resampler */
+ srcResampler = AL_SOURCE_RESAMPLER_SOFT,
+
+ /* AL_SOFT_source_spatialize */
+ srcSpatialize = AL_SOURCE_SPATIALIZE_SOFT,
+
+ /* ALC_SOFT_device_clock */
+ srcSampleOffsetClockSOFT = AL_SAMPLE_OFFSET_CLOCK_SOFT,
+ srcSecOffsetClockSOFT = AL_SEC_OFFSET_CLOCK_SOFT,
+};
+
+/**
+ * Returns if the last known state for the source was playing or paused. Does
+ * not sync with the mixer voice.
+ */
+inline bool IsPlayingOrPaused(ALsource *source)
+{ return source->state == AL_PLAYING || source->state == AL_PAUSED; }
+
+/**
+ * Returns an updated source state using the matching voice's status (or lack
+ * thereof).
+ */
+inline ALenum GetSourceState(ALsource *source, ALvoice *voice)
+{
+ if(!voice && source->state == AL_PLAYING)
+ source->state = AL_STOPPED;
+ return source->state;
+}
+
+/**
+ * Returns if the source should specify an update, given the context's
+ * deferring state and the source's last known state.
+ */
+inline bool SourceShouldUpdate(ALsource *source, ALCcontext *context)
+{
+ return !context->DeferUpdates.load(std::memory_order_acquire) &&
+ IsPlayingOrPaused(source);
+}
+
+
+/** Can only be called while the mixer is locked! */
+void SendStateChangeEvent(ALCcontext *context, ALuint id, ALenum state)
+{
+ ALbitfieldSOFT enabledevt{context->EnabledEvts.load(std::memory_order_acquire)};
+ if(!(enabledevt&EventType_SourceStateChange)) return;
+
+ /* The mixer may have queued a state change that's not yet been processed,
+ * and we don't want state change messages to occur out of order, so send
+ * it through the async queue to ensure proper ordering.
+ */
+ RingBuffer *ring{context->AsyncEvents.get()};
+ auto evt_vec = ring->getWriteVector();
+ if(evt_vec.first.len < 1) return;
+
+ AsyncEvent *evt{new (evt_vec.first.buf) AsyncEvent{EventType_SourceStateChange}};
+ evt->u.srcstate.id = id;
+ evt->u.srcstate.state = state;
+ ring->writeAdvance(1);
+ context->EventSem.post();
+}
+
+
+ALint FloatValsByProp(ALenum prop)
+{
+ switch(static_cast<SourceProp>(prop))
+ {
+ case AL_PITCH:
+ case AL_GAIN:
+ case AL_MIN_GAIN:
+ case AL_MAX_GAIN:
+ case AL_MAX_DISTANCE:
+ case AL_ROLLOFF_FACTOR:
+ case AL_DOPPLER_FACTOR:
+ case AL_CONE_OUTER_GAIN:
+ case AL_SEC_OFFSET:
+ case AL_SAMPLE_OFFSET:
+ case AL_BYTE_OFFSET:
+ case AL_CONE_INNER_ANGLE:
+ case AL_CONE_OUTER_ANGLE:
+ case AL_REFERENCE_DISTANCE:
+ case AL_CONE_OUTER_GAINHF:
+ case AL_AIR_ABSORPTION_FACTOR:
+ case AL_ROOM_ROLLOFF_FACTOR:
+ case AL_DIRECT_FILTER_GAINHF_AUTO:
+ case AL_AUXILIARY_SEND_FILTER_GAIN_AUTO:
+ case AL_AUXILIARY_SEND_FILTER_GAINHF_AUTO:
+ case AL_DIRECT_CHANNELS_SOFT:
+ case AL_DISTANCE_MODEL:
+ case AL_SOURCE_RELATIVE:
+ case AL_LOOPING:
+ case AL_SOURCE_STATE:
+ case AL_BUFFERS_QUEUED:
+ case AL_BUFFERS_PROCESSED:
+ case AL_SOURCE_TYPE:
+ case AL_SOURCE_RADIUS:
+ case AL_SOURCE_RESAMPLER_SOFT:
+ case AL_SOURCE_SPATIALIZE_SOFT:
+ return 1;
+
+ case AL_STEREO_ANGLES:
+ return 2;
+
+ case AL_POSITION:
+ case AL_VELOCITY:
+ case AL_DIRECTION:
+ return 3;
+
+ case AL_ORIENTATION:
+ return 6;
+
+ case AL_SEC_OFFSET_LATENCY_SOFT:
+ case AL_SEC_OFFSET_CLOCK_SOFT:
+ break; /* Double only */
+
+ case AL_BUFFER:
+ case AL_DIRECT_FILTER:
+ case AL_AUXILIARY_SEND_FILTER:
+ break; /* i/i64 only */
+ case AL_SAMPLE_OFFSET_LATENCY_SOFT:
+ case AL_SAMPLE_OFFSET_CLOCK_SOFT:
+ break; /* i64 only */
+ }
+ return 0;
+}
+ALint DoubleValsByProp(ALenum prop)
+{
+ switch(static_cast<SourceProp>(prop))
+ {
+ case AL_PITCH:
+ case AL_GAIN:
+ case AL_MIN_GAIN:
+ case AL_MAX_GAIN:
+ case AL_MAX_DISTANCE:
+ case AL_ROLLOFF_FACTOR:
+ case AL_DOPPLER_FACTOR:
+ case AL_CONE_OUTER_GAIN:
+ case AL_SEC_OFFSET:
+ case AL_SAMPLE_OFFSET:
+ case AL_BYTE_OFFSET:
+ case AL_CONE_INNER_ANGLE:
+ case AL_CONE_OUTER_ANGLE:
+ case AL_REFERENCE_DISTANCE:
+ case AL_CONE_OUTER_GAINHF:
+ case AL_AIR_ABSORPTION_FACTOR:
+ case AL_ROOM_ROLLOFF_FACTOR:
+ case AL_DIRECT_FILTER_GAINHF_AUTO:
+ case AL_AUXILIARY_SEND_FILTER_GAIN_AUTO:
+ case AL_AUXILIARY_SEND_FILTER_GAINHF_AUTO:
+ case AL_DIRECT_CHANNELS_SOFT:
+ case AL_DISTANCE_MODEL:
+ case AL_SOURCE_RELATIVE:
+ case AL_LOOPING:
+ case AL_SOURCE_STATE:
+ case AL_BUFFERS_QUEUED:
+ case AL_BUFFERS_PROCESSED:
+ case AL_SOURCE_TYPE:
+ case AL_SOURCE_RADIUS:
+ case AL_SOURCE_RESAMPLER_SOFT:
+ case AL_SOURCE_SPATIALIZE_SOFT:
+ return 1;
+
+ case AL_SEC_OFFSET_LATENCY_SOFT:
+ case AL_SEC_OFFSET_CLOCK_SOFT:
+ case AL_STEREO_ANGLES:
+ return 2;
+
+ case AL_POSITION:
+ case AL_VELOCITY:
+ case AL_DIRECTION:
+ return 3;
+
+ case AL_ORIENTATION:
+ return 6;
+
+ case AL_BUFFER:
+ case AL_DIRECT_FILTER:
+ case AL_AUXILIARY_SEND_FILTER:
+ break; /* i/i64 only */
+ case AL_SAMPLE_OFFSET_LATENCY_SOFT:
+ case AL_SAMPLE_OFFSET_CLOCK_SOFT:
+ break; /* i64 only */
+ }
+ return 0;
+}
+
+ALint IntValsByProp(ALenum prop)
+{
+ switch(static_cast<SourceProp>(prop))
+ {
+ case AL_PITCH:
+ case AL_GAIN:
+ case AL_MIN_GAIN:
+ case AL_MAX_GAIN:
+ case AL_MAX_DISTANCE:
+ case AL_ROLLOFF_FACTOR:
+ case AL_DOPPLER_FACTOR:
+ case AL_CONE_OUTER_GAIN:
+ case AL_SEC_OFFSET:
+ case AL_SAMPLE_OFFSET:
+ case AL_BYTE_OFFSET:
+ case AL_CONE_INNER_ANGLE:
+ case AL_CONE_OUTER_ANGLE:
+ case AL_REFERENCE_DISTANCE:
+ case AL_CONE_OUTER_GAINHF:
+ case AL_AIR_ABSORPTION_FACTOR:
+ case AL_ROOM_ROLLOFF_FACTOR:
+ case AL_DIRECT_FILTER_GAINHF_AUTO:
+ case AL_AUXILIARY_SEND_FILTER_GAIN_AUTO:
+ case AL_AUXILIARY_SEND_FILTER_GAINHF_AUTO:
+ case AL_DIRECT_CHANNELS_SOFT:
+ case AL_DISTANCE_MODEL:
+ case AL_SOURCE_RELATIVE:
+ case AL_LOOPING:
+ case AL_BUFFER:
+ case AL_SOURCE_STATE:
+ case AL_BUFFERS_QUEUED:
+ case AL_BUFFERS_PROCESSED:
+ case AL_SOURCE_TYPE:
+ case AL_DIRECT_FILTER:
+ case AL_SOURCE_RADIUS:
+ case AL_SOURCE_RESAMPLER_SOFT:
+ case AL_SOURCE_SPATIALIZE_SOFT:
+ return 1;
+
+ case AL_POSITION:
+ case AL_VELOCITY:
+ case AL_DIRECTION:
+ case AL_AUXILIARY_SEND_FILTER:
+ return 3;
+
+ case AL_ORIENTATION:
+ return 6;
+
+ case AL_SAMPLE_OFFSET_LATENCY_SOFT:
+ case AL_SAMPLE_OFFSET_CLOCK_SOFT:
+ break; /* i64 only */
+ case AL_SEC_OFFSET_LATENCY_SOFT:
+ case AL_SEC_OFFSET_CLOCK_SOFT:
+ break; /* Double only */
+ case AL_STEREO_ANGLES:
+ break; /* Float/double only */
+ }
+ return 0;
+}
+ALint Int64ValsByProp(ALenum prop)
+{
+ switch(static_cast<SourceProp>(prop))
+ {
+ case AL_PITCH:
+ case AL_GAIN:
+ case AL_MIN_GAIN:
+ case AL_MAX_GAIN:
+ case AL_MAX_DISTANCE:
+ case AL_ROLLOFF_FACTOR:
+ case AL_DOPPLER_FACTOR:
+ case AL_CONE_OUTER_GAIN:
+ case AL_SEC_OFFSET:
+ case AL_SAMPLE_OFFSET:
+ case AL_BYTE_OFFSET:
+ case AL_CONE_INNER_ANGLE:
+ case AL_CONE_OUTER_ANGLE:
+ case AL_REFERENCE_DISTANCE:
+ case AL_CONE_OUTER_GAINHF:
+ case AL_AIR_ABSORPTION_FACTOR:
+ case AL_ROOM_ROLLOFF_FACTOR:
+ case AL_DIRECT_FILTER_GAINHF_AUTO:
+ case AL_AUXILIARY_SEND_FILTER_GAIN_AUTO:
+ case AL_AUXILIARY_SEND_FILTER_GAINHF_AUTO:
+ case AL_DIRECT_CHANNELS_SOFT:
+ case AL_DISTANCE_MODEL:
+ case AL_SOURCE_RELATIVE:
+ case AL_LOOPING:
+ case AL_BUFFER:
+ case AL_SOURCE_STATE:
+ case AL_BUFFERS_QUEUED:
+ case AL_BUFFERS_PROCESSED:
+ case AL_SOURCE_TYPE:
+ case AL_DIRECT_FILTER:
+ case AL_SOURCE_RADIUS:
+ case AL_SOURCE_RESAMPLER_SOFT:
+ case AL_SOURCE_SPATIALIZE_SOFT:
+ return 1;
+
+ case AL_SAMPLE_OFFSET_LATENCY_SOFT:
+ case AL_SAMPLE_OFFSET_CLOCK_SOFT:
+ return 2;
+
+ case AL_POSITION:
+ case AL_VELOCITY:
+ case AL_DIRECTION:
+ case AL_AUXILIARY_SEND_FILTER:
+ return 3;
+
+ case AL_ORIENTATION:
+ return 6;
+
+ case AL_SEC_OFFSET_LATENCY_SOFT:
+ case AL_SEC_OFFSET_CLOCK_SOFT:
+ break; /* Double only */
+ case AL_STEREO_ANGLES:
+ break; /* Float/double only */
+ }
+ return 0;
+}
+
+
+ALboolean SetSourcefv(ALsource *Source, ALCcontext *Context, SourceProp prop, const ALfloat *values);
+ALboolean SetSourceiv(ALsource *Source, ALCcontext *Context, SourceProp prop, const ALint *values);
+ALboolean SetSourcei64v(ALsource *Source, ALCcontext *Context, SourceProp prop, const ALint64SOFT *values);
+
+#define CHECKVAL(x) do { \
+ if(!(x)) \
+ { \
+ alSetError(Context, AL_INVALID_VALUE, "Value out of range"); \
+ return AL_FALSE; \
+ } \
+} while(0)
+
+void UpdateSourceProps(ALsource *source, ALCcontext *context)
+{
+ ALvoice *voice;
+ if(SourceShouldUpdate(source, context) && (voice=GetSourceVoice(source, context)) != nullptr)
+ UpdateSourceProps(source, voice, context);
+ else
+ source->PropsClean.clear(std::memory_order_release);
+}
+
+ALboolean SetSourcefv(ALsource *Source, ALCcontext *Context, SourceProp prop, const ALfloat *values)
+{
+ ALint ival;
+
+ switch(prop)
+ {
+ case AL_SEC_OFFSET_LATENCY_SOFT:
+ case AL_SEC_OFFSET_CLOCK_SOFT:
+ /* Query only */
+ SETERR_RETURN(Context, AL_INVALID_OPERATION, AL_FALSE,
+ "Setting read-only source property 0x%04x", prop);
+
+ case AL_PITCH:
+ CHECKVAL(*values >= 0.0f);
+
+ Source->Pitch = *values;
+ UpdateSourceProps(Source, Context);
+ return AL_TRUE;
+
+ case AL_CONE_INNER_ANGLE:
+ CHECKVAL(*values >= 0.0f && *values <= 360.0f);
+
+ Source->InnerAngle = *values;
+ UpdateSourceProps(Source, Context);
+ return AL_TRUE;
+
+ case AL_CONE_OUTER_ANGLE:
+ CHECKVAL(*values >= 0.0f && *values <= 360.0f);
+
+ Source->OuterAngle = *values;
+ UpdateSourceProps(Source, Context);
+ return AL_TRUE;
+
+ case AL_GAIN:
+ CHECKVAL(*values >= 0.0f);
+
+ Source->Gain = *values;
+ UpdateSourceProps(Source, Context);
+ return AL_TRUE;
+
+ case AL_MAX_DISTANCE:
+ CHECKVAL(*values >= 0.0f);
+
+ Source->MaxDistance = *values;
+ UpdateSourceProps(Source, Context);
+ return AL_TRUE;
+
+ case AL_ROLLOFF_FACTOR:
+ CHECKVAL(*values >= 0.0f);
+
+ Source->RolloffFactor = *values;
+ UpdateSourceProps(Source, Context);
+ return AL_TRUE;
+
+ case AL_REFERENCE_DISTANCE:
+ CHECKVAL(*values >= 0.0f);
+
+ Source->RefDistance = *values;
+ UpdateSourceProps(Source, Context);
+ return AL_TRUE;
+
+ case AL_MIN_GAIN:
+ CHECKVAL(*values >= 0.0f);
+
+ Source->MinGain = *values;
+ UpdateSourceProps(Source, Context);
+ return AL_TRUE;
+
+ case AL_MAX_GAIN:
+ CHECKVAL(*values >= 0.0f);
+
+ Source->MaxGain = *values;
+ UpdateSourceProps(Source, Context);
+ return AL_TRUE;
+
+ case AL_CONE_OUTER_GAIN:
+ CHECKVAL(*values >= 0.0f && *values <= 1.0f);
+
+ Source->OuterGain = *values;
+ UpdateSourceProps(Source, Context);
+ return AL_TRUE;
+
+ case AL_CONE_OUTER_GAINHF:
+ CHECKVAL(*values >= 0.0f && *values <= 1.0f);
+
+ Source->OuterGainHF = *values;
+ UpdateSourceProps(Source, Context);
+ return AL_TRUE;
+
+ case AL_AIR_ABSORPTION_FACTOR:
+ CHECKVAL(*values >= 0.0f && *values <= 10.0f);
+
+ Source->AirAbsorptionFactor = *values;
+ UpdateSourceProps(Source, Context);
+ return AL_TRUE;
+
+ case AL_ROOM_ROLLOFF_FACTOR:
+ CHECKVAL(*values >= 0.0f && *values <= 10.0f);
+
+ Source->RoomRolloffFactor = *values;
+ UpdateSourceProps(Source, Context);
+ return AL_TRUE;
+
+ case AL_DOPPLER_FACTOR:
+ CHECKVAL(*values >= 0.0f && *values <= 1.0f);
+
+ Source->DopplerFactor = *values;
+ UpdateSourceProps(Source, Context);
+ return AL_TRUE;
+
+ case AL_SEC_OFFSET:
+ case AL_SAMPLE_OFFSET:
+ case AL_BYTE_OFFSET:
+ CHECKVAL(*values >= 0.0f);
+
+ Source->OffsetType = prop;
+ Source->Offset = *values;
+
+ if(IsPlayingOrPaused(Source))
+ {
+ ALCdevice *device{Context->Device};
+ BackendLockGuard _{*device->Backend};
+ /* Double-check that the source is still playing while we have
+ * the lock.
+ */
+ if(ALvoice *voice{GetSourceVoice(Source, Context)})
+ {
+ if(ApplyOffset(Source, voice) == AL_FALSE)
+ SETERR_RETURN(Context, AL_INVALID_VALUE, AL_FALSE, "Invalid offset");
+ }
+ }
+ return AL_TRUE;
+
+ case AL_SOURCE_RADIUS:
+ CHECKVAL(*values >= 0.0f && std::isfinite(*values));
+
+ Source->Radius = *values;
+ UpdateSourceProps(Source, Context);
+ return AL_TRUE;
+
+ case AL_STEREO_ANGLES:
+ CHECKVAL(std::isfinite(values[0]) && std::isfinite(values[1]));
+
+ Source->StereoPan[0] = values[0];
+ Source->StereoPan[1] = values[1];
+ UpdateSourceProps(Source, Context);
+ return AL_TRUE;
+
+
+ case AL_POSITION:
+ CHECKVAL(std::isfinite(values[0]) && std::isfinite(values[1]) && std::isfinite(values[2]));
+
+ Source->Position[0] = values[0];
+ Source->Position[1] = values[1];
+ Source->Position[2] = values[2];
+ UpdateSourceProps(Source, Context);
+ return AL_TRUE;
+
+ case AL_VELOCITY:
+ CHECKVAL(std::isfinite(values[0]) && std::isfinite(values[1]) && std::isfinite(values[2]));
+
+ Source->Velocity[0] = values[0];
+ Source->Velocity[1] = values[1];
+ Source->Velocity[2] = values[2];
+ UpdateSourceProps(Source, Context);
+ return AL_TRUE;
+
+ case AL_DIRECTION:
+ CHECKVAL(std::isfinite(values[0]) && std::isfinite(values[1]) && std::isfinite(values[2]));
+
+ Source->Direction[0] = values[0];
+ Source->Direction[1] = values[1];
+ Source->Direction[2] = values[2];
+ UpdateSourceProps(Source, Context);
+ return AL_TRUE;
+
+ case AL_ORIENTATION:
+ CHECKVAL(std::isfinite(values[0]) && std::isfinite(values[1]) && std::isfinite(values[2]) &&
+ std::isfinite(values[3]) && std::isfinite(values[4]) && std::isfinite(values[5]));
+
+ Source->OrientAt[0] = values[0];
+ Source->OrientAt[1] = values[1];
+ Source->OrientAt[2] = values[2];
+ Source->OrientUp[0] = values[3];
+ Source->OrientUp[1] = values[4];
+ Source->OrientUp[2] = values[5];
+ UpdateSourceProps(Source, Context);
+ return AL_TRUE;
+
+
+ case AL_SOURCE_RELATIVE:
+ case AL_LOOPING:
+ case AL_SOURCE_STATE:
+ case AL_SOURCE_TYPE:
+ case AL_DISTANCE_MODEL:
+ case AL_DIRECT_FILTER_GAINHF_AUTO:
+ case AL_AUXILIARY_SEND_FILTER_GAIN_AUTO:
+ case AL_AUXILIARY_SEND_FILTER_GAINHF_AUTO:
+ case AL_DIRECT_CHANNELS_SOFT:
+ case AL_SOURCE_RESAMPLER_SOFT:
+ case AL_SOURCE_SPATIALIZE_SOFT:
+ ival = static_cast<ALint>(values[0]);
+ return SetSourceiv(Source, Context, prop, &ival);
+
+ case AL_BUFFERS_QUEUED:
+ case AL_BUFFERS_PROCESSED:
+ ival = static_cast<ALint>(static_cast<ALuint>(values[0]));
+ return SetSourceiv(Source, Context, prop, &ival);
+
+ case AL_BUFFER:
+ case AL_DIRECT_FILTER:
+ case AL_AUXILIARY_SEND_FILTER:
+ case AL_SAMPLE_OFFSET_LATENCY_SOFT:
+ case AL_SAMPLE_OFFSET_CLOCK_SOFT:
+ break;
+ }
+
+ ERR("Unexpected property: 0x%04x\n", prop);
+ SETERR_RETURN(Context, AL_INVALID_ENUM, AL_FALSE, "Invalid source float property 0x%04x", prop);
+}
+
+ALboolean SetSourceiv(ALsource *Source, ALCcontext *Context, SourceProp prop, const ALint *values)
+{
+ ALCdevice *device{Context->Device};
+ ALbuffer *buffer{nullptr};
+ ALfilter *filter{nullptr};
+ ALeffectslot *slot{nullptr};
+ ALbufferlistitem *oldlist{nullptr};
+ std::unique_lock<std::mutex> slotlock;
+ std::unique_lock<std::mutex> filtlock;
+ std::unique_lock<std::mutex> buflock;
+ ALfloat fvals[6];
+
+ switch(prop)
+ {
+ case AL_SOURCE_STATE:
+ case AL_SOURCE_TYPE:
+ case AL_BUFFERS_QUEUED:
+ case AL_BUFFERS_PROCESSED:
+ /* Query only */
+ SETERR_RETURN(Context, AL_INVALID_OPERATION, AL_FALSE,
+ "Setting read-only source property 0x%04x", prop);
+
+ case AL_SOURCE_RELATIVE:
+ CHECKVAL(*values == AL_FALSE || *values == AL_TRUE);
+
+ Source->HeadRelative = static_cast<ALboolean>(*values);
+ UpdateSourceProps(Source, Context);
+ return AL_TRUE;
+
+ case AL_LOOPING:
+ CHECKVAL(*values == AL_FALSE || *values == AL_TRUE);
+
+ Source->Looping = static_cast<ALboolean>(*values);
+ if(IsPlayingOrPaused(Source))
+ {
+ ALvoice *voice{GetSourceVoice(Source, Context)};
+ if(voice)
+ {
+ if(Source->Looping)
+ voice->mLoopBuffer.store(Source->queue, std::memory_order_release);
+ else
+ voice->mLoopBuffer.store(nullptr, std::memory_order_release);
+
+ /* If the source is playing, wait for the current mix to finish
+ * to ensure it isn't currently looping back or reaching the
+ * end.
+ */
+ while((device->MixCount.load(std::memory_order_acquire)&1))
+ std::this_thread::yield();
+ }
+ }
+ return AL_TRUE;
+
+ case AL_BUFFER:
+ buflock = std::unique_lock<std::mutex>{device->BufferLock};
+ if(!(*values == 0 || (buffer=LookupBuffer(device, *values)) != nullptr))
+ SETERR_RETURN(Context, AL_INVALID_VALUE, AL_FALSE, "Invalid buffer ID %u",
+ *values);
+
+ if(buffer && buffer->MappedAccess != 0 &&
+ !(buffer->MappedAccess&AL_MAP_PERSISTENT_BIT_SOFT))
+ SETERR_RETURN(Context, AL_INVALID_OPERATION, AL_FALSE,
+ "Setting non-persistently mapped buffer %u", buffer->id);
+ else
+ {
+ ALenum state = GetSourceState(Source, GetSourceVoice(Source, Context));
+ if(state == AL_PLAYING || state == AL_PAUSED)
+ SETERR_RETURN(Context, AL_INVALID_OPERATION, AL_FALSE,
+ "Setting buffer on playing or paused source %u", Source->id);
+ }
+
+ oldlist = Source->queue;
+ if(buffer != nullptr)
+ {
+ /* Add the selected buffer to a one-item queue */
+ auto newlist = static_cast<ALbufferlistitem*>(al_calloc(alignof(void*),
+ ALbufferlistitem::Sizeof(1u)));
+ newlist->next.store(nullptr, std::memory_order_relaxed);
+ newlist->max_samples = buffer->SampleLen;
+ newlist->num_buffers = 1;
+ newlist->buffers[0] = buffer;
+ IncrementRef(&buffer->ref);
+
+ /* Source is now Static */
+ Source->SourceType = AL_STATIC;
+ Source->queue = newlist;
+ }
+ else
+ {
+ /* Source is now Undetermined */
+ Source->SourceType = AL_UNDETERMINED;
+ Source->queue = nullptr;
+ }
+ buflock.unlock();
+
+ /* Delete all elements in the previous queue */
+ while(oldlist != nullptr)
+ {
+ ALbufferlistitem *temp{oldlist};
+ oldlist = temp->next.load(std::memory_order_relaxed);
+
+ for(ALsizei i{0};i < temp->num_buffers;i++)
+ {
+ if(temp->buffers[i])
+ DecrementRef(&temp->buffers[i]->ref);
+ }
+ al_free(temp);
+ }
+ return AL_TRUE;
+
+ case AL_SEC_OFFSET:
+ case AL_SAMPLE_OFFSET:
+ case AL_BYTE_OFFSET:
+ CHECKVAL(*values >= 0);
+
+ Source->OffsetType = prop;
+ Source->Offset = *values;
+
+ if(IsPlayingOrPaused(Source))
+ {
+ ALCdevice *device{Context->Device};
+ BackendLockGuard _{*device->Backend};
+ if(ALvoice *voice{GetSourceVoice(Source, Context)})
+ {
+ if(ApplyOffset(Source, voice) == AL_FALSE)
+ SETERR_RETURN(Context, AL_INVALID_VALUE, AL_FALSE,
+ "Invalid source offset");
+ }
+ }
+ return AL_TRUE;
+
+ case AL_DIRECT_FILTER:
+ filtlock = std::unique_lock<std::mutex>{device->FilterLock};
+ if(!(*values == 0 || (filter=LookupFilter(device, *values)) != nullptr))
+ SETERR_RETURN(Context, AL_INVALID_VALUE, AL_FALSE, "Invalid filter ID %u",
+ *values);
+
+ if(!filter)
+ {
+ Source->Direct.Gain = 1.0f;
+ Source->Direct.GainHF = 1.0f;
+ Source->Direct.HFReference = LOWPASSFREQREF;
+ Source->Direct.GainLF = 1.0f;
+ Source->Direct.LFReference = HIGHPASSFREQREF;
+ }
+ else
+ {
+ Source->Direct.Gain = filter->Gain;
+ Source->Direct.GainHF = filter->GainHF;
+ Source->Direct.HFReference = filter->HFReference;
+ Source->Direct.GainLF = filter->GainLF;
+ Source->Direct.LFReference = filter->LFReference;
+ }
+ filtlock.unlock();
+ UpdateSourceProps(Source, Context);
+ return AL_TRUE;
+
+ case AL_DIRECT_FILTER_GAINHF_AUTO:
+ CHECKVAL(*values == AL_FALSE || *values == AL_TRUE);
+
+ Source->DryGainHFAuto = *values;
+ UpdateSourceProps(Source, Context);
+ return AL_TRUE;
+
+ case AL_AUXILIARY_SEND_FILTER_GAIN_AUTO:
+ CHECKVAL(*values == AL_FALSE || *values == AL_TRUE);
+
+ Source->WetGainAuto = *values;
+ UpdateSourceProps(Source, Context);
+ return AL_TRUE;
+
+ case AL_AUXILIARY_SEND_FILTER_GAINHF_AUTO:
+ CHECKVAL(*values == AL_FALSE || *values == AL_TRUE);
+
+ Source->WetGainHFAuto = *values;
+ UpdateSourceProps(Source, Context);
+ return AL_TRUE;
+
+ case AL_DIRECT_CHANNELS_SOFT:
+ CHECKVAL(*values == AL_FALSE || *values == AL_TRUE);
+
+ Source->DirectChannels = *values;
+ UpdateSourceProps(Source, Context);
+ return AL_TRUE;
+
+ case AL_DISTANCE_MODEL:
+ CHECKVAL(*values == AL_NONE ||
+ *values == AL_INVERSE_DISTANCE ||
+ *values == AL_INVERSE_DISTANCE_CLAMPED ||
+ *values == AL_LINEAR_DISTANCE ||
+ *values == AL_LINEAR_DISTANCE_CLAMPED ||
+ *values == AL_EXPONENT_DISTANCE ||
+ *values == AL_EXPONENT_DISTANCE_CLAMPED);
+
+ Source->mDistanceModel = static_cast<DistanceModel>(*values);
+ if(Context->SourceDistanceModel)
+ UpdateSourceProps(Source, Context);
+ return AL_TRUE;
+
+ case AL_SOURCE_RESAMPLER_SOFT:
+ CHECKVAL(*values >= 0 && *values <= ResamplerMax);
+
+ Source->mResampler = static_cast<Resampler>(*values);
+ UpdateSourceProps(Source, Context);
+ return AL_TRUE;
+
+ case AL_SOURCE_SPATIALIZE_SOFT:
+ CHECKVAL(*values >= AL_FALSE && *values <= AL_AUTO_SOFT);
+
+ Source->mSpatialize = static_cast<SpatializeMode>(*values);
+ UpdateSourceProps(Source, Context);
+ return AL_TRUE;
+
+
+ case AL_AUXILIARY_SEND_FILTER:
+ slotlock = std::unique_lock<std::mutex>{Context->EffectSlotLock};
+ if(!(values[0] == 0 || (slot=LookupEffectSlot(Context, values[0])) != nullptr))
+ SETERR_RETURN(Context, AL_INVALID_VALUE, AL_FALSE, "Invalid effect ID %u",
+ values[0]);
+ if(static_cast<ALuint>(values[1]) >= static_cast<ALuint>(device->NumAuxSends))
+ SETERR_RETURN(Context, AL_INVALID_VALUE, AL_FALSE, "Invalid send %u", values[1]);
+
+ filtlock = std::unique_lock<std::mutex>{device->FilterLock};
+ if(!(values[2] == 0 || (filter=LookupFilter(device, values[2])) != nullptr))
+ SETERR_RETURN(Context, AL_INVALID_VALUE, AL_FALSE, "Invalid filter ID %u",
+ values[2]);
+
+ if(!filter)
+ {
+ /* Disable filter */
+ Source->Send[values[1]].Gain = 1.0f;
+ Source->Send[values[1]].GainHF = 1.0f;
+ Source->Send[values[1]].HFReference = LOWPASSFREQREF;
+ Source->Send[values[1]].GainLF = 1.0f;
+ Source->Send[values[1]].LFReference = HIGHPASSFREQREF;
+ }
+ else
+ {
+ Source->Send[values[1]].Gain = filter->Gain;
+ Source->Send[values[1]].GainHF = filter->GainHF;
+ Source->Send[values[1]].HFReference = filter->HFReference;
+ Source->Send[values[1]].GainLF = filter->GainLF;
+ Source->Send[values[1]].LFReference = filter->LFReference;
+ }
+ filtlock.unlock();
+
+ if(slot != Source->Send[values[1]].Slot && IsPlayingOrPaused(Source))
+ {
+ /* Add refcount on the new slot, and release the previous slot */
+ if(slot) IncrementRef(&slot->ref);
+ if(Source->Send[values[1]].Slot)
+ DecrementRef(&Source->Send[values[1]].Slot->ref);
+ Source->Send[values[1]].Slot = slot;
+
+ /* We must force an update if the auxiliary slot changed on an
+ * active source, in case the slot is about to be deleted.
+ */
+ ALvoice *voice{GetSourceVoice(Source, Context)};
+ if(voice) UpdateSourceProps(Source, voice, Context);
+ else Source->PropsClean.clear(std::memory_order_release);
+ }
+ else
+ {
+ if(slot) IncrementRef(&slot->ref);
+ if(Source->Send[values[1]].Slot)
+ DecrementRef(&Source->Send[values[1]].Slot->ref);
+ Source->Send[values[1]].Slot = slot;
+ UpdateSourceProps(Source, Context);
+ }
+
+ return AL_TRUE;
+
+
+ /* 1x float */
+ case AL_CONE_INNER_ANGLE:
+ case AL_CONE_OUTER_ANGLE:
+ case AL_PITCH:
+ case AL_GAIN:
+ case AL_MIN_GAIN:
+ case AL_MAX_GAIN:
+ case AL_REFERENCE_DISTANCE:
+ case AL_ROLLOFF_FACTOR:
+ case AL_CONE_OUTER_GAIN:
+ case AL_MAX_DISTANCE:
+ case AL_DOPPLER_FACTOR:
+ case AL_CONE_OUTER_GAINHF:
+ case AL_AIR_ABSORPTION_FACTOR:
+ case AL_ROOM_ROLLOFF_FACTOR:
+ case AL_SOURCE_RADIUS:
+ fvals[0] = static_cast<ALfloat>(*values);
+ return SetSourcefv(Source, Context, prop, fvals);
+
+ /* 3x float */
+ case AL_POSITION:
+ case AL_VELOCITY:
+ case AL_DIRECTION:
+ fvals[0] = static_cast<ALfloat>(values[0]);
+ fvals[1] = static_cast<ALfloat>(values[1]);
+ fvals[2] = static_cast<ALfloat>(values[2]);
+ return SetSourcefv(Source, Context, prop, fvals);
+
+ /* 6x float */
+ case AL_ORIENTATION:
+ fvals[0] = static_cast<ALfloat>(values[0]);
+ fvals[1] = static_cast<ALfloat>(values[1]);
+ fvals[2] = static_cast<ALfloat>(values[2]);
+ fvals[3] = static_cast<ALfloat>(values[3]);
+ fvals[4] = static_cast<ALfloat>(values[4]);
+ fvals[5] = static_cast<ALfloat>(values[5]);
+ return SetSourcefv(Source, Context, prop, fvals);
+
+ case AL_SAMPLE_OFFSET_LATENCY_SOFT:
+ case AL_SEC_OFFSET_LATENCY_SOFT:
+ case AL_SEC_OFFSET_CLOCK_SOFT:
+ case AL_SAMPLE_OFFSET_CLOCK_SOFT:
+ case AL_STEREO_ANGLES:
+ break;
+ }
+
+ ERR("Unexpected property: 0x%04x\n", prop);
+ SETERR_RETURN(Context, AL_INVALID_ENUM, AL_FALSE, "Invalid source integer property 0x%04x",
+ prop);
+}
+
+ALboolean SetSourcei64v(ALsource *Source, ALCcontext *Context, SourceProp prop, const ALint64SOFT *values)
+{
+ ALfloat fvals[6];
+ ALint ivals[3];
+
+ switch(prop)
+ {
+ case AL_SOURCE_TYPE:
+ case AL_BUFFERS_QUEUED:
+ case AL_BUFFERS_PROCESSED:
+ case AL_SOURCE_STATE:
+ case AL_SAMPLE_OFFSET_LATENCY_SOFT:
+ case AL_SAMPLE_OFFSET_CLOCK_SOFT:
+ /* Query only */
+ SETERR_RETURN(Context, AL_INVALID_OPERATION, AL_FALSE,
+ "Setting read-only source property 0x%04x", prop);
+
+ /* 1x int */
+ case AL_SOURCE_RELATIVE:
+ case AL_LOOPING:
+ case AL_SEC_OFFSET:
+ case AL_SAMPLE_OFFSET:
+ case AL_BYTE_OFFSET:
+ case AL_DIRECT_FILTER_GAINHF_AUTO:
+ case AL_AUXILIARY_SEND_FILTER_GAIN_AUTO:
+ case AL_AUXILIARY_SEND_FILTER_GAINHF_AUTO:
+ case AL_DIRECT_CHANNELS_SOFT:
+ case AL_DISTANCE_MODEL:
+ case AL_SOURCE_RESAMPLER_SOFT:
+ case AL_SOURCE_SPATIALIZE_SOFT:
+ CHECKVAL(*values <= INT_MAX && *values >= INT_MIN);
+
+ ivals[0] = static_cast<ALint>(*values);
+ return SetSourceiv(Source, Context, prop, ivals);
+
+ /* 1x uint */
+ case AL_BUFFER:
+ case AL_DIRECT_FILTER:
+ CHECKVAL(*values <= UINT_MAX && *values >= 0);
+
+ ivals[0] = static_cast<ALuint>(*values);
+ return SetSourceiv(Source, Context, prop, ivals);
+
+ /* 3x uint */
+ case AL_AUXILIARY_SEND_FILTER:
+ CHECKVAL(values[0] <= UINT_MAX && values[0] >= 0 &&
+ values[1] <= UINT_MAX && values[1] >= 0 &&
+ values[2] <= UINT_MAX && values[2] >= 0);
+
+ ivals[0] = static_cast<ALuint>(values[0]);
+ ivals[1] = static_cast<ALuint>(values[1]);
+ ivals[2] = static_cast<ALuint>(values[2]);
+ return SetSourceiv(Source, Context, prop, ivals);
+
+ /* 1x float */
+ case AL_CONE_INNER_ANGLE:
+ case AL_CONE_OUTER_ANGLE:
+ case AL_PITCH:
+ case AL_GAIN:
+ case AL_MIN_GAIN:
+ case AL_MAX_GAIN:
+ case AL_REFERENCE_DISTANCE:
+ case AL_ROLLOFF_FACTOR:
+ case AL_CONE_OUTER_GAIN:
+ case AL_MAX_DISTANCE:
+ case AL_DOPPLER_FACTOR:
+ case AL_CONE_OUTER_GAINHF:
+ case AL_AIR_ABSORPTION_FACTOR:
+ case AL_ROOM_ROLLOFF_FACTOR:
+ case AL_SOURCE_RADIUS:
+ fvals[0] = static_cast<ALfloat>(*values);
+ return SetSourcefv(Source, Context, prop, fvals);
+
+ /* 3x float */
+ case AL_POSITION:
+ case AL_VELOCITY:
+ case AL_DIRECTION:
+ fvals[0] = static_cast<ALfloat>(values[0]);
+ fvals[1] = static_cast<ALfloat>(values[1]);
+ fvals[2] = static_cast<ALfloat>(values[2]);
+ return SetSourcefv(Source, Context, prop, fvals);
+
+ /* 6x float */
+ case AL_ORIENTATION:
+ fvals[0] = static_cast<ALfloat>(values[0]);
+ fvals[1] = static_cast<ALfloat>(values[1]);
+ fvals[2] = static_cast<ALfloat>(values[2]);
+ fvals[3] = static_cast<ALfloat>(values[3]);
+ fvals[4] = static_cast<ALfloat>(values[4]);
+ fvals[5] = static_cast<ALfloat>(values[5]);
+ return SetSourcefv(Source, Context, prop, fvals);
+
+ case AL_SEC_OFFSET_LATENCY_SOFT:
+ case AL_SEC_OFFSET_CLOCK_SOFT:
+ case AL_STEREO_ANGLES:
+ break;
+ }
+
+ ERR("Unexpected property: 0x%04x\n", prop);
+ SETERR_RETURN(Context, AL_INVALID_ENUM, AL_FALSE, "Invalid source integer64 property 0x%04x",
+ prop);
+}
+
+#undef CHECKVAL
+
+
+ALboolean GetSourcedv(ALsource *Source, ALCcontext *Context, SourceProp prop, ALdouble *values);
+ALboolean GetSourceiv(ALsource *Source, ALCcontext *Context, SourceProp prop, ALint *values);
+ALboolean GetSourcei64v(ALsource *Source, ALCcontext *Context, SourceProp prop, ALint64SOFT *values);
+
+ALboolean GetSourcedv(ALsource *Source, ALCcontext *Context, SourceProp prop, ALdouble *values)
+{
+ ALCdevice *device{Context->Device};
+ ClockLatency clocktime;
+ std::chrono::nanoseconds srcclock;
+ ALint ivals[3];
+ ALboolean err;
+
+ switch(prop)
+ {
+ case AL_GAIN:
+ *values = Source->Gain;
+ return AL_TRUE;
+
+ case AL_PITCH:
+ *values = Source->Pitch;
+ return AL_TRUE;
+
+ case AL_MAX_DISTANCE:
+ *values = Source->MaxDistance;
+ return AL_TRUE;
+
+ case AL_ROLLOFF_FACTOR:
+ *values = Source->RolloffFactor;
+ return AL_TRUE;
+
+ case AL_REFERENCE_DISTANCE:
+ *values = Source->RefDistance;
+ return AL_TRUE;
+
+ case AL_CONE_INNER_ANGLE:
+ *values = Source->InnerAngle;
+ return AL_TRUE;
+
+ case AL_CONE_OUTER_ANGLE:
+ *values = Source->OuterAngle;
+ return AL_TRUE;
+
+ case AL_MIN_GAIN:
+ *values = Source->MinGain;
+ return AL_TRUE;
+
+ case AL_MAX_GAIN:
+ *values = Source->MaxGain;
+ return AL_TRUE;
+
+ case AL_CONE_OUTER_GAIN:
+ *values = Source->OuterGain;
+ return AL_TRUE;
+
+ case AL_SEC_OFFSET:
+ case AL_SAMPLE_OFFSET:
+ case AL_BYTE_OFFSET:
+ *values = GetSourceOffset(Source, prop, Context);
+ return AL_TRUE;
+
+ case AL_CONE_OUTER_GAINHF:
+ *values = Source->OuterGainHF;
+ return AL_TRUE;
+
+ case AL_AIR_ABSORPTION_FACTOR:
+ *values = Source->AirAbsorptionFactor;
+ return AL_TRUE;
+
+ case AL_ROOM_ROLLOFF_FACTOR:
+ *values = Source->RoomRolloffFactor;
+ return AL_TRUE;
+
+ case AL_DOPPLER_FACTOR:
+ *values = Source->DopplerFactor;
+ return AL_TRUE;
+
+ case AL_SOURCE_RADIUS:
+ *values = Source->Radius;
+ return AL_TRUE;
+
+ case AL_STEREO_ANGLES:
+ values[0] = Source->StereoPan[0];
+ values[1] = Source->StereoPan[1];
+ return AL_TRUE;
+
+ case AL_SEC_OFFSET_LATENCY_SOFT:
+ /* Get the source offset with the clock time first. Then get the
+ * clock time with the device latency. Order is important.
+ */
+ values[0] = GetSourceSecOffset(Source, Context, &srcclock);
+ { std::lock_guard<std::mutex> _{device->StateLock};
+ clocktime = GetClockLatency(device);
+ }
+ if(srcclock == clocktime.ClockTime)
+ values[1] = static_cast<ALdouble>(clocktime.Latency.count()) / 1000000000.0;
+ else
+ {
+ /* If the clock time incremented, reduce the latency by that
+ * much since it's that much closer to the source offset it got
+ * earlier.
+ */
+ std::chrono::nanoseconds diff = clocktime.ClockTime - srcclock;
+ values[1] = static_cast<ALdouble>((clocktime.Latency - std::min(clocktime.Latency, diff)).count()) /
+ 1000000000.0;
+ }
+ return AL_TRUE;
+
+ case AL_SEC_OFFSET_CLOCK_SOFT:
+ values[0] = GetSourceSecOffset(Source, Context, &srcclock);
+ values[1] = srcclock.count() / 1000000000.0;
+ return AL_TRUE;
+
+ case AL_POSITION:
+ values[0] = Source->Position[0];
+ values[1] = Source->Position[1];
+ values[2] = Source->Position[2];
+ return AL_TRUE;
+
+ case AL_VELOCITY:
+ values[0] = Source->Velocity[0];
+ values[1] = Source->Velocity[1];
+ values[2] = Source->Velocity[2];
+ return AL_TRUE;
+
+ case AL_DIRECTION:
+ values[0] = Source->Direction[0];
+ values[1] = Source->Direction[1];
+ values[2] = Source->Direction[2];
+ return AL_TRUE;
+
+ case AL_ORIENTATION:
+ values[0] = Source->OrientAt[0];
+ values[1] = Source->OrientAt[1];
+ values[2] = Source->OrientAt[2];
+ values[3] = Source->OrientUp[0];
+ values[4] = Source->OrientUp[1];
+ values[5] = Source->OrientUp[2];
+ return AL_TRUE;
+
+ /* 1x int */
+ case AL_SOURCE_RELATIVE:
+ case AL_LOOPING:
+ case AL_SOURCE_STATE:
+ case AL_BUFFERS_QUEUED:
+ case AL_BUFFERS_PROCESSED:
+ case AL_SOURCE_TYPE:
+ case AL_DIRECT_FILTER_GAINHF_AUTO:
+ case AL_AUXILIARY_SEND_FILTER_GAIN_AUTO:
+ case AL_AUXILIARY_SEND_FILTER_GAINHF_AUTO:
+ case AL_DIRECT_CHANNELS_SOFT:
+ case AL_DISTANCE_MODEL:
+ case AL_SOURCE_RESAMPLER_SOFT:
+ case AL_SOURCE_SPATIALIZE_SOFT:
+ if((err=GetSourceiv(Source, Context, prop, ivals)) != AL_FALSE)
+ *values = static_cast<ALdouble>(ivals[0]);
+ return err;
+
+ case AL_BUFFER:
+ case AL_DIRECT_FILTER:
+ case AL_AUXILIARY_SEND_FILTER:
+ case AL_SAMPLE_OFFSET_LATENCY_SOFT:
+ case AL_SAMPLE_OFFSET_CLOCK_SOFT:
+ break;
+ }
+
+ ERR("Unexpected property: 0x%04x\n", prop);
+ SETERR_RETURN(Context, AL_INVALID_ENUM, AL_FALSE, "Invalid source double property 0x%04x",
+ prop);
+}
+
+ALboolean GetSourceiv(ALsource *Source, ALCcontext *Context, SourceProp prop, ALint *values)
+{
+ ALbufferlistitem *BufferList;
+ ALdouble dvals[6];
+ ALboolean err;
+
+ switch(prop)
+ {
+ case AL_SOURCE_RELATIVE:
+ *values = Source->HeadRelative;
+ return AL_TRUE;
+
+ case AL_LOOPING:
+ *values = Source->Looping;
+ return AL_TRUE;
+
+ case AL_BUFFER:
+ BufferList = (Source->SourceType == AL_STATIC) ? Source->queue : nullptr;
+ *values = (BufferList && BufferList->num_buffers >= 1 && BufferList->buffers[0]) ?
+ BufferList->buffers[0]->id : 0;
+ return AL_TRUE;
+
+ case AL_SOURCE_STATE:
+ *values = GetSourceState(Source, GetSourceVoice(Source, Context));
+ return AL_TRUE;
+
+ case AL_BUFFERS_QUEUED:
+ if(!(BufferList=Source->queue))
+ *values = 0;
+ else
+ {
+ ALsizei count = 0;
+ do {
+ count += BufferList->num_buffers;
+ BufferList = BufferList->next.load(std::memory_order_relaxed);
+ } while(BufferList != nullptr);
+ *values = count;
+ }
+ return AL_TRUE;
+
+ case AL_BUFFERS_PROCESSED:
+ if(Source->Looping || Source->SourceType != AL_STREAMING)
+ {
+ /* Buffers on a looping source are in a perpetual state of
+ * PENDING, so don't report any as PROCESSED */
+ *values = 0;
+ }
+ else
+ {
+ const ALbufferlistitem *BufferList{Source->queue};
+ const ALbufferlistitem *Current{nullptr};
+ ALsizei played{0};
+
+ ALvoice *voice{GetSourceVoice(Source, Context)};
+ if(voice != nullptr)
+ Current = voice->mCurrentBuffer.load(std::memory_order_relaxed);
+ else if(Source->state == AL_INITIAL)
+ Current = BufferList;
+
+ while(BufferList && BufferList != Current)
+ {
+ played += BufferList->num_buffers;
+ BufferList = BufferList->next.load(std::memory_order_relaxed);
+ }
+ *values = played;
+ }
+ return AL_TRUE;
+
+ case AL_SOURCE_TYPE:
+ *values = Source->SourceType;
+ return AL_TRUE;
+
+ case AL_DIRECT_FILTER_GAINHF_AUTO:
+ *values = Source->DryGainHFAuto;
+ return AL_TRUE;
+
+ case AL_AUXILIARY_SEND_FILTER_GAIN_AUTO:
+ *values = Source->WetGainAuto;
+ return AL_TRUE;
+
+ case AL_AUXILIARY_SEND_FILTER_GAINHF_AUTO:
+ *values = Source->WetGainHFAuto;
+ return AL_TRUE;
+
+ case AL_DIRECT_CHANNELS_SOFT:
+ *values = Source->DirectChannels;
+ return AL_TRUE;
+
+ case AL_DISTANCE_MODEL:
+ *values = static_cast<int>(Source->mDistanceModel);
+ return AL_TRUE;
+
+ case AL_SOURCE_RESAMPLER_SOFT:
+ *values = Source->mResampler;
+ return AL_TRUE;
+
+ case AL_SOURCE_SPATIALIZE_SOFT:
+ *values = Source->mSpatialize;
+ return AL_TRUE;
+
+ /* 1x float/double */
+ case AL_CONE_INNER_ANGLE:
+ case AL_CONE_OUTER_ANGLE:
+ case AL_PITCH:
+ case AL_GAIN:
+ case AL_MIN_GAIN:
+ case AL_MAX_GAIN:
+ case AL_REFERENCE_DISTANCE:
+ case AL_ROLLOFF_FACTOR:
+ case AL_CONE_OUTER_GAIN:
+ case AL_MAX_DISTANCE:
+ case AL_SEC_OFFSET:
+ case AL_SAMPLE_OFFSET:
+ case AL_BYTE_OFFSET:
+ case AL_DOPPLER_FACTOR:
+ case AL_AIR_ABSORPTION_FACTOR:
+ case AL_ROOM_ROLLOFF_FACTOR:
+ case AL_CONE_OUTER_GAINHF:
+ case AL_SOURCE_RADIUS:
+ if((err=GetSourcedv(Source, Context, prop, dvals)) != AL_FALSE)
+ *values = static_cast<ALint>(dvals[0]);
+ return err;
+
+ /* 3x float/double */
+ case AL_POSITION:
+ case AL_VELOCITY:
+ case AL_DIRECTION:
+ if((err=GetSourcedv(Source, Context, prop, dvals)) != AL_FALSE)
+ {
+ values[0] = static_cast<ALint>(dvals[0]);
+ values[1] = static_cast<ALint>(dvals[1]);
+ values[2] = static_cast<ALint>(dvals[2]);
+ }
+ return err;
+
+ /* 6x float/double */
+ case AL_ORIENTATION:
+ if((err=GetSourcedv(Source, Context, prop, dvals)) != AL_FALSE)
+ {
+ values[0] = static_cast<ALint>(dvals[0]);
+ values[1] = static_cast<ALint>(dvals[1]);
+ values[2] = static_cast<ALint>(dvals[2]);
+ values[3] = static_cast<ALint>(dvals[3]);
+ values[4] = static_cast<ALint>(dvals[4]);
+ values[5] = static_cast<ALint>(dvals[5]);
+ }
+ return err;
+
+ case AL_SAMPLE_OFFSET_LATENCY_SOFT:
+ case AL_SAMPLE_OFFSET_CLOCK_SOFT:
+ break; /* i64 only */
+ case AL_SEC_OFFSET_LATENCY_SOFT:
+ case AL_SEC_OFFSET_CLOCK_SOFT:
+ break; /* Double only */
+ case AL_STEREO_ANGLES:
+ break; /* Float/double only */
+
+ case AL_DIRECT_FILTER:
+ case AL_AUXILIARY_SEND_FILTER:
+ break; /* ??? */
+ }
+
+ ERR("Unexpected property: 0x%04x\n", prop);
+ SETERR_RETURN(Context, AL_INVALID_ENUM, AL_FALSE, "Invalid source integer property 0x%04x",
+ prop);
+}
+
+ALboolean GetSourcei64v(ALsource *Source, ALCcontext *Context, SourceProp prop, ALint64SOFT *values)
+{
+ ALCdevice *device = Context->Device;
+ ClockLatency clocktime;
+ std::chrono::nanoseconds srcclock;
+ ALdouble dvals[6];
+ ALint ivals[3];
+ ALboolean err;
+
+ switch(prop)
+ {
+ case AL_SAMPLE_OFFSET_LATENCY_SOFT:
+ /* Get the source offset with the clock time first. Then get the
+ * clock time with the device latency. Order is important.
+ */
+ values[0] = GetSourceSampleOffset(Source, Context, &srcclock);
+ { std::lock_guard<std::mutex> _{device->StateLock};
+ clocktime = GetClockLatency(device);
+ }
+ if(srcclock == clocktime.ClockTime)
+ values[1] = clocktime.Latency.count();
+ else
+ {
+ /* If the clock time incremented, reduce the latency by that
+ * much since it's that much closer to the source offset it got
+ * earlier.
+ */
+ auto diff = clocktime.ClockTime - srcclock;
+ values[1] = (clocktime.Latency - std::min(clocktime.Latency, diff)).count();
+ }
+ return AL_TRUE;
+
+ case AL_SAMPLE_OFFSET_CLOCK_SOFT:
+ values[0] = GetSourceSampleOffset(Source, Context, &srcclock);
+ values[1] = srcclock.count();
+ return AL_TRUE;
+
+ /* 1x float/double */
+ case AL_CONE_INNER_ANGLE:
+ case AL_CONE_OUTER_ANGLE:
+ case AL_PITCH:
+ case AL_GAIN:
+ case AL_MIN_GAIN:
+ case AL_MAX_GAIN:
+ case AL_REFERENCE_DISTANCE:
+ case AL_ROLLOFF_FACTOR:
+ case AL_CONE_OUTER_GAIN:
+ case AL_MAX_DISTANCE:
+ case AL_SEC_OFFSET:
+ case AL_SAMPLE_OFFSET:
+ case AL_BYTE_OFFSET:
+ case AL_DOPPLER_FACTOR:
+ case AL_AIR_ABSORPTION_FACTOR:
+ case AL_ROOM_ROLLOFF_FACTOR:
+ case AL_CONE_OUTER_GAINHF:
+ case AL_SOURCE_RADIUS:
+ if((err=GetSourcedv(Source, Context, prop, dvals)) != AL_FALSE)
+ *values = static_cast<int64_t>(dvals[0]);
+ return err;
+
+ /* 3x float/double */
+ case AL_POSITION:
+ case AL_VELOCITY:
+ case AL_DIRECTION:
+ if((err=GetSourcedv(Source, Context, prop, dvals)) != AL_FALSE)
+ {
+ values[0] = static_cast<int64_t>(dvals[0]);
+ values[1] = static_cast<int64_t>(dvals[1]);
+ values[2] = static_cast<int64_t>(dvals[2]);
+ }
+ return err;
+
+ /* 6x float/double */
+ case AL_ORIENTATION:
+ if((err=GetSourcedv(Source, Context, prop, dvals)) != AL_FALSE)
+ {
+ values[0] = static_cast<int64_t>(dvals[0]);
+ values[1] = static_cast<int64_t>(dvals[1]);
+ values[2] = static_cast<int64_t>(dvals[2]);
+ values[3] = static_cast<int64_t>(dvals[3]);
+ values[4] = static_cast<int64_t>(dvals[4]);
+ values[5] = static_cast<int64_t>(dvals[5]);
+ }
+ return err;
+
+ /* 1x int */
+ case AL_SOURCE_RELATIVE:
+ case AL_LOOPING:
+ case AL_SOURCE_STATE:
+ case AL_BUFFERS_QUEUED:
+ case AL_BUFFERS_PROCESSED:
+ case AL_SOURCE_TYPE:
+ case AL_DIRECT_FILTER_GAINHF_AUTO:
+ case AL_AUXILIARY_SEND_FILTER_GAIN_AUTO:
+ case AL_AUXILIARY_SEND_FILTER_GAINHF_AUTO:
+ case AL_DIRECT_CHANNELS_SOFT:
+ case AL_DISTANCE_MODEL:
+ case AL_SOURCE_RESAMPLER_SOFT:
+ case AL_SOURCE_SPATIALIZE_SOFT:
+ if((err=GetSourceiv(Source, Context, prop, ivals)) != AL_FALSE)
+ *values = ivals[0];
+ return err;
+
+ /* 1x uint */
+ case AL_BUFFER:
+ case AL_DIRECT_FILTER:
+ if((err=GetSourceiv(Source, Context, prop, ivals)) != AL_FALSE)
+ *values = static_cast<ALuint>(ivals[0]);
+ return err;
+
+ /* 3x uint */
+ case AL_AUXILIARY_SEND_FILTER:
+ if((err=GetSourceiv(Source, Context, prop, ivals)) != AL_FALSE)
+ {
+ values[0] = static_cast<ALuint>(ivals[0]);
+ values[1] = static_cast<ALuint>(ivals[1]);
+ values[2] = static_cast<ALuint>(ivals[2]);
+ }
+ return err;
+
+ case AL_SEC_OFFSET_LATENCY_SOFT:
+ case AL_SEC_OFFSET_CLOCK_SOFT:
+ break; /* Double only */
+ case AL_STEREO_ANGLES:
+ break; /* Float/double only */
+ }
+
+ ERR("Unexpected property: 0x%04x\n", prop);
+ SETERR_RETURN(Context, AL_INVALID_ENUM, AL_FALSE, "Invalid source integer64 property 0x%04x",
+ prop);
+}
+
+} // namespace
+
+AL_API ALvoid AL_APIENTRY alGenSources(ALsizei n, ALuint *sources)
+START_API_FUNC
+{
+ ContextRef context{GetContextRef()};
+ if(UNLIKELY(!context)) return;
+
+ if(n < 0)
+ alSetError(context.get(), AL_INVALID_VALUE, "Generating %d sources", n);
+ else if(n == 1)
+ {
+ ALsource *source = AllocSource(context.get());
+ if(source) sources[0] = source->id;
+ }
+ else
+ {
+ al::vector<ALuint> tempids(n);
+ auto alloc_end = std::find_if_not(tempids.begin(), tempids.end(),
+ [&context](ALuint &id) -> bool
+ {
+ ALsource *source{AllocSource(context.get())};
+ if(!source) return false;
+ id = source->id;
+ return true;
+ }
+ );
+ if(alloc_end != tempids.end())
+ alDeleteSources(static_cast<ALsizei>(std::distance(tempids.begin(), alloc_end)),
+ tempids.data());
+ else
+ std::copy(tempids.cbegin(), tempids.cend(), sources);
+ }
+}
+END_API_FUNC
+
+AL_API ALvoid AL_APIENTRY alDeleteSources(ALsizei n, const ALuint *sources)
+START_API_FUNC
+{
+ ContextRef context{GetContextRef()};
+ if(UNLIKELY(!context)) return;
+
+ if(n < 0)
+ SETERR_RETURN(context.get(), AL_INVALID_VALUE,, "Deleting %d sources", n);
+
+ std::lock_guard<std::mutex> _{context->SourceLock};
+
+ /* Check that all Sources are valid */
+ const ALuint *sources_end = sources + n;
+ auto invsrc = std::find_if_not(sources, sources_end,
+ [&context](ALuint sid) -> bool
+ {
+ if(!LookupSource(context.get(), sid))
+ {
+ alSetError(context.get(), AL_INVALID_NAME, "Invalid source ID %u", sid);
+ return false;
+ }
+ return true;
+ }
+ );
+ if(LIKELY(invsrc == sources_end))
+ {
+ /* All good. Delete source IDs. */
+ std::for_each(sources, sources_end,
+ [&context](ALuint sid) -> void
+ {
+ ALsource *src{LookupSource(context.get(), sid)};
+ if(src) FreeSource(context.get(), src);
+ }
+ );
+ }
+}
+END_API_FUNC
+
+AL_API ALboolean AL_APIENTRY alIsSource(ALuint source)
+START_API_FUNC
+{
+ ContextRef context{GetContextRef()};
+ if(LIKELY(context))
+ {
+ std::lock_guard<std::mutex> _{context->SourceLock};
+ if(LookupSource(context.get(), source) != nullptr)
+ return AL_TRUE;
+ }
+ return AL_FALSE;
+}
+END_API_FUNC
+
+
+AL_API ALvoid AL_APIENTRY alSourcef(ALuint source, ALenum param, ALfloat value)
+START_API_FUNC
+{
+ ContextRef context{GetContextRef()};
+ if(UNLIKELY(!context)) return;
+
+ std::lock_guard<std::mutex> _{context->PropLock};
+ std::lock_guard<std::mutex> __{context->SourceLock};
+ ALsource *Source = LookupSource(context.get(), source);
+ if(UNLIKELY(!Source))
+ alSetError(context.get(), AL_INVALID_NAME, "Invalid source ID %u", source);
+ else if(FloatValsByProp(param) != 1)
+ alSetError(context.get(), AL_INVALID_ENUM, "Invalid float property 0x%04x", param);
+ else
+ SetSourcefv(Source, context.get(), static_cast<SourceProp>(param), &value);
+}
+END_API_FUNC
+
+AL_API ALvoid AL_APIENTRY alSource3f(ALuint source, ALenum param, ALfloat value1, ALfloat value2, ALfloat value3)
+START_API_FUNC
+{
+ ContextRef context{GetContextRef()};
+ if(UNLIKELY(!context)) return;
+
+ std::lock_guard<std::mutex> _{context->PropLock};
+ std::lock_guard<std::mutex> __{context->SourceLock};
+ ALsource *Source = LookupSource(context.get(), source);
+ if(UNLIKELY(!Source))
+ alSetError(context.get(), AL_INVALID_NAME, "Invalid source ID %u", source);
+ else if(FloatValsByProp(param) != 3)
+ alSetError(context.get(), AL_INVALID_ENUM, "Invalid 3-float property 0x%04x", param);
+ else
+ {
+ ALfloat fvals[3] = { value1, value2, value3 };
+ SetSourcefv(Source, context.get(), static_cast<SourceProp>(param), fvals);
+ }
+}
+END_API_FUNC
+
+AL_API ALvoid AL_APIENTRY alSourcefv(ALuint source, ALenum param, const ALfloat *values)
+START_API_FUNC
+{
+ ContextRef context{GetContextRef()};
+ if(UNLIKELY(!context)) return;
+
+ std::lock_guard<std::mutex> _{context->PropLock};
+ std::lock_guard<std::mutex> __{context->SourceLock};
+ ALsource *Source = LookupSource(context.get(), source);
+ if(UNLIKELY(!Source))
+ alSetError(context.get(), AL_INVALID_NAME, "Invalid source ID %u", source);
+ else if(!values)
+ alSetError(context.get(), AL_INVALID_VALUE, "NULL pointer");
+ else if(FloatValsByProp(param) < 1)
+ alSetError(context.get(), AL_INVALID_ENUM, "Invalid float-vector property 0x%04x", param);
+ else
+ SetSourcefv(Source, context.get(), static_cast<SourceProp>(param), values);
+}
+END_API_FUNC
+
+
+AL_API ALvoid AL_APIENTRY alSourcedSOFT(ALuint source, ALenum param, ALdouble value)
+START_API_FUNC
+{
+ ContextRef context{GetContextRef()};
+ if(UNLIKELY(!context)) return;
+
+ std::lock_guard<std::mutex> _{context->PropLock};
+ std::lock_guard<std::mutex> __{context->SourceLock};
+ ALsource *Source = LookupSource(context.get(), source);
+ if(UNLIKELY(!Source))
+ alSetError(context.get(), AL_INVALID_NAME, "Invalid source ID %u", source);
+ else if(DoubleValsByProp(param) != 1)
+ alSetError(context.get(), AL_INVALID_ENUM, "Invalid double property 0x%04x", param);
+ else
+ {
+ ALfloat fval = static_cast<ALfloat>(value);
+ SetSourcefv(Source, context.get(), static_cast<SourceProp>(param), &fval);
+ }
+}
+END_API_FUNC
+
+AL_API ALvoid AL_APIENTRY alSource3dSOFT(ALuint source, ALenum param, ALdouble value1, ALdouble value2, ALdouble value3)
+START_API_FUNC
+{
+ ContextRef context{GetContextRef()};
+ if(UNLIKELY(!context)) return;
+
+ std::lock_guard<std::mutex> _{context->PropLock};
+ std::lock_guard<std::mutex> __{context->SourceLock};
+ ALsource *Source = LookupSource(context.get(), source);
+ if(UNLIKELY(!Source))
+ alSetError(context.get(), AL_INVALID_NAME, "Invalid source ID %u", source);
+ else if(DoubleValsByProp(param) != 3)
+ alSetError(context.get(), AL_INVALID_ENUM, "Invalid 3-double property 0x%04x", param);
+ else {
+ ALfloat fvals[3] = {static_cast<ALfloat>(value1),
+ static_cast<ALfloat>(value2),
+ static_cast<ALfloat>(value3)};
+ SetSourcefv(Source, context.get(), static_cast<SourceProp>(param), fvals);
+ }
+}
+END_API_FUNC
+
+AL_API ALvoid AL_APIENTRY alSourcedvSOFT(ALuint source, ALenum param, const ALdouble *values)
+START_API_FUNC
+{
+ ContextRef context{GetContextRef()};
+ if(UNLIKELY(!context)) return;
+
+ std::lock_guard<std::mutex> _{context->PropLock};
+ std::lock_guard<std::mutex> __{context->SourceLock};
+ ALsource *Source = LookupSource(context.get(), source);
+ if(UNLIKELY(!Source))
+ alSetError(context.get(), AL_INVALID_NAME, "Invalid source ID %u", source);
+ else if(!values)
+ alSetError(context.get(), AL_INVALID_VALUE, "NULL pointer");
+ else
+ {
+ ALint count{DoubleValsByProp(param)};
+ if(count < 1 || count > 6)
+ alSetError(context.get(), AL_INVALID_ENUM, "Invalid double-vector property 0x%04x", param);
+ else
+ {
+ ALfloat fvals[6];
+ ALint i;
+
+ for(i = 0;i < count;i++)
+ fvals[i] = static_cast<ALfloat>(values[i]);
+ SetSourcefv(Source, context.get(), static_cast<SourceProp>(param), fvals);
+ }
+ }
+}
+END_API_FUNC
+
+
+AL_API ALvoid AL_APIENTRY alSourcei(ALuint source, ALenum param, ALint value)
+START_API_FUNC
+{
+ ContextRef context{GetContextRef()};
+ if(UNLIKELY(!context)) return;
+
+ std::lock_guard<std::mutex> _{context->PropLock};
+ std::lock_guard<std::mutex> __{context->SourceLock};
+ ALsource *Source = LookupSource(context.get(), source);
+ if(UNLIKELY(!Source))
+ alSetError(context.get(), AL_INVALID_NAME, "Invalid source ID %u", source);
+ else if(IntValsByProp(param) != 1)
+ alSetError(context.get(), AL_INVALID_ENUM, "Invalid integer property 0x%04x", param);
+ else
+ SetSourceiv(Source, context.get(), static_cast<SourceProp>(param), &value);
+}
+END_API_FUNC
+
+AL_API void AL_APIENTRY alSource3i(ALuint source, ALenum param, ALint value1, ALint value2, ALint value3)
+START_API_FUNC
+{
+ ContextRef context{GetContextRef()};
+ if(UNLIKELY(!context)) return;
+
+ std::lock_guard<std::mutex> _{context->PropLock};
+ std::lock_guard<std::mutex> __{context->SourceLock};
+ ALsource *Source = LookupSource(context.get(), source);
+ if(UNLIKELY(!Source))
+ alSetError(context.get(), AL_INVALID_NAME, "Invalid source ID %u", source);
+ else if(IntValsByProp(param) != 3)
+ alSetError(context.get(), AL_INVALID_ENUM, "Invalid 3-integer property 0x%04x", param);
+ else
+ {
+ ALint ivals[3] = { value1, value2, value3 };
+ SetSourceiv(Source, context.get(), static_cast<SourceProp>(param), ivals);
+ }
+}
+END_API_FUNC
+
+AL_API void AL_APIENTRY alSourceiv(ALuint source, ALenum param, const ALint *values)
+START_API_FUNC
+{
+ ContextRef context{GetContextRef()};
+ if(UNLIKELY(!context)) return;
+
+ std::lock_guard<std::mutex> _{context->PropLock};
+ std::lock_guard<std::mutex> __{context->SourceLock};
+ ALsource *Source = LookupSource(context.get(), source);
+ if(UNLIKELY(!Source))
+ alSetError(context.get(), AL_INVALID_NAME, "Invalid source ID %u", source);
+ else if(!values)
+ alSetError(context.get(), AL_INVALID_VALUE, "NULL pointer");
+ else if(IntValsByProp(param) < 1)
+ alSetError(context.get(), AL_INVALID_ENUM, "Invalid integer-vector property 0x%04x", param);
+ else
+ SetSourceiv(Source, context.get(), static_cast<SourceProp>(param), values);
+}
+END_API_FUNC
+
+
+AL_API ALvoid AL_APIENTRY alSourcei64SOFT(ALuint source, ALenum param, ALint64SOFT value)
+START_API_FUNC
+{
+ ContextRef context{GetContextRef()};
+ if(UNLIKELY(!context)) return;
+
+ std::lock_guard<std::mutex> _{context->PropLock};
+ std::lock_guard<std::mutex> __{context->SourceLock};
+ ALsource *Source{LookupSource(context.get(), source)};
+ if(UNLIKELY(!Source))
+ alSetError(context.get(), AL_INVALID_NAME, "Invalid source ID %u", source);
+ else if(Int64ValsByProp(param) != 1)
+ alSetError(context.get(), AL_INVALID_ENUM, "Invalid integer64 property 0x%04x", param);
+ else
+ SetSourcei64v(Source, context.get(), static_cast<SourceProp>(param), &value);
+}
+END_API_FUNC
+
+AL_API void AL_APIENTRY alSource3i64SOFT(ALuint source, ALenum param, ALint64SOFT value1, ALint64SOFT value2, ALint64SOFT value3)
+START_API_FUNC
+{
+ ContextRef context{GetContextRef()};
+ if(UNLIKELY(!context)) return;
+
+ std::lock_guard<std::mutex> _{context->PropLock};
+ std::lock_guard<std::mutex> __{context->SourceLock};
+ ALsource *Source{LookupSource(context.get(), source)};
+ if(UNLIKELY(!Source))
+ alSetError(context.get(), AL_INVALID_NAME, "Invalid source ID %u", source);
+ else if(Int64ValsByProp(param) != 3)
+ alSetError(context.get(), AL_INVALID_ENUM, "Invalid 3-integer64 property 0x%04x", param);
+ else
+ {
+ ALint64SOFT i64vals[3] = { value1, value2, value3 };
+ SetSourcei64v(Source, context.get(), static_cast<SourceProp>(param), i64vals);
+ }
+}
+END_API_FUNC
+
+AL_API void AL_APIENTRY alSourcei64vSOFT(ALuint source, ALenum param, const ALint64SOFT *values)
+START_API_FUNC
+{
+ ContextRef context{GetContextRef()};
+ if(UNLIKELY(!context)) return;
+
+ std::lock_guard<std::mutex> _{context->PropLock};
+ std::lock_guard<std::mutex> __{context->SourceLock};
+ ALsource *Source{LookupSource(context.get(), source)};
+ if(UNLIKELY(!Source))
+ alSetError(context.get(), AL_INVALID_NAME, "Invalid source ID %u", source);
+ else if(!values)
+ alSetError(context.get(), AL_INVALID_VALUE, "NULL pointer");
+ else if(Int64ValsByProp(param) < 1)
+ alSetError(context.get(), AL_INVALID_ENUM, "Invalid integer64-vector property 0x%04x", param);
+ else
+ SetSourcei64v(Source, context.get(), static_cast<SourceProp>(param), values);
+}
+END_API_FUNC
+
+
+AL_API ALvoid AL_APIENTRY alGetSourcef(ALuint source, ALenum param, ALfloat *value)
+START_API_FUNC
+{
+ ContextRef context{GetContextRef()};
+ if(UNLIKELY(!context)) return;
+
+ std::lock_guard<std::mutex> _{context->SourceLock};
+ ALsource *Source{LookupSource(context.get(), source)};
+ if(UNLIKELY(!Source))
+ alSetError(context.get(), AL_INVALID_NAME, "Invalid source ID %u", source);
+ else if(!value)
+ alSetError(context.get(), AL_INVALID_VALUE, "NULL pointer");
+ else if(FloatValsByProp(param) != 1)
+ alSetError(context.get(), AL_INVALID_ENUM, "Invalid float property 0x%04x", param);
+ else
+ {
+ ALdouble dval;
+ if(GetSourcedv(Source, context.get(), static_cast<SourceProp>(param), &dval))
+ *value = static_cast<ALfloat>(dval);
+ }
+}
+END_API_FUNC
+
+AL_API ALvoid AL_APIENTRY alGetSource3f(ALuint source, ALenum param, ALfloat *value1, ALfloat *value2, ALfloat *value3)
+START_API_FUNC
+{
+ ContextRef context{GetContextRef()};
+ if(UNLIKELY(!context)) return;
+
+ std::lock_guard<std::mutex> _{context->SourceLock};
+ ALsource *Source{LookupSource(context.get(), source)};
+ if(UNLIKELY(!Source))
+ alSetError(context.get(), AL_INVALID_NAME, "Invalid source ID %u", source);
+ else if(!(value1 && value2 && value3))
+ alSetError(context.get(), AL_INVALID_VALUE, "NULL pointer");
+ else if(FloatValsByProp(param) != 3)
+ alSetError(context.get(), AL_INVALID_ENUM, "Invalid 3-float property 0x%04x", param);
+ else
+ {
+ ALdouble dvals[3];
+ if(GetSourcedv(Source, context.get(), static_cast<SourceProp>(param), dvals))
+ {
+ *value1 = static_cast<ALfloat>(dvals[0]);
+ *value2 = static_cast<ALfloat>(dvals[1]);
+ *value3 = static_cast<ALfloat>(dvals[2]);
+ }
+ }
+}
+END_API_FUNC
+
+AL_API ALvoid AL_APIENTRY alGetSourcefv(ALuint source, ALenum param, ALfloat *values)
+START_API_FUNC
+{
+ ContextRef context{GetContextRef()};
+ if(UNLIKELY(!context)) return;
+
+ std::lock_guard<std::mutex> _{context->SourceLock};
+ ALsource *Source{LookupSource(context.get(), source)};
+ if(UNLIKELY(!Source))
+ alSetError(context.get(), AL_INVALID_NAME, "Invalid source ID %u", source);
+ else if(!values)
+ alSetError(context.get(), AL_INVALID_VALUE, "NULL pointer");
+ else
+ {
+ ALint count{FloatValsByProp(param)};
+ if(count < 1 && count > 6)
+ alSetError(context.get(), AL_INVALID_ENUM, "Invalid float-vector property 0x%04x", param);
+ else
+ {
+ ALdouble dvals[6];
+ if(GetSourcedv(Source, context.get(), static_cast<SourceProp>(param), dvals))
+ {
+ for(ALint i{0};i < count;i++)
+ values[i] = static_cast<ALfloat>(dvals[i]);
+ }
+ }
+ }
+}
+END_API_FUNC
+
+
+AL_API void AL_APIENTRY alGetSourcedSOFT(ALuint source, ALenum param, ALdouble *value)
+START_API_FUNC
+{
+ ContextRef context{GetContextRef()};
+ if(UNLIKELY(!context)) return;
+
+ std::lock_guard<std::mutex> _{context->SourceLock};
+ ALsource *Source{LookupSource(context.get(), source)};
+ if(UNLIKELY(!Source))
+ alSetError(context.get(), AL_INVALID_NAME, "Invalid source ID %u", source);
+ else if(!value)
+ alSetError(context.get(), AL_INVALID_VALUE, "NULL pointer");
+ else if(DoubleValsByProp(param) != 1)
+ alSetError(context.get(), AL_INVALID_ENUM, "Invalid double property 0x%04x", param);
+ else
+ GetSourcedv(Source, context.get(), static_cast<SourceProp>(param), value);
+}
+END_API_FUNC
+
+AL_API void AL_APIENTRY alGetSource3dSOFT(ALuint source, ALenum param, ALdouble *value1, ALdouble *value2, ALdouble *value3)
+START_API_FUNC
+{
+ ContextRef context{GetContextRef()};
+ if(UNLIKELY(!context)) return;
+
+ std::lock_guard<std::mutex> _{context->SourceLock};
+ ALsource *Source{LookupSource(context.get(), source)};
+ if(UNLIKELY(!Source))
+ alSetError(context.get(), AL_INVALID_NAME, "Invalid source ID %u", source);
+ else if(!(value1 && value2 && value3))
+ alSetError(context.get(), AL_INVALID_VALUE, "NULL pointer");
+ else if(DoubleValsByProp(param) != 3)
+ alSetError(context.get(), AL_INVALID_ENUM, "Invalid 3-double property 0x%04x", param);
+ else
+ {
+ ALdouble dvals[3];
+ if(GetSourcedv(Source, context.get(), static_cast<SourceProp>(param), dvals))
+ {
+ *value1 = dvals[0];
+ *value2 = dvals[1];
+ *value3 = dvals[2];
+ }
+ }
+}
+END_API_FUNC
+
+AL_API void AL_APIENTRY alGetSourcedvSOFT(ALuint source, ALenum param, ALdouble *values)
+START_API_FUNC
+{
+ ContextRef context{GetContextRef()};
+ if(UNLIKELY(!context)) return;
+
+ std::lock_guard<std::mutex> _{context->SourceLock};
+ ALsource *Source{LookupSource(context.get(), source)};
+ if(UNLIKELY(!Source))
+ alSetError(context.get(), AL_INVALID_NAME, "Invalid source ID %u", source);
+ else if(!values)
+ alSetError(context.get(), AL_INVALID_VALUE, "NULL pointer");
+ else if(DoubleValsByProp(param) < 1)
+ alSetError(context.get(), AL_INVALID_ENUM, "Invalid double-vector property 0x%04x", param);
+ else
+ GetSourcedv(Source, context.get(), static_cast<SourceProp>(param), values);
+}
+END_API_FUNC
+
+
+AL_API ALvoid AL_APIENTRY alGetSourcei(ALuint source, ALenum param, ALint *value)
+START_API_FUNC
+{
+ ContextRef context{GetContextRef()};
+ if(UNLIKELY(!context)) return;
+
+ std::lock_guard<std::mutex> _{context->SourceLock};
+ ALsource *Source{LookupSource(context.get(), source)};
+ if(UNLIKELY(!Source))
+ alSetError(context.get(), AL_INVALID_NAME, "Invalid source ID %u", source);
+ else if(!value)
+ alSetError(context.get(), AL_INVALID_VALUE, "NULL pointer");
+ else if(IntValsByProp(param) != 1)
+ alSetError(context.get(), AL_INVALID_ENUM, "Invalid integer property 0x%04x", param);
+ else
+ GetSourceiv(Source, context.get(), static_cast<SourceProp>(param), value);
+}
+END_API_FUNC
+
+AL_API void AL_APIENTRY alGetSource3i(ALuint source, ALenum param, ALint *value1, ALint *value2, ALint *value3)
+START_API_FUNC
+{
+ ContextRef context{GetContextRef()};
+ if(UNLIKELY(!context)) return;
+
+ std::lock_guard<std::mutex> _{context->SourceLock};
+ ALsource *Source{LookupSource(context.get(), source)};
+ if(UNLIKELY(!Source))
+ alSetError(context.get(), AL_INVALID_NAME, "Invalid source ID %u", source);
+ else if(!(value1 && value2 && value3))
+ alSetError(context.get(), AL_INVALID_VALUE, "NULL pointer");
+ else if(IntValsByProp(param) != 3)
+ alSetError(context.get(), AL_INVALID_ENUM, "Invalid 3-integer property 0x%04x", param);
+ else
+ {
+ ALint ivals[3];
+ if(GetSourceiv(Source, context.get(), static_cast<SourceProp>(param), ivals))
+ {
+ *value1 = ivals[0];
+ *value2 = ivals[1];
+ *value3 = ivals[2];
+ }
+ }
+}
+END_API_FUNC
+
+AL_API void AL_APIENTRY alGetSourceiv(ALuint source, ALenum param, ALint *values)
+START_API_FUNC
+{
+ ContextRef context{GetContextRef()};
+ if(UNLIKELY(!context)) return;
+
+ std::lock_guard<std::mutex> _{context->SourceLock};
+ ALsource *Source{LookupSource(context.get(), source)};
+ if(UNLIKELY(!Source))
+ alSetError(context.get(), AL_INVALID_NAME, "Invalid source ID %u", source);
+ else if(!values)
+ alSetError(context.get(), AL_INVALID_VALUE, "NULL pointer");
+ else if(IntValsByProp(param) < 1)
+ alSetError(context.get(), AL_INVALID_ENUM, "Invalid integer-vector property 0x%04x", param);
+ else
+ GetSourceiv(Source, context.get(), static_cast<SourceProp>(param), values);
+}
+END_API_FUNC
+
+
+AL_API void AL_APIENTRY alGetSourcei64SOFT(ALuint source, ALenum param, ALint64SOFT *value)
+START_API_FUNC
+{
+ ContextRef context{GetContextRef()};
+ if(UNLIKELY(!context)) return;
+
+ std::lock_guard<std::mutex> _{context->SourceLock};
+ ALsource *Source{LookupSource(context.get(), source)};
+ if(UNLIKELY(!Source))
+ alSetError(context.get(), AL_INVALID_NAME, "Invalid source ID %u", source);
+ else if(!value)
+ alSetError(context.get(), AL_INVALID_VALUE, "NULL pointer");
+ else if(Int64ValsByProp(param) != 1)
+ alSetError(context.get(), AL_INVALID_ENUM, "Invalid integer64 property 0x%04x", param);
+ else
+ GetSourcei64v(Source, context.get(), static_cast<SourceProp>(param), value);
+}
+END_API_FUNC
+
+AL_API void AL_APIENTRY alGetSource3i64SOFT(ALuint source, ALenum param, ALint64SOFT *value1, ALint64SOFT *value2, ALint64SOFT *value3)
+START_API_FUNC
+{
+ ContextRef context{GetContextRef()};
+ if(UNLIKELY(!context)) return;
+
+ std::lock_guard<std::mutex> _{context->SourceLock};
+ ALsource *Source{LookupSource(context.get(), source)};
+ if(UNLIKELY(!Source))
+ alSetError(context.get(), AL_INVALID_NAME, "Invalid source ID %u", source);
+ else if(!(value1 && value2 && value3))
+ alSetError(context.get(), AL_INVALID_VALUE, "NULL pointer");
+ else if(Int64ValsByProp(param) != 3)
+ alSetError(context.get(), AL_INVALID_ENUM, "Invalid 3-integer64 property 0x%04x", param);
+ else
+ {
+ ALint64SOFT i64vals[3];
+ if(GetSourcei64v(Source, context.get(), static_cast<SourceProp>(param), i64vals))
+ {
+ *value1 = i64vals[0];
+ *value2 = i64vals[1];
+ *value3 = i64vals[2];
+ }
+ }
+}
+END_API_FUNC
+
+AL_API void AL_APIENTRY alGetSourcei64vSOFT(ALuint source, ALenum param, ALint64SOFT *values)
+START_API_FUNC
+{
+ ContextRef context{GetContextRef()};
+ if(UNLIKELY(!context)) return;
+
+ std::lock_guard<std::mutex> _{context->SourceLock};
+ ALsource *Source{LookupSource(context.get(), source)};
+ if(UNLIKELY(!Source))
+ alSetError(context.get(), AL_INVALID_NAME, "Invalid source ID %u", source);
+ else if(!values)
+ alSetError(context.get(), AL_INVALID_VALUE, "NULL pointer");
+ else if(Int64ValsByProp(param) < 1)
+ alSetError(context.get(), AL_INVALID_ENUM, "Invalid integer64-vector property 0x%04x", param);
+ else
+ GetSourcei64v(Source, context.get(), static_cast<SourceProp>(param), values);
+}
+END_API_FUNC
+
+
+AL_API ALvoid AL_APIENTRY alSourcePlay(ALuint source)
+START_API_FUNC
+{ alSourcePlayv(1, &source); }
+END_API_FUNC
+
+AL_API ALvoid AL_APIENTRY alSourcePlayv(ALsizei n, const ALuint *sources)
+START_API_FUNC
+{
+ ContextRef context{GetContextRef()};
+ if(UNLIKELY(!context)) return;
+
+ if(n < 0)
+ SETERR_RETURN(context.get(), AL_INVALID_VALUE,, "Playing %d sources", n);
+ if(n == 0) return;
+
+ al::vector<ALsource*> extra_sources;
+ std::array<ALsource*,16> source_storage;
+ ALsource **srchandles{source_storage.data()};
+ if(UNLIKELY(static_cast<ALuint>(n) > source_storage.size()))
+ {
+ extra_sources.resize(n);
+ srchandles = extra_sources.data();
+ }
+
+ std::lock_guard<std::mutex> _{context->SourceLock};
+ for(ALsizei i{0};i < n;i++)
+ {
+ srchandles[i] = LookupSource(context.get(), sources[i]);
+ if(!srchandles[i])
+ SETERR_RETURN(context.get(), AL_INVALID_NAME,, "Invalid source ID %u", sources[i]);
+ }
+
+ ALCdevice *device{context->Device};
+ BackendLockGuard __{*device->Backend};
+ /* If the device is disconnected, go right to stopped. */
+ if(UNLIKELY(!device->Connected.load(std::memory_order_acquire)))
+ {
+ /* TODO: Send state change event? */
+ std::for_each(srchandles, srchandles+n,
+ [](ALsource *source) -> void
+ {
+ source->OffsetType = AL_NONE;
+ source->Offset = 0.0;
+ source->state = AL_STOPPED;
+ }
+ );
+ return;
+ }
+
+ /* Count the number of reusable voices. */
+ auto voices_end = context->Voices->begin() +
+ context->VoiceCount.load(std::memory_order_relaxed);
+ auto free_voices = std::accumulate(context->Voices->begin(), voices_end, ALsizei{0},
+ [](const ALsizei count, const ALvoice &voice) noexcept -> ALsizei
+ {
+ if(voice.mPlayState.load(std::memory_order_acquire) == ALvoice::Stopped &&
+ voice.mSourceID.load(std::memory_order_relaxed) == 0u)
+ return count + 1;
+ return count;
+ }
+ );
+ if(UNLIKELY(n > free_voices))
+ {
+ /* Increment the number of voices to handle the request. */
+ const ALuint need_voices{static_cast<ALuint>(n) - free_voices};
+ const size_t rem_voices{context->Voices->size() -
+ context->VoiceCount.load(std::memory_order_relaxed)};
+
+ if(UNLIKELY(need_voices > rem_voices))
+ {
+ /* Allocate more voices to get enough. */
+ const size_t alloc_count{need_voices - rem_voices};
+ if(UNLIKELY(context->Voices->size() > std::numeric_limits<ALsizei>::max()-alloc_count))
+ SETERR_RETURN(context.get(), AL_OUT_OF_MEMORY,,
+ "Overflow increasing voice count to %zu + %zu", context->Voices->size(),
+ alloc_count);
+
+ const size_t newcount{context->Voices->size() + alloc_count};
+ AllocateVoices(context.get(), newcount);
+ }
+
+ context->VoiceCount.fetch_add(need_voices, std::memory_order_relaxed);
+ }
+
+ auto start_source = [&context,device](ALsource *source) -> void
+ {
+ /* Check that there is a queue containing at least one valid, non zero
+ * length buffer.
+ */
+ ALbufferlistitem *BufferList{source->queue};
+ while(BufferList && BufferList->max_samples == 0)
+ BufferList = BufferList->next.load(std::memory_order_relaxed);
+
+ /* If there's nothing to play, go right to stopped. */
+ if(UNLIKELY(!BufferList))
+ {
+ /* NOTE: A source without any playable buffers should not have an
+ * ALvoice since it shouldn't be in a playing or paused state. So
+ * there's no need to look up its voice and clear the source.
+ */
+ ALenum oldstate{GetSourceState(source, nullptr)};
+ source->OffsetType = AL_NONE;
+ source->Offset = 0.0;
+ if(oldstate != AL_STOPPED)
+ {
+ source->state = AL_STOPPED;
+ SendStateChangeEvent(context.get(), source->id, AL_STOPPED);
+ }
+ return;
+ }
+
+ ALvoice *voice{GetSourceVoice(source, context.get())};
+ switch(GetSourceState(source, voice))
+ {
+ case AL_PLAYING:
+ assert(voice != nullptr);
+ /* A source that's already playing is restarted from the beginning. */
+ voice->mCurrentBuffer.store(BufferList, std::memory_order_relaxed);
+ voice->mPosition.store(0u, std::memory_order_relaxed);
+ voice->mPositionFrac.store(0, std::memory_order_release);
+ return;
+
+ case AL_PAUSED:
+ assert(voice != nullptr);
+ /* A source that's paused simply resumes. */
+ voice->mPlayState.store(ALvoice::Playing, std::memory_order_release);
+ source->state = AL_PLAYING;
+ SendStateChangeEvent(context.get(), source->id, AL_PLAYING);
+ return;
+
+ default:
+ assert(voice == nullptr);
+ break;
+ }
+
+ /* Look for an unused voice to play this source with. */
+ auto voices_end = context->Voices->begin() +
+ context->VoiceCount.load(std::memory_order_relaxed);
+ voice = std::find_if(context->Voices->begin(), voices_end,
+ [](const ALvoice &voice) noexcept -> bool
+ {
+ return voice.mPlayState.load(std::memory_order_acquire) == ALvoice::Stopped &&
+ voice.mSourceID.load(std::memory_order_relaxed) == 0u;
+ }
+ );
+ assert(voice != voices_end);
+ auto vidx = static_cast<ALint>(std::distance(context->Voices->begin(), voice));
+ voice->mPlayState.store(ALvoice::Stopped, std::memory_order_release);
+
+ source->PropsClean.test_and_set(std::memory_order_acquire);
+ UpdateSourceProps(source, voice, context.get());
+
+ /* A source that's not playing or paused has any offset applied when it
+ * starts playing.
+ */
+ if(source->Looping)
+ voice->mLoopBuffer.store(source->queue, std::memory_order_relaxed);
+ else
+ voice->mLoopBuffer.store(nullptr, std::memory_order_relaxed);
+ voice->mCurrentBuffer.store(BufferList, std::memory_order_relaxed);
+ voice->mPosition.store(0u, std::memory_order_relaxed);
+ voice->mPositionFrac.store(0, std::memory_order_relaxed);
+ bool start_fading{false};
+ if(ApplyOffset(source, voice) != AL_FALSE)
+ start_fading = voice->mPosition.load(std::memory_order_relaxed) != 0 ||
+ voice->mPositionFrac.load(std::memory_order_relaxed) != 0 ||
+ voice->mCurrentBuffer.load(std::memory_order_relaxed) != BufferList;
+
+ auto buffers_end = BufferList->buffers + BufferList->num_buffers;
+ auto buffer = std::find_if(BufferList->buffers, buffers_end,
+ std::bind(std::not_equal_to<const ALbuffer*>{}, _1, nullptr));
+ if(buffer != buffers_end)
+ {
+ voice->mFrequency = (*buffer)->Frequency;
+ voice->mFmtChannels = (*buffer)->mFmtChannels;
+ voice->mNumChannels = ChannelsFromFmt((*buffer)->mFmtChannels);
+ voice->mSampleSize = BytesFromFmt((*buffer)->mFmtType);
+ }
+
+ /* Clear the stepping value so the mixer knows not to mix this until
+ * the update gets applied.
+ */
+ voice->mStep = 0;
+
+ voice->mFlags = start_fading ? VOICE_IS_FADING : 0;
+ if(source->SourceType == AL_STATIC) voice->mFlags |= VOICE_IS_STATIC;
+
+ /* Don't need to set the VOICE_IS_AMBISONIC flag if the device is
+ * mixing in first order. No HF scaling is necessary to mix it.
+ */
+ if((voice->mFmtChannels == FmtBFormat2D || voice->mFmtChannels == FmtBFormat3D) &&
+ device->mAmbiOrder > 1)
+ {
+ const int *OrderFromChan;
+ if(voice->mFmtChannels == FmtBFormat2D)
+ {
+ static constexpr int Order2DFromChan[MAX_AMBI2D_CHANNELS]{
+ 0, 1,1, 2,2, 3,3
+ };
+ OrderFromChan = Order2DFromChan;
+ }
+ else
+ {
+ static constexpr int Order3DFromChan[MAX_AMBI_CHANNELS]{
+ 0, 1,1,1, 2,2,2,2,2, 3,3,3,3,3,3,3,
+ };
+ OrderFromChan = Order3DFromChan;
+ }
+
+ BandSplitter splitter{400.0f / static_cast<ALfloat>(device->Frequency)};
+
+ const auto scales = BFormatDec::GetHFOrderScales(1, device->mAmbiOrder);
+ auto init_ambi = [scales,&OrderFromChan,&splitter](ALvoice::ChannelData &chandata) -> void
+ {
+ chandata.mPrevSamples.fill(0.0f);
+ chandata.mAmbiScale = scales[*(OrderFromChan++)];
+ chandata.mAmbiSplitter = splitter;
+ };
+ std::for_each(voice->mChans.begin(), voice->mChans.begin()+voice->mNumChannels,
+ init_ambi);
+
+ voice->mFlags |= VOICE_IS_AMBISONIC;
+ }
+ else
+ {
+ /* Clear previous samples. */
+ auto clear_prevs = [](ALvoice::ChannelData &chandata) -> void
+ { chandata.mPrevSamples.fill(0.0f); };
+ std::for_each(voice->mChans.begin(), voice->mChans.begin()+voice->mNumChannels,
+ clear_prevs);
+ }
+
+ auto clear_params = [device](ALvoice::ChannelData &chandata) -> void
+ {
+ chandata.mDryParams = DirectParams{};
+ std::fill_n(chandata.mWetParams.begin(), device->NumAuxSends, SendParams{});
+ };
+ std::for_each(voice->mChans.begin(), voice->mChans.begin()+voice->mNumChannels,
+ clear_params);
+
+ if(device->AvgSpeakerDist > 0.0f)
+ {
+ const ALfloat w1{SPEEDOFSOUNDMETRESPERSEC /
+ (device->AvgSpeakerDist * device->Frequency)};
+ auto init_nfc = [w1](ALvoice::ChannelData &chandata) -> void
+ { chandata.mDryParams.NFCtrlFilter.init(w1); };
+ std::for_each(voice->mChans.begin(), voice->mChans.begin()+voice->mNumChannels,
+ init_nfc);
+ }
+
+ voice->mSourceID.store(source->id, std::memory_order_relaxed);
+ voice->mPlayState.store(ALvoice::Playing, std::memory_order_release);
+ source->state = AL_PLAYING;
+ source->VoiceIdx = vidx;
+
+ SendStateChangeEvent(context.get(), source->id, AL_PLAYING);
+ };
+ std::for_each(srchandles, srchandles+n, start_source);
+}
+END_API_FUNC
+
+
+AL_API ALvoid AL_APIENTRY alSourcePause(ALuint source)
+START_API_FUNC
+{ alSourcePausev(1, &source); }
+END_API_FUNC
+
+AL_API ALvoid AL_APIENTRY alSourcePausev(ALsizei n, const ALuint *sources)
+START_API_FUNC
+{
+ ContextRef context{GetContextRef()};
+ if(UNLIKELY(!context)) return;
+
+ if(n < 0)
+ SETERR_RETURN(context.get(), AL_INVALID_VALUE,, "Pausing %d sources", n);
+ if(n == 0) return;
+
+ al::vector<ALsource*> extra_sources;
+ std::array<ALsource*,16> source_storage;
+ ALsource **srchandles{source_storage.data()};
+ if(UNLIKELY(static_cast<ALuint>(n) > source_storage.size()))
+ {
+ extra_sources.resize(n);
+ srchandles = extra_sources.data();
+ }
+
+ std::lock_guard<std::mutex> _{context->SourceLock};
+ for(ALsizei i{0};i < n;i++)
+ {
+ srchandles[i] = LookupSource(context.get(), sources[i]);
+ if(!srchandles[i])
+ SETERR_RETURN(context.get(), AL_INVALID_NAME,, "Invalid source ID %u", sources[i]);
+ }
+
+ ALCdevice *device{context->Device};
+ BackendLockGuard __{*device->Backend};
+ auto pause_source = [&context](ALsource *source) -> void
+ {
+ ALvoice *voice{GetSourceVoice(source, context.get())};
+ if(voice)
+ {
+ std::atomic_thread_fence(std::memory_order_release);
+ ALvoice::State oldvstate{ALvoice::Playing};
+ voice->mPlayState.compare_exchange_strong(oldvstate, ALvoice::Stopping,
+ std::memory_order_acq_rel, std::memory_order_acquire);
+ }
+ if(GetSourceState(source, voice) == AL_PLAYING)
+ {
+ source->state = AL_PAUSED;
+ SendStateChangeEvent(context.get(), source->id, AL_PAUSED);
+ }
+ };
+ std::for_each(srchandles, srchandles+n, pause_source);
+}
+END_API_FUNC
+
+
+AL_API ALvoid AL_APIENTRY alSourceStop(ALuint source)
+START_API_FUNC
+{ alSourceStopv(1, &source); }
+END_API_FUNC
+
+AL_API ALvoid AL_APIENTRY alSourceStopv(ALsizei n, const ALuint *sources)
+START_API_FUNC
+{
+ ContextRef context{GetContextRef()};
+ if(UNLIKELY(!context)) return;
+
+ if(n < 0)
+ SETERR_RETURN(context.get(), AL_INVALID_VALUE,, "Stopping %d sources", n);
+ if(n == 0) return;
+
+ al::vector<ALsource*> extra_sources;
+ std::array<ALsource*,16> source_storage;
+ ALsource **srchandles{source_storage.data()};
+ if(UNLIKELY(static_cast<ALuint>(n) > source_storage.size()))
+ {
+ extra_sources.resize(n);
+ srchandles = extra_sources.data();
+ }
+
+ std::lock_guard<std::mutex> _{context->SourceLock};
+ for(ALsizei i{0};i < n;i++)
+ {
+ srchandles[i] = LookupSource(context.get(), sources[i]);
+ if(!srchandles[i])
+ SETERR_RETURN(context.get(), AL_INVALID_NAME,, "Invalid source ID %u", sources[i]);
+ }
+
+ ALCdevice *device{context->Device};
+ BackendLockGuard __{*device->Backend};
+ auto stop_source = [&context](ALsource *source) -> void
+ {
+ ALvoice *voice{GetSourceVoice(source, context.get())};
+ if(voice != nullptr)
+ {
+ voice->mCurrentBuffer.store(nullptr, std::memory_order_relaxed);
+ voice->mLoopBuffer.store(nullptr, std::memory_order_relaxed);
+ voice->mSourceID.store(0u, std::memory_order_relaxed);
+ std::atomic_thread_fence(std::memory_order_release);
+ ALvoice::State oldvstate{ALvoice::Playing};
+ voice->mPlayState.compare_exchange_strong(oldvstate, ALvoice::Stopping,
+ std::memory_order_acq_rel, std::memory_order_acquire);
+ voice = nullptr;
+ }
+ ALenum oldstate{GetSourceState(source, voice)};
+ if(oldstate != AL_INITIAL && oldstate != AL_STOPPED)
+ {
+ source->state = AL_STOPPED;
+ SendStateChangeEvent(context.get(), source->id, AL_STOPPED);
+ }
+ source->OffsetType = AL_NONE;
+ source->Offset = 0.0;
+ };
+ std::for_each(srchandles, srchandles+n, stop_source);
+}
+END_API_FUNC
+
+
+AL_API ALvoid AL_APIENTRY alSourceRewind(ALuint source)
+START_API_FUNC
+{ alSourceRewindv(1, &source); }
+END_API_FUNC
+
+AL_API ALvoid AL_APIENTRY alSourceRewindv(ALsizei n, const ALuint *sources)
+START_API_FUNC
+{
+ ContextRef context{GetContextRef()};
+ if(UNLIKELY(!context)) return;
+
+ if(n < 0)
+ SETERR_RETURN(context.get(), AL_INVALID_VALUE,, "Rewinding %d sources", n);
+ if(n == 0) return;
+
+ al::vector<ALsource*> extra_sources;
+ std::array<ALsource*,16> source_storage;
+ ALsource **srchandles{source_storage.data()};
+ if(UNLIKELY(static_cast<ALuint>(n) > source_storage.size()))
+ {
+ extra_sources.resize(n);
+ srchandles = extra_sources.data();
+ }
+
+ std::lock_guard<std::mutex> _{context->SourceLock};
+ for(ALsizei i{0};i < n;i++)
+ {
+ srchandles[i] = LookupSource(context.get(), sources[i]);
+ if(!srchandles[i])
+ SETERR_RETURN(context.get(), AL_INVALID_NAME,, "Invalid source ID %u", sources[i]);
+ }
+
+ ALCdevice *device{context->Device};
+ BackendLockGuard __{*device->Backend};
+ auto rewind_source = [&context](ALsource *source) -> void
+ {
+ ALvoice *voice{GetSourceVoice(source, context.get())};
+ if(voice != nullptr)
+ {
+ voice->mCurrentBuffer.store(nullptr, std::memory_order_relaxed);
+ voice->mLoopBuffer.store(nullptr, std::memory_order_relaxed);
+ voice->mSourceID.store(0u, std::memory_order_relaxed);
+ std::atomic_thread_fence(std::memory_order_release);
+ ALvoice::State oldvstate{ALvoice::Playing};
+ voice->mPlayState.compare_exchange_strong(oldvstate, ALvoice::Stopping,
+ std::memory_order_acq_rel, std::memory_order_acquire);
+ voice = nullptr;
+ }
+ if(GetSourceState(source, voice) != AL_INITIAL)
+ {
+ source->state = AL_INITIAL;
+ SendStateChangeEvent(context.get(), source->id, AL_INITIAL);
+ }
+ source->OffsetType = AL_NONE;
+ source->Offset = 0.0;
+ };
+ std::for_each(srchandles, srchandles+n, rewind_source);
+}
+END_API_FUNC
+
+
+AL_API ALvoid AL_APIENTRY alSourceQueueBuffers(ALuint src, ALsizei nb, const ALuint *buffers)
+START_API_FUNC
+{
+ ContextRef context{GetContextRef()};
+ if(UNLIKELY(!context)) return;
+
+ if(nb < 0)
+ SETERR_RETURN(context.get(), AL_INVALID_VALUE,, "Queueing %d buffers", nb);
+ if(nb == 0) return;
+
+ std::lock_guard<std::mutex> _{context->SourceLock};
+ ALsource *source{LookupSource(context.get(),src)};
+ if(UNLIKELY(!source))
+ SETERR_RETURN(context.get(), AL_INVALID_NAME,, "Invalid source ID %u", src);
+
+ /* Can't queue on a Static Source */
+ if(UNLIKELY(source->SourceType == AL_STATIC))
+ SETERR_RETURN(context.get(), AL_INVALID_OPERATION,, "Queueing onto static source %u", src);
+
+ /* Check for a valid Buffer, for its frequency and format */
+ ALCdevice *device{context->Device};
+ ALbuffer *BufferFmt{nullptr};
+ ALbufferlistitem *BufferList{source->queue};
+ while(BufferList)
+ {
+ for(ALsizei i{0};i < BufferList->num_buffers;i++)
+ {
+ if((BufferFmt=BufferList->buffers[i]) != nullptr)
+ break;
+ }
+ if(BufferFmt) break;
+ BufferList = BufferList->next.load(std::memory_order_relaxed);
+ }
+
+ std::unique_lock<std::mutex> buflock{device->BufferLock};
+ ALbufferlistitem *BufferListStart{nullptr};
+ BufferList = nullptr;
+ for(ALsizei i{0};i < nb;i++)
+ {
+ ALbuffer *buffer{nullptr};
+ if(buffers[i] && (buffer=LookupBuffer(device, buffers[i])) == nullptr)
+ {
+ alSetError(context.get(), AL_INVALID_NAME, "Queueing invalid buffer ID %u",
+ buffers[i]);
+ goto buffer_error;
+ }
+
+ if(!BufferListStart)
+ {
+ BufferListStart = static_cast<ALbufferlistitem*>(al_calloc(alignof(void*),
+ ALbufferlistitem::Sizeof(1u)));
+ BufferList = BufferListStart;
+ }
+ else
+ {
+ auto item = static_cast<ALbufferlistitem*>(al_calloc(alignof(void*),
+ ALbufferlistitem::Sizeof(1u)));
+ BufferList->next.store(item, std::memory_order_relaxed);
+ BufferList = item;
+ }
+ BufferList->next.store(nullptr, std::memory_order_relaxed);
+ BufferList->max_samples = buffer ? buffer->SampleLen : 0;
+ BufferList->num_buffers = 1;
+ BufferList->buffers[0] = buffer;
+ if(!buffer) continue;
+
+ IncrementRef(&buffer->ref);
+
+ if(buffer->MappedAccess != 0 && !(buffer->MappedAccess&AL_MAP_PERSISTENT_BIT_SOFT))
+ {
+ alSetError(context.get(), AL_INVALID_OPERATION,
+ "Queueing non-persistently mapped buffer %u", buffer->id);
+ goto buffer_error;
+ }
+
+ if(BufferFmt == nullptr)
+ BufferFmt = buffer;
+ else if(BufferFmt->Frequency != buffer->Frequency ||
+ BufferFmt->mFmtChannels != buffer->mFmtChannels ||
+ BufferFmt->OriginalType != buffer->OriginalType)
+ {
+ alSetError(context.get(), AL_INVALID_OPERATION,
+ "Queueing buffer with mismatched format");
+
+ buffer_error:
+ /* A buffer failed (invalid ID or format), so unlock and release
+ * each buffer we had. */
+ while(BufferListStart)
+ {
+ ALbufferlistitem *next = BufferListStart->next.load(std::memory_order_relaxed);
+ for(i = 0;i < BufferListStart->num_buffers;i++)
+ {
+ if((buffer=BufferListStart->buffers[i]) != nullptr)
+ DecrementRef(&buffer->ref);
+ }
+ al_free(BufferListStart);
+ BufferListStart = next;
+ }
+ return;
+ }
+ }
+ /* All buffers good. */
+ buflock.unlock();
+
+ /* Source is now streaming */
+ source->SourceType = AL_STREAMING;
+
+ if(!(BufferList=source->queue))
+ source->queue = BufferListStart;
+ else
+ {
+ ALbufferlistitem *next;
+ while((next=BufferList->next.load(std::memory_order_relaxed)) != nullptr)
+ BufferList = next;
+ BufferList->next.store(BufferListStart, std::memory_order_release);
+ }
+}
+END_API_FUNC
+
+AL_API void AL_APIENTRY alSourceQueueBufferLayersSOFT(ALuint src, ALsizei nb, const ALuint *buffers)
+START_API_FUNC
+{
+ ContextRef context{GetContextRef()};
+ if(UNLIKELY(!context)) return;
+
+ if(nb < 0)
+ SETERR_RETURN(context.get(), AL_INVALID_VALUE,, "Queueing %d buffer layers", nb);
+ if(nb == 0) return;
+
+ std::lock_guard<std::mutex> _{context->SourceLock};
+ ALsource *source{LookupSource(context.get(),src)};
+ if(UNLIKELY(!source))
+ SETERR_RETURN(context.get(), AL_INVALID_NAME,, "Invalid source ID %u", src);
+
+ /* Can't queue on a Static Source */
+ if(UNLIKELY(source->SourceType == AL_STATIC))
+ SETERR_RETURN(context.get(), AL_INVALID_OPERATION,, "Queueing onto static source %u", src);
+
+ /* Check for a valid Buffer, for its frequency and format */
+ ALCdevice *device{context->Device};
+ ALbuffer *BufferFmt{nullptr};
+ ALbufferlistitem *BufferList{source->queue};
+ while(BufferList)
+ {
+ for(ALsizei i{0};i < BufferList->num_buffers;i++)
+ {
+ if((BufferFmt=BufferList->buffers[i]) != nullptr)
+ break;
+ }
+ if(BufferFmt) break;
+ BufferList = BufferList->next.load(std::memory_order_relaxed);
+ }
+
+ std::unique_lock<std::mutex> buflock{device->BufferLock};
+ auto BufferListStart = static_cast<ALbufferlistitem*>(al_calloc(alignof(void*),
+ ALbufferlistitem::Sizeof(nb)));
+ BufferList = BufferListStart;
+ BufferList->next.store(nullptr, std::memory_order_relaxed);
+ BufferList->max_samples = 0;
+ BufferList->num_buffers = 0;
+
+ for(ALsizei i{0};i < nb;i++)
+ {
+ ALbuffer *buffer{nullptr};
+ if(buffers[i] && (buffer=LookupBuffer(device, buffers[i])) == nullptr)
+ {
+ alSetError(context.get(), AL_INVALID_NAME, "Queueing invalid buffer ID %u",
+ buffers[i]);
+ goto buffer_error;
+ }
+
+ BufferList->buffers[BufferList->num_buffers++] = buffer;
+ if(!buffer) continue;
+
+ IncrementRef(&buffer->ref);
+
+ BufferList->max_samples = maxi(BufferList->max_samples, buffer->SampleLen);
+
+ if(buffer->MappedAccess != 0 && !(buffer->MappedAccess&AL_MAP_PERSISTENT_BIT_SOFT))
+ {
+ alSetError(context.get(), AL_INVALID_OPERATION,
+ "Queueing non-persistently mapped buffer %u", buffer->id);
+ goto buffer_error;
+ }
+
+ if(BufferFmt == nullptr)
+ BufferFmt = buffer;
+ else if(BufferFmt->Frequency != buffer->Frequency ||
+ BufferFmt->mFmtChannels != buffer->mFmtChannels ||
+ BufferFmt->OriginalType != buffer->OriginalType)
+ {
+ alSetError(context.get(), AL_INVALID_OPERATION,
+ "Queueing buffer with mismatched format");
+
+ buffer_error:
+ /* A buffer failed (invalid ID or format), so unlock and release
+ * each buffer we had. */
+ while(BufferListStart)
+ {
+ ALbufferlistitem *next{BufferListStart->next.load(std::memory_order_relaxed)};
+ for(i = 0;i < BufferListStart->num_buffers;i++)
+ {
+ if((buffer=BufferListStart->buffers[i]) != nullptr)
+ DecrementRef(&buffer->ref);
+ }
+ al_free(BufferListStart);
+ BufferListStart = next;
+ }
+ return;
+ }
+ }
+ /* All buffers good. */
+ buflock.unlock();
+
+ /* Source is now streaming */
+ source->SourceType = AL_STREAMING;
+
+ if(!(BufferList=source->queue))
+ source->queue = BufferListStart;
+ else
+ {
+ ALbufferlistitem *next;
+ while((next=BufferList->next.load(std::memory_order_relaxed)) != nullptr)
+ BufferList = next;
+ BufferList->next.store(BufferListStart, std::memory_order_release);
+ }
+}
+END_API_FUNC
+
+AL_API ALvoid AL_APIENTRY alSourceUnqueueBuffers(ALuint src, ALsizei nb, ALuint *buffers)
+START_API_FUNC
+{
+ ContextRef context{GetContextRef()};
+ if(UNLIKELY(!context)) return;
+
+ if(nb < 0)
+ SETERR_RETURN(context.get(), AL_INVALID_VALUE,, "Unqueueing %d buffers", nb);
+ if(nb == 0) return;
+
+ std::lock_guard<std::mutex> _{context->SourceLock};
+ ALsource *source{LookupSource(context.get(),src)};
+ if(UNLIKELY(!source))
+ SETERR_RETURN(context.get(), AL_INVALID_NAME,, "Invalid source ID %u", src);
+
+ if(UNLIKELY(source->Looping))
+ SETERR_RETURN(context.get(), AL_INVALID_VALUE,, "Unqueueing from looping source %u", src);
+ if(UNLIKELY(source->SourceType != AL_STREAMING))
+ SETERR_RETURN(context.get(), AL_INVALID_VALUE,,
+ "Unqueueing from a non-streaming source %u", src);
+
+ /* Make sure enough buffers have been processed to unqueue. */
+ ALbufferlistitem *BufferList{source->queue};
+ ALvoice *voice{GetSourceVoice(source, context.get())};
+ ALbufferlistitem *Current{nullptr};
+ if(voice)
+ Current = voice->mCurrentBuffer.load(std::memory_order_relaxed);
+ else if(source->state == AL_INITIAL)
+ Current = BufferList;
+ if(UNLIKELY(BufferList == Current))
+ SETERR_RETURN(context.get(), AL_INVALID_VALUE,, "Unqueueing pending buffers");
+
+ ALsizei i{BufferList->num_buffers};
+ while(i < nb)
+ {
+ /* If the next bufferlist to check is NULL or is the current one, it's
+ * trying to unqueue pending buffers.
+ */
+ ALbufferlistitem *next{BufferList->next.load(std::memory_order_relaxed)};
+ if(UNLIKELY(!next) || UNLIKELY(next == Current))
+ SETERR_RETURN(context.get(), AL_INVALID_VALUE,, "Unqueueing pending buffers");
+ BufferList = next;
+
+ i += BufferList->num_buffers;
+ }
+
+ while(nb > 0)
+ {
+ ALbufferlistitem *head{source->queue};
+ ALbufferlistitem *next{head->next.load(std::memory_order_relaxed)};
+ for(i = 0;i < head->num_buffers && nb > 0;i++,nb--)
+ {
+ ALbuffer *buffer{head->buffers[i]};
+ if(!buffer)
+ *(buffers++) = 0;
+ else
+ {
+ *(buffers++) = buffer->id;
+ DecrementRef(&buffer->ref);
+ }
+ }
+ if(i < head->num_buffers)
+ {
+ /* This head has some buffers left over, so move them to the front
+ * and update the sample and buffer count.
+ */
+ ALsizei max_length{0};
+ ALsizei j{0};
+ while(i < head->num_buffers)
+ {
+ ALbuffer *buffer{head->buffers[i++]};
+ if(buffer) max_length = maxi(max_length, buffer->SampleLen);
+ head->buffers[j++] = buffer;
+ }
+ head->max_samples = max_length;
+ head->num_buffers = j;
+ break;
+ }
+
+ /* Otherwise, free this item and set the source queue head to the next
+ * one.
+ */
+ al_free(head);
+ source->queue = next;
+ }
+}
+END_API_FUNC
+
+
+ALsource::ALsource(ALsizei num_sends)
+{
+ InnerAngle = 360.0f;
+ OuterAngle = 360.0f;
+ Pitch = 1.0f;
+ Position[0] = 0.0f;
+ Position[1] = 0.0f;
+ Position[2] = 0.0f;
+ Velocity[0] = 0.0f;
+ Velocity[1] = 0.0f;
+ Velocity[2] = 0.0f;
+ Direction[0] = 0.0f;
+ Direction[1] = 0.0f;
+ Direction[2] = 0.0f;
+ OrientAt[0] = 0.0f;
+ OrientAt[1] = 0.0f;
+ OrientAt[2] = -1.0f;
+ OrientUp[0] = 0.0f;
+ OrientUp[1] = 1.0f;
+ OrientUp[2] = 0.0f;
+ RefDistance = 1.0f;
+ MaxDistance = std::numeric_limits<float>::max();
+ RolloffFactor = 1.0f;
+ Gain = 1.0f;
+ MinGain = 0.0f;
+ MaxGain = 1.0f;
+ OuterGain = 0.0f;
+ OuterGainHF = 1.0f;
+
+ DryGainHFAuto = AL_TRUE;
+ WetGainAuto = AL_TRUE;
+ WetGainHFAuto = AL_TRUE;
+ AirAbsorptionFactor = 0.0f;
+ RoomRolloffFactor = 0.0f;
+ DopplerFactor = 1.0f;
+ HeadRelative = AL_FALSE;
+ Looping = AL_FALSE;
+ mDistanceModel = DistanceModel::Default;
+ mResampler = ResamplerDefault;
+ DirectChannels = AL_FALSE;
+ mSpatialize = SpatializeAuto;
+
+ StereoPan[0] = Deg2Rad( 30.0f);
+ StereoPan[1] = Deg2Rad(-30.0f);
+
+ Radius = 0.0f;
+
+ Direct.Gain = 1.0f;
+ Direct.GainHF = 1.0f;
+ Direct.HFReference = LOWPASSFREQREF;
+ Direct.GainLF = 1.0f;
+ Direct.LFReference = HIGHPASSFREQREF;
+ Send.resize(num_sends);
+ for(auto &send : Send)
+ {
+ send.Slot = nullptr;
+ send.Gain = 1.0f;
+ send.GainHF = 1.0f;
+ send.HFReference = LOWPASSFREQREF;
+ send.GainLF = 1.0f;
+ send.LFReference = HIGHPASSFREQREF;
+ }
+
+ Offset = 0.0;
+ OffsetType = AL_NONE;
+ SourceType = AL_UNDETERMINED;
+ state = AL_INITIAL;
+
+ queue = nullptr;
+
+ PropsClean.test_and_set(std::memory_order_relaxed);
+
+ VoiceIdx = -1;
+}
+
+ALsource::~ALsource()
+{
+ ALbufferlistitem *BufferList{queue};
+ while(BufferList != nullptr)
+ {
+ ALbufferlistitem *next{BufferList->next.load(std::memory_order_relaxed)};
+ for(ALsizei i{0};i < BufferList->num_buffers;i++)
+ {
+ if(BufferList->buffers[i])
+ DecrementRef(&BufferList->buffers[i]->ref);
+ }
+ al_free(BufferList);
+ BufferList = next;
+ }
+ queue = nullptr;
+
+ std::for_each(Send.begin(), Send.end(),
+ [](ALsource::SendData &send) -> void
+ {
+ if(send.Slot)
+ DecrementRef(&send.Slot->ref);
+ send.Slot = nullptr;
+ }
+ );
+}
+
+void UpdateAllSourceProps(ALCcontext *context)
+{
+ auto voices_end = context->Voices->begin() +
+ context->VoiceCount.load(std::memory_order_relaxed);
+ std::for_each(context->Voices->begin(), voices_end,
+ [context](ALvoice &voice) -> void
+ {
+ ALuint sid{voice.mSourceID.load(std::memory_order_acquire)};
+ ALsource *source = sid ? LookupSource(context, sid) : nullptr;
+ if(source && !source->PropsClean.test_and_set(std::memory_order_acq_rel))
+ UpdateSourceProps(source, &voice, context);
+ }
+ );
+}
+
+SourceSubList::~SourceSubList()
+{
+ uint64_t usemask{~FreeMask};
+ while(usemask)
+ {
+ ALsizei idx{CTZ64(usemask)};
+ al::destroy_at(Sources+idx);
+ usemask &= ~(1_u64 << idx);
+ }
+ FreeMask = ~usemask;
+ al_free(Sources);
+ Sources = nullptr;
+}
diff --git a/al/alSource.h b/al/alSource.h
new file mode 100644
index 00000000..c9892398
--- /dev/null
+++ b/al/alSource.h
@@ -0,0 +1,131 @@
+#ifndef AL_SOURCE_H
+#define AL_SOURCE_H
+
+#include <array>
+#include <atomic>
+#include <cstddef>
+
+#include "AL/al.h"
+#include "AL/alc.h"
+
+#include "alcontext.h"
+#include "alnumeric.h"
+#include "alu.h"
+#include "vector.h"
+
+struct ALbuffer;
+struct ALeffectslot;
+
+
+#define DEFAULT_SENDS 2
+
+
+struct ALbufferlistitem {
+ std::atomic<ALbufferlistitem*> next;
+ ALsizei max_samples;
+ ALsizei num_buffers;
+ ALbuffer *buffers[];
+
+ static constexpr size_t Sizeof(size_t num_buffers) noexcept
+ {
+ return maxz(offsetof(ALbufferlistitem, buffers) + sizeof(ALbuffer*)*num_buffers,
+ sizeof(ALbufferlistitem));
+ }
+};
+
+
+struct ALsource {
+ /** Source properties. */
+ ALfloat Pitch;
+ ALfloat Gain;
+ ALfloat OuterGain;
+ ALfloat MinGain;
+ ALfloat MaxGain;
+ ALfloat InnerAngle;
+ ALfloat OuterAngle;
+ ALfloat RefDistance;
+ ALfloat MaxDistance;
+ ALfloat RolloffFactor;
+ std::array<ALfloat,3> Position;
+ std::array<ALfloat,3> Velocity;
+ std::array<ALfloat,3> Direction;
+ std::array<ALfloat,3> OrientAt;
+ std::array<ALfloat,3> OrientUp;
+ ALboolean HeadRelative;
+ ALboolean Looping;
+ DistanceModel mDistanceModel;
+ Resampler mResampler;
+ ALboolean DirectChannels;
+ SpatializeMode mSpatialize;
+
+ ALboolean DryGainHFAuto;
+ ALboolean WetGainAuto;
+ ALboolean WetGainHFAuto;
+ ALfloat OuterGainHF;
+
+ ALfloat AirAbsorptionFactor;
+ ALfloat RoomRolloffFactor;
+ ALfloat DopplerFactor;
+
+ /* NOTE: Stereo pan angles are specified in radians, counter-clockwise
+ * rather than clockwise.
+ */
+ std::array<ALfloat,2> StereoPan;
+
+ ALfloat Radius;
+
+ /** Direct filter and auxiliary send info. */
+ struct {
+ ALfloat Gain;
+ ALfloat GainHF;
+ ALfloat HFReference;
+ ALfloat GainLF;
+ ALfloat LFReference;
+ } Direct;
+ struct SendData {
+ ALeffectslot *Slot;
+ ALfloat Gain;
+ ALfloat GainHF;
+ ALfloat HFReference;
+ ALfloat GainLF;
+ ALfloat LFReference;
+ };
+ al::vector<SendData> Send;
+
+ /**
+ * Last user-specified offset, and the offset type (bytes, samples, or
+ * seconds).
+ */
+ ALdouble Offset;
+ ALenum OffsetType;
+
+ /** Source type (static, streaming, or undetermined) */
+ ALint SourceType;
+
+ /** Source state (initial, playing, paused, or stopped) */
+ ALenum state;
+
+ /** Source Buffer Queue head. */
+ ALbufferlistitem *queue;
+
+ std::atomic_flag PropsClean;
+
+ /* Index into the context's Voices array. Lazily updated, only checked and
+ * reset when looking up the voice.
+ */
+ ALint VoiceIdx;
+
+ /** Self ID */
+ ALuint id;
+
+
+ ALsource(ALsizei num_sends);
+ ~ALsource();
+
+ ALsource(const ALsource&) = delete;
+ ALsource& operator=(const ALsource&) = delete;
+};
+
+void UpdateAllSourceProps(ALCcontext *context);
+
+#endif
diff --git a/al/alState.cpp b/al/alState.cpp
new file mode 100644
index 00000000..ee8d3a1c
--- /dev/null
+++ b/al/alState.cpp
@@ -0,0 +1,859 @@
+/**
+ * OpenAL cross platform audio library
+ * Copyright (C) 1999-2000 by authors.
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library; if not, write to the
+ * Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ * Or go to http://www.gnu.org/copyleft/lgpl.html
+ */
+
+#include "config.h"
+
+#include "version.h"
+
+#include <atomic>
+#include <cmath>
+#include <cstdlib>
+#include <cstring>
+#include <mutex>
+
+#include "AL/al.h"
+#include "AL/alc.h"
+#include "AL/alext.h"
+
+#include "alError.h"
+#include "alcmain.h"
+#include "alcontext.h"
+#include "alexcpt.h"
+#include "almalloc.h"
+#include "alspan.h"
+#include "alu.h"
+#include "atomic.h"
+#include "inprogext.h"
+#include "opthelpers.h"
+
+
+namespace {
+
+constexpr ALchar alVendor[] = "OpenAL Community";
+constexpr ALchar alVersion[] = "1.1 ALSOFT " ALSOFT_VERSION;
+constexpr ALchar alRenderer[] = "OpenAL Soft";
+
+// Error Messages
+constexpr ALchar alNoError[] = "No Error";
+constexpr ALchar alErrInvalidName[] = "Invalid Name";
+constexpr ALchar alErrInvalidEnum[] = "Invalid Enum";
+constexpr ALchar alErrInvalidValue[] = "Invalid Value";
+constexpr ALchar alErrInvalidOp[] = "Invalid Operation";
+constexpr ALchar alErrOutOfMemory[] = "Out of Memory";
+
+/* Resampler strings */
+constexpr ALchar alPointResampler[] = "Nearest";
+constexpr ALchar alLinearResampler[] = "Linear";
+constexpr ALchar alCubicResampler[] = "Cubic";
+constexpr ALchar alBSinc12Resampler[] = "11th order Sinc";
+constexpr ALchar alBSinc24Resampler[] = "23rd order Sinc";
+
+} // namespace
+
+/* WARNING: Non-standard export! Not part of any extension, or exposed in the
+ * alcFunctions list.
+ */
+extern "C" AL_API const ALchar* AL_APIENTRY alsoft_get_version(void)
+START_API_FUNC
+{
+ const char *spoof{getenv("ALSOFT_SPOOF_VERSION")};
+ if(spoof && spoof[0] != '\0') return spoof;
+ return ALSOFT_VERSION;
+}
+END_API_FUNC
+
+#define DO_UPDATEPROPS() do { \
+ if(!context->DeferUpdates.load(std::memory_order_acquire)) \
+ UpdateContextProps(context.get()); \
+ else \
+ context->PropsClean.clear(std::memory_order_release); \
+} while(0)
+
+
+AL_API ALvoid AL_APIENTRY alEnable(ALenum capability)
+START_API_FUNC
+{
+ ContextRef context{GetContextRef()};
+ if(UNLIKELY(!context)) return;
+
+ std::lock_guard<std::mutex> _{context->PropLock};
+ switch(capability)
+ {
+ case AL_SOURCE_DISTANCE_MODEL:
+ context->SourceDistanceModel = AL_TRUE;
+ DO_UPDATEPROPS();
+ break;
+
+ default:
+ alSetError(context.get(), AL_INVALID_VALUE, "Invalid enable property 0x%04x", capability);
+ }
+}
+END_API_FUNC
+
+AL_API ALvoid AL_APIENTRY alDisable(ALenum capability)
+START_API_FUNC
+{
+ ContextRef context{GetContextRef()};
+ if(UNLIKELY(!context)) return;
+
+ std::lock_guard<std::mutex> _{context->PropLock};
+ switch(capability)
+ {
+ case AL_SOURCE_DISTANCE_MODEL:
+ context->SourceDistanceModel = AL_FALSE;
+ DO_UPDATEPROPS();
+ break;
+
+ default:
+ alSetError(context.get(), AL_INVALID_VALUE, "Invalid disable property 0x%04x", capability);
+ }
+}
+END_API_FUNC
+
+AL_API ALboolean AL_APIENTRY alIsEnabled(ALenum capability)
+START_API_FUNC
+{
+ ContextRef context{GetContextRef()};
+ if(UNLIKELY(!context)) return AL_FALSE;
+
+ std::lock_guard<std::mutex> _{context->PropLock};
+ ALboolean value{AL_FALSE};
+ switch(capability)
+ {
+ case AL_SOURCE_DISTANCE_MODEL:
+ value = context->SourceDistanceModel;
+ break;
+
+ default:
+ alSetError(context.get(), AL_INVALID_VALUE, "Invalid is enabled property 0x%04x", capability);
+ }
+
+ return value;
+}
+END_API_FUNC
+
+AL_API ALboolean AL_APIENTRY alGetBoolean(ALenum pname)
+START_API_FUNC
+{
+ ContextRef context{GetContextRef()};
+ if(UNLIKELY(!context)) return AL_FALSE;
+
+ std::lock_guard<std::mutex> _{context->PropLock};
+ ALboolean value{AL_FALSE};
+ switch(pname)
+ {
+ case AL_DOPPLER_FACTOR:
+ if(context->DopplerFactor != 0.0f)
+ value = AL_TRUE;
+ break;
+
+ case AL_DOPPLER_VELOCITY:
+ if(context->DopplerVelocity != 0.0f)
+ value = AL_TRUE;
+ break;
+
+ case AL_DISTANCE_MODEL:
+ if(context->mDistanceModel == DistanceModel::Default)
+ value = AL_TRUE;
+ break;
+
+ case AL_SPEED_OF_SOUND:
+ if(context->SpeedOfSound != 0.0f)
+ value = AL_TRUE;
+ break;
+
+ case AL_DEFERRED_UPDATES_SOFT:
+ if(context->DeferUpdates.load(std::memory_order_acquire))
+ value = AL_TRUE;
+ break;
+
+ case AL_GAIN_LIMIT_SOFT:
+ if(GAIN_MIX_MAX/context->GainBoost != 0.0f)
+ value = AL_TRUE;
+ break;
+
+ case AL_NUM_RESAMPLERS_SOFT:
+ /* Always non-0. */
+ value = AL_TRUE;
+ break;
+
+ case AL_DEFAULT_RESAMPLER_SOFT:
+ value = ResamplerDefault ? AL_TRUE : AL_FALSE;
+ break;
+
+ default:
+ alSetError(context.get(), AL_INVALID_VALUE, "Invalid boolean property 0x%04x", pname);
+ }
+
+ return value;
+}
+END_API_FUNC
+
+AL_API ALdouble AL_APIENTRY alGetDouble(ALenum pname)
+START_API_FUNC
+{
+ ContextRef context{GetContextRef()};
+ if(UNLIKELY(!context)) return 0.0;
+
+ std::lock_guard<std::mutex> _{context->PropLock};
+ ALdouble value{0.0};
+ switch(pname)
+ {
+ case AL_DOPPLER_FACTOR:
+ value = static_cast<ALdouble>(context->DopplerFactor);
+ break;
+
+ case AL_DOPPLER_VELOCITY:
+ value = static_cast<ALdouble>(context->DopplerVelocity);
+ break;
+
+ case AL_DISTANCE_MODEL:
+ value = static_cast<ALdouble>(context->mDistanceModel);
+ break;
+
+ case AL_SPEED_OF_SOUND:
+ value = static_cast<ALdouble>(context->SpeedOfSound);
+ break;
+
+ case AL_DEFERRED_UPDATES_SOFT:
+ if(context->DeferUpdates.load(std::memory_order_acquire))
+ value = static_cast<ALdouble>(AL_TRUE);
+ break;
+
+ case AL_GAIN_LIMIT_SOFT:
+ value = static_cast<ALdouble>GAIN_MIX_MAX/context->GainBoost;
+ break;
+
+ case AL_NUM_RESAMPLERS_SOFT:
+ value = static_cast<ALdouble>(ResamplerMax + 1);
+ break;
+
+ case AL_DEFAULT_RESAMPLER_SOFT:
+ value = static_cast<ALdouble>(ResamplerDefault);
+ break;
+
+ default:
+ alSetError(context.get(), AL_INVALID_VALUE, "Invalid double property 0x%04x", pname);
+ }
+
+ return value;
+}
+END_API_FUNC
+
+AL_API ALfloat AL_APIENTRY alGetFloat(ALenum pname)
+START_API_FUNC
+{
+ ContextRef context{GetContextRef()};
+ if(UNLIKELY(!context)) return 0.0f;
+
+ std::lock_guard<std::mutex> _{context->PropLock};
+ ALfloat value{0.0f};
+ switch(pname)
+ {
+ case AL_DOPPLER_FACTOR:
+ value = context->DopplerFactor;
+ break;
+
+ case AL_DOPPLER_VELOCITY:
+ value = context->DopplerVelocity;
+ break;
+
+ case AL_DISTANCE_MODEL:
+ value = static_cast<ALfloat>(context->mDistanceModel);
+ break;
+
+ case AL_SPEED_OF_SOUND:
+ value = context->SpeedOfSound;
+ break;
+
+ case AL_DEFERRED_UPDATES_SOFT:
+ if(context->DeferUpdates.load(std::memory_order_acquire))
+ value = static_cast<ALfloat>(AL_TRUE);
+ break;
+
+ case AL_GAIN_LIMIT_SOFT:
+ value = GAIN_MIX_MAX/context->GainBoost;
+ break;
+
+ case AL_NUM_RESAMPLERS_SOFT:
+ value = static_cast<ALfloat>(ResamplerMax + 1);
+ break;
+
+ case AL_DEFAULT_RESAMPLER_SOFT:
+ value = static_cast<ALfloat>(ResamplerDefault);
+ break;
+
+ default:
+ alSetError(context.get(), AL_INVALID_VALUE, "Invalid float property 0x%04x", pname);
+ }
+
+ return value;
+}
+END_API_FUNC
+
+AL_API ALint AL_APIENTRY alGetInteger(ALenum pname)
+START_API_FUNC
+{
+ ContextRef context{GetContextRef()};
+ if(UNLIKELY(!context)) return 0;
+
+ std::lock_guard<std::mutex> _{context->PropLock};
+ ALint value{0};
+ switch(pname)
+ {
+ case AL_DOPPLER_FACTOR:
+ value = static_cast<ALint>(context->DopplerFactor);
+ break;
+
+ case AL_DOPPLER_VELOCITY:
+ value = static_cast<ALint>(context->DopplerVelocity);
+ break;
+
+ case AL_DISTANCE_MODEL:
+ value = static_cast<ALint>(context->mDistanceModel);
+ break;
+
+ case AL_SPEED_OF_SOUND:
+ value = static_cast<ALint>(context->SpeedOfSound);
+ break;
+
+ case AL_DEFERRED_UPDATES_SOFT:
+ if(context->DeferUpdates.load(std::memory_order_acquire))
+ value = static_cast<ALint>(AL_TRUE);
+ break;
+
+ case AL_GAIN_LIMIT_SOFT:
+ value = static_cast<ALint>(GAIN_MIX_MAX/context->GainBoost);
+ break;
+
+ case AL_NUM_RESAMPLERS_SOFT:
+ value = ResamplerMax + 1;
+ break;
+
+ case AL_DEFAULT_RESAMPLER_SOFT:
+ value = ResamplerDefault;
+ break;
+
+ default:
+ alSetError(context.get(), AL_INVALID_VALUE, "Invalid integer property 0x%04x", pname);
+ }
+
+ return value;
+}
+END_API_FUNC
+
+extern "C" AL_API ALint64SOFT AL_APIENTRY alGetInteger64SOFT(ALenum pname)
+START_API_FUNC
+{
+ ContextRef context{GetContextRef()};
+ if(UNLIKELY(!context)) return 0;
+
+ std::lock_guard<std::mutex> _{context->PropLock};
+ ALint64SOFT value{0};
+ switch(pname)
+ {
+ case AL_DOPPLER_FACTOR:
+ value = (ALint64SOFT)context->DopplerFactor;
+ break;
+
+ case AL_DOPPLER_VELOCITY:
+ value = (ALint64SOFT)context->DopplerVelocity;
+ break;
+
+ case AL_DISTANCE_MODEL:
+ value = (ALint64SOFT)context->mDistanceModel;
+ break;
+
+ case AL_SPEED_OF_SOUND:
+ value = (ALint64SOFT)context->SpeedOfSound;
+ break;
+
+ case AL_DEFERRED_UPDATES_SOFT:
+ if(context->DeferUpdates.load(std::memory_order_acquire))
+ value = (ALint64SOFT)AL_TRUE;
+ break;
+
+ case AL_GAIN_LIMIT_SOFT:
+ value = (ALint64SOFT)(GAIN_MIX_MAX/context->GainBoost);
+ break;
+
+ case AL_NUM_RESAMPLERS_SOFT:
+ value = (ALint64SOFT)(ResamplerMax + 1);
+ break;
+
+ case AL_DEFAULT_RESAMPLER_SOFT:
+ value = (ALint64SOFT)ResamplerDefault;
+ break;
+
+ default:
+ alSetError(context.get(), AL_INVALID_VALUE, "Invalid integer64 property 0x%04x", pname);
+ }
+
+ return value;
+}
+END_API_FUNC
+
+AL_API void* AL_APIENTRY alGetPointerSOFT(ALenum pname)
+START_API_FUNC
+{
+ ContextRef context{GetContextRef()};
+ if(UNLIKELY(!context)) return nullptr;
+
+ std::lock_guard<std::mutex> _{context->PropLock};
+ void *value{nullptr};
+ switch(pname)
+ {
+ case AL_EVENT_CALLBACK_FUNCTION_SOFT:
+ value = reinterpret_cast<void*>(context->EventCb);
+ break;
+
+ case AL_EVENT_CALLBACK_USER_PARAM_SOFT:
+ value = context->EventParam;
+ break;
+
+ default:
+ alSetError(context.get(), AL_INVALID_VALUE, "Invalid pointer property 0x%04x", pname);
+ }
+
+ return value;
+}
+END_API_FUNC
+
+AL_API ALvoid AL_APIENTRY alGetBooleanv(ALenum pname, ALboolean *values)
+START_API_FUNC
+{
+ if(values)
+ {
+ switch(pname)
+ {
+ case AL_DOPPLER_FACTOR:
+ case AL_DOPPLER_VELOCITY:
+ case AL_DISTANCE_MODEL:
+ case AL_SPEED_OF_SOUND:
+ case AL_DEFERRED_UPDATES_SOFT:
+ case AL_GAIN_LIMIT_SOFT:
+ case AL_NUM_RESAMPLERS_SOFT:
+ case AL_DEFAULT_RESAMPLER_SOFT:
+ values[0] = alGetBoolean(pname);
+ return;
+ }
+ }
+
+ ContextRef context{GetContextRef()};
+ if(UNLIKELY(!context)) return;
+
+ if(!values)
+ alSetError(context.get(), AL_INVALID_VALUE, "NULL pointer");
+ else switch(pname)
+ {
+ default:
+ alSetError(context.get(), AL_INVALID_VALUE, "Invalid boolean-vector property 0x%04x", pname);
+ }
+}
+END_API_FUNC
+
+AL_API ALvoid AL_APIENTRY alGetDoublev(ALenum pname, ALdouble *values)
+START_API_FUNC
+{
+ if(values)
+ {
+ switch(pname)
+ {
+ case AL_DOPPLER_FACTOR:
+ case AL_DOPPLER_VELOCITY:
+ case AL_DISTANCE_MODEL:
+ case AL_SPEED_OF_SOUND:
+ case AL_DEFERRED_UPDATES_SOFT:
+ case AL_GAIN_LIMIT_SOFT:
+ case AL_NUM_RESAMPLERS_SOFT:
+ case AL_DEFAULT_RESAMPLER_SOFT:
+ values[0] = alGetDouble(pname);
+ return;
+ }
+ }
+
+ ContextRef context{GetContextRef()};
+ if(UNLIKELY(!context)) return;
+
+ if(!values)
+ alSetError(context.get(), AL_INVALID_VALUE, "NULL pointer");
+ else switch(pname)
+ {
+ default:
+ alSetError(context.get(), AL_INVALID_VALUE, "Invalid double-vector property 0x%04x", pname);
+ }
+}
+END_API_FUNC
+
+AL_API ALvoid AL_APIENTRY alGetFloatv(ALenum pname, ALfloat *values)
+START_API_FUNC
+{
+ if(values)
+ {
+ switch(pname)
+ {
+ case AL_DOPPLER_FACTOR:
+ case AL_DOPPLER_VELOCITY:
+ case AL_DISTANCE_MODEL:
+ case AL_SPEED_OF_SOUND:
+ case AL_DEFERRED_UPDATES_SOFT:
+ case AL_GAIN_LIMIT_SOFT:
+ case AL_NUM_RESAMPLERS_SOFT:
+ case AL_DEFAULT_RESAMPLER_SOFT:
+ values[0] = alGetFloat(pname);
+ return;
+ }
+ }
+
+ ContextRef context{GetContextRef()};
+ if(UNLIKELY(!context)) return;
+
+ if(!values)
+ alSetError(context.get(), AL_INVALID_VALUE, "NULL pointer");
+ else switch(pname)
+ {
+ default:
+ alSetError(context.get(), AL_INVALID_VALUE, "Invalid float-vector property 0x%04x", pname);
+ }
+}
+END_API_FUNC
+
+AL_API ALvoid AL_APIENTRY alGetIntegerv(ALenum pname, ALint *values)
+START_API_FUNC
+{
+ if(values)
+ {
+ switch(pname)
+ {
+ case AL_DOPPLER_FACTOR:
+ case AL_DOPPLER_VELOCITY:
+ case AL_DISTANCE_MODEL:
+ case AL_SPEED_OF_SOUND:
+ case AL_DEFERRED_UPDATES_SOFT:
+ case AL_GAIN_LIMIT_SOFT:
+ case AL_NUM_RESAMPLERS_SOFT:
+ case AL_DEFAULT_RESAMPLER_SOFT:
+ values[0] = alGetInteger(pname);
+ return;
+ }
+ }
+
+ ContextRef context{GetContextRef()};
+ if(UNLIKELY(!context)) return;
+
+ if(!values)
+ alSetError(context.get(), AL_INVALID_VALUE, "NULL pointer");
+ else switch(pname)
+ {
+ default:
+ alSetError(context.get(), AL_INVALID_VALUE, "Invalid integer-vector property 0x%04x", pname);
+ }
+}
+END_API_FUNC
+
+extern "C" AL_API void AL_APIENTRY alGetInteger64vSOFT(ALenum pname, ALint64SOFT *values)
+START_API_FUNC
+{
+ if(values)
+ {
+ switch(pname)
+ {
+ case AL_DOPPLER_FACTOR:
+ case AL_DOPPLER_VELOCITY:
+ case AL_DISTANCE_MODEL:
+ case AL_SPEED_OF_SOUND:
+ case AL_DEFERRED_UPDATES_SOFT:
+ case AL_GAIN_LIMIT_SOFT:
+ case AL_NUM_RESAMPLERS_SOFT:
+ case AL_DEFAULT_RESAMPLER_SOFT:
+ values[0] = alGetInteger64SOFT(pname);
+ return;
+ }
+ }
+
+ ContextRef context{GetContextRef()};
+ if(UNLIKELY(!context)) return;
+
+ if(!values)
+ alSetError(context.get(), AL_INVALID_VALUE, "NULL pointer");
+ else switch(pname)
+ {
+ default:
+ alSetError(context.get(), AL_INVALID_VALUE, "Invalid integer64-vector property 0x%04x", pname);
+ }
+}
+END_API_FUNC
+
+AL_API void AL_APIENTRY alGetPointervSOFT(ALenum pname, void **values)
+START_API_FUNC
+{
+ if(values)
+ {
+ switch(pname)
+ {
+ case AL_EVENT_CALLBACK_FUNCTION_SOFT:
+ case AL_EVENT_CALLBACK_USER_PARAM_SOFT:
+ values[0] = alGetPointerSOFT(pname);
+ return;
+ }
+ }
+
+ ContextRef context{GetContextRef()};
+ if(UNLIKELY(!context)) return;
+
+ if(!values)
+ alSetError(context.get(), AL_INVALID_VALUE, "NULL pointer");
+ else switch(pname)
+ {
+ default:
+ alSetError(context.get(), AL_INVALID_VALUE, "Invalid pointer-vector property 0x%04x", pname);
+ }
+}
+END_API_FUNC
+
+AL_API const ALchar* AL_APIENTRY alGetString(ALenum pname)
+START_API_FUNC
+{
+ ContextRef context{GetContextRef()};
+ if(UNLIKELY(!context)) return nullptr;
+
+ const ALchar *value{nullptr};
+ switch(pname)
+ {
+ case AL_VENDOR:
+ value = alVendor;
+ break;
+
+ case AL_VERSION:
+ value = alVersion;
+ break;
+
+ case AL_RENDERER:
+ value = alRenderer;
+ break;
+
+ case AL_EXTENSIONS:
+ value = context->ExtensionList;
+ break;
+
+ case AL_NO_ERROR:
+ value = alNoError;
+ break;
+
+ case AL_INVALID_NAME:
+ value = alErrInvalidName;
+ break;
+
+ case AL_INVALID_ENUM:
+ value = alErrInvalidEnum;
+ break;
+
+ case AL_INVALID_VALUE:
+ value = alErrInvalidValue;
+ break;
+
+ case AL_INVALID_OPERATION:
+ value = alErrInvalidOp;
+ break;
+
+ case AL_OUT_OF_MEMORY:
+ value = alErrOutOfMemory;
+ break;
+
+ default:
+ alSetError(context.get(), AL_INVALID_VALUE, "Invalid string property 0x%04x", pname);
+ }
+ return value;
+}
+END_API_FUNC
+
+AL_API ALvoid AL_APIENTRY alDopplerFactor(ALfloat value)
+START_API_FUNC
+{
+ ContextRef context{GetContextRef()};
+ if(UNLIKELY(!context)) return;
+
+ if(!(value >= 0.0f && std::isfinite(value)))
+ alSetError(context.get(), AL_INVALID_VALUE, "Doppler factor %f out of range", value);
+ else
+ {
+ std::lock_guard<std::mutex> _{context->PropLock};
+ context->DopplerFactor = value;
+ DO_UPDATEPROPS();
+ }
+}
+END_API_FUNC
+
+AL_API ALvoid AL_APIENTRY alDopplerVelocity(ALfloat value)
+START_API_FUNC
+{
+ ContextRef context{GetContextRef()};
+ if(UNLIKELY(!context)) return;
+
+ if((context->EnabledEvts.load(std::memory_order_relaxed)&EventType_Deprecated))
+ {
+ static constexpr ALCchar msg[] =
+ "alDopplerVelocity is deprecated in AL1.1, use alSpeedOfSound";
+ const ALsizei msglen = static_cast<ALsizei>(strlen(msg));
+ std::lock_guard<std::mutex> _{context->EventCbLock};
+ ALbitfieldSOFT enabledevts{context->EnabledEvts.load(std::memory_order_relaxed)};
+ if((enabledevts&EventType_Deprecated) && context->EventCb)
+ (*context->EventCb)(AL_EVENT_TYPE_DEPRECATED_SOFT, 0, 0, msglen, msg,
+ context->EventParam);
+ }
+
+ if(!(value >= 0.0f && std::isfinite(value)))
+ alSetError(context.get(), AL_INVALID_VALUE, "Doppler velocity %f out of range", value);
+ else
+ {
+ std::lock_guard<std::mutex> _{context->PropLock};
+ context->DopplerVelocity = value;
+ DO_UPDATEPROPS();
+ }
+}
+END_API_FUNC
+
+AL_API ALvoid AL_APIENTRY alSpeedOfSound(ALfloat value)
+START_API_FUNC
+{
+ ContextRef context{GetContextRef()};
+ if(UNLIKELY(!context)) return;
+
+ if(!(value > 0.0f && std::isfinite(value)))
+ alSetError(context.get(), AL_INVALID_VALUE, "Speed of sound %f out of range", value);
+ else
+ {
+ std::lock_guard<std::mutex> _{context->PropLock};
+ context->SpeedOfSound = value;
+ DO_UPDATEPROPS();
+ }
+}
+END_API_FUNC
+
+AL_API ALvoid AL_APIENTRY alDistanceModel(ALenum value)
+START_API_FUNC
+{
+ ContextRef context{GetContextRef()};
+ if(UNLIKELY(!context)) return;
+
+ if(!(value == AL_INVERSE_DISTANCE || value == AL_INVERSE_DISTANCE_CLAMPED ||
+ value == AL_LINEAR_DISTANCE || value == AL_LINEAR_DISTANCE_CLAMPED ||
+ value == AL_EXPONENT_DISTANCE || value == AL_EXPONENT_DISTANCE_CLAMPED ||
+ value == AL_NONE))
+ alSetError(context.get(), AL_INVALID_VALUE, "Distance model 0x%04x out of range", value);
+ else
+ {
+ std::lock_guard<std::mutex> _{context->PropLock};
+ context->mDistanceModel = static_cast<DistanceModel>(value);
+ if(!context->SourceDistanceModel)
+ DO_UPDATEPROPS();
+ }
+}
+END_API_FUNC
+
+
+AL_API ALvoid AL_APIENTRY alDeferUpdatesSOFT(void)
+START_API_FUNC
+{
+ ContextRef context{GetContextRef()};
+ if(UNLIKELY(!context)) return;
+
+ ALCcontext_DeferUpdates(context.get());
+}
+END_API_FUNC
+
+AL_API ALvoid AL_APIENTRY alProcessUpdatesSOFT(void)
+START_API_FUNC
+{
+ ContextRef context{GetContextRef()};
+ if(UNLIKELY(!context)) return;
+
+ ALCcontext_ProcessUpdates(context.get());
+}
+END_API_FUNC
+
+
+AL_API const ALchar* AL_APIENTRY alGetStringiSOFT(ALenum pname, ALsizei index)
+START_API_FUNC
+{
+ const char *ResamplerNames[] = {
+ alPointResampler, alLinearResampler,
+ alCubicResampler, alBSinc12Resampler,
+ alBSinc24Resampler,
+ };
+ static_assert(al::size(ResamplerNames) == ResamplerMax+1, "Incorrect ResamplerNames list");
+
+ ContextRef context{GetContextRef()};
+ if(UNLIKELY(!context)) return nullptr;
+
+ const ALchar *value{nullptr};
+ switch(pname)
+ {
+ case AL_RESAMPLER_NAME_SOFT:
+ if(index < 0 || static_cast<size_t>(index) >= al::size(ResamplerNames))
+ alSetError(context.get(), AL_INVALID_VALUE, "Resampler name index %d out of range",
+ index);
+ else
+ value = ResamplerNames[index];
+ break;
+
+ default:
+ alSetError(context.get(), AL_INVALID_VALUE, "Invalid string indexed property");
+ }
+ return value;
+}
+END_API_FUNC
+
+
+void UpdateContextProps(ALCcontext *context)
+{
+ /* Get an unused proprty container, or allocate a new one as needed. */
+ ALcontextProps *props{context->FreeContextProps.load(std::memory_order_acquire)};
+ if(!props)
+ props = static_cast<ALcontextProps*>(al_calloc(16, sizeof(*props)));
+ else
+ {
+ ALcontextProps *next;
+ do {
+ next = props->next.load(std::memory_order_relaxed);
+ } while(context->FreeContextProps.compare_exchange_weak(props, next,
+ std::memory_order_seq_cst, std::memory_order_acquire) == 0);
+ }
+
+ /* Copy in current property values. */
+ props->MetersPerUnit = context->MetersPerUnit;
+
+ props->DopplerFactor = context->DopplerFactor;
+ props->DopplerVelocity = context->DopplerVelocity;
+ props->SpeedOfSound = context->SpeedOfSound;
+
+ props->SourceDistanceModel = context->SourceDistanceModel;
+ props->mDistanceModel = context->mDistanceModel;
+
+ /* Set the new container for updating internal parameters. */
+ props = context->Update.exchange(props, std::memory_order_acq_rel);
+ if(props)
+ {
+ /* If there was an unused update container, put it back in the
+ * freelist.
+ */
+ AtomicReplaceHead(context->FreeContextProps, props);
+ }
+}
diff --git a/al/event.cpp b/al/event.cpp
new file mode 100644
index 00000000..d50cef2e
--- /dev/null
+++ b/al/event.cpp
@@ -0,0 +1,216 @@
+
+#include "config.h"
+
+#include <algorithm>
+#include <atomic>
+#include <cstring>
+#include <exception>
+#include <memory>
+#include <mutex>
+#include <new>
+#include <string>
+#include <thread>
+
+#include "AL/al.h"
+#include "AL/alc.h"
+
+#include "alError.h"
+#include "albyte.h"
+#include "alcmain.h"
+#include "alcontext.h"
+#include "alexcpt.h"
+#include "almalloc.h"
+#include "effects/base.h"
+#include "inprogext.h"
+#include "logging.h"
+#include "opthelpers.h"
+#include "ringbuffer.h"
+#include "threads.h"
+
+
+static int EventThread(ALCcontext *context)
+{
+ RingBuffer *ring{context->AsyncEvents.get()};
+ bool quitnow{false};
+ while(LIKELY(!quitnow))
+ {
+ auto evt_data = ring->getReadVector().first;
+ if(evt_data.len == 0)
+ {
+ context->EventSem.wait();
+ continue;
+ }
+
+ std::lock_guard<std::mutex> _{context->EventCbLock};
+ do {
+ auto &evt = *reinterpret_cast<AsyncEvent*>(evt_data.buf);
+ evt_data.buf += sizeof(AsyncEvent);
+ evt_data.len -= 1;
+ /* This automatically destructs the event object and advances the
+ * ringbuffer's read offset at the end of scope.
+ */
+ const struct EventAutoDestructor {
+ AsyncEvent &evt_;
+ RingBuffer *ring_;
+ ~EventAutoDestructor()
+ {
+ al::destroy_at(&evt_);
+ ring_->readAdvance(1);
+ }
+ } _{evt, ring};
+
+ quitnow = evt.EnumType == EventType_KillThread;
+ if(UNLIKELY(quitnow)) break;
+
+ if(evt.EnumType == EventType_ReleaseEffectState)
+ {
+ evt.u.mEffectState->DecRef();
+ continue;
+ }
+
+ ALbitfieldSOFT enabledevts{context->EnabledEvts.load(std::memory_order_acquire)};
+ if(!context->EventCb) continue;
+
+ if(evt.EnumType == EventType_SourceStateChange)
+ {
+ if(!(enabledevts&EventType_SourceStateChange))
+ continue;
+ std::string msg{"Source ID " + std::to_string(evt.u.srcstate.id)};
+ msg += " state has changed to ";
+ msg += (evt.u.srcstate.state==AL_INITIAL) ? "AL_INITIAL" :
+ (evt.u.srcstate.state==AL_PLAYING) ? "AL_PLAYING" :
+ (evt.u.srcstate.state==AL_PAUSED) ? "AL_PAUSED" :
+ (evt.u.srcstate.state==AL_STOPPED) ? "AL_STOPPED" : "<unknown>";
+ context->EventCb(AL_EVENT_TYPE_SOURCE_STATE_CHANGED_SOFT, evt.u.srcstate.id,
+ evt.u.srcstate.state, static_cast<ALsizei>(msg.length()), msg.c_str(),
+ context->EventParam
+ );
+ }
+ else if(evt.EnumType == EventType_BufferCompleted)
+ {
+ if(!(enabledevts&EventType_BufferCompleted))
+ continue;
+ std::string msg{std::to_string(evt.u.bufcomp.count)};
+ if(evt.u.bufcomp.count == 1) msg += " buffer completed";
+ else msg += " buffers completed";
+ context->EventCb(AL_EVENT_TYPE_BUFFER_COMPLETED_SOFT, evt.u.bufcomp.id,
+ evt.u.bufcomp.count, static_cast<ALsizei>(msg.length()), msg.c_str(),
+ context->EventParam
+ );
+ }
+ else if((enabledevts&evt.EnumType) == evt.EnumType)
+ context->EventCb(evt.u.user.type, evt.u.user.id, evt.u.user.param,
+ static_cast<ALsizei>(strlen(evt.u.user.msg)), evt.u.user.msg,
+ context->EventParam
+ );
+ } while(evt_data.len != 0);
+ }
+ return 0;
+}
+
+void StartEventThrd(ALCcontext *ctx)
+{
+ try {
+ ctx->EventThread = std::thread{EventThread, ctx};
+ }
+ catch(std::exception& e) {
+ ERR("Failed to start event thread: %s\n", e.what());
+ }
+ catch(...) {
+ ERR("Failed to start event thread! Expect problems.\n");
+ }
+}
+
+void StopEventThrd(ALCcontext *ctx)
+{
+ static constexpr AsyncEvent kill_evt{EventType_KillThread};
+ RingBuffer *ring{ctx->AsyncEvents.get()};
+ auto evt_data = ring->getWriteVector().first;
+ if(evt_data.len == 0)
+ {
+ do {
+ std::this_thread::yield();
+ evt_data = ring->getWriteVector().first;
+ } while(evt_data.len == 0);
+ }
+ new (evt_data.buf) AsyncEvent{kill_evt};
+ ring->writeAdvance(1);
+
+ ctx->EventSem.post();
+ if(ctx->EventThread.joinable())
+ ctx->EventThread.join();
+}
+
+AL_API void AL_APIENTRY alEventControlSOFT(ALsizei count, const ALenum *types, ALboolean enable)
+START_API_FUNC
+{
+ ContextRef context{GetContextRef()};
+ if(UNLIKELY(!context)) return;
+
+ if(count < 0) SETERR_RETURN(context.get(), AL_INVALID_VALUE,, "Controlling %d events", count);
+ if(count == 0) return;
+ if(!types) SETERR_RETURN(context.get(), AL_INVALID_VALUE,, "NULL pointer");
+
+ ALbitfieldSOFT flags{0};
+ const ALenum *types_end = types+count;
+ auto bad_type = std::find_if_not(types, types_end,
+ [&flags](ALenum type) noexcept -> bool
+ {
+ if(type == AL_EVENT_TYPE_BUFFER_COMPLETED_SOFT)
+ flags |= EventType_BufferCompleted;
+ else if(type == AL_EVENT_TYPE_SOURCE_STATE_CHANGED_SOFT)
+ flags |= EventType_SourceStateChange;
+ else if(type == AL_EVENT_TYPE_ERROR_SOFT)
+ flags |= EventType_Error;
+ else if(type == AL_EVENT_TYPE_PERFORMANCE_SOFT)
+ flags |= EventType_Performance;
+ else if(type == AL_EVENT_TYPE_DEPRECATED_SOFT)
+ flags |= EventType_Deprecated;
+ else if(type == AL_EVENT_TYPE_DISCONNECTED_SOFT)
+ flags |= EventType_Disconnected;
+ else
+ return false;
+ return true;
+ }
+ );
+ if(bad_type != types_end)
+ SETERR_RETURN(context.get(), AL_INVALID_ENUM,, "Invalid event type 0x%04x", *bad_type);
+
+ if(enable)
+ {
+ ALbitfieldSOFT enabledevts{context->EnabledEvts.load(std::memory_order_relaxed)};
+ while(context->EnabledEvts.compare_exchange_weak(enabledevts, enabledevts|flags,
+ std::memory_order_acq_rel, std::memory_order_acquire) == 0)
+ {
+ /* enabledevts is (re-)filled with the current value on failure, so
+ * just try again.
+ */
+ }
+ }
+ else
+ {
+ ALbitfieldSOFT enabledevts{context->EnabledEvts.load(std::memory_order_relaxed)};
+ while(context->EnabledEvts.compare_exchange_weak(enabledevts, enabledevts&~flags,
+ std::memory_order_acq_rel, std::memory_order_acquire) == 0)
+ {
+ }
+ /* Wait to ensure the event handler sees the changed flags before
+ * returning.
+ */
+ std::lock_guard<std::mutex>{context->EventCbLock};
+ }
+}
+END_API_FUNC
+
+AL_API void AL_APIENTRY alEventCallbackSOFT(ALEVENTPROCSOFT callback, void *userParam)
+START_API_FUNC
+{
+ ContextRef context{GetContextRef()};
+ if(UNLIKELY(!context)) return;
+
+ std::lock_guard<std::mutex> _{context->PropLock};
+ std::lock_guard<std::mutex> __{context->EventCbLock};
+ context->EventCb = callback;
+ context->EventParam = userParam;
+}
+END_API_FUNC