diff options
Diffstat (limited to 'al')
-rw-r--r-- | al/auxeffectslot.cpp | 792 | ||||
-rw-r--r-- | al/auxeffectslot.h | 105 | ||||
-rw-r--r-- | al/buffer.cpp | 1391 | ||||
-rw-r--r-- | al/buffer.h | 99 | ||||
-rw-r--r-- | al/effect.cpp | 725 | ||||
-rw-r--r-- | al/effect.h | 61 | ||||
-rw-r--r-- | al/error.cpp | 117 | ||||
-rw-r--r-- | al/event.cpp | 205 | ||||
-rw-r--r-- | al/event.h | 55 | ||||
-rw-r--r-- | al/extension.cpp | 79 | ||||
-rw-r--r-- | al/filter.cpp | 650 | ||||
-rw-r--r-- | al/filter.h | 56 | ||||
-rw-r--r-- | al/listener.cpp | 452 | ||||
-rw-r--r-- | al/listener.h | 64 | ||||
-rw-r--r-- | al/source.cpp | 3348 | ||||
-rw-r--r-- | al/source.h | 129 | ||||
-rw-r--r-- | al/state.cpp | 880 |
17 files changed, 9208 insertions, 0 deletions
diff --git a/al/auxeffectslot.cpp b/al/auxeffectslot.cpp new file mode 100644 index 00000000..3c312c66 --- /dev/null +++ b/al/auxeffectslot.cpp @@ -0,0 +1,792 @@ +/** + * 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 "auxeffectslot.h" + +#include <algorithm> +#include <cstdint> +#include <iterator> +#include <memory> +#include <mutex> +#include <numeric> +#include <thread> + +#include "AL/al.h" +#include "AL/alc.h" +#include "AL/efx.h" + +#include "alcmain.h" +#include "alcontext.h" +#include "alexcpt.h" +#include "almalloc.h" +#include "alnumeric.h" +#include "alspan.h" +#include "alu.h" +#include "effect.h" +#include "fpu_modes.h" +#include "inprogext.h" +#include "logging.h" +#include "opthelpers.h" + + +namespace { + +inline ALeffectslot *LookupEffectSlot(ALCcontext *context, ALuint id) noexcept +{ + const size_t lidx{(id-1) >> 6}; + const ALuint slidx{(id-1) & 0x3f}; + + if UNLIKELY(lidx >= context->mEffectSlotList.size()) + return nullptr; + EffectSlotSubList &sublist{context->mEffectSlotList[lidx]}; + if UNLIKELY(sublist.FreeMask & (1_u64 << slidx)) + return nullptr; + return sublist.EffectSlots + slidx; +} + +inline ALeffect *LookupEffect(ALCdevice *device, ALuint id) noexcept +{ + const size_t lidx{(id-1) >> 6}; + const ALuint 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, size_t count, ALCcontext *context) +{ + if(count < 1) return; + ALeffectslotArray *curarray{context->mActiveAuxSlots.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->mActiveAuxSlots.exchange(newarray, std::memory_order_acq_rel); + ALCdevice *device{context->mDevice.get()}; + while((device->MixCount.load(std::memory_order_acquire)&1)) + std::this_thread::yield(); + delete curarray; +} + +void RemoveActiveEffectSlots(const ALuint *slotids, size_t count, ALCcontext *context) +{ + if(count < 1) return; + ALeffectslotArray *curarray{context->mActiveAuxSlots.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->mActiveAuxSlots.exchange(newarray, std::memory_order_acq_rel); + ALCdevice *device{context->mDevice.get()}; + while((device->MixCount.load(std::memory_order_acquire)&1)) + std::this_thread::yield(); + delete curarray; +} + + +bool EnsureEffectSlots(ALCcontext *context, size_t needed) +{ + size_t count{std::accumulate(context->mEffectSlotList.cbegin(), + context->mEffectSlotList.cend(), size_t{0}, + [](size_t cur, const EffectSlotSubList &sublist) noexcept -> size_t + { return cur + static_cast<ALuint>(POPCNT64(sublist.FreeMask)); } + )}; + + while(needed > count) + { + if UNLIKELY(context->mEffectSlotList.size() >= 1<<25) + return false; + + context->mEffectSlotList.emplace_back(); + auto sublist = context->mEffectSlotList.end() - 1; + sublist->FreeMask = ~0_u64; + sublist->EffectSlots = static_cast<ALeffectslot*>( + al_calloc(alignof(ALeffectslot), sizeof(ALeffectslot)*64)); + if UNLIKELY(!sublist->EffectSlots) + { + context->mEffectSlotList.pop_back(); + return false; + } + count += 64; + } + return true; +} + +ALeffectslot *AllocEffectSlot(ALCcontext *context) +{ + auto sublist = std::find_if(context->mEffectSlotList.begin(), context->mEffectSlotList.end(), + [](const EffectSlotSubList &entry) noexcept -> bool + { return entry.FreeMask != 0; } + ); + auto lidx = static_cast<ALuint>(std::distance(context->mEffectSlotList.begin(), sublist)); + auto slidx = static_cast<ALuint>(CTZ64(sublist->FreeMask)); + + ALeffectslot *slot{::new (sublist->EffectSlots + slidx) ALeffectslot{}}; + if(ALenum err{InitEffectSlot(slot)}) + { + al::destroy_at(slot); + context->setError(err, "Effect slot object initialization failed"); + return nullptr; + } + aluInitEffectPanning(slot, context->mDevice.get()); + + /* Add 1 to avoid source ID 0. */ + slot->id = ((lidx<<6) | slidx) + 1; + + context->mNumEffectSlots += 1; + sublist->FreeMask &= ~(1_u64 << slidx); + + return slot; +} + +void FreeEffectSlot(ALCcontext *context, ALeffectslot *slot) +{ + const ALuint id{slot->id - 1}; + const size_t lidx{id >> 6}; + const ALuint slidx{id & 0x3f}; + + al::destroy_at(slot); + + context->mEffectSlotList[lidx].FreeMask |= 1_u64 << slidx; + context->mNumEffectSlots--; +} + + +#define DO_UPDATEPROPS() do { \ + if(!context->mDeferUpdates.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 UNLIKELY(n < 0) + context->setError(AL_INVALID_VALUE, "Generating %d effect slots", n); + if UNLIKELY(n <= 0) return; + + std::unique_lock<std::mutex> slotlock{context->mEffectSlotLock}; + ALCdevice *device{context->mDevice.get()}; + if(static_cast<ALuint>(n) > device->AuxiliaryEffectSlotMax-context->mNumEffectSlots) + { + context->setError(AL_OUT_OF_MEMORY, "Exceeding %u effect slot limit (%u + %d)", + device->AuxiliaryEffectSlotMax, context->mNumEffectSlots, n); + return; + } + if(!EnsureEffectSlots(context.get(), static_cast<ALuint>(n))) + { + context->setError(AL_OUT_OF_MEMORY, "Failed to allocate %d effectslot%s", n, + (n==1) ? "" : "s"); + return; + } + + if(n == 1) + { + ALeffectslot *slot{AllocEffectSlot(context.get())}; + if(!slot) return; + effectslots[0] = slot->id; + } + else + { + al::vector<ALuint> ids; + ALsizei count{n}; + ids.reserve(static_cast<ALuint>(count)); + do { + ALeffectslot *slot{AllocEffectSlot(context.get())}; + if(!slot) + { + slotlock.unlock(); + alDeleteAuxiliaryEffectSlots(static_cast<ALsizei>(ids.size()), ids.data()); + return; + } + ids.emplace_back(slot->id); + } while(--count); + std::copy(ids.cbegin(), ids.cend(), effectslots); + } + + AddActiveEffectSlots(effectslots, static_cast<ALuint>(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 UNLIKELY(n < 0) + context->setError(AL_INVALID_VALUE, "Deleting %d effect slots", n); + if UNLIKELY(n <= 0) return; + + std::lock_guard<std::mutex> _{context->mEffectSlotLock}; + auto validate_slot = [&context](const ALuint id) -> bool + { + ALeffectslot *slot{LookupEffectSlot(context.get(), id)}; + if UNLIKELY(!slot) + { + context->setError(AL_INVALID_NAME, "Invalid effect slot ID %u", id); + return false; + } + if UNLIKELY(ReadRef(slot->ref) != 0) + { + context->setError(AL_INVALID_OPERATION, "Deleting in-use effect slot %u", id); + return false; + } + return true; + }; + auto effectslots_end = effectslots + n; + auto bad_slot = std::find_if_not(effectslots, effectslots_end, validate_slot); + if UNLIKELY(bad_slot != effectslots_end) return; + + // All effectslots are valid, remove and delete them + RemoveActiveEffectSlots(effectslots, static_cast<ALuint>(n), context.get()); + auto delete_slot = [&context](const ALuint sid) -> void + { + ALeffectslot *slot{LookupEffectSlot(context.get(), sid)}; + if(slot) FreeEffectSlot(context.get(), slot); + }; + std::for_each(effectslots, effectslots_end, delete_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->mEffectSlotLock}; + 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->mPropLock}; + std::lock_guard<std::mutex> __{context->mEffectSlotLock}; + ALeffectslot *slot = LookupEffectSlot(context.get(), effectslot); + if UNLIKELY(!slot) + SETERR_RETURN(context, AL_INVALID_NAME,, "Invalid effect slot ID %u", effectslot); + + ALeffectslot *target{}; + ALCdevice *device{}; + ALenum err{}; + switch(param) + { + case AL_EFFECTSLOT_EFFECT: + device = context->mDevice.get(); + + { std::lock_guard<std::mutex> ___{device->EffectLock}; + ALeffect *effect{value ? LookupEffect(device, static_cast<ALuint>(value)) : nullptr}; + if(!(value == 0 || effect != nullptr)) + SETERR_RETURN(context, AL_INVALID_VALUE,, "Invalid effect ID %u", value); + err = InitializeEffect(context.get(), slot, effect); + } + if(err != AL_NO_ERROR) + { + context->setError(err, "Effect initialization failed"); + return; + } + break; + + case AL_EFFECTSLOT_AUXILIARY_SEND_AUTO: + if(!(value == AL_TRUE || value == AL_FALSE)) + SETERR_RETURN(context, AL_INVALID_VALUE,, + "Effect slot auxiliary send auto out of range"); + slot->AuxSendAuto = static_cast<ALboolean>(value); + break; + + case AL_EFFECTSLOT_TARGET_SOFT: + target = LookupEffectSlot(context.get(), static_cast<ALuint>(value)); + if(value && !target) + SETERR_RETURN(context, 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, 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, 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->mEffectSlotLock}; + ALeffectslot *slot = LookupEffectSlot(context.get(), effectslot); + if UNLIKELY(!slot) + SETERR_RETURN(context, AL_INVALID_NAME,, "Invalid effect slot ID %u", effectslot); + + switch(param) + { + default: + SETERR_RETURN(context, 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->mPropLock}; + std::lock_guard<std::mutex> __{context->mEffectSlotLock}; + ALeffectslot *slot = LookupEffectSlot(context.get(), effectslot); + if UNLIKELY(!slot) + SETERR_RETURN(context, 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, AL_INVALID_VALUE,, "Effect slot gain out of range"); + slot->Gain = value; + break; + + default: + SETERR_RETURN(context, 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->mEffectSlotLock}; + ALeffectslot *slot = LookupEffectSlot(context.get(), effectslot); + if UNLIKELY(!slot) + SETERR_RETURN(context, AL_INVALID_NAME,, "Invalid effect slot ID %u", effectslot); + + switch(param) + { + default: + SETERR_RETURN(context, 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->mEffectSlotLock}; + ALeffectslot *slot = LookupEffectSlot(context.get(), effectslot); + if UNLIKELY(!slot) + SETERR_RETURN(context, 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: + if(auto *target = slot->Target) + *value = static_cast<ALint>(target->id); + else + *value = 0; + break; + + default: + context->setError(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->mEffectSlotLock}; + ALeffectslot *slot = LookupEffectSlot(context.get(), effectslot); + if UNLIKELY(!slot) + SETERR_RETURN(context, AL_INVALID_NAME,, "Invalid effect slot ID %u", effectslot); + + switch(param) + { + default: + context->setError(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->mEffectSlotLock}; + ALeffectslot *slot = LookupEffectSlot(context.get(), effectslot); + if UNLIKELY(!slot) + SETERR_RETURN(context, AL_INVALID_NAME,, "Invalid effect slot ID %u", effectslot); + + switch(param) + { + case AL_EFFECTSLOT_GAIN: + *value = slot->Gain; + break; + + default: + context->setError(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->mEffectSlotLock}; + ALeffectslot *slot = LookupEffectSlot(context.get(), effectslot); + if UNLIKELY(!slot) + SETERR_RETURN(context, AL_INVALID_NAME,, "Invalid effect slot ID %u", effectslot); + + switch(param) + { + default: + context->setError(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->mDevice.get()}; + 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->release(); + 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->release(); + EffectSlot->Effect.State = State; + } + else if(effect) + EffectSlot->Effect.Props = effect->Props; + + /* Remove state references from old effect slot property updates. */ + ALeffectslotProps *props{Context->mFreeEffectslotProps.load()}; + while(props) + { + if(props->State) + props->State->release(); + props->State = nullptr; + props = props->next.load(std::memory_order_relaxed); + } + + return AL_NO_ERROR; +} + + +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->add_ref(); + slot->Params.mEffectState = slot->Effect.State; + return AL_NO_ERROR; +} + +ALeffectslot::~ALeffectslot() +{ + if(Target) + DecrementRef(Target->ref); + Target = nullptr; + + ALeffectslotProps *props{Params.Update.load()}; + if(props) + { + if(props->State) props->State->release(); + TRACE("Freed unapplied AuxiliaryEffectSlot update %p\n", + decltype(std::declval<void*>()){props}); + delete props; + } + + if(Effect.State) + Effect.State->release(); + if(Params.mEffectState) + Params.mEffectState->release(); +} + +void UpdateEffectSlotProps(ALeffectslot *slot, ALCcontext *context) +{ + /* Get an unused property container, or allocate a new one as needed. */ + ALeffectslotProps *props{context->mFreeEffectslotProps.load(std::memory_order_relaxed)}; + if(!props) + props = new ALeffectslotProps{}; + else + { + ALeffectslotProps *next; + do { + next = props->next.load(std::memory_order_relaxed); + } while(context->mFreeEffectslotProps.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->add_ref(); + props->State = slot->Effect.State; + + /* Set the new container for updating internal parameters. */ + props = slot->Params.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->release(); + props->State = nullptr; + AtomicReplaceHead(context->mFreeEffectslotProps, props); + } + + if(oldstate) + oldstate->release(); +} + +void UpdateAllEffectSlotProps(ALCcontext *context) +{ + std::lock_guard<std::mutex> _{context->mEffectSlotLock}; + ALeffectslotArray *auxslots{context->mActiveAuxSlots.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/auxeffectslot.h b/al/auxeffectslot.h new file mode 100644 index 00000000..2471447f --- /dev/null +++ b/al/auxeffectslot.h @@ -0,0 +1,105 @@ +#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; + + DEF_NEWDEL(ALeffectslotProps) +}; + + +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}; + + struct { + std::atomic<ALeffectslotProps*> Update{nullptr}; + + 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_NEWDEL(ALeffectslot) +}; + +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/buffer.cpp b/al/buffer.cpp new file mode 100644 index 00000000..8f4228a8 --- /dev/null +++ b/al/buffer.cpp @@ -0,0 +1,1391 @@ +/** + * 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 "buffer.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 <numeric> +#include <utility> + +#include "AL/al.h" +#include "AL/alc.h" +#include "AL/alext.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, size_t numchans, size_t align) +{ + ALint sample[MAX_INPUT_CHANNELS]{}; + ALint index[MAX_INPUT_CHANNELS]{}; + ALuint code[MAX_INPUT_CHANNELS]{}; + + for(size_t 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++) = static_cast<ALshort>(sample[c]); + } + + for(size_t i{1};i < align;i++) + { + if((i&7) == 1) + { + for(size_t 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(size_t 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++) = static_cast<ALshort>(sample[c]); + } + } +} + +void DecodeMSADPCMBlock(ALshort *dst, const al::byte *src, size_t numchans, size_t align) +{ + ALubyte blockpred[MAX_INPUT_CHANNELS]{}; + ALint delta[MAX_INPUT_CHANNELS]{}; + ALshort samples[MAX_INPUT_CHANNELS][2]{}; + + for(size_t c{0};c < numchans;c++) + { + blockpred[c] = std::min<ALubyte>(al::to_integer<ALubyte>(src[0]), 6); + ++src; + } + for(size_t 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(size_t c{0};c < numchans;c++) + { + samples[c][0] = static_cast<ALshort>(al::to_integer<int>(src[0]) | + (al::to_integer<int>(src[1])<<8)); + src += 2; + } + for(size_t c{0};c < numchans;c++) + { + samples[c][1] = static_cast<ALshort>(al::to_integer<int>(src[0]) | + (al::to_integer<int>(src[1])<<8)); + src += 2; + } + + /* Second sample is written first. */ + for(size_t c{0};c < numchans;c++) + *(dst++) = samples[c][1]; + for(size_t c{0};c < numchans;c++) + *(dst++) = samples[c][0]; + + int num{0}; + for(size_t i{2};i < align;i++) + { + for(size_t 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] = static_cast<ALshort>(pred); + + delta[c] = (MSADPCMAdaption[al::to_integer<ALubyte>(nibble)] * delta[c]) / 256; + delta[c] = maxi(16, delta[c]); + + *(dst++) = static_cast<ALshort>(pred); + } + } +} + +void Convert_ALshort_ALima4(ALshort *dst, const al::byte *src, size_t numchans, size_t len, + size_t align) +{ + const size_t 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, size_t numchans, size_t len, + size_t align) +{ + const size_t byte_align{((align-2)/2 + 7) * numchans}; + + len /= align; + while(len--) + { + DecodeMSADPCMBlock(dst, src, numchans, align); + src += byte_align; + dst += align*numchans; + } +} + + +ALuint 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; +} +ALuint 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; +} +inline ALuint FrameSizeFromUserFmt(UserFmtChannels chans, UserFmtType type) +{ return ChannelsFromUserFmt(chans) * BytesFromUserFmt(type); } + + +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)}; + + +bool EnsureBuffers(ALCdevice *device, size_t needed) +{ + size_t count{std::accumulate(device->BufferList.cbegin(), device->BufferList.cend(), size_t{0}, + [](size_t cur, const BufferSubList &sublist) noexcept -> size_t + { return cur + static_cast<ALuint>(POPCNT64(sublist.FreeMask)); } + )}; + + while(needed > count) + { + if UNLIKELY(device->BufferList.size() >= 1<<25) + return false; + + device->BufferList.emplace_back(); + auto sublist = device->BufferList.end() - 1; + sublist->FreeMask = ~0_u64; + sublist->Buffers = static_cast<ALbuffer*>(al_calloc(alignof(ALbuffer), sizeof(ALbuffer)*64)); + if UNLIKELY(!sublist->Buffers) + { + device->BufferList.pop_back(); + return false; + } + count += 64; + } + return true; +} + +ALbuffer *AllocBuffer(ALCdevice *device) +{ + auto sublist = std::find_if(device->BufferList.begin(), device->BufferList.end(), + [](const BufferSubList &entry) noexcept -> bool + { return entry.FreeMask != 0; } + ); + + auto lidx = static_cast<ALuint>(std::distance(device->BufferList.begin(), sublist)); + auto slidx = static_cast<ALuint>(CTZ64(sublist->FreeMask)); + + ALbuffer *buffer{::new (sublist->Buffers + slidx) 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) +{ + const ALuint id{buffer->id - 1}; + const size_t lidx{id >> 6}; + const ALuint slidx{id & 0x3f}; + + al::destroy_at(buffer); + + device->BufferList[lidx].FreeMask |= 1_u64 << slidx; +} + +inline ALbuffer *LookupBuffer(ALCdevice *device, ALuint id) +{ + const size_t lidx{(id-1) >> 6}; + const ALuint 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; +} + + +ALuint SanitizeAlignment(UserFmtType type, ALuint align) +{ + 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 static_cast<ALuint>(align); + return 0; + } + if(type == UserFmtMSADPCM) + { + /* MSADPCM block alignment must be a multiple of 2. */ + if((align&1) == 0) return static_cast<ALuint>(align); + return 0; + } + + return static_cast<ALuint>(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>"; +} + +/** Loads the specified data into the buffer, using the specified format. */ +void LoadData(ALCcontext *context, ALbuffer *ALBuf, ALsizei freq, ALuint 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 ALuint unpackalign{ALBuf->UnpackAlign}; + const ALuint align{SanitizeAlignment(SrcType, unpackalign)}; + if UNLIKELY(align < 1) + SETERR_RETURN(context, AL_INVALID_VALUE,, "Invalid unpack alignment %u 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 ALuint 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 ALuint frames{size / SrcByteAlign * align}; + + /* Convert the sample frames to the number of bytes needed for internal + * storage. + */ + ALuint NumChannels{ChannelsFromFmt(DstChannels)}; + ALuint FrameSize{NumChannels * BytesFromFmt(DstType)}; + if UNLIKELY(frames > std::numeric_limits<size_t>::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 = static_cast<ALuint>(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 const 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) + context->setError(AL_INVALID_VALUE, "Generating %d buffers", n); + if UNLIKELY(n <= 0) return; + + ALCdevice *device{context->mDevice.get()}; + std::lock_guard<std::mutex> _{device->BufferLock}; + if(!EnsureBuffers(device, static_cast<ALuint>(n))) + { + context->setError(AL_OUT_OF_MEMORY, "Failed to allocate %d buffer%s", n, (n==1)?"":"s"); + return; + } + + if LIKELY(n == 1) + { + /* Special handling for the easy and normal case. */ + ALbuffer *buffer{AllocBuffer(device)}; + buffers[0] = buffer->id; + } + else + { + /* 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(static_cast<ALuint>(n)); + do { + ALbuffer *buffer{AllocBuffer(device)}; + 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) + context->setError(AL_INVALID_VALUE, "Deleting %d buffers", n); + if UNLIKELY(n <= 0) return; + + ALCdevice *device{context->mDevice.get()}; + std::lock_guard<std::mutex> _{device->BufferLock}; + + /* First try to find any buffers that are invalid or in-use. */ + auto validate_buffer = [device, &context](const ALuint bid) -> bool + { + if(!bid) return true; + ALbuffer *ALBuf{LookupBuffer(device, bid)}; + if UNLIKELY(!ALBuf) + { + context->setError(AL_INVALID_NAME, "Invalid buffer ID %u", bid); + return false; + } + if UNLIKELY(ReadRef(ALBuf->ref) != 0) + { + context->setError(AL_INVALID_OPERATION, "Deleting in-use buffer %u", bid); + return false; + } + return true; + }; + const ALuint *buffers_end = buffers + n; + auto invbuf = std::find_if_not(buffers, buffers_end, validate_buffer); + if UNLIKELY(invbuf != buffers_end) return; + + /* All good. Delete non-0 buffer IDs. */ + auto delete_buffer = [device](const ALuint bid) -> void + { + ALbuffer *buffer{bid ? LookupBuffer(device, bid) : nullptr}; + if(buffer) FreeBuffer(device, buffer); + }; + std::for_each(buffers, buffers_end, delete_buffer); +} +END_API_FUNC + +AL_API ALboolean AL_APIENTRY alIsBuffer(ALuint buffer) +START_API_FUNC +{ + ContextRef context{GetContextRef()}; + if LIKELY(context) + { + ALCdevice *device{context->mDevice.get()}; + 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->mDevice.get()}; + std::lock_guard<std::mutex> _{device->BufferLock}; + + ALbuffer *albuf = LookupBuffer(device, buffer); + if UNLIKELY(!albuf) + context->setError(AL_INVALID_NAME, "Invalid buffer ID %u", buffer); + else if UNLIKELY(size < 0) + context->setError(AL_INVALID_VALUE, "Negative storage size %d", size); + else if UNLIKELY(freq < 1) + context->setError(AL_INVALID_VALUE, "Invalid sample rate %d", freq); + else if UNLIKELY((flags&INVALID_STORAGE_MASK) != 0) + context->setError(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)) + context->setError(AL_INVALID_VALUE, + "Declaring persistently mapped storage without read or write access"); + else + { + auto usrfmt = DecomposeUserFormat(format); + if UNLIKELY(!usrfmt) + context->setError(AL_INVALID_ENUM, "Invalid format 0x%04x", format); + else + LoadData(context.get(), albuf, freq, static_cast<ALuint>(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->mDevice.get()}; + std::lock_guard<std::mutex> _{device->BufferLock}; + + ALbuffer *albuf = LookupBuffer(device, buffer); + if UNLIKELY(!albuf) + context->setError(AL_INVALID_NAME, "Invalid buffer ID %u", buffer); + else if UNLIKELY((access&INVALID_MAP_FLAGS) != 0) + context->setError(AL_INVALID_VALUE, "Invalid map flags 0x%x", access&INVALID_MAP_FLAGS); + else if UNLIKELY(!(access&MAP_READ_WRITE_FLAGS)) + context->setError(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)) + context->setError(AL_INVALID_OPERATION, + "Mapping in-use buffer %u without persistent mapping", buffer); + else if UNLIKELY(albuf->MappedAccess != 0) + context->setError(AL_INVALID_OPERATION, "Mapping already-mapped buffer %u", buffer); + else if UNLIKELY((unavailable&AL_MAP_READ_BIT_SOFT)) + context->setError(AL_INVALID_VALUE, + "Mapping buffer %u for reading without read access", buffer); + else if UNLIKELY((unavailable&AL_MAP_WRITE_BIT_SOFT)) + context->setError(AL_INVALID_VALUE, + "Mapping buffer %u for writing without write access", buffer); + else if UNLIKELY((unavailable&AL_MAP_PERSISTENT_BIT_SOFT)) + context->setError(AL_INVALID_VALUE, + "Mapping buffer %u persistently without persistent access", buffer); + else if UNLIKELY(offset < 0 || length <= 0 + || static_cast<ALuint>(offset) >= albuf->OriginalSize + || static_cast<ALuint>(length) > albuf->OriginalSize - static_cast<ALuint>(offset)) + context->setError(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->mDevice.get()}; + std::lock_guard<std::mutex> _{device->BufferLock}; + + ALbuffer *albuf = LookupBuffer(device, buffer); + if UNLIKELY(!albuf) + context->setError(AL_INVALID_NAME, "Invalid buffer ID %u", buffer); + else if UNLIKELY(albuf->MappedAccess == 0) + context->setError(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->mDevice.get()}; + std::lock_guard<std::mutex> _{device->BufferLock}; + + ALbuffer *albuf = LookupBuffer(device, buffer); + if UNLIKELY(!albuf) + context->setError(AL_INVALID_NAME, "Invalid buffer ID %u", buffer); + else if UNLIKELY(!(albuf->MappedAccess&AL_MAP_WRITE_BIT_SOFT)) + context->setError(AL_INVALID_OPERATION, "Flushing buffer %u while not mapped for writing", + buffer); + else if UNLIKELY(offset < albuf->MappedOffset || length <= 0 + || offset >= albuf->MappedOffset+albuf->MappedSize + || length > albuf->MappedOffset+albuf->MappedSize-offset) + context->setError(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->mDevice.get()}; + std::lock_guard<std::mutex> _{device->BufferLock}; + + ALbuffer *albuf = LookupBuffer(device, buffer); + if UNLIKELY(!albuf) + { + context->setError(AL_INVALID_NAME, "Invalid buffer ID %u", buffer); + return; + } + + auto usrfmt = DecomposeUserFormat(format); + if UNLIKELY(!usrfmt) + { + context->setError(AL_INVALID_ENUM, "Invalid format 0x%04x", format); + return; + } + + ALuint unpack_align{albuf->UnpackAlign}; + ALuint align{SanitizeAlignment(usrfmt->type, unpack_align)}; + if UNLIKELY(align < 1) + context->setError(AL_INVALID_VALUE, "Invalid unpack alignment %u", unpack_align); + else if UNLIKELY(long{usrfmt->channels} != long{albuf->mFmtChannels} + || usrfmt->type != albuf->OriginalType) + context->setError(AL_INVALID_ENUM, "Unpacking data with mismatched format"); + else if UNLIKELY(align != albuf->OriginalAlign) + context->setError(AL_INVALID_VALUE, + "Unpacking data with alignment %u does not match original alignment %u", align, + albuf->OriginalAlign); + else if UNLIKELY(albuf->MappedAccess != 0) + context->setError(AL_INVALID_OPERATION, "Unpacking data into mapped buffer %u", buffer); + else + { + ALuint num_chans{ChannelsFromFmt(albuf->mFmtChannels)}; + ALuint frame_size{num_chans * BytesFromFmt(albuf->mFmtType)}; + ALuint 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 || static_cast<ALuint>(offset) > albuf->OriginalSize + || static_cast<ALuint>(length) > albuf->OriginalSize-static_cast<ALuint>(offset)) + context->setError(AL_INVALID_VALUE, "Invalid data sub-range %d+%d on buffer %u", + offset, length, buffer); + else if UNLIKELY((static_cast<ALuint>(offset)%byte_align) != 0) + context->setError(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((static_cast<ALuint>(length)%byte_align) != 0) + context->setError(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 */ + size_t byteoff{static_cast<ALuint>(offset)/byte_align * align * frame_size}; + size_t samplen{static_cast<ALuint>(length)/byte_align * align}; + + void *dst = albuf->mData.data() + byteoff; + if(usrfmt->type == UserFmtIMA4 && albuf->mFmtType == FmtShort) + Convert_ALshort_ALima4(static_cast<ALshort*>(dst), + static_cast<const al::byte*>(data), num_chans, samplen, align); + else if(usrfmt->type == UserFmtMSADPCM && albuf->mFmtType == FmtShort) + Convert_ALshort_ALmsadpcm(static_cast<ALshort*>(dst), + static_cast<const al::byte*>(data), num_chans, samplen, align); + else + { + assert(long{usrfmt->type} == long{albuf->mFmtType}); + memcpy(dst, data, size_t{samplen} * 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; + + context->setError(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; + + context->setError(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; + + context->setError(AL_INVALID_OPERATION, "alGetBufferSamplesSOFT not supported"); +} +END_API_FUNC + +AL_API ALboolean AL_APIENTRY alIsBufferFormatSupportedSOFT(ALenum /*format*/) +START_API_FUNC +{ + ContextRef context{GetContextRef()}; + if UNLIKELY(!context) return AL_FALSE; + + context->setError(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->mDevice.get()}; + std::lock_guard<std::mutex> _{device->BufferLock}; + + if UNLIKELY(LookupBuffer(device, buffer) == nullptr) + context->setError(AL_INVALID_NAME, "Invalid buffer ID %u", buffer); + else switch(param) + { + default: + context->setError(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->mDevice.get()}; + std::lock_guard<std::mutex> _{device->BufferLock}; + + if UNLIKELY(LookupBuffer(device, buffer) == nullptr) + context->setError(AL_INVALID_NAME, "Invalid buffer ID %u", buffer); + else switch(param) + { + default: + context->setError(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->mDevice.get()}; + std::lock_guard<std::mutex> _{device->BufferLock}; + + if UNLIKELY(LookupBuffer(device, buffer) == nullptr) + context->setError(AL_INVALID_NAME, "Invalid buffer ID %u", buffer); + else if UNLIKELY(!values) + context->setError(AL_INVALID_VALUE, "NULL pointer"); + else switch(param) + { + default: + context->setError(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->mDevice.get()}; + std::lock_guard<std::mutex> _{device->BufferLock}; + + ALbuffer *albuf = LookupBuffer(device, buffer); + if UNLIKELY(!albuf) + context->setError(AL_INVALID_NAME, "Invalid buffer ID %u", buffer); + else switch(param) + { + case AL_UNPACK_BLOCK_ALIGNMENT_SOFT: + if UNLIKELY(value < 0) + context->setError(AL_INVALID_VALUE, "Invalid unpack block alignment %d", value); + else + albuf->UnpackAlign = static_cast<ALuint>(value); + break; + + case AL_PACK_BLOCK_ALIGNMENT_SOFT: + if UNLIKELY(value < 0) + context->setError(AL_INVALID_VALUE, "Invalid pack block alignment %d", value); + else + albuf->PackAlign = static_cast<ALuint>(value); + break; + + default: + context->setError(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->mDevice.get()}; + std::lock_guard<std::mutex> _{device->BufferLock}; + + if UNLIKELY(LookupBuffer(device, buffer) == nullptr) + context->setError(AL_INVALID_NAME, "Invalid buffer ID %u", buffer); + else switch(param) + { + default: + context->setError(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->mDevice.get()}; + std::lock_guard<std::mutex> _{device->BufferLock}; + + ALbuffer *albuf = LookupBuffer(device, buffer); + if UNLIKELY(!albuf) + context->setError(AL_INVALID_NAME, "Invalid buffer ID %u", buffer); + else if UNLIKELY(!values) + context->setError(AL_INVALID_VALUE, "NULL pointer"); + else switch(param) + { + case AL_LOOP_POINTS_SOFT: + if UNLIKELY(ReadRef(albuf->ref) != 0) + context->setError(AL_INVALID_OPERATION, "Modifying in-use buffer %u's loop points", + buffer); + else if UNLIKELY(values[0] < 0 || values[0] >= values[1] + || static_cast<ALuint>(values[1]) > albuf->SampleLen) + context->setError(AL_INVALID_VALUE, "Invalid loop point range %d -> %d on buffer %u", + values[0], values[1], buffer); + else + { + albuf->LoopStart = static_cast<ALuint>(values[0]); + albuf->LoopEnd = static_cast<ALuint>(values[1]); + } + break; + + default: + context->setError(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->mDevice.get()}; + std::lock_guard<std::mutex> _{device->BufferLock}; + + ALbuffer *albuf = LookupBuffer(device, buffer); + if UNLIKELY(!albuf) + context->setError(AL_INVALID_NAME, "Invalid buffer ID %u", buffer); + else if UNLIKELY(!value) + context->setError(AL_INVALID_VALUE, "NULL pointer"); + else switch(param) + { + default: + context->setError(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->mDevice.get()}; + std::lock_guard<std::mutex> _{device->BufferLock}; + + if UNLIKELY(LookupBuffer(device, buffer) == nullptr) + context->setError(AL_INVALID_NAME, "Invalid buffer ID %u", buffer); + else if UNLIKELY(!value1 || !value2 || !value3) + context->setError(AL_INVALID_VALUE, "NULL pointer"); + else switch(param) + { + default: + context->setError(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->mDevice.get()}; + std::lock_guard<std::mutex> _{device->BufferLock}; + + if UNLIKELY(LookupBuffer(device, buffer) == nullptr) + context->setError(AL_INVALID_NAME, "Invalid buffer ID %u", buffer); + else if UNLIKELY(!values) + context->setError(AL_INVALID_VALUE, "NULL pointer"); + else switch(param) + { + default: + context->setError(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->mDevice.get()}; + std::lock_guard<std::mutex> _{device->BufferLock}; + ALbuffer *albuf = LookupBuffer(device, buffer); + if UNLIKELY(!albuf) + context->setError(AL_INVALID_NAME, "Invalid buffer ID %u", buffer); + else if UNLIKELY(!value) + context->setError(AL_INVALID_VALUE, "NULL pointer"); + else switch(param) + { + case AL_FREQUENCY: + *value = static_cast<ALint>(albuf->Frequency); + break; + + case AL_BITS: + *value = static_cast<ALint>(BytesFromFmt(albuf->mFmtType) * 8); + break; + + case AL_CHANNELS: + *value = static_cast<ALint>(ChannelsFromFmt(albuf->mFmtChannels)); + break; + + case AL_SIZE: + *value = static_cast<ALint>(albuf->SampleLen * + FrameSizeFromFmt(albuf->mFmtChannels, albuf->mFmtType)); + break; + + case AL_UNPACK_BLOCK_ALIGNMENT_SOFT: + *value = static_cast<ALint>(albuf->UnpackAlign); + break; + + case AL_PACK_BLOCK_ALIGNMENT_SOFT: + *value = static_cast<ALint>(albuf->PackAlign); + break; + + default: + context->setError(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->mDevice.get()}; + std::lock_guard<std::mutex> _{device->BufferLock}; + if UNLIKELY(LookupBuffer(device, buffer) == nullptr) + context->setError(AL_INVALID_NAME, "Invalid buffer ID %u", buffer); + else if UNLIKELY(!value1 || !value2 || !value3) + context->setError(AL_INVALID_VALUE, "NULL pointer"); + else switch(param) + { + default: + context->setError(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->mDevice.get()}; + std::lock_guard<std::mutex> _{device->BufferLock}; + ALbuffer *albuf = LookupBuffer(device, buffer); + if UNLIKELY(!albuf) + context->setError(AL_INVALID_NAME, "Invalid buffer ID %u", buffer); + else if UNLIKELY(!values) + context->setError(AL_INVALID_VALUE, "NULL pointer"); + else switch(param) + { + case AL_LOOP_POINTS_SOFT: + values[0] = static_cast<ALint>(albuf->LoopStart); + values[1] = static_cast<ALint>(albuf->LoopEnd); + break; + + default: + context->setError(AL_INVALID_ENUM, "Invalid buffer integer-vector property 0x%04x", param); + } +} +END_API_FUNC + + +ALuint 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; +} +ALuint 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/buffer.h b/al/buffer.h new file mode 100644 index 00000000..d41eec5d --- /dev/null +++ b/al/buffer.h @@ -0,0 +1,99 @@ +#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 */ +}; + + +/* 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) + + +ALuint BytesFromFmt(FmtType type); +ALuint ChannelsFromFmt(FmtChannels chans); +inline ALuint FrameSizeFromFmt(FmtChannels chans, FmtType type) +{ return ChannelsFromFmt(chans) * BytesFromFmt(type); } + + +struct ALbuffer { + al::vector<al::byte,16> mData; + + ALuint Frequency{0u}; + ALbitfieldSOFT Access{0u}; + ALuint SampleLen{0u}; + + FmtChannels mFmtChannels{}; + FmtType mFmtType{}; + + UserFmtType OriginalType{}; + ALuint OriginalSize{0}; + ALuint OriginalAlign{0}; + + ALuint LoopStart{0u}; + ALuint LoopEnd{0u}; + + ALuint UnpackAlign{0}; + ALuint 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/effect.cpp b/al/effect.cpp new file mode 100644 index 00000000..f7d17f50 --- /dev/null +++ b/al/effect.cpp @@ -0,0 +1,725 @@ +/** + * 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 "effect.h" + +#include <algorithm> +#include <cstdint> +#include <cstring> +#include <iterator> +#include <memory> +#include <mutex> +#include <new> +#include <numeric> +#include <utility> + +#include "AL/al.h" +#include "AL/alc.h" +#include "AL/alext.h" +#include "AL/efx-presets.h" +#include "AL/efx.h" + +#include "alcmain.h" +#include "alcontext.h" +#include "alexcpt.h" +#include "almalloc.h" +#include "alnumeric.h" +#include "alstring.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; +} + +bool EnsureEffects(ALCdevice *device, size_t needed) +{ + size_t count{std::accumulate(device->EffectList.cbegin(), device->EffectList.cend(), size_t{0}, + [](size_t cur, const EffectSubList &sublist) noexcept -> size_t + { return cur + static_cast<ALuint>(POPCNT64(sublist.FreeMask)); } + )}; + + while(needed > count) + { + if UNLIKELY(device->EffectList.size() >= 1<<25) + return false; + + device->EffectList.emplace_back(); + auto sublist = device->EffectList.end() - 1; + sublist->FreeMask = ~0_u64; + sublist->Effects = static_cast<ALeffect*>(al_calloc(alignof(ALeffect), sizeof(ALeffect)*64)); + if UNLIKELY(!sublist->Effects) + { + device->EffectList.pop_back(); + return false; + } + count += 64; + } + return true; +} + +ALeffect *AllocEffect(ALCdevice *device) +{ + auto sublist = std::find_if(device->EffectList.begin(), device->EffectList.end(), + [](const EffectSubList &entry) noexcept -> bool + { return entry.FreeMask != 0; } + ); + auto lidx = static_cast<ALuint>(std::distance(device->EffectList.begin(), sublist)); + auto slidx = static_cast<ALuint>(CTZ64(sublist->FreeMask)); + + ALeffect *effect{::new (sublist->Effects + slidx) 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) +{ + const ALuint id{effect->id - 1}; + const size_t lidx{id >> 6}; + const ALuint slidx{id & 0x3f}; + + al::destroy_at(effect); + + device->EffectList[lidx].FreeMask |= 1_u64 << slidx; +} + +inline ALeffect *LookupEffect(ALCdevice *device, ALuint id) +{ + const size_t lidx{(id-1) >> 6}; + const ALuint 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) + context->setError(AL_INVALID_VALUE, "Generating %d effects", n); + if UNLIKELY(n <= 0) return; + + ALCdevice *device{context->mDevice.get()}; + std::lock_guard<std::mutex> _{device->EffectLock}; + if(!EnsureEffects(device, static_cast<ALuint>(n))) + { + context->setError(AL_OUT_OF_MEMORY, "Failed to allocate %d effect%s", n, (n==1)?"":"s"); + return; + } + + if LIKELY(n == 1) + { + /* Special handling for the easy and normal case. */ + ALeffect *effect{AllocEffect(device)}; + effects[0] = effect->id; + } + else + { + /* 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(static_cast<ALuint>(n)); + do { + ALeffect *effect{AllocEffect(device)}; + ids.emplace_back(effect->id); + } while(--n); + std::copy(ids.cbegin(), ids.cend(), 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) + context->setError(AL_INVALID_VALUE, "Deleting %d effects", n); + if UNLIKELY(n <= 0) return; + + ALCdevice *device{context->mDevice.get()}; + std::lock_guard<std::mutex> _{device->EffectLock}; + + /* First try to find any effects that are invalid. */ + auto validate_effect = [device](const ALuint eid) -> bool + { return !eid || LookupEffect(device, eid) != nullptr; }; + + const ALuint *effects_end = effects + n; + auto inveffect = std::find_if_not(effects, effects_end, validate_effect); + if UNLIKELY(inveffect != effects_end) + { + context->setError(AL_INVALID_NAME, "Invalid effect ID %u", *inveffect); + return; + } + + /* All good. Delete non-0 effect IDs. */ + auto delete_effect = [device](ALuint eid) -> void + { + ALeffect *effect{eid ? LookupEffect(device, eid) : nullptr}; + if(effect) FreeEffect(device, effect); + }; + std::for_each(effects, effects_end, delete_effect); +} +END_API_FUNC + +AL_API ALboolean AL_APIENTRY alIsEffect(ALuint effect) +START_API_FUNC +{ + ContextRef context{GetContextRef()}; + if LIKELY(context) + { + ALCdevice *device{context->mDevice.get()}; + 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->mDevice.get()}; + std::lock_guard<std::mutex> _{device->EffectLock}; + + ALeffect *aleffect{LookupEffect(device, effect)}; + if UNLIKELY(!aleffect) + context->setError(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 + context->setError(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->mDevice.get()}; + std::lock_guard<std::mutex> _{device->EffectLock}; + + ALeffect *aleffect{LookupEffect(device, effect)}; + if UNLIKELY(!aleffect) + context->setError(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->mDevice.get()}; + std::lock_guard<std::mutex> _{device->EffectLock}; + + ALeffect *aleffect{LookupEffect(device, effect)}; + if UNLIKELY(!aleffect) + context->setError(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->mDevice.get()}; + std::lock_guard<std::mutex> _{device->EffectLock}; + + ALeffect *aleffect{LookupEffect(device, effect)}; + if UNLIKELY(!aleffect) + context->setError(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->mDevice.get()}; + std::lock_guard<std::mutex> _{device->EffectLock}; + + const ALeffect *aleffect{LookupEffect(device, effect)}; + if UNLIKELY(!aleffect) + context->setError(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->mDevice.get()}; + std::lock_guard<std::mutex> _{device->EffectLock}; + + const ALeffect *aleffect{LookupEffect(device, effect)}; + if UNLIKELY(!aleffect) + context->setError(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->mDevice.get()}; + std::lock_guard<std::mutex> _{device->EffectLock}; + + const ALeffect *aleffect{LookupEffect(device, effect)}; + if UNLIKELY(!aleffect) + context->setError(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->mDevice.get()}; + std::lock_guard<std::mutex> _{device->EffectLock}; + + const ALeffect *aleffect{LookupEffect(device, effect)}; + if UNLIKELY(!aleffect) + context->setError(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(al::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(al::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 ? AL_TRUE : AL_FALSE; + return; + } + + WARN("Reverb preset '%s' not found\n", name); +} diff --git a/al/effect.h b/al/effect.h new file mode 100644 index 00000000..270b8e20 --- /dev/null +++ b/al/effect.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/error.cpp b/al/error.cpp new file mode 100644 index 00000000..b667d14f --- /dev/null +++ b/al/error.cpp @@ -0,0 +1,117 @@ +/** + * 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" + +#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 "alcontext.h" +#include "alexcpt.h" +#include "almalloc.h" +#include "event.h" +#include "inprogext.h" +#include "logging.h" +#include "opthelpers.h" +#include "vector.h" + + +bool TrapALError{false}; + +void ALCcontext::setError(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", + decltype(std::declval<void*>()){this}, 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}; + mLastError.compare_exchange_strong(curerr, errorCode); + if((mEnabledEvts.load(std::memory_order_relaxed)&EventType_Error)) + { + std::lock_guard<std::mutex> _{mEventCbLock}; + ALbitfieldSOFT enabledevts{mEnabledEvts.load(std::memory_order_relaxed)}; + if((enabledevts&EventType_Error) && mEventCb) + (*mEventCb)(AL_EVENT_TYPE_ERROR_SOFT, 0, static_cast<ALuint>(errorCode), msglen, msg, + mEventParam); + } +} + +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->mLastError.exchange(AL_NO_ERROR); +} +END_API_FUNC diff --git a/al/event.cpp b/al/event.cpp new file mode 100644 index 00000000..0da48cbf --- /dev/null +++ b/al/event.cpp @@ -0,0 +1,205 @@ + +#include "config.h" + +#include "event.h" + +#include <algorithm> +#include <atomic> +#include <cstring> +#include <exception> +#include <memory> +#include <mutex> +#include <new> +#include <string> +#include <thread> +#include <utility> + +#include "AL/al.h" +#include "AL/alc.h" + +#include "albyte.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->mAsyncEvents.get()}; + bool quitnow{false}; + while LIKELY(!quitnow) + { + auto evt_data = ring->getReadVector().first; + if(evt_data.len == 0) + { + context->mEventSem.wait(); + continue; + } + + std::lock_guard<std::mutex> _{context->mEventCbLock}; + do { + auto *evt_ptr = reinterpret_cast<AsyncEvent*>(evt_data.buf); + evt_data.buf += sizeof(AsyncEvent); + evt_data.len -= 1; + + AsyncEvent evt{*evt_ptr}; + al::destroy_at(evt_ptr); + ring->readAdvance(1); + + quitnow = evt.EnumType == EventType_KillThread; + if UNLIKELY(quitnow) break; + + if(evt.EnumType == EventType_ReleaseEffectState) + { + evt.u.mEffectState->release(); + continue; + } + + ALbitfieldSOFT enabledevts{context->mEnabledEvts.load(std::memory_order_acquire)}; + if(!context->mEventCb) 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->mEventCb(AL_EVENT_TYPE_SOURCE_STATE_CHANGED_SOFT, evt.u.srcstate.id, + static_cast<ALuint>(evt.u.srcstate.state), static_cast<ALsizei>(msg.length()), + msg.c_str(), context->mEventParam); + } + 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->mEventCb(AL_EVENT_TYPE_BUFFER_COMPLETED_SOFT, evt.u.bufcomp.id, + evt.u.bufcomp.count, static_cast<ALsizei>(msg.length()), msg.c_str(), + context->mEventParam); + } + else if((enabledevts&evt.EnumType) == evt.EnumType) + context->mEventCb(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->mEventParam); + } while(evt_data.len != 0); + } + return 0; +} + +void StartEventThrd(ALCcontext *ctx) +{ + try { + ctx->mEventThread = 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) +{ + RingBuffer *ring{ctx->mAsyncEvents.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{EventType_KillThread}; + ring->writeAdvance(1); + + ctx->mEventSem.post(); + if(ctx->mEventThread.joinable()) + ctx->mEventThread.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) context->setError(AL_INVALID_VALUE, "Controlling %d events", count); + if(count <= 0) return; + if(!types) SETERR_RETURN(context, 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, AL_INVALID_ENUM,, "Invalid event type 0x%04x", *bad_type); + + if(enable) + { + ALbitfieldSOFT enabledevts{context->mEnabledEvts.load(std::memory_order_relaxed)}; + while(context->mEnabledEvts.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->mEnabledEvts.load(std::memory_order_relaxed)}; + while(context->mEnabledEvts.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->mEventCbLock}; + } +} +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->mPropLock}; + std::lock_guard<std::mutex> __{context->mEventCbLock}; + context->mEventCb = callback; + context->mEventParam = userParam; +} +END_API_FUNC diff --git a/al/event.h b/al/event.h new file mode 100644 index 00000000..9056d577 --- /dev/null +++ b/al/event.h @@ -0,0 +1,55 @@ +#ifndef AL_EVENT_H +#define AL_EVENT_H + +#include "AL/al.h" +#include "AL/alc.h" + +struct EffectState; + + +enum { + /* End event thread processing. */ + EventType_KillThread = 0, + + /* User event types. */ + EventType_SourceStateChange = 1<<0, + EventType_BufferCompleted = 1<<1, + EventType_Error = 1<<2, + EventType_Performance = 1<<3, + EventType_Deprecated = 1<<4, + EventType_Disconnected = 1<<5, + + /* Internal events. */ + EventType_ReleaseEffectState = 65536, +}; + +struct AsyncEvent { + unsigned int EnumType{0u}; + union { + char dummy; + struct { + ALuint id; + ALenum state; + } srcstate; + struct { + ALuint id; + ALuint count; + } bufcomp; + struct { + ALenum type; + ALuint id; + ALuint param; + ALchar msg[232]; + } user; + EffectState *mEffectState; + } u{}; + + AsyncEvent() noexcept = default; + constexpr AsyncEvent(unsigned int type) noexcept : EnumType{type} { } +}; + + +void StartEventThrd(ALCcontext *ctx); +void StopEventThrd(ALCcontext *ctx); + +#endif diff --git a/al/extension.cpp b/al/extension.cpp new file mode 100644 index 00000000..35c53136 --- /dev/null +++ b/al/extension.cpp @@ -0,0 +1,79 @@ +/** + * 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 "alcontext.h" +#include "alexcpt.h" +#include "alstring.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, AL_INVALID_VALUE, AL_FALSE, "NULL pointer"); + + size_t len{strlen(extName)}; + const char *ptr{context->mExtensionList}; + while(ptr && *ptr) + { + if(al::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/filter.cpp b/al/filter.cpp new file mode 100644 index 00000000..33887254 --- /dev/null +++ b/al/filter.cpp @@ -0,0 +1,650 @@ +/** + * 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 "filter.h" + +#include <algorithm> +#include <cstdint> +#include <iterator> +#include <memory> +#include <mutex> +#include <new> +#include <numeric> + +#include "AL/al.h" +#include "AL/alc.h" +#include "AL/efx.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) +{ context->setError(AL_INVALID_ENUM, "Invalid low-pass integer property 0x%04x", param); } +void ALlowpass_setParamiv(ALfilter*, ALCcontext *context, ALenum param, const ALint*) +{ context->setError(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: + context->setError(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*) +{ context->setError(AL_INVALID_ENUM, "Invalid low-pass integer property 0x%04x", param); } +void ALlowpass_getParamiv(ALfilter*, ALCcontext *context, ALenum param, ALint*) +{ context->setError(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: + context->setError(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) +{ context->setError(AL_INVALID_ENUM, "Invalid high-pass integer property 0x%04x", param); } +void ALhighpass_setParamiv(ALfilter*, ALCcontext *context, ALenum param, const ALint*) +{ context->setError(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: + context->setError(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*) +{ context->setError(AL_INVALID_ENUM, "Invalid high-pass integer property 0x%04x", param); } +void ALhighpass_getParamiv(ALfilter*, ALCcontext *context, ALenum param, ALint*) +{ context->setError(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: + context->setError(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) +{ context->setError(AL_INVALID_ENUM, "Invalid band-pass integer property 0x%04x", param); } +void ALbandpass_setParamiv(ALfilter*, ALCcontext *context, ALenum param, const ALint*) +{ context->setError(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: + context->setError(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*) +{ context->setError(AL_INVALID_ENUM, "Invalid band-pass integer property 0x%04x", param); } +void ALbandpass_getParamiv(ALfilter*, ALCcontext *context, ALenum param, ALint*) +{ context->setError(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: + context->setError(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) +{ context->setError(AL_INVALID_ENUM, "Invalid null filter property 0x%04x", param); } +void ALnullfilter_setParamiv(ALfilter*, ALCcontext *context, ALenum param, const ALint*) +{ context->setError(AL_INVALID_ENUM, "Invalid null filter property 0x%04x", param); } +void ALnullfilter_setParamf(ALfilter*, ALCcontext *context, ALenum param, ALfloat) +{ context->setError(AL_INVALID_ENUM, "Invalid null filter property 0x%04x", param); } +void ALnullfilter_setParamfv(ALfilter*, ALCcontext *context, ALenum param, const ALfloat*) +{ context->setError(AL_INVALID_ENUM, "Invalid null filter property 0x%04x", param); } + +void ALnullfilter_getParami(ALfilter*, ALCcontext *context, ALenum param, ALint*) +{ context->setError(AL_INVALID_ENUM, "Invalid null filter property 0x%04x", param); } +void ALnullfilter_getParamiv(ALfilter*, ALCcontext *context, ALenum param, ALint*) +{ context->setError(AL_INVALID_ENUM, "Invalid null filter property 0x%04x", param); } +void ALnullfilter_getParamf(ALfilter*, ALCcontext *context, ALenum param, ALfloat*) +{ context->setError(AL_INVALID_ENUM, "Invalid null filter property 0x%04x", param); } +void ALnullfilter_getParamfv(ALfilter*, ALCcontext *context, ALenum param, ALfloat*) +{ context->setError(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; +} + +bool EnsureFilters(ALCdevice *device, size_t needed) +{ + size_t count{std::accumulate(device->FilterList.cbegin(), device->FilterList.cend(), size_t{0}, + [](size_t cur, const FilterSubList &sublist) noexcept -> size_t + { return cur + static_cast<ALuint>(POPCNT64(sublist.FreeMask)); } + )}; + + while(needed > count) + { + if UNLIKELY(device->FilterList.size() >= 1<<25) + return false; + + device->FilterList.emplace_back(); + auto sublist = device->FilterList.end() - 1; + sublist->FreeMask = ~0_u64; + sublist->Filters = static_cast<ALfilter*>(al_calloc(alignof(ALfilter), sizeof(ALfilter)*64)); + if UNLIKELY(!sublist->Filters) + { + device->FilterList.pop_back(); + return false; + } + count += 64; + } + return true; +} + + +ALfilter *AllocFilter(ALCdevice *device) +{ + auto sublist = std::find_if(device->FilterList.begin(), device->FilterList.end(), + [](const FilterSubList &entry) noexcept -> bool + { return entry.FreeMask != 0; } + ); + auto lidx = static_cast<ALuint>(std::distance(device->FilterList.begin(), sublist)); + auto slidx = static_cast<ALuint>(CTZ64(sublist->FreeMask)); + + ALfilter *filter{::new (sublist->Filters + slidx) 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) +{ + const ALuint id{filter->id - 1}; + const size_t lidx{id >> 6}; + const ALuint slidx{id & 0x3f}; + + al::destroy_at(filter); + + device->FilterList[lidx].FreeMask |= 1_u64 << slidx; +} + + +inline ALfilter *LookupFilter(ALCdevice *device, ALuint id) +{ + const size_t lidx{(id-1) >> 6}; + const ALuint 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) + context->setError(AL_INVALID_VALUE, "Generating %d filters", n); + if UNLIKELY(n <= 0) return; + + ALCdevice *device{context->mDevice.get()}; + std::lock_guard<std::mutex> _{device->EffectLock}; + if(!EnsureFilters(device, static_cast<ALuint>(n))) + { + context->setError(AL_OUT_OF_MEMORY, "Failed to allocate %d filter%s", n, (n==1)?"":"s"); + return; + } + + if LIKELY(n == 1) + { + /* Special handling for the easy and normal case. */ + ALfilter *filter{AllocFilter(device)}; + if(filter) filters[0] = filter->id; + } + else + { + /* 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(static_cast<ALuint>(n)); + do { + ALfilter *filter{AllocFilter(device)}; + 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) + context->setError(AL_INVALID_VALUE, "Deleting %d filters", n); + if UNLIKELY(n <= 0) return; + + ALCdevice *device{context->mDevice.get()}; + std::lock_guard<std::mutex> _{device->FilterLock}; + + /* First try to find any filters that are invalid. */ + auto validate_filter = [device](const ALuint fid) -> bool + { return !fid || LookupFilter(device, fid) != nullptr; }; + + const ALuint *filters_end = filters + n; + auto invflt = std::find_if_not(filters, filters_end, validate_filter); + if UNLIKELY(invflt != filters_end) + { + context->setError(AL_INVALID_NAME, "Invalid filter ID %u", *invflt); + return; + } + + /* All good. Delete non-0 filter IDs. */ + auto delete_filter = [device](const ALuint fid) -> void + { + ALfilter *filter{fid ? LookupFilter(device, fid) : nullptr}; + if(filter) FreeFilter(device, filter); + }; + std::for_each(filters, filters_end, delete_filter); +} +END_API_FUNC + +AL_API ALboolean AL_APIENTRY alIsFilter(ALuint filter) +START_API_FUNC +{ + ContextRef context{GetContextRef()}; + if LIKELY(context) + { + ALCdevice *device{context->mDevice.get()}; + 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->mDevice.get()}; + std::lock_guard<std::mutex> _{device->FilterLock}; + + ALfilter *alfilt{LookupFilter(device, filter)}; + if UNLIKELY(!alfilt) + context->setError(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 + context->setError(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->mDevice.get()}; + std::lock_guard<std::mutex> _{device->FilterLock}; + + ALfilter *alfilt{LookupFilter(device, filter)}; + if UNLIKELY(!alfilt) + context->setError(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->mDevice.get()}; + std::lock_guard<std::mutex> _{device->FilterLock}; + + ALfilter *alfilt{LookupFilter(device, filter)}; + if UNLIKELY(!alfilt) + context->setError(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->mDevice.get()}; + std::lock_guard<std::mutex> _{device->FilterLock}; + + ALfilter *alfilt{LookupFilter(device, filter)}; + if UNLIKELY(!alfilt) + context->setError(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->mDevice.get()}; + std::lock_guard<std::mutex> _{device->FilterLock}; + + ALfilter *alfilt{LookupFilter(device, filter)}; + if UNLIKELY(!alfilt) + context->setError(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->mDevice.get()}; + std::lock_guard<std::mutex> _{device->FilterLock}; + + ALfilter *alfilt{LookupFilter(device, filter)}; + if UNLIKELY(!alfilt) + context->setError(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->mDevice.get()}; + std::lock_guard<std::mutex> _{device->FilterLock}; + + ALfilter *alfilt{LookupFilter(device, filter)}; + if UNLIKELY(!alfilt) + context->setError(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->mDevice.get()}; + std::lock_guard<std::mutex> _{device->FilterLock}; + + ALfilter *alfilt{LookupFilter(device, filter)}; + if UNLIKELY(!alfilt) + context->setError(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/filter.h b/al/filter.h new file mode 100644 index 00000000..db098d70 --- /dev/null +++ b/al/filter.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/listener.cpp b/al/listener.cpp new file mode 100644 index 00000000..7a14a9ba --- /dev/null +++ b/al/listener.cpp @@ -0,0 +1,452 @@ +/** + * 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 "listener.h" + +#include <cmath> +#include <mutex> + +#include "AL/al.h" +#include "AL/alc.h" +#include "AL/efx.h" + +#include "alcontext.h" +#include "alexcpt.h" +#include "almalloc.h" +#include "atomic.h" +#include "opthelpers.h" + + +#define DO_UPDATEPROPS() do { \ + if(!context->mDeferUpdates.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->mListener; + std::lock_guard<std::mutex> _{context->mPropLock}; + switch(param) + { + case AL_GAIN: + if(!(value >= 0.0f && std::isfinite(value))) + SETERR_RETURN(context, 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, AL_INVALID_VALUE,, "Listener meters per unit out of range"); + listener.mMetersPerUnit = value; + DO_UPDATEPROPS(); + break; + + default: + context->setError(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->mListener; + std::lock_guard<std::mutex> _{context->mPropLock}; + switch(param) + { + case AL_POSITION: + if(!(std::isfinite(value1) && std::isfinite(value2) && std::isfinite(value3))) + SETERR_RETURN(context, 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, AL_INVALID_VALUE,, "Listener velocity out of range"); + listener.Velocity[0] = value1; + listener.Velocity[1] = value2; + listener.Velocity[2] = value3; + DO_UPDATEPROPS(); + break; + + default: + context->setError(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->mListener; + std::lock_guard<std::mutex> _{context->mPropLock}; + if(!values) SETERR_RETURN(context, 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, 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: + context->setError(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->mPropLock}; + switch(param) + { + default: + context->setError(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->mPropLock}; + switch(param) + { + default: + context->setError(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->mPropLock}; + if(!values) + context->setError(AL_INVALID_VALUE, "NULL pointer"); + else switch(param) + { + default: + context->setError(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->mListener; + std::lock_guard<std::mutex> _{context->mPropLock}; + if(!value) + context->setError(AL_INVALID_VALUE, "NULL pointer"); + else switch(param) + { + case AL_GAIN: + *value = listener.Gain; + break; + + case AL_METERS_PER_UNIT: + *value = listener.mMetersPerUnit; + break; + + default: + context->setError(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->mListener; + std::lock_guard<std::mutex> _{context->mPropLock}; + if(!value1 || !value2 || !value3) + context->setError(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: + context->setError(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->mListener; + std::lock_guard<std::mutex> _{context->mPropLock}; + if(!values) + context->setError(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: + context->setError(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->mPropLock}; + if(!value) + context->setError(AL_INVALID_VALUE, "NULL pointer"); + else switch(param) + { + default: + context->setError(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->mListener; + std::lock_guard<std::mutex> _{context->mPropLock}; + if(!value1 || !value2 || !value3) + context->setError(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: + context->setError(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->mListener; + std::lock_guard<std::mutex> _{context->mPropLock}; + if(!values) + context->setError(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: + context->setError(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->mFreeListenerProps.load(std::memory_order_acquire)}; + if(!props) + props = new ALlistenerProps{}; + else + { + ALlistenerProps *next; + do { + next = props->next.load(std::memory_order_relaxed); + } while(context->mFreeListenerProps.compare_exchange_weak(props, next, + std::memory_order_seq_cst, std::memory_order_acquire) == 0); + } + + /* Copy in current property values. */ + ALlistener &listener = context->mListener; + props->Position = listener.Position; + props->Velocity = listener.Velocity; + props->OrientAt = listener.OrientAt; + props->OrientUp = listener.OrientUp; + props->Gain = listener.Gain; + props->MetersPerUnit = listener.mMetersPerUnit; + + /* Set the new container for updating internal parameters. */ + props = listener.Params.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->mFreeListenerProps, props); + } +} diff --git a/al/listener.h b/al/listener.h new file mode 100644 index 00000000..318ab024 --- /dev/null +++ b/al/listener.h @@ -0,0 +1,64 @@ +#ifndef AL_LISTENER_H +#define AL_LISTENER_H + +#include <array> +#include <atomic> + +#include "AL/al.h" +#include "AL/alc.h" +#include "AL/efx.h" + +#include "almalloc.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; + ALfloat MetersPerUnit; + + std::atomic<ALlistenerProps*> next; + + DEF_NEWDEL(ALlistenerProps) +}; + +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}; + ALfloat mMetersPerUnit{AL_DEFAULT_METERS_PER_UNIT}; + + std::atomic_flag PropsClean; + + struct { + /* Pointer to the most recent property values that are awaiting an + * update. + */ + std::atomic<ALlistenerProps*> Update{nullptr}; + + alu::Matrix Matrix; + alu::Vector Velocity; + + ALfloat Gain; + ALfloat MetersPerUnit; + + ALfloat DopplerFactor; + ALfloat SpeedOfSound; /* in units 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/source.cpp b/al/source.cpp new file mode 100644 index 00000000..8b8e6382 --- /dev/null +++ b/al/source.cpp @@ -0,0 +1,3348 @@ +/** + * 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 "source.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 "alcmain.h" +#include "alcontext.h" +#include "alexcpt.h" +#include "almalloc.h" +#include "alnumeric.h" +#include "aloptional.h" +#include "alspan.h" +#include "alu.h" +#include "ambidefs.h" +#include "atomic.h" +#include "auxeffectslot.h" +#include "backends/base.h" +#include "bformatdec.h" +#include "buffer.h" +#include "event.h" +#include "filter.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; +using std::chrono::nanoseconds; + +ALvoice *GetSourceVoice(ALsource *source, ALCcontext *context) +{ + ALuint idx{source->VoiceIdx}; + if(idx < context->mVoices.size()) + { + ALuint sid{source->id}; + ALvoice &voice = context->mVoices[idx]; + if(voice.mSourceID.load(std::memory_order_acquire) == sid) + return &voice; + } + source->VoiceIdx = INVALID_VOICE_IDX; + 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->mFreeVoiceProps.load(std::memory_order_acquire)}; + if(!props) + props = new ALvoiceProps{}; + else + { + ALvoiceProps *next; + do { + next = props->next.load(std::memory_order_relaxed); + } while(context->mFreeVoiceProps.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->mFreeVoiceProps, 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, nanoseconds *clocktime) +{ + ALCdevice *device{context->mDevice.get()}; + 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 |= uint64_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 += uint64_t{BufferList->mSampleLen} << 32; + BufferList = BufferList->mNext.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, nanoseconds *clocktime) +{ + ALCdevice *device{context->mDevice.get()}; + 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) + { + if(!BufferFmt) BufferFmt = BufferList->mBuffer; + readPos += uint64_t{BufferList->mSampleLen} << FRACTIONBITS; + BufferList = BufferList->mNext.load(std::memory_order_relaxed); + } + + while(BufferList && !BufferFmt) + { + BufferFmt = BufferList->mBuffer; + BufferList = BufferList->mNext.load(std::memory_order_relaxed); + } + assert(BufferFmt != nullptr); + + offset = static_cast<ALdouble>(readPos) / ALdouble{FRACTIONONE} / 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->mDevice.get()}; + const ALbufferlistitem *Current; + ALuint readPos; + ALuint 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) return offset; + + const ALbufferlistitem *BufferList{Source->queue}; + const ALbuffer *BufferFmt{nullptr}; + ALuint totalBufferLen{0u}; + bool readFin{false}; + + while(BufferList) + { + if(!BufferFmt) BufferFmt = BufferList->mBuffer; + + readFin |= (BufferList == Current); + totalBufferLen += BufferList->mSampleLen; + if(!readFin) readPos += BufferList->mSampleLen; + + BufferList = BufferList->mNext.load(std::memory_order_relaxed); + } + assert(BufferFmt != nullptr); + + if(Source->Looping) + readPos %= totalBufferLen; + else + { + /* Wrap back to 0 */ + if(readPos >= totalBufferLen) + readPos = readPosFrac = 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) + { + ALuint FrameBlockSize{BufferFmt->OriginalAlign}; + ALuint align{(BufferFmt->OriginalAlign-1)/2 + 4}; + ALuint BlockSize{align * ChannelsFromFmt(BufferFmt->mFmtChannels)}; + + /* Round down to nearest ADPCM block */ + offset = static_cast<ALdouble>(readPos / FrameBlockSize * BlockSize); + } + else if(BufferFmt->OriginalType == UserFmtMSADPCM) + { + ALuint FrameBlockSize{BufferFmt->OriginalAlign}; + ALuint align{(FrameBlockSize-2)/2 + 7}; + ALuint BlockSize{align * ChannelsFromFmt(BufferFmt->mFmtChannels)}; + + /* Round down to nearest ADPCM block */ + offset = static_cast<ALdouble>(readPos / FrameBlockSize * BlockSize); + } + else + { + const ALuint FrameSize{FrameSizeFromFmt(BufferFmt->mFmtChannels, BufferFmt->mFmtType)}; + offset = static_cast<ALdouble>(readPos * FrameSize); + } + break; + } + + return offset; +} + + +struct VoicePos { + ALuint pos, frac; + ALbufferlistitem *bufferitem; +}; + +/** + * GetSampleOffset + * + * Retrieves the voice position, fixed-point fraction, and bufferlist item + * using the source's stored offset and offset type. If the source has no + * stored offset, or the offset is out of range, returns an empty optional. + */ +al::optional<VoicePos> GetSampleOffset(ALsource *Source) +{ + al::optional<VoicePos> ret; + + /* Find the first valid Buffer in the Queue */ + const ALbuffer *BufferFmt{nullptr}; + ALbufferlistitem *BufferList{Source->queue}; + while(BufferList) + { + if((BufferFmt=BufferList->mBuffer) != nullptr) break; + BufferList = BufferList->mNext.load(std::memory_order_relaxed); + } + if(!BufferList) + { + Source->OffsetType = AL_NONE; + Source->Offset = 0.0; + return ret; + } + + /* Get sample frame offset */ + ALuint offset{0u}, frac{0u}; + 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) + { + const ALuint align{(BufferFmt->OriginalAlign-1)/2 + 4}; + offset /= align * ChannelsFromFmt(BufferFmt->mFmtChannels); + offset *= BufferFmt->OriginalAlign; + } + else if(BufferFmt->OriginalType == UserFmtMSADPCM) + { + const ALuint 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 = std::modf(Source->Offset, &dbloff); + offset = static_cast<ALuint>(mind(dbloff, std::numeric_limits<ALuint>::max())); + frac = static_cast<ALuint>(mind(dblfrac*FRACTIONONE, FRACTIONONE-1.0)); + break; + + case AL_SEC_OFFSET: + dblfrac = std::modf(Source->Offset*BufferFmt->Frequency, &dbloff); + offset = static_cast<ALuint>(mind(dbloff, std::numeric_limits<ALuint>::max())); + frac = static_cast<ALuint>(mind(dblfrac*FRACTIONONE, FRACTIONONE-1.0)); + break; + } + Source->OffsetType = AL_NONE; + Source->Offset = 0.0; + + /* Find the bufferlist item this offset belongs to. */ + ALuint totalBufferLen{0u}; + while(BufferList && totalBufferLen <= offset) + { + if(BufferList->mSampleLen > offset-totalBufferLen) + { + /* Offset is in this buffer */ + ret = {offset-totalBufferLen, frac, BufferList}; + return ret; + } + totalBufferLen += BufferList->mSampleLen; + + BufferList = BufferList->mNext.load(std::memory_order_relaxed); + } + + /* Offset is out of range of the queue */ + return ret; +} + + +/** + * 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->mDeferUpdates.load(std::memory_order_acquire) && + IsPlayingOrPaused(source); +} + + +bool EnsureSources(ALCcontext *context, size_t needed) +{ + size_t count{std::accumulate(context->mSourceList.cbegin(), context->mSourceList.cend(), + size_t{0}, + [](size_t cur, const SourceSubList &sublist) noexcept -> size_t + { return cur + static_cast<ALuint>(POPCNT64(sublist.FreeMask)); } + )}; + + while(needed > count) + { + if UNLIKELY(context->mSourceList.size() >= 1<<25) + return false; + + context->mSourceList.emplace_back(); + auto sublist = context->mSourceList.end() - 1; + sublist->FreeMask = ~0_u64; + sublist->Sources = static_cast<ALsource*>(al_calloc(alignof(ALsource), sizeof(ALsource)*64)); + if UNLIKELY(!sublist->Sources) + { + context->mSourceList.pop_back(); + return false; + } + count += 64; + } + return true; +} + +ALsource *AllocSource(ALCcontext *context, ALuint num_sends) +{ + auto sublist = std::find_if(context->mSourceList.begin(), context->mSourceList.end(), + [](const SourceSubList &entry) noexcept -> bool + { return entry.FreeMask != 0; } + ); + auto lidx = static_cast<ALuint>(std::distance(context->mSourceList.begin(), sublist)); + auto slidx = static_cast<ALuint>(CTZ64(sublist->FreeMask)); + + ALsource *source{::new (sublist->Sources + slidx) ALsource{num_sends}}; + + /* Add 1 to avoid source ID 0. */ + source->id = ((lidx<<6) | slidx) + 1; + + context->mNumSources += 1; + sublist->FreeMask &= ~(1_u64 << slidx); + + return source; +} + +void FreeSource(ALCcontext *context, ALsource *source) +{ + const ALuint id{source->id - 1}; + const size_t lidx{id >> 6}; + const ALuint slidx{id & 0x3f}; + + if(IsPlayingOrPaused(source)) + { + ALCdevice *device{context->mDevice.get()}; + BackendLockGuard _{*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); + } + } + + al::destroy_at(source); + + context->mSourceList[lidx].FreeMask |= 1_u64 << slidx; + context->mNumSources--; +} + + +inline ALsource *LookupSource(ALCcontext *context, ALuint id) noexcept +{ + const size_t lidx{(id-1) >> 6}; + const ALuint slidx{(id-1) & 0x3f}; + + if UNLIKELY(lidx >= context->mSourceList.size()) + return nullptr; + SourceSubList &sublist{context->mSourceList[lidx]}; + if UNLIKELY(sublist.FreeMask & (1_u64 << slidx)) + return nullptr; + return sublist.Sources + slidx; +} + +inline ALbuffer *LookupBuffer(ALCdevice *device, ALuint id) noexcept +{ + const size_t lidx{(id-1) >> 6}; + const ALuint 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 +{ + const size_t lidx{(id-1) >> 6}; + const ALuint 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 +{ + const size_t lidx{(id-1) >> 6}; + const ALuint slidx{(id-1) & 0x3f}; + + if UNLIKELY(lidx >= context->mEffectSlotList.size()) + return nullptr; + EffectSlotSubList &sublist{context->mEffectSlotList[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, +}; + + +/** Can only be called while the mixer is locked! */ +void SendStateChangeEvent(ALCcontext *context, ALuint id, ALenum state) +{ + ALbitfieldSOFT enabledevt{context->mEnabledEvts.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->mAsyncEvents.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->mEventSem.post(); +} + + +constexpr size_t MaxValues{6u}; + +ALuint 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; +} +ALuint 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; +} + + +bool SetSourcefv(ALsource *Source, ALCcontext *Context, SourceProp prop, const al::span<const ALfloat> values); +bool SetSourceiv(ALsource *Source, ALCcontext *Context, SourceProp prop, const al::span<const ALint> values); +bool SetSourcei64v(ALsource *Source, ALCcontext *Context, SourceProp prop, const al::span<const ALint64SOFT> values); + +#define CHECKSIZE(v, s) do { \ + if LIKELY((v).size() == (s) || (v).size() == MaxValues) break; \ + Context->setError(AL_INVALID_ENUM, \ + "Property 0x%04x expects %d value(s), got %zu", prop, (s), \ + (v).size()); \ + return false; \ +} while(0) +#define CHECKVAL(x) do { \ + if LIKELY(x) break; \ + Context->setError(AL_INVALID_VALUE, "Value out of range"); \ + return false; \ +} while(0) + +bool 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); + return true; +} + +bool SetSourcefv(ALsource *Source, ALCcontext *Context, SourceProp prop, const al::span<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, false, + "Setting read-only source property 0x%04x", prop); + + case AL_PITCH: + CHECKSIZE(values, 1); + CHECKVAL(values[0] >= 0.0f); + + Source->Pitch = values[0]; + return UpdateSourceProps(Source, Context); + + case AL_CONE_INNER_ANGLE: + CHECKSIZE(values, 1); + CHECKVAL(values[0] >= 0.0f && values[0] <= 360.0f); + + Source->InnerAngle = values[0]; + return UpdateSourceProps(Source, Context); + + case AL_CONE_OUTER_ANGLE: + CHECKSIZE(values, 1); + CHECKVAL(values[0] >= 0.0f && values[0] <= 360.0f); + + Source->OuterAngle = values[0]; + return UpdateSourceProps(Source, Context); + + case AL_GAIN: + CHECKSIZE(values, 1); + CHECKVAL(values[0] >= 0.0f); + + Source->Gain = values[0]; + return UpdateSourceProps(Source, Context); + + case AL_MAX_DISTANCE: + CHECKSIZE(values, 1); + CHECKVAL(values[0] >= 0.0f); + + Source->MaxDistance = values[0]; + return UpdateSourceProps(Source, Context); + + case AL_ROLLOFF_FACTOR: + CHECKSIZE(values, 1); + CHECKVAL(values[0] >= 0.0f); + + Source->RolloffFactor = values[0]; + return UpdateSourceProps(Source, Context); + + case AL_REFERENCE_DISTANCE: + CHECKSIZE(values, 1); + CHECKVAL(values[0] >= 0.0f); + + Source->RefDistance = values[0]; + return UpdateSourceProps(Source, Context); + + case AL_MIN_GAIN: + CHECKSIZE(values, 1); + CHECKVAL(values[0] >= 0.0f); + + Source->MinGain = values[0]; + return UpdateSourceProps(Source, Context); + + case AL_MAX_GAIN: + CHECKSIZE(values, 1); + CHECKVAL(values[0] >= 0.0f); + + Source->MaxGain = values[0]; + return UpdateSourceProps(Source, Context); + + case AL_CONE_OUTER_GAIN: + CHECKSIZE(values, 1); + CHECKVAL(values[0] >= 0.0f && values[0] <= 1.0f); + + Source->OuterGain = values[0]; + return UpdateSourceProps(Source, Context); + + case AL_CONE_OUTER_GAINHF: + CHECKSIZE(values, 1); + CHECKVAL(values[0] >= 0.0f && values[0] <= 1.0f); + + Source->OuterGainHF = values[0]; + return UpdateSourceProps(Source, Context); + + case AL_AIR_ABSORPTION_FACTOR: + CHECKSIZE(values, 1); + CHECKVAL(values[0] >= 0.0f && values[0] <= 10.0f); + + Source->AirAbsorptionFactor = values[0]; + return UpdateSourceProps(Source, Context); + + case AL_ROOM_ROLLOFF_FACTOR: + CHECKSIZE(values, 1); + CHECKVAL(values[0] >= 0.0f && values[0] <= 10.0f); + + Source->RoomRolloffFactor = values[0]; + return UpdateSourceProps(Source, Context); + + case AL_DOPPLER_FACTOR: + CHECKSIZE(values, 1); + CHECKVAL(values[0] >= 0.0f && values[0] <= 1.0f); + + Source->DopplerFactor = values[0]; + return UpdateSourceProps(Source, Context); + + case AL_SEC_OFFSET: + case AL_SAMPLE_OFFSET: + case AL_BYTE_OFFSET: + CHECKSIZE(values, 1); + CHECKVAL(values[0] >= 0.0f); + + Source->OffsetType = prop; + Source->Offset = values[0]; + + if(IsPlayingOrPaused(Source)) + { + ALCdevice *device{Context->mDevice.get()}; + BackendLockGuard _{*device->Backend}; + /* Double-check that the source is still playing while we have the + * lock. + */ + if(ALvoice *voice{GetSourceVoice(Source, Context)}) + { + auto vpos = GetSampleOffset(Source); + if(!vpos) SETERR_RETURN(Context, AL_INVALID_VALUE, false, "Invalid offset"); + + voice->mPosition.store(vpos->pos, std::memory_order_relaxed); + voice->mPositionFrac.store(vpos->frac, std::memory_order_relaxed); + voice->mCurrentBuffer.store(vpos->bufferitem, std::memory_order_release); + } + } + return true; + + case AL_SOURCE_RADIUS: + CHECKSIZE(values, 1); + CHECKVAL(values[0] >= 0.0f && std::isfinite(values[0])); + + Source->Radius = values[0]; + return UpdateSourceProps(Source, Context); + + case AL_STEREO_ANGLES: + CHECKSIZE(values, 2); + CHECKVAL(std::isfinite(values[0]) && std::isfinite(values[1])); + + Source->StereoPan[0] = values[0]; + Source->StereoPan[1] = values[1]; + return UpdateSourceProps(Source, Context); + + + case AL_POSITION: + CHECKSIZE(values, 3); + 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]; + return UpdateSourceProps(Source, Context); + + case AL_VELOCITY: + CHECKSIZE(values, 3); + 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]; + return UpdateSourceProps(Source, Context); + + case AL_DIRECTION: + CHECKSIZE(values, 3); + 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]; + return UpdateSourceProps(Source, Context); + + case AL_ORIENTATION: + CHECKSIZE(values, 6); + 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]; + return UpdateSourceProps(Source, Context); + + + 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: + CHECKSIZE(values, 1); + ival = static_cast<ALint>(values[0]); + return SetSourceiv(Source, Context, prop, {&ival, 1u}); + + case AL_BUFFERS_QUEUED: + case AL_BUFFERS_PROCESSED: + CHECKSIZE(values, 1); + ival = static_cast<ALint>(static_cast<ALuint>(values[0])); + return SetSourceiv(Source, Context, prop, {&ival, 1u}); + + 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); + Context->setError(AL_INVALID_ENUM, "Invalid source float property 0x%04x", prop); + return false; +} + +bool SetSourceiv(ALsource *Source, ALCcontext *Context, SourceProp prop, const al::span<const ALint> values) +{ + ALCdevice *device{Context->mDevice.get()}; + 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, false, + "Setting read-only source property 0x%04x", prop); + + case AL_SOURCE_RELATIVE: + CHECKSIZE(values, 1); + CHECKVAL(values[0] == AL_FALSE || values[0] == AL_TRUE); + + Source->HeadRelative = values[0] != AL_FALSE; + return UpdateSourceProps(Source, Context); + + case AL_LOOPING: + CHECKSIZE(values, 1); + CHECKVAL(values[0] == AL_FALSE || values[0] == AL_TRUE); + + Source->Looping = values[0] != AL_FALSE; + if(IsPlayingOrPaused(Source)) + { + if(ALvoice *voice{GetSourceVoice(Source, Context)}) + { + 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 true; + + case AL_BUFFER: + CHECKSIZE(values, 1); + buflock = std::unique_lock<std::mutex>{device->BufferLock}; + if(values[0] && (buffer=LookupBuffer(device, static_cast<ALuint>(values[0]))) == nullptr) + SETERR_RETURN(Context, AL_INVALID_VALUE, false, "Invalid buffer ID %u", + static_cast<ALuint>(values[0])); + + if(buffer && buffer->MappedAccess != 0 && + !(buffer->MappedAccess&AL_MAP_PERSISTENT_BIT_SOFT)) + SETERR_RETURN(Context, AL_INVALID_OPERATION, 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, 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 = new ALbufferlistitem{}; + newlist->mSampleLen = buffer->SampleLen; + newlist->mBuffer = 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) + { + std::unique_ptr<ALbufferlistitem> temp{oldlist}; + oldlist = temp->mNext.load(std::memory_order_relaxed); + + if((buffer=temp->mBuffer) != nullptr) + DecrementRef(buffer->ref); + } + return true; + + case AL_SEC_OFFSET: + case AL_SAMPLE_OFFSET: + case AL_BYTE_OFFSET: + CHECKSIZE(values, 1); + CHECKVAL(values[0] >= 0); + + Source->OffsetType = prop; + Source->Offset = values[0]; + + if(IsPlayingOrPaused(Source)) + { + BackendLockGuard _{*device->Backend}; + if(ALvoice *voice{GetSourceVoice(Source, Context)}) + { + auto vpos = GetSampleOffset(Source); + if(!vpos) SETERR_RETURN(Context, AL_INVALID_VALUE, false, "Invalid source offset"); + + voice->mPosition.store(vpos->pos, std::memory_order_relaxed); + voice->mPositionFrac.store(vpos->frac, std::memory_order_relaxed); + voice->mCurrentBuffer.store(vpos->bufferitem, std::memory_order_release); + } + } + return true; + + case AL_DIRECT_FILTER: + CHECKSIZE(values, 1); + filtlock = std::unique_lock<std::mutex>{device->FilterLock}; + if(values[0] && (filter=LookupFilter(device, static_cast<ALuint>(values[0]))) == nullptr) + SETERR_RETURN(Context, AL_INVALID_VALUE, false, "Invalid filter ID %u", + static_cast<ALuint>(values[0])); + + 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(); + return UpdateSourceProps(Source, Context); + + case AL_DIRECT_FILTER_GAINHF_AUTO: + CHECKSIZE(values, 1); + CHECKVAL(values[0] == AL_FALSE || values[0] == AL_TRUE); + + Source->DryGainHFAuto = values[0] != AL_FALSE; + return UpdateSourceProps(Source, Context); + + case AL_AUXILIARY_SEND_FILTER_GAIN_AUTO: + CHECKSIZE(values, 1); + CHECKVAL(values[0] == AL_FALSE || values[0] == AL_TRUE); + + Source->WetGainAuto = values[0] != AL_FALSE; + return UpdateSourceProps(Source, Context); + + case AL_AUXILIARY_SEND_FILTER_GAINHF_AUTO: + CHECKSIZE(values, 1); + CHECKVAL(values[0] == AL_FALSE || values[0] == AL_TRUE); + + Source->WetGainHFAuto = values[0] != AL_FALSE; + return UpdateSourceProps(Source, Context); + + case AL_DIRECT_CHANNELS_SOFT: + CHECKSIZE(values, 1); + CHECKVAL(values[0] == AL_FALSE || values[0] == AL_TRUE); + + Source->DirectChannels = values[0] != AL_FALSE; + return UpdateSourceProps(Source, Context); + + case AL_DISTANCE_MODEL: + CHECKSIZE(values, 1); + CHECKVAL(values[0] == AL_NONE || + values[0] == AL_INVERSE_DISTANCE || values[0] == AL_INVERSE_DISTANCE_CLAMPED || + values[0] == AL_LINEAR_DISTANCE || values[0] == AL_LINEAR_DISTANCE_CLAMPED || + values[0] == AL_EXPONENT_DISTANCE || values[0] == AL_EXPONENT_DISTANCE_CLAMPED); + + Source->mDistanceModel = static_cast<DistanceModel>(values[0]); + if(Context->mSourceDistanceModel) + return UpdateSourceProps(Source, Context); + return true; + + case AL_SOURCE_RESAMPLER_SOFT: + CHECKSIZE(values, 1); + CHECKVAL(values[0] >= 0 && values[0] <= static_cast<int>(Resampler::Max)); + + Source->mResampler = static_cast<Resampler>(values[0]); + return UpdateSourceProps(Source, Context); + + case AL_SOURCE_SPATIALIZE_SOFT: + CHECKSIZE(values, 1); + CHECKVAL(values[0] >= AL_FALSE && values[0] <= AL_AUTO_SOFT); + + Source->mSpatialize = static_cast<SpatializeMode>(values[0]); + return UpdateSourceProps(Source, Context); + + + case AL_AUXILIARY_SEND_FILTER: + CHECKSIZE(values, 3); + slotlock = std::unique_lock<std::mutex>{Context->mEffectSlotLock}; + if(values[0] && (slot=LookupEffectSlot(Context, static_cast<ALuint>(values[0]))) == nullptr) + SETERR_RETURN(Context, AL_INVALID_VALUE, false, "Invalid effect ID %u", values[0]); + if(static_cast<ALuint>(values[1]) >= device->NumAuxSends) + SETERR_RETURN(Context, AL_INVALID_VALUE, false, "Invalid send %u", values[1]); + + filtlock = std::unique_lock<std::mutex>{device->FilterLock}; + if(values[2] && (filter=LookupFilter(device, static_cast<ALuint>(values[2]))) == nullptr) + SETERR_RETURN(Context, AL_INVALID_VALUE, false, "Invalid filter ID %u", values[2]); + + if(!filter) + { + /* Disable filter */ + auto &send = Source->Send[static_cast<ALuint>(values[1])]; + send.Gain = 1.0f; + send.GainHF = 1.0f; + send.HFReference = LOWPASSFREQREF; + send.GainLF = 1.0f; + send.LFReference = HIGHPASSFREQREF; + } + else + { + auto &send = Source->Send[static_cast<ALuint>(values[1])]; + send.Gain = filter->Gain; + send.GainHF = filter->GainHF; + send.HFReference = filter->HFReference; + send.GainLF = filter->GainLF; + send.LFReference = filter->LFReference; + } + filtlock.unlock(); + + if(slot != Source->Send[static_cast<ALuint>(values[1])].Slot && IsPlayingOrPaused(Source)) + { + /* Add refcount on the new slot, and release the previous slot */ + if(slot) IncrementRef(slot->ref); + if(auto *oldslot = Source->Send[static_cast<ALuint>(values[1])].Slot) + DecrementRef(oldslot->ref); + Source->Send[static_cast<ALuint>(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(auto *oldslot = Source->Send[static_cast<ALuint>(values[1])].Slot) + DecrementRef(oldslot->ref); + Source->Send[static_cast<ALuint>(values[1])].Slot = slot; + UpdateSourceProps(Source, Context); + } + return 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: + CHECKSIZE(values, 1); + fvals[0] = static_cast<ALfloat>(values[0]); + return SetSourcefv(Source, Context, prop, {fvals, 1u}); + + /* 3x float */ + case AL_POSITION: + case AL_VELOCITY: + case AL_DIRECTION: + CHECKSIZE(values, 3); + 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, 3u}); + + /* 6x float */ + case AL_ORIENTATION: + CHECKSIZE(values, 6); + 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, 6u}); + + 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); + Context->setError(AL_INVALID_ENUM, "Invalid source integer property 0x%04x", prop); + return false; +} + +bool SetSourcei64v(ALsource *Source, ALCcontext *Context, SourceProp prop, const al::span<const ALint64SOFT> values) +{ + ALfloat fvals[MaxValues]; + ALint ivals[MaxValues]; + + 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, 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: + CHECKSIZE(values, 1); + CHECKVAL(values[0] <= INT_MAX && values[0] >= INT_MIN); + + ivals[0] = static_cast<ALint>(values[0]); + return SetSourceiv(Source, Context, prop, {ivals, 1u}); + + /* 1x uint */ + case AL_BUFFER: + case AL_DIRECT_FILTER: + CHECKSIZE(values, 1); + CHECKVAL(values[0] <= UINT_MAX && values[0] >= 0); + + ivals[0] = static_cast<ALint>(values[0]); + return SetSourceiv(Source, Context, prop, {ivals, 1u}); + + /* 3x uint */ + case AL_AUXILIARY_SEND_FILTER: + CHECKSIZE(values, 3); + 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<ALint>(values[0]); + ivals[1] = static_cast<ALint>(values[1]); + ivals[2] = static_cast<ALint>(values[2]); + return SetSourceiv(Source, Context, prop, {ivals, 3u}); + + /* 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: + CHECKSIZE(values, 1); + fvals[0] = static_cast<ALfloat>(values[0]); + return SetSourcefv(Source, Context, prop, {fvals, 1u}); + + /* 3x float */ + case AL_POSITION: + case AL_VELOCITY: + case AL_DIRECTION: + CHECKSIZE(values, 3); + 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, 3u}); + + /* 6x float */ + case AL_ORIENTATION: + CHECKSIZE(values, 6); + 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, 6u}); + + case AL_SEC_OFFSET_LATENCY_SOFT: + case AL_SEC_OFFSET_CLOCK_SOFT: + case AL_STEREO_ANGLES: + break; + } + + ERR("Unexpected property: 0x%04x\n", prop); + Context->setError(AL_INVALID_ENUM, "Invalid source integer64 property 0x%04x", prop); + return false; +} + +#undef CHECKVAL + + +bool GetSourcedv(ALsource *Source, ALCcontext *Context, SourceProp prop, const al::span<ALdouble> values); +bool GetSourceiv(ALsource *Source, ALCcontext *Context, SourceProp prop, const al::span<ALint> values); +bool GetSourcei64v(ALsource *Source, ALCcontext *Context, SourceProp prop, const al::span<ALint64SOFT> values); + +bool GetSourcedv(ALsource *Source, ALCcontext *Context, SourceProp prop, const al::span<ALdouble> values) +{ + ALCdevice *device{Context->mDevice.get()}; + ClockLatency clocktime; + nanoseconds srcclock; + ALint ivals[MaxValues]; + bool err; + + switch(prop) + { + case AL_GAIN: + CHECKSIZE(values, 1); + values[0] = Source->Gain; + return true; + + case AL_PITCH: + CHECKSIZE(values, 1); + values[0] = Source->Pitch; + return true; + + case AL_MAX_DISTANCE: + CHECKSIZE(values, 1); + values[0] = Source->MaxDistance; + return true; + + case AL_ROLLOFF_FACTOR: + CHECKSIZE(values, 1); + values[0] = Source->RolloffFactor; + return true; + + case AL_REFERENCE_DISTANCE: + CHECKSIZE(values, 1); + values[0] = Source->RefDistance; + return true; + + case AL_CONE_INNER_ANGLE: + CHECKSIZE(values, 1); + values[0] = Source->InnerAngle; + return true; + + case AL_CONE_OUTER_ANGLE: + CHECKSIZE(values, 1); + values[0] = Source->OuterAngle; + return true; + + case AL_MIN_GAIN: + CHECKSIZE(values, 1); + values[0] = Source->MinGain; + return true; + + case AL_MAX_GAIN: + CHECKSIZE(values, 1); + values[0] = Source->MaxGain; + return true; + + case AL_CONE_OUTER_GAIN: + CHECKSIZE(values, 1); + values[0] = Source->OuterGain; + return true; + + case AL_SEC_OFFSET: + case AL_SAMPLE_OFFSET: + case AL_BYTE_OFFSET: + CHECKSIZE(values, 1); + values[0] = GetSourceOffset(Source, prop, Context); + return true; + + case AL_CONE_OUTER_GAINHF: + CHECKSIZE(values, 1); + values[0] = Source->OuterGainHF; + return true; + + case AL_AIR_ABSORPTION_FACTOR: + CHECKSIZE(values, 1); + values[0] = Source->AirAbsorptionFactor; + return true; + + case AL_ROOM_ROLLOFF_FACTOR: + CHECKSIZE(values, 1); + values[0] = Source->RoomRolloffFactor; + return true; + + case AL_DOPPLER_FACTOR: + CHECKSIZE(values, 1); + values[0] = Source->DopplerFactor; + return true; + + case AL_SOURCE_RADIUS: + CHECKSIZE(values, 1); + values[0] = Source->Radius; + return true; + + case AL_STEREO_ANGLES: + CHECKSIZE(values, 2); + values[0] = Source->StereoPan[0]; + values[1] = Source->StereoPan[1]; + return true; + + case AL_SEC_OFFSET_LATENCY_SOFT: + CHECKSIZE(values, 2); + /* 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. + */ + const nanoseconds diff{clocktime.ClockTime - srcclock}; + const nanoseconds latency{clocktime.Latency - std::min(clocktime.Latency, diff)}; + values[1] = static_cast<ALdouble>(latency.count()) / 1000000000.0; + } + return true; + + case AL_SEC_OFFSET_CLOCK_SOFT: + CHECKSIZE(values, 2); + values[0] = GetSourceSecOffset(Source, Context, &srcclock); + values[1] = static_cast<ALdouble>(srcclock.count()) / 1000000000.0; + return true; + + case AL_POSITION: + CHECKSIZE(values, 3); + values[0] = Source->Position[0]; + values[1] = Source->Position[1]; + values[2] = Source->Position[2]; + return true; + + case AL_VELOCITY: + CHECKSIZE(values, 3); + values[0] = Source->Velocity[0]; + values[1] = Source->Velocity[1]; + values[2] = Source->Velocity[2]; + return true; + + case AL_DIRECTION: + CHECKSIZE(values, 3); + values[0] = Source->Direction[0]; + values[1] = Source->Direction[1]; + values[2] = Source->Direction[2]; + return true; + + case AL_ORIENTATION: + CHECKSIZE(values, 6); + 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 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: + CHECKSIZE(values, 1); + if((err=GetSourceiv(Source, Context, prop, {ivals, 1u})) != false) + values[0] = 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); + Context->setError(AL_INVALID_ENUM, "Invalid source double property 0x%04x", prop); + return false; +} + +bool GetSourceiv(ALsource *Source, ALCcontext *Context, SourceProp prop, const al::span<ALint> values) +{ + ALdouble dvals[MaxValues]; + bool err; + + switch(prop) + { + case AL_SOURCE_RELATIVE: + CHECKSIZE(values, 1); + values[0] = Source->HeadRelative; + return true; + + case AL_LOOPING: + CHECKSIZE(values, 1); + values[0] = Source->Looping; + return true; + + case AL_BUFFER: + CHECKSIZE(values, 1); + { + ALbufferlistitem *BufferList{nullptr}; + if(Source->SourceType == AL_STATIC) BufferList = Source->queue; + ALbuffer *buffer{nullptr}; + if(BufferList) buffer = BufferList->mBuffer; + values[0] = buffer ? static_cast<ALint>(buffer->id) : 0; + } + return true; + + case AL_SOURCE_STATE: + CHECKSIZE(values, 1); + values[0] = GetSourceState(Source, GetSourceVoice(Source, Context)); + return true; + + case AL_BUFFERS_QUEUED: + CHECKSIZE(values, 1); + if(ALbufferlistitem *BufferList{Source->queue}) + { + ALsizei count{0}; + do { + ++count; + BufferList = BufferList->mNext.load(std::memory_order_relaxed); + } while(BufferList != nullptr); + values[0] = count; + } + else + values[0] = 0; + return true; + + case AL_BUFFERS_PROCESSED: + CHECKSIZE(values, 1); + 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] = 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 = BufferList->mNext.load(std::memory_order_relaxed); + } + values[0] = played; + } + return true; + + case AL_SOURCE_TYPE: + CHECKSIZE(values, 1); + values[0] = Source->SourceType; + return true; + + case AL_DIRECT_FILTER_GAINHF_AUTO: + CHECKSIZE(values, 1); + values[0] = Source->DryGainHFAuto; + return true; + + case AL_AUXILIARY_SEND_FILTER_GAIN_AUTO: + CHECKSIZE(values, 1); + values[0] = Source->WetGainAuto; + return true; + + case AL_AUXILIARY_SEND_FILTER_GAINHF_AUTO: + CHECKSIZE(values, 1); + values[0] = Source->WetGainHFAuto; + return true; + + case AL_DIRECT_CHANNELS_SOFT: + CHECKSIZE(values, 1); + values[0] = Source->DirectChannels; + return true; + + case AL_DISTANCE_MODEL: + CHECKSIZE(values, 1); + values[0] = static_cast<int>(Source->mDistanceModel); + return true; + + case AL_SOURCE_RESAMPLER_SOFT: + CHECKSIZE(values, 1); + values[0] = static_cast<int>(Source->mResampler); + return true; + + case AL_SOURCE_SPATIALIZE_SOFT: + CHECKSIZE(values, 1); + values[0] = Source->mSpatialize; + return 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: + CHECKSIZE(values, 1); + if((err=GetSourcedv(Source, Context, prop, {dvals, 1u})) != false) + values[0] = static_cast<ALint>(dvals[0]); + return err; + + /* 3x float/double */ + case AL_POSITION: + case AL_VELOCITY: + case AL_DIRECTION: + CHECKSIZE(values, 3); + if((err=GetSourcedv(Source, Context, prop, {dvals, 3u})) != 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: + CHECKSIZE(values, 6); + if((err=GetSourcedv(Source, Context, prop, {dvals, 6u})) != 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); + Context->setError(AL_INVALID_ENUM, "Invalid source integer property 0x%04x", prop); + return false; +} + +bool GetSourcei64v(ALsource *Source, ALCcontext *Context, SourceProp prop, const al::span<ALint64SOFT> values) +{ + ALCdevice *device = Context->mDevice.get(); + ClockLatency clocktime; + nanoseconds srcclock; + ALdouble dvals[MaxValues]; + ALint ivals[MaxValues]; + bool err; + + switch(prop) + { + case AL_SAMPLE_OFFSET_LATENCY_SOFT: + CHECKSIZE(values, 2); + /* 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. + */ + const nanoseconds diff{clocktime.ClockTime - srcclock}; + values[1] = nanoseconds{clocktime.Latency - std::min(clocktime.Latency, diff)}.count(); + } + return true; + + case AL_SAMPLE_OFFSET_CLOCK_SOFT: + CHECKSIZE(values, 2); + values[0] = GetSourceSampleOffset(Source, Context, &srcclock); + values[1] = srcclock.count(); + return 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: + CHECKSIZE(values, 1); + if((err=GetSourcedv(Source, Context, prop, {dvals, 1u})) != false) + values[0] = static_cast<int64_t>(dvals[0]); + return err; + + /* 3x float/double */ + case AL_POSITION: + case AL_VELOCITY: + case AL_DIRECTION: + CHECKSIZE(values, 3); + if((err=GetSourcedv(Source, Context, prop, {dvals, 3u})) != 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: + CHECKSIZE(values, 6); + if((err=GetSourcedv(Source, Context, prop, {dvals, 6u})) != 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: + CHECKSIZE(values, 1); + if((err=GetSourceiv(Source, Context, prop, {ivals, 1u})) != false) + values[0] = ivals[0]; + return err; + + /* 1x uint */ + case AL_BUFFER: + case AL_DIRECT_FILTER: + CHECKSIZE(values, 1); + if((err=GetSourceiv(Source, Context, prop, {ivals, 1u})) != false) + values[0] = static_cast<ALuint>(ivals[0]); + return err; + + /* 3x uint */ + case AL_AUXILIARY_SEND_FILTER: + CHECKSIZE(values, 3); + if((err=GetSourceiv(Source, Context, prop, {ivals, 3u})) != 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); + Context->setError(AL_INVALID_ENUM, "Invalid source integer64 property 0x%04x", prop); + return false; +} + +} // namespace + +AL_API ALvoid AL_APIENTRY alGenSources(ALsizei n, ALuint *sources) +START_API_FUNC +{ + ContextRef context{GetContextRef()}; + if UNLIKELY(!context) return; + + if UNLIKELY(n < 0) + context->setError(AL_INVALID_VALUE, "Generating %d sources", n); + if UNLIKELY(n <= 0) return; + + std::unique_lock<std::mutex> srclock{context->mSourceLock}; + ALCdevice *device{context->mDevice.get()}; + if(static_cast<ALuint>(n) > device->SourcesMax-context->mNumSources) + { + context->setError(AL_OUT_OF_MEMORY, "Exceeding %u source limit (%u + %d)", + device->SourcesMax, context->mNumSources, n); + return; + } + if(!EnsureSources(context.get(), static_cast<ALuint>(n))) + { + context->setError(AL_OUT_OF_MEMORY, "Failed to allocate %d source%s", n, (n==1)?"":"s"); + return; + } + + if(n == 1) + { + ALsource *source{AllocSource(context.get(), device->NumAuxSends)}; + sources[0] = source->id; + } + else + { + const ALuint num_sends{device->NumAuxSends}; + al::vector<ALuint> ids; + ids.reserve(static_cast<ALuint>(n)); + do { + ALsource *source{AllocSource(context.get(), num_sends)}; + ids.emplace_back(source->id); + } while(--n); + std::copy(ids.cbegin(), ids.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 UNLIKELY(n < 0) + SETERR_RETURN(context, AL_INVALID_VALUE,, "Deleting %d sources", n); + + std::lock_guard<std::mutex> _{context->mSourceLock}; + + /* Check that all Sources are valid */ + auto validate_source = [&context](const ALuint sid) -> bool + { return LookupSource(context.get(), sid) != nullptr; }; + + const ALuint *sources_end = sources + n; + auto invsrc = std::find_if_not(sources, sources_end, validate_source); + if UNLIKELY(invsrc != sources_end) + { + context->setError(AL_INVALID_NAME, "Invalid source ID %u", *invsrc); + return; + } + + /* All good. Delete source IDs. */ + auto delete_source = [&context](const ALuint sid) -> void + { + ALsource *src{LookupSource(context.get(), sid)}; + if(src) FreeSource(context.get(), src); + }; + std::for_each(sources, sources_end, delete_source); +} +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->mSourceLock}; + 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->mPropLock}; + std::lock_guard<std::mutex> __{context->mSourceLock}; + ALsource *Source = LookupSource(context.get(), source); + if UNLIKELY(!Source) + context->setError(AL_INVALID_NAME, "Invalid source ID %u", source); + else + SetSourcefv(Source, context.get(), static_cast<SourceProp>(param), {&value, 1u}); +} +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->mPropLock}; + std::lock_guard<std::mutex> __{context->mSourceLock}; + ALsource *Source = LookupSource(context.get(), source); + if UNLIKELY(!Source) + context->setError(AL_INVALID_NAME, "Invalid source ID %u", source); + else + { + const 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->mPropLock}; + std::lock_guard<std::mutex> __{context->mSourceLock}; + ALsource *Source = LookupSource(context.get(), source); + if UNLIKELY(!Source) + context->setError(AL_INVALID_NAME, "Invalid source ID %u", source); + else if UNLIKELY(!values) + context->setError(AL_INVALID_VALUE, "NULL pointer"); + else + SetSourcefv(Source, context.get(), static_cast<SourceProp>(param), {values, MaxValues}); +} +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->mPropLock}; + std::lock_guard<std::mutex> __{context->mSourceLock}; + ALsource *Source = LookupSource(context.get(), source); + if UNLIKELY(!Source) + context->setError(AL_INVALID_NAME, "Invalid source ID %u", source); + else + { + const ALfloat fval[1]{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->mPropLock}; + std::lock_guard<std::mutex> __{context->mSourceLock}; + ALsource *Source = LookupSource(context.get(), source); + if UNLIKELY(!Source) + context->setError(AL_INVALID_NAME, "Invalid source ID %u", source); + else + { + const 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->mPropLock}; + std::lock_guard<std::mutex> __{context->mSourceLock}; + ALsource *Source = LookupSource(context.get(), source); + if UNLIKELY(!Source) + context->setError(AL_INVALID_NAME, "Invalid source ID %u", source); + else if UNLIKELY(!values) + context->setError(AL_INVALID_VALUE, "NULL pointer"); + else + { + const ALuint count{DoubleValsByProp(param)}; + ALfloat fvals[MaxValues]; + for(ALuint i{0};i < count;i++) + fvals[i] = static_cast<ALfloat>(values[i]); + SetSourcefv(Source, context.get(), static_cast<SourceProp>(param), {fvals, count}); + } +} +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->mPropLock}; + std::lock_guard<std::mutex> __{context->mSourceLock}; + ALsource *Source = LookupSource(context.get(), source); + if UNLIKELY(!Source) + context->setError(AL_INVALID_NAME, "Invalid source ID %u", source); + else + SetSourceiv(Source, context.get(), static_cast<SourceProp>(param), {&value, 1u}); +} +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->mPropLock}; + std::lock_guard<std::mutex> __{context->mSourceLock}; + ALsource *Source = LookupSource(context.get(), source); + if UNLIKELY(!Source) + context->setError(AL_INVALID_NAME, "Invalid source ID %u", source); + else + { + const 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->mPropLock}; + std::lock_guard<std::mutex> __{context->mSourceLock}; + ALsource *Source = LookupSource(context.get(), source); + if UNLIKELY(!Source) + context->setError(AL_INVALID_NAME, "Invalid source ID %u", source); + else if UNLIKELY(!values) + context->setError(AL_INVALID_VALUE, "NULL pointer"); + else + SetSourceiv(Source, context.get(), static_cast<SourceProp>(param), {values, MaxValues}); +} +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->mPropLock}; + std::lock_guard<std::mutex> __{context->mSourceLock}; + ALsource *Source{LookupSource(context.get(), source)}; + if UNLIKELY(!Source) + context->setError(AL_INVALID_NAME, "Invalid source ID %u", source); + else + SetSourcei64v(Source, context.get(), static_cast<SourceProp>(param), {&value, 1u}); +} +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->mPropLock}; + std::lock_guard<std::mutex> __{context->mSourceLock}; + ALsource *Source{LookupSource(context.get(), source)}; + if UNLIKELY(!Source) + context->setError(AL_INVALID_NAME, "Invalid source ID %u", source); + else + { + const 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->mPropLock}; + std::lock_guard<std::mutex> __{context->mSourceLock}; + ALsource *Source{LookupSource(context.get(), source)}; + if UNLIKELY(!Source) + context->setError(AL_INVALID_NAME, "Invalid source ID %u", source); + else if UNLIKELY(!values) + context->setError(AL_INVALID_VALUE, "NULL pointer"); + else + SetSourcei64v(Source, context.get(), static_cast<SourceProp>(param), {values, MaxValues}); +} +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->mSourceLock}; + ALsource *Source{LookupSource(context.get(), source)}; + if UNLIKELY(!Source) + context->setError(AL_INVALID_NAME, "Invalid source ID %u", source); + else if UNLIKELY(!value) + context->setError(AL_INVALID_VALUE, "NULL pointer"); + else + { + ALdouble dval[1]; + if(GetSourcedv(Source, context.get(), static_cast<SourceProp>(param), dval)) + *value = static_cast<ALfloat>(dval[0]); + } +} +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->mSourceLock}; + ALsource *Source{LookupSource(context.get(), source)}; + if UNLIKELY(!Source) + context->setError(AL_INVALID_NAME, "Invalid source ID %u", source); + else if UNLIKELY(!(value1 && value2 && value3)) + context->setError(AL_INVALID_VALUE, "NULL pointer"); + 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->mSourceLock}; + ALsource *Source{LookupSource(context.get(), source)}; + if UNLIKELY(!Source) + context->setError(AL_INVALID_NAME, "Invalid source ID %u", source); + else if UNLIKELY(!values) + context->setError(AL_INVALID_VALUE, "NULL pointer"); + else + { + const ALuint count{FloatValsByProp(param)}; + ALdouble dvals[MaxValues]; + if(GetSourcedv(Source, context.get(), static_cast<SourceProp>(param), {dvals, count})) + { + for(ALuint 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->mSourceLock}; + ALsource *Source{LookupSource(context.get(), source)}; + if UNLIKELY(!Source) + context->setError(AL_INVALID_NAME, "Invalid source ID %u", source); + else if UNLIKELY(!value) + context->setError(AL_INVALID_VALUE, "NULL pointer"); + else + GetSourcedv(Source, context.get(), static_cast<SourceProp>(param), {value, 1u}); +} +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->mSourceLock}; + ALsource *Source{LookupSource(context.get(), source)}; + if UNLIKELY(!Source) + context->setError(AL_INVALID_NAME, "Invalid source ID %u", source); + else if UNLIKELY(!(value1 && value2 && value3)) + context->setError(AL_INVALID_VALUE, "NULL pointer"); + 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->mSourceLock}; + ALsource *Source{LookupSource(context.get(), source)}; + if UNLIKELY(!Source) + context->setError(AL_INVALID_NAME, "Invalid source ID %u", source); + else if UNLIKELY(!values) + context->setError(AL_INVALID_VALUE, "NULL pointer"); + else + GetSourcedv(Source, context.get(), static_cast<SourceProp>(param), {values, MaxValues}); +} +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->mSourceLock}; + ALsource *Source{LookupSource(context.get(), source)}; + if UNLIKELY(!Source) + context->setError(AL_INVALID_NAME, "Invalid source ID %u", source); + else if UNLIKELY(!value) + context->setError(AL_INVALID_VALUE, "NULL pointer"); + else + GetSourceiv(Source, context.get(), static_cast<SourceProp>(param), {value, 1u}); +} +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->mSourceLock}; + ALsource *Source{LookupSource(context.get(), source)}; + if UNLIKELY(!Source) + context->setError(AL_INVALID_NAME, "Invalid source ID %u", source); + else if UNLIKELY(!(value1 && value2 && value3)) + context->setError(AL_INVALID_VALUE, "NULL pointer"); + 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->mSourceLock}; + ALsource *Source{LookupSource(context.get(), source)}; + if UNLIKELY(!Source) + context->setError(AL_INVALID_NAME, "Invalid source ID %u", source); + else if UNLIKELY(!values) + context->setError(AL_INVALID_VALUE, "NULL pointer"); + else + GetSourceiv(Source, context.get(), static_cast<SourceProp>(param), {values, MaxValues}); +} +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->mSourceLock}; + ALsource *Source{LookupSource(context.get(), source)}; + if UNLIKELY(!Source) + context->setError(AL_INVALID_NAME, "Invalid source ID %u", source); + else if UNLIKELY(!value) + context->setError(AL_INVALID_VALUE, "NULL pointer"); + else + GetSourcei64v(Source, context.get(), static_cast<SourceProp>(param), {value, 1u}); +} +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->mSourceLock}; + ALsource *Source{LookupSource(context.get(), source)}; + if UNLIKELY(!Source) + context->setError(AL_INVALID_NAME, "Invalid source ID %u", source); + else if UNLIKELY(!(value1 && value2 && value3)) + context->setError(AL_INVALID_VALUE, "NULL pointer"); + 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->mSourceLock}; + ALsource *Source{LookupSource(context.get(), source)}; + if UNLIKELY(!Source) + context->setError(AL_INVALID_NAME, "Invalid source ID %u", source); + else if UNLIKELY(!values) + context->setError(AL_INVALID_VALUE, "NULL pointer"); + else + GetSourcei64v(Source, context.get(), static_cast<SourceProp>(param), {values, MaxValues}); +} +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 UNLIKELY(n < 0) + context->setError(AL_INVALID_VALUE, "Playing %d sources", n); + if UNLIKELY(n <= 0) return; + + al::vector<ALsource*> extra_sources; + std::array<ALsource*,8> source_storage; + al::span<ALsource*> srchandles; + if LIKELY(static_cast<ALuint>(n) <= source_storage.size()) + srchandles = {source_storage.data(), static_cast<ALuint>(n)}; + else + { + extra_sources.resize(static_cast<ALuint>(n)); + srchandles = {extra_sources.data(), extra_sources.size()}; + } + + std::lock_guard<std::mutex> _{context->mSourceLock}; + for(auto &srchdl : srchandles) + { + srchdl = LookupSource(context.get(), *sources); + if(!srchdl) + SETERR_RETURN(context, AL_INVALID_NAME,, "Invalid source ID %u", *sources); + ++sources; + } + + ALCdevice *device{context->mDevice.get()}; + 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.begin(), srchandles.end(), + [](ALsource *source) -> void + { + source->OffsetType = AL_NONE; + source->Offset = 0.0; + source->state = AL_STOPPED; + } + ); + return; + } + + /* Count the number of reusable voices. */ + auto count_free_voices = [](const ALuint count, const ALvoice &voice) noexcept -> ALuint + { + if(voice.mPlayState.load(std::memory_order_acquire) == ALvoice::Stopped + && voice.mSourceID.load(std::memory_order_relaxed) == 0u) + return count + 1; + return count; + }; + auto free_voices = std::accumulate(context->mVoices.begin(), context->mVoices.end(), + ALuint{0}, count_free_voices); + if UNLIKELY(srchandles.size() > free_voices) + { + /* Increase the number of voices to handle the request. */ + const size_t need_voices{srchandles.size() - free_voices}; + context->mVoices.resize(context->mVoices.size() + need_voices); + } + + 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->mSampleLen == 0) + BufferList = BufferList->mNext.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_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; + + case AL_PLAYING: + assert(voice != nullptr); + /* A source that's already playing is restarted from the beginning. + * Stop the current voice and start a new one so it properly cross- + * fades back to the beginning. + */ + voice->mCurrentBuffer.store(nullptr, std::memory_order_relaxed); + voice->mLoopBuffer.store(nullptr, std::memory_order_relaxed); + voice->mSourceID.store(0u, std::memory_order_release); + voice->mPlayState.store(ALvoice::Stopping, std::memory_order_release); + voice = nullptr; + break; + + default: + assert(voice == nullptr); + break; + } + + /* Look for an unused voice to play this source with. */ + auto find_voice = [](const ALvoice &v) noexcept -> bool + { + return v.mPlayState.load(std::memory_order_acquire) == ALvoice::Stopped + && v.mSourceID.load(std::memory_order_relaxed) == 0u; + }; + auto voices_end = context->mVoices.data() + context->mVoices.size(); + voice = std::find_if(context->mVoices.data(), voices_end, find_voice); + assert(voice != voices_end); + + auto vidx = static_cast<ALuint>(std::distance(context->mVoices.data(), 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(auto vpos = GetSampleOffset(source)) + { + start_fading = vpos->pos != 0 || vpos->frac != 0 || vpos->bufferitem != BufferList; + voice->mPosition.store(vpos->pos, std::memory_order_relaxed); + voice->mPositionFrac.store(vpos->frac, std::memory_order_relaxed); + voice->mCurrentBuffer.store(vpos->bufferitem, std::memory_order_relaxed); + } + + ALbuffer *buffer{BufferList->mBuffer}; + 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 ALuint *OrderFromChan; + if(voice->mFmtChannels == FmtBFormat2D) + { + static const ALuint Order2DFromChan[MAX_AMBI2D_CHANNELS]{ + 0, 1,1, 2,2, 3,3,}; + OrderFromChan = Order2DFromChan; + } + else + { + static const ALuint 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<float>(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 * static_cast<float>(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->VoiceIdx = vidx; + + if(source->state != AL_PLAYING) + { + source->state = AL_PLAYING; + SendStateChangeEvent(context.get(), source->id, AL_PLAYING); + } + }; + std::for_each(srchandles.begin(), srchandles.end(), 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 UNLIKELY(n < 0) + context->setError(AL_INVALID_VALUE, "Pausing %d sources", n); + if UNLIKELY(n <= 0) return; + + al::vector<ALsource*> extra_sources; + std::array<ALsource*,8> source_storage; + al::span<ALsource*> srchandles; + if LIKELY(static_cast<ALuint>(n) <= source_storage.size()) + srchandles = {source_storage.data(), static_cast<ALuint>(n)}; + else + { + extra_sources.resize(static_cast<ALuint>(n)); + srchandles = {extra_sources.data(), extra_sources.size()}; + } + + std::lock_guard<std::mutex> _{context->mSourceLock}; + for(auto &srchdl : srchandles) + { + srchdl = LookupSource(context.get(), *sources); + if(!srchdl) + SETERR_RETURN(context, AL_INVALID_NAME,, "Invalid source ID %u", *sources); + ++sources; + } + + ALCdevice *device{context->mDevice.get()}; + 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.begin(), srchandles.end(), 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 UNLIKELY(n < 0) + context->setError(AL_INVALID_VALUE, "Stopping %d sources", n); + if UNLIKELY(n <= 0) return; + + al::vector<ALsource*> extra_sources; + std::array<ALsource*,8> source_storage; + al::span<ALsource*> srchandles; + if LIKELY(static_cast<ALuint>(n) <= source_storage.size()) + srchandles = {source_storage.data(), static_cast<ALuint>(n)}; + else + { + extra_sources.resize(static_cast<ALuint>(n)); + srchandles = {extra_sources.data(), extra_sources.size()}; + } + + std::lock_guard<std::mutex> _{context->mSourceLock}; + for(auto &srchdl : srchandles) + { + srchdl = LookupSource(context.get(), *sources); + if(!srchdl) + SETERR_RETURN(context, AL_INVALID_NAME,, "Invalid source ID %u", *sources); + ++sources; + } + + ALCdevice *device{context->mDevice.get()}; + BackendLockGuard __{*device->Backend}; + auto stop_source = [&context](ALsource *source) -> void + { + /* Get the source state before clearing from the voice, so we know what + * state the source+voice was actually in. + */ + ALvoice *voice{GetSourceVoice(source, context.get())}; + const ALenum oldstate{GetSourceState(source, voice)}; + 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(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.begin(), srchandles.end(), 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 UNLIKELY(n < 0) + context->setError(AL_INVALID_VALUE, "Rewinding %d sources", n); + if UNLIKELY(n <= 0) return; + + al::vector<ALsource*> extra_sources; + std::array<ALsource*,8> source_storage; + al::span<ALsource*> srchandles; + if LIKELY(static_cast<ALuint>(n) <= source_storage.size()) + srchandles = {source_storage.data(), static_cast<ALuint>(n)}; + else + { + extra_sources.resize(static_cast<ALuint>(n)); + srchandles = {extra_sources.data(), extra_sources.size()}; + } + + std::lock_guard<std::mutex> _{context->mSourceLock}; + for(auto &srchdl : srchandles) + { + srchdl = LookupSource(context.get(), *sources); + if(!srchdl) + SETERR_RETURN(context, AL_INVALID_NAME,, "Invalid source ID %u", *sources); + ++sources; + } + + ALCdevice *device{context->mDevice.get()}; + 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(source->state != 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.begin(), srchandles.end(), 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 UNLIKELY(nb < 0) + context->setError(AL_INVALID_VALUE, "Queueing %d buffers", nb); + if UNLIKELY(nb <= 0) return; + + std::lock_guard<std::mutex> _{context->mSourceLock}; + ALsource *source{LookupSource(context.get(),src)}; + if UNLIKELY(!source) + SETERR_RETURN(context, AL_INVALID_NAME,, "Invalid source ID %u", src); + + /* Can't queue on a Static Source */ + if UNLIKELY(source->SourceType == AL_STATIC) + SETERR_RETURN(context, AL_INVALID_OPERATION,, "Queueing onto static source %u", src); + + /* Check for a valid Buffer, for its frequency and format */ + ALCdevice *device{context->mDevice.get()}; + ALbuffer *BufferFmt{nullptr}; + ALbufferlistitem *BufferList{source->queue}; + while(BufferList && !BufferFmt) + { + BufferFmt = BufferList->mBuffer; + BufferList = BufferList->mNext.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) + { + context->setError(AL_INVALID_NAME, "Queueing invalid buffer ID %u", buffers[i]); + goto buffer_error; + } + + if(!BufferListStart) + { + BufferListStart = new ALbufferlistitem{}; + BufferList = BufferListStart; + } + else + { + auto item = new ALbufferlistitem{}; + BufferList->mNext.store(item, std::memory_order_relaxed); + BufferList = item; + } + BufferList->mNext.store(nullptr, std::memory_order_relaxed); + BufferList->mSampleLen = buffer ? buffer->SampleLen : 0; + BufferList->mBuffer = buffer; + if(!buffer) continue; + + IncrementRef(buffer->ref); + + if(buffer->MappedAccess != 0 && !(buffer->MappedAccess&AL_MAP_PERSISTENT_BIT_SOFT)) + { + context->setError(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) + { + context->setError(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) + { + std::unique_ptr<ALbufferlistitem> head{BufferListStart}; + BufferListStart = head->mNext.load(std::memory_order_relaxed); + if((buffer=head->mBuffer) != nullptr) DecrementRef(buffer->ref); + } + return; + } + } + /* All buffers good. */ + buflock.unlock(); + + /* Source is now streaming */ + source->SourceType = AL_STREAMING; + + BufferList = source->queue; + if(!BufferList) + source->queue = BufferListStart; + else + { + ALbufferlistitem *next; + while((next=BufferList->mNext.load(std::memory_order_relaxed)) != nullptr) + BufferList = next; + BufferList->mNext.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 UNLIKELY(nb < 0) + context->setError(AL_INVALID_VALUE, "Unqueueing %d buffers", nb); + if UNLIKELY(nb <= 0) return; + + std::lock_guard<std::mutex> _{context->mSourceLock}; + ALsource *source{LookupSource(context.get(),src)}; + if UNLIKELY(!source) + SETERR_RETURN(context, AL_INVALID_NAME,, "Invalid source ID %u", src); + + if UNLIKELY(source->Looping) + SETERR_RETURN(context, AL_INVALID_VALUE,, "Unqueueing from looping source %u", src); + if UNLIKELY(source->SourceType != AL_STREAMING) + SETERR_RETURN(context, 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, AL_INVALID_VALUE,, "Unqueueing pending buffers"); + + ALuint i{1u}; + while(i < static_cast<ALuint>(nb)) + { + /* If the next bufferlist to check is NULL or is the current one, it's + * trying to unqueue pending buffers. + */ + ALbufferlistitem *next{BufferList->mNext.load(std::memory_order_relaxed)}; + if UNLIKELY(!next || next == Current) + SETERR_RETURN(context, AL_INVALID_VALUE,, "Unqueueing pending buffers"); + BufferList = next; + + ++i; + } + + do { + std::unique_ptr<ALbufferlistitem> head{source->queue}; + source->queue = head->mNext.load(std::memory_order_relaxed); + + if(ALbuffer *buffer{head->mBuffer}) + { + *(buffers++) = buffer->id; + DecrementRef(buffer->ref); + } + else + *(buffers++) = 0; + } while(--nb); +} +END_API_FUNC + + +ALsource::ALsource(ALuint 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; + } + + PropsClean.test_and_set(std::memory_order_relaxed); +} + +ALsource::~ALsource() +{ + ALbufferlistitem *BufferList{queue}; + while(BufferList != nullptr) + { + std::unique_ptr<ALbufferlistitem> head{BufferList}; + BufferList = head->mNext.load(std::memory_order_relaxed); + if(ALbuffer *buffer{head->mBuffer}) DecrementRef(buffer->ref); + } + 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) +{ + std::lock_guard<std::mutex> _{context->mSourceLock}; + std::for_each(context->mVoices.begin(), context->mVoices.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/source.h b/al/source.h new file mode 100644 index 00000000..7ca889d7 --- /dev/null +++ b/al/source.h @@ -0,0 +1,129 @@ +#ifndef AL_SOURCE_H +#define AL_SOURCE_H + +#include <array> +#include <atomic> +#include <cstddef> +#include <iterator> + +#include "AL/al.h" +#include "AL/alc.h" + +#include "alcontext.h" +#include "almalloc.h" +#include "alnumeric.h" +#include "alu.h" +#include "vector.h" + +struct ALbuffer; +struct ALeffectslot; + + +#define DEFAULT_SENDS 2 + +#define INVALID_VOICE_IDX static_cast<ALuint>(-1) + +struct ALbufferlistitem { + std::atomic<ALbufferlistitem*> mNext{nullptr}; + ALuint mSampleLen{0u}; + ALbuffer *mBuffer{nullptr}; + + DEF_NEWDEL(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; + bool HeadRelative; + bool Looping; + DistanceModel mDistanceModel; + Resampler mResampler; + bool DirectChannels; + SpatializeMode mSpatialize; + + bool DryGainHFAuto; + bool WetGainAuto; + bool 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{0.0}; + ALenum OffsetType{AL_NONE}; + + /** Source type (static, streaming, or undetermined) */ + ALenum SourceType{AL_UNDETERMINED}; + + /** Source state (initial, playing, paused, or stopped) */ + ALenum state{AL_INITIAL}; + + /** Source Buffer Queue head. */ + ALbufferlistitem *queue{nullptr}; + + std::atomic_flag PropsClean; + + /* Index into the context's Voices array. Lazily updated, only checked and + * reset when looking up the voice. + */ + ALuint VoiceIdx{INVALID_VOICE_IDX}; + + /** Self ID */ + ALuint id{0}; + + + ALsource(ALuint num_sends); + ~ALsource(); + + ALsource(const ALsource&) = delete; + ALsource& operator=(const ALsource&) = delete; +}; + +void UpdateAllSourceProps(ALCcontext *context); + +#endif diff --git a/al/state.cpp b/al/state.cpp new file mode 100644 index 00000000..25a0efd1 --- /dev/null +++ b/al/state.cpp @@ -0,0 +1,880 @@ +/** + * 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 "alcontext.h" +#include "alexcpt.h" +#include "almalloc.h" +#include "alnumeric.h" +#include "alspan.h" +#include "alu.h" +#include "atomic.h" +#include "event.h" +#include "inprogext.h" +#include "opthelpers.h" +#include "strutils.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 */ +template<Resampler rtype> struct ResamplerName { }; +template<> struct ResamplerName<Resampler::Point> +{ static constexpr const ALchar *Get() noexcept { return "Nearest"; } }; +template<> struct ResamplerName<Resampler::Linear> +{ static constexpr const ALchar *Get() noexcept { return "Linear"; } }; +template<> struct ResamplerName<Resampler::Cubic> +{ static constexpr const ALchar *Get() noexcept { return "Cubic"; } }; +template<> struct ResamplerName<Resampler::FastBSinc12> +{ static constexpr const ALchar *Get() noexcept { return "11th order Sinc (fast)"; } }; +template<> struct ResamplerName<Resampler::BSinc12> +{ static constexpr const ALchar *Get() noexcept { return "11th order Sinc"; } }; +template<> struct ResamplerName<Resampler::FastBSinc24> +{ static constexpr const ALchar *Get() noexcept { return "23rd order Sinc (fast)"; } }; +template<> struct ResamplerName<Resampler::BSinc24> +{ static constexpr const ALchar *Get() noexcept { return "23rd order Sinc"; } }; + +const ALchar *GetResamplerName(const Resampler rtype) +{ +#define HANDLE_RESAMPLER(r) case r: return ResamplerName<r>::Get() + switch(rtype) + { + HANDLE_RESAMPLER(Resampler::Point); + HANDLE_RESAMPLER(Resampler::Linear); + HANDLE_RESAMPLER(Resampler::Cubic); + HANDLE_RESAMPLER(Resampler::FastBSinc12); + HANDLE_RESAMPLER(Resampler::BSinc12); + HANDLE_RESAMPLER(Resampler::FastBSinc24); + HANDLE_RESAMPLER(Resampler::BSinc24); + } +#undef HANDLE_RESAMPLER + /* Should never get here. */ + throw std::runtime_error{"Unexpected resampler index"}; +} + +} // 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 +{ + static const auto spoof = al::getenv("ALSOFT_SPOOF_VERSION"); + if(spoof) return spoof->c_str(); + return ALSOFT_VERSION; +} +END_API_FUNC + +#define DO_UPDATEPROPS() do { \ + if(!context->mDeferUpdates.load(std::memory_order_acquire)) \ + UpdateContextProps(context.get()); \ + else \ + context->mPropsClean.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->mPropLock}; + switch(capability) + { + case AL_SOURCE_DISTANCE_MODEL: + context->mSourceDistanceModel = AL_TRUE; + DO_UPDATEPROPS(); + break; + + default: + context->setError(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->mPropLock}; + switch(capability) + { + case AL_SOURCE_DISTANCE_MODEL: + context->mSourceDistanceModel = AL_FALSE; + DO_UPDATEPROPS(); + break; + + default: + context->setError(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->mPropLock}; + ALboolean value{AL_FALSE}; + switch(capability) + { + case AL_SOURCE_DISTANCE_MODEL: + value = context->mSourceDistanceModel; + break; + + default: + context->setError(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->mPropLock}; + ALboolean value{AL_FALSE}; + switch(pname) + { + case AL_DOPPLER_FACTOR: + if(context->mDopplerFactor != 0.0f) + value = AL_TRUE; + break; + + case AL_DOPPLER_VELOCITY: + if(context->mDopplerVelocity != 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->mSpeedOfSound != 0.0f) + value = AL_TRUE; + break; + + case AL_DEFERRED_UPDATES_SOFT: + if(context->mDeferUpdates.load(std::memory_order_acquire)) + value = AL_TRUE; + break; + + case AL_GAIN_LIMIT_SOFT: + if(GAIN_MIX_MAX/context->mGainBoost != 0.0f) + value = AL_TRUE; + break; + + case AL_NUM_RESAMPLERS_SOFT: + /* Always non-0. */ + value = AL_TRUE; + break; + + case AL_DEFAULT_RESAMPLER_SOFT: + value = static_cast<int>(ResamplerDefault) ? AL_TRUE : AL_FALSE; + break; + + default: + context->setError(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->mPropLock}; + ALdouble value{0.0}; + switch(pname) + { + case AL_DOPPLER_FACTOR: + value = context->mDopplerFactor; + break; + + case AL_DOPPLER_VELOCITY: + value = context->mDopplerVelocity; + break; + + case AL_DISTANCE_MODEL: + value = static_cast<ALdouble>(context->mDistanceModel); + break; + + case AL_SPEED_OF_SOUND: + value = context->mSpeedOfSound; + break; + + case AL_DEFERRED_UPDATES_SOFT: + if(context->mDeferUpdates.load(std::memory_order_acquire)) + value = static_cast<ALdouble>(AL_TRUE); + break; + + case AL_GAIN_LIMIT_SOFT: + value = ALdouble{GAIN_MIX_MAX}/context->mGainBoost; + break; + + case AL_NUM_RESAMPLERS_SOFT: + value = static_cast<ALdouble>(Resampler::Max) + 1.0; + break; + + case AL_DEFAULT_RESAMPLER_SOFT: + value = static_cast<ALdouble>(ResamplerDefault); + break; + + default: + context->setError(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->mPropLock}; + ALfloat value{0.0f}; + switch(pname) + { + case AL_DOPPLER_FACTOR: + value = context->mDopplerFactor; + break; + + case AL_DOPPLER_VELOCITY: + value = context->mDopplerVelocity; + break; + + case AL_DISTANCE_MODEL: + value = static_cast<ALfloat>(context->mDistanceModel); + break; + + case AL_SPEED_OF_SOUND: + value = context->mSpeedOfSound; + break; + + case AL_DEFERRED_UPDATES_SOFT: + if(context->mDeferUpdates.load(std::memory_order_acquire)) + value = static_cast<ALfloat>(AL_TRUE); + break; + + case AL_GAIN_LIMIT_SOFT: + value = GAIN_MIX_MAX/context->mGainBoost; + break; + + case AL_NUM_RESAMPLERS_SOFT: + value = static_cast<ALfloat>(Resampler::Max) + 1.0f; + break; + + case AL_DEFAULT_RESAMPLER_SOFT: + value = static_cast<ALfloat>(ResamplerDefault); + break; + + default: + context->setError(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->mPropLock}; + ALint value{0}; + switch(pname) + { + case AL_DOPPLER_FACTOR: + value = static_cast<ALint>(context->mDopplerFactor); + break; + + case AL_DOPPLER_VELOCITY: + value = static_cast<ALint>(context->mDopplerVelocity); + break; + + case AL_DISTANCE_MODEL: + value = static_cast<ALint>(context->mDistanceModel); + break; + + case AL_SPEED_OF_SOUND: + value = static_cast<ALint>(context->mSpeedOfSound); + break; + + case AL_DEFERRED_UPDATES_SOFT: + if(context->mDeferUpdates.load(std::memory_order_acquire)) + value = AL_TRUE; + break; + + case AL_GAIN_LIMIT_SOFT: + value = static_cast<ALint>(GAIN_MIX_MAX/context->mGainBoost); + break; + + case AL_NUM_RESAMPLERS_SOFT: + value = static_cast<int>(Resampler::Max) + 1; + break; + + case AL_DEFAULT_RESAMPLER_SOFT: + value = static_cast<int>(ResamplerDefault); + break; + + default: + context->setError(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_i64; + + std::lock_guard<std::mutex> _{context->mPropLock}; + ALint64SOFT value{0}; + switch(pname) + { + case AL_DOPPLER_FACTOR: + value = static_cast<ALint64SOFT>(context->mDopplerFactor); + break; + + case AL_DOPPLER_VELOCITY: + value = static_cast<ALint64SOFT>(context->mDopplerVelocity); + break; + + case AL_DISTANCE_MODEL: + value = static_cast<ALint64SOFT>(context->mDistanceModel); + break; + + case AL_SPEED_OF_SOUND: + value = static_cast<ALint64SOFT>(context->mSpeedOfSound); + break; + + case AL_DEFERRED_UPDATES_SOFT: + if(context->mDeferUpdates.load(std::memory_order_acquire)) + value = AL_TRUE; + break; + + case AL_GAIN_LIMIT_SOFT: + value = static_cast<ALint64SOFT>(GAIN_MIX_MAX/context->mGainBoost); + break; + + case AL_NUM_RESAMPLERS_SOFT: + value = static_cast<ALint64SOFT>(Resampler::Max) + 1; + break; + + case AL_DEFAULT_RESAMPLER_SOFT: + value = static_cast<ALint64SOFT>(ResamplerDefault); + break; + + default: + context->setError(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->mPropLock}; + void *value{nullptr}; + switch(pname) + { + case AL_EVENT_CALLBACK_FUNCTION_SOFT: + value = reinterpret_cast<void*>(context->mEventCb); + break; + + case AL_EVENT_CALLBACK_USER_PARAM_SOFT: + value = context->mEventParam; + break; + + default: + context->setError(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) + context->setError(AL_INVALID_VALUE, "NULL pointer"); + else switch(pname) + { + default: + context->setError(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) + context->setError(AL_INVALID_VALUE, "NULL pointer"); + else switch(pname) + { + default: + context->setError(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) + context->setError(AL_INVALID_VALUE, "NULL pointer"); + else switch(pname) + { + default: + context->setError(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) + context->setError(AL_INVALID_VALUE, "NULL pointer"); + else switch(pname) + { + default: + context->setError(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) + context->setError(AL_INVALID_VALUE, "NULL pointer"); + else switch(pname) + { + default: + context->setError(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) + context->setError(AL_INVALID_VALUE, "NULL pointer"); + else switch(pname) + { + default: + context->setError(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->mExtensionList; + 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: + context->setError(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))) + context->setError(AL_INVALID_VALUE, "Doppler factor %f out of range", value); + else + { + std::lock_guard<std::mutex> _{context->mPropLock}; + context->mDopplerFactor = 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->mEnabledEvts.load(std::memory_order_relaxed)&EventType_Deprecated)) + { + std::lock_guard<std::mutex> _{context->mEventCbLock}; + ALbitfieldSOFT enabledevts{context->mEnabledEvts.load(std::memory_order_relaxed)}; + if((enabledevts&EventType_Deprecated) && context->mEventCb) + { + static const char msg[] = + "alDopplerVelocity is deprecated in AL1.1, use alSpeedOfSound"; + const ALsizei msglen{sizeof(msg)-1}; + (*context->mEventCb)(AL_EVENT_TYPE_DEPRECATED_SOFT, 0, 0, msglen, msg, + context->mEventParam); + } + } + + if(!(value >= 0.0f && std::isfinite(value))) + context->setError(AL_INVALID_VALUE, "Doppler velocity %f out of range", value); + else + { + std::lock_guard<std::mutex> _{context->mPropLock}; + context->mDopplerVelocity = 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))) + context->setError(AL_INVALID_VALUE, "Speed of sound %f out of range", value); + else + { + std::lock_guard<std::mutex> _{context->mPropLock}; + context->mSpeedOfSound = 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)) + context->setError(AL_INVALID_VALUE, "Distance model 0x%04x out of range", value); + else + { + std::lock_guard<std::mutex> _{context->mPropLock}; + context->mDistanceModel = static_cast<DistanceModel>(value); + if(!context->mSourceDistanceModel) + DO_UPDATEPROPS(); + } +} +END_API_FUNC + + +AL_API ALvoid AL_APIENTRY alDeferUpdatesSOFT(void) +START_API_FUNC +{ + ContextRef context{GetContextRef()}; + if UNLIKELY(!context) return; + + context->deferUpdates(); +} +END_API_FUNC + +AL_API ALvoid AL_APIENTRY alProcessUpdatesSOFT(void) +START_API_FUNC +{ + ContextRef context{GetContextRef()}; + if UNLIKELY(!context) return; + + context->processUpdates(); +} +END_API_FUNC + + +AL_API const ALchar* AL_APIENTRY alGetStringiSOFT(ALenum pname, ALsizei index) +START_API_FUNC +{ + ContextRef context{GetContextRef()}; + if UNLIKELY(!context) return nullptr; + + const ALchar *value{nullptr}; + switch(pname) + { + case AL_RESAMPLER_NAME_SOFT: + if(index < 0 || index > static_cast<ALint>(Resampler::Max)) + context->setError(AL_INVALID_VALUE, "Resampler name index %d out of range", index); + else + value = GetResamplerName(static_cast<Resampler>(index)); + break; + + default: + context->setError(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->mFreeContextProps.load(std::memory_order_acquire)}; + if(!props) + props = new ALcontextProps{}; + else + { + ALcontextProps *next; + do { + next = props->next.load(std::memory_order_relaxed); + } while(context->mFreeContextProps.compare_exchange_weak(props, next, + std::memory_order_seq_cst, std::memory_order_acquire) == 0); + } + + /* Copy in current property values. */ + props->DopplerFactor = context->mDopplerFactor; + props->DopplerVelocity = context->mDopplerVelocity; + props->SpeedOfSound = context->mSpeedOfSound; + + props->SourceDistanceModel = context->mSourceDistanceModel; + props->mDistanceModel = context->mDistanceModel; + + /* Set the new container for updating internal parameters. */ + props = context->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->mFreeContextProps, props); + } +} |