Improve some checks for compiler analysis
[openal-soft.git] / OpenAL32 / alAuxEffectSlot.cpp
blobad33fe50d2253c9cd5a8eb206737d797a9c2d324
1 /**
2 * OpenAL cross platform audio library
3 * Copyright (C) 1999-2007 by authors.
4 * This library is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Library General Public
6 * License as published by the Free Software Foundation; either
7 * version 2 of the License, or (at your option) any later version.
9 * This library is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Library General Public License for more details.
14 * You should have received a copy of the GNU Library General Public
15 * License along with this library; if not, write to the
16 * Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 * Or go to http://www.gnu.org/copyleft/lgpl.html
21 #include "config.h"
23 #include <stdlib.h>
24 #include <math.h>
26 #include <thread>
27 #include <algorithm>
29 #include "AL/al.h"
30 #include "AL/alc.h"
32 #include "alMain.h"
33 #include "alcontext.h"
34 #include "alAuxEffectSlot.h"
35 #include "alError.h"
36 #include "alListener.h"
37 #include "alSource.h"
39 #include "fpu_modes.h"
40 #include "almalloc.h"
43 namespace {
45 inline ALeffectslot *LookupEffectSlot(ALCcontext *context, ALuint id) noexcept
47 --id;
48 if(UNLIKELY(id >= context->EffectSlotList.size()))
49 return nullptr;
50 return context->EffectSlotList[id].get();
53 inline ALeffect *LookupEffect(ALCdevice *device, ALuint id) noexcept
55 ALuint lidx = (id-1) >> 6;
56 ALsizei slidx = (id-1) & 0x3f;
58 if(UNLIKELY(lidx >= device->EffectList.size()))
59 return nullptr;
60 EffectSubList &sublist = device->EffectList[lidx];
61 if(UNLIKELY(sublist.FreeMask & (U64(1)<<slidx)))
62 return nullptr;
63 return sublist.Effects + slidx;
67 void AddActiveEffectSlots(const ALuint *slotids, ALsizei count, ALCcontext *context)
69 if(count < 1) return;
70 ALeffectslotArray *curarray{context->ActiveAuxSlots.load(std::memory_order_acquire)};
71 ALsizei newcount{curarray->count + count};
73 /* Insert the new effect slots into the head of the array, followed by the
74 * existing ones.
76 auto newarray = static_cast<ALeffectslotArray*>(al_calloc(DEF_ALIGN,
77 FAM_SIZE(ALeffectslotArray, slot, newcount)));
78 newarray->count = newcount;
79 auto slotiter = std::transform(slotids, slotids+count, newarray->slot,
80 [context](ALuint id) noexcept -> ALeffectslot*
81 { return LookupEffectSlot(context, id); }
83 std::copy_n(curarray->slot, curarray->count, slotiter);
85 /* Remove any duplicates (first instance of each will be kept). */
86 ALeffectslot **last = newarray->slot + newarray->count;
87 for(ALeffectslot **start=newarray->slot+1;;)
89 last = std::remove(start, last, *(start-1));
90 if(start == last) break;
91 ++start;
93 newcount = std::distance(newarray->slot, last);
95 /* Reallocate newarray if the new size ended up smaller from duplicate
96 * removal.
98 if(UNLIKELY(newcount < newarray->count))
100 curarray = newarray;
101 newarray = static_cast<ALeffectslotArray*>(al_calloc(DEF_ALIGN,
102 FAM_SIZE(ALeffectslotArray, slot, newcount)));
103 newarray->count = newcount;
104 std::copy_n(curarray->slot, newcount, newarray->slot);
105 al_free(curarray);
106 curarray = nullptr;
109 curarray = context->ActiveAuxSlots.exchange(newarray, std::memory_order_acq_rel);
110 ALCdevice *device{context->Device};
111 while((device->MixCount.load(std::memory_order_acquire)&1))
112 std::this_thread::yield();
113 al_free(curarray);
116 void RemoveActiveEffectSlots(const ALuint *slotids, ALsizei count, ALCcontext *context)
118 if(count < 1) return;
119 ALeffectslotArray *curarray{context->ActiveAuxSlots.load(std::memory_order_acquire)};
121 /* Don't shrink the allocated array size since we don't know how many (if
122 * any) of the effect slots to remove are in the array.
124 auto newarray = static_cast<ALeffectslotArray*>(al_calloc(DEF_ALIGN,
125 FAM_SIZE(ALeffectslotArray, slot, curarray->count)));
127 /* Copy each element in curarray to newarray whose ID is not in slotids. */
128 const ALuint *slotids_end{slotids + count};
129 auto slotiter = std::copy_if(curarray->slot, curarray->slot+curarray->count, newarray->slot,
130 [slotids, slotids_end](const ALeffectslot *slot) -> bool
131 { return std::find(slotids, slotids_end, slot->id) == slotids_end; }
133 newarray->count = std::distance(newarray->slot, slotiter);
135 /* TODO: Could reallocate newarray now that we know it's needed size. */
137 curarray = context->ActiveAuxSlots.exchange(newarray, std::memory_order_acq_rel);
138 ALCdevice *device{context->Device};
139 while((device->MixCount.load(std::memory_order_acquire)&1))
140 std::this_thread::yield();
141 al_free(curarray);
144 constexpr struct FactoryItem {
145 ALenum Type;
146 EffectStateFactory* (&GetFactory)(void);
147 } FactoryList[] = {
148 { AL_EFFECT_NULL, NullStateFactory_getFactory },
149 { AL_EFFECT_EAXREVERB, ReverbStateFactory_getFactory },
150 { AL_EFFECT_REVERB, ReverbStateFactory_getFactory },
151 { AL_EFFECT_AUTOWAH, AutowahStateFactory_getFactory },
152 { AL_EFFECT_CHORUS, ChorusStateFactory_getFactory },
153 { AL_EFFECT_COMPRESSOR, CompressorStateFactory_getFactory },
154 { AL_EFFECT_DISTORTION, DistortionStateFactory_getFactory },
155 { AL_EFFECT_ECHO, EchoStateFactory_getFactory },
156 { AL_EFFECT_EQUALIZER, EqualizerStateFactory_getFactory },
157 { AL_EFFECT_FLANGER, FlangerStateFactory_getFactory },
158 { AL_EFFECT_FREQUENCY_SHIFTER, FshifterStateFactory_getFactory },
159 { AL_EFFECT_RING_MODULATOR, ModulatorStateFactory_getFactory },
160 { AL_EFFECT_PITCH_SHIFTER, PshifterStateFactory_getFactory},
161 { AL_EFFECT_DEDICATED_DIALOGUE, DedicatedStateFactory_getFactory },
162 { AL_EFFECT_DEDICATED_LOW_FREQUENCY_EFFECT, DedicatedStateFactory_getFactory }
165 inline EffectStateFactory *getFactoryByType(ALenum type)
167 auto iter = std::find_if(std::begin(FactoryList), std::end(FactoryList),
168 [type](const FactoryItem &item) noexcept -> bool
169 { return item.Type == type; }
171 return (iter != std::end(FactoryList)) ? iter->GetFactory() : nullptr;
175 #define DO_UPDATEPROPS() do { \
176 if(!context->DeferUpdates.load(std::memory_order_acquire)) \
177 UpdateEffectSlotProps(slot, context.get()); \
178 else \
179 slot->PropsClean.clear(std::memory_order_release); \
180 } while(0)
182 } // namespace
184 AL_API ALvoid AL_APIENTRY alGenAuxiliaryEffectSlots(ALsizei n, ALuint *effectslots)
186 ContextRef context{GetContextRef()};
187 if(UNLIKELY(!context)) return;
189 if(n < 0)
190 SETERR_RETURN(context.get(), AL_INVALID_VALUE,, "Generating %d effect slots", n);
191 if(n == 0) return;
193 std::unique_lock<std::mutex> slotlock{context->EffectSlotLock};
194 ALCdevice *device{context->Device};
195 for(ALsizei cur{0};cur < n;cur++)
197 auto iter = std::find_if(context->EffectSlotList.begin(), context->EffectSlotList.end(),
198 [](const ALeffectslotPtr &entry) noexcept -> bool
199 { return !entry; }
201 if(iter == context->EffectSlotList.end())
203 if(UNLIKELY(device->AuxiliaryEffectSlotMax == context->EffectSlotList.size()))
205 slotlock.unlock();
206 alDeleteAuxiliaryEffectSlots(cur, effectslots);
207 alSetError(context.get(), AL_OUT_OF_MEMORY,
208 "Exceeding %u auxiliary effect slot limit", device->AuxiliaryEffectSlotMax);
209 return;
211 context->EffectSlotList.emplace_back(nullptr);
212 iter = context->EffectSlotList.end() - 1;
215 *iter = std::unique_ptr<ALeffectslot>(new ALeffectslot{});
216 ALenum err{InitEffectSlot(iter->get())};
217 if(err != AL_NO_ERROR)
219 *iter = nullptr;
220 slotlock.unlock();
222 alDeleteAuxiliaryEffectSlots(cur, effectslots);
223 alSetError(context.get(), err, "Effect slot object allocation failed");
224 return;
226 aluInitEffectPanning(iter->get());
228 ALuint id = std::distance(context->EffectSlotList.begin(), iter) + 1;
229 (*iter)->id = id;
230 effectslots[cur] = id;
232 AddActiveEffectSlots(effectslots, n, context.get());
235 AL_API ALvoid AL_APIENTRY alDeleteAuxiliaryEffectSlots(ALsizei n, const ALuint *effectslots)
237 ContextRef context{GetContextRef()};
238 if(UNLIKELY(!context)) return;
240 if(n < 0)
241 SETERR_RETURN(context.get(), AL_INVALID_VALUE,, "Deleting %d effect slots", n);
242 if(n == 0) return;
244 std::lock_guard<std::mutex> _{context->EffectSlotLock};
245 auto effectslots_end = effectslots + n;
246 auto bad_slot = std::find_if(effectslots, effectslots_end,
247 [&context](ALuint id) -> bool
249 ALeffectslot *slot{LookupEffectSlot(context.get(), id)};
250 if(!slot)
252 alSetError(context.get(), AL_INVALID_NAME, "Invalid effect slot ID %u", id);
253 return true;
255 if(ReadRef(&slot->ref) != 0)
257 alSetError(context.get(), AL_INVALID_NAME, "Deleting in-use effect slot %u", id);
258 return true;
260 return false;
263 if(bad_slot != effectslots_end)
264 return;
266 // All effectslots are valid, remove and delete them
267 RemoveActiveEffectSlots(effectslots, n, context.get());
268 std::for_each(effectslots, effectslots_end,
269 [&context](ALuint id) noexcept -> void
270 { context->EffectSlotList[id-1] = nullptr; }
274 AL_API ALboolean AL_APIENTRY alIsAuxiliaryEffectSlot(ALuint effectslot)
276 ContextRef context{GetContextRef()};
277 if(LIKELY(context))
279 std::lock_guard<std::mutex> _{context->EffectSlotLock};
280 if(LookupEffectSlot(context.get(), effectslot) != nullptr)
281 return AL_TRUE;
283 return AL_FALSE;
286 AL_API ALvoid AL_APIENTRY alAuxiliaryEffectSloti(ALuint effectslot, ALenum param, ALint value)
288 ContextRef context{GetContextRef()};
289 if(UNLIKELY(!context)) return;
291 std::lock_guard<std::mutex> _{context->PropLock};
292 std::lock_guard<std::mutex> __{context->EffectSlotLock};
293 ALeffectslot *slot = LookupEffectSlot(context.get(), effectslot);
294 if(UNLIKELY(!slot))
295 SETERR_RETURN(context.get(), AL_INVALID_NAME,, "Invalid effect slot ID %u", effectslot);
297 ALCdevice *device{};
298 ALenum err{};
299 switch(param)
301 case AL_EFFECTSLOT_EFFECT:
302 device = context->Device;
304 { std::lock_guard<std::mutex> ___{device->EffectLock};
305 ALeffect *effect{value ? LookupEffect(device, value) : nullptr};
306 if(!(value == 0 || effect != nullptr))
307 SETERR_RETURN(context.get(), AL_INVALID_VALUE,, "Invalid effect ID %u", value);
308 err = InitializeEffect(context.get(), slot, effect);
310 if(err != AL_NO_ERROR)
312 alSetError(context.get(), err, "Effect initialization failed");
313 return;
315 break;
317 case AL_EFFECTSLOT_AUXILIARY_SEND_AUTO:
318 if(!(value == AL_TRUE || value == AL_FALSE))
319 SETERR_RETURN(context.get(), AL_INVALID_VALUE,,
320 "Effect slot auxiliary send auto out of range");
321 slot->AuxSendAuto = value;
322 break;
324 default:
325 SETERR_RETURN(context.get(), AL_INVALID_ENUM,,
326 "Invalid effect slot integer property 0x%04x", param);
328 DO_UPDATEPROPS();
331 AL_API ALvoid AL_APIENTRY alAuxiliaryEffectSlotiv(ALuint effectslot, ALenum param, const ALint *values)
333 switch(param)
335 case AL_EFFECTSLOT_EFFECT:
336 case AL_EFFECTSLOT_AUXILIARY_SEND_AUTO:
337 alAuxiliaryEffectSloti(effectslot, param, values[0]);
338 return;
341 ContextRef context{GetContextRef()};
342 if(UNLIKELY(!context)) return;
344 std::lock_guard<std::mutex> _{context->EffectSlotLock};
345 ALeffectslot *slot = LookupEffectSlot(context.get(), effectslot);
346 if(UNLIKELY(!slot))
347 SETERR_RETURN(context.get(), AL_INVALID_NAME,, "Invalid effect slot ID %u", effectslot);
349 switch(param)
351 default:
352 SETERR_RETURN(context.get(), AL_INVALID_ENUM,,
353 "Invalid effect slot integer-vector property 0x%04x", param);
357 AL_API ALvoid AL_APIENTRY alAuxiliaryEffectSlotf(ALuint effectslot, ALenum param, ALfloat value)
359 ContextRef context{GetContextRef()};
360 if(UNLIKELY(!context)) return;
362 std::lock_guard<std::mutex> _{context->PropLock};
363 std::lock_guard<std::mutex> __{context->EffectSlotLock};
364 ALeffectslot *slot = LookupEffectSlot(context.get(), effectslot);
365 if(UNLIKELY(!slot))
366 SETERR_RETURN(context.get(), AL_INVALID_NAME,, "Invalid effect slot ID %u", effectslot);
368 switch(param)
370 case AL_EFFECTSLOT_GAIN:
371 if(!(value >= 0.0f && value <= 1.0f))
372 SETERR_RETURN(context.get(), AL_INVALID_VALUE,, "Effect slot gain out of range");
373 slot->Gain = value;
374 break;
376 default:
377 SETERR_RETURN(context.get(), AL_INVALID_ENUM,, "Invalid effect slot float property 0x%04x",
378 param);
380 DO_UPDATEPROPS();
383 AL_API ALvoid AL_APIENTRY alAuxiliaryEffectSlotfv(ALuint effectslot, ALenum param, const ALfloat *values)
385 switch(param)
387 case AL_EFFECTSLOT_GAIN:
388 alAuxiliaryEffectSlotf(effectslot, param, values[0]);
389 return;
392 ContextRef context{GetContextRef()};
393 if(UNLIKELY(!context)) return;
395 std::lock_guard<std::mutex> _{context->EffectSlotLock};
396 ALeffectslot *slot = LookupEffectSlot(context.get(), effectslot);
397 if(UNLIKELY(!slot))
398 SETERR_RETURN(context.get(), AL_INVALID_NAME,, "Invalid effect slot ID %u", effectslot);
400 switch(param)
402 default:
403 SETERR_RETURN(context.get(), AL_INVALID_ENUM,,
404 "Invalid effect slot float-vector property 0x%04x", param);
408 AL_API ALvoid AL_APIENTRY alGetAuxiliaryEffectSloti(ALuint effectslot, ALenum param, ALint *value)
410 ContextRef context{GetContextRef()};
411 if(UNLIKELY(!context)) return;
413 std::lock_guard<std::mutex> _{context->EffectSlotLock};
414 ALeffectslot *slot = LookupEffectSlot(context.get(), effectslot);
415 if(UNLIKELY(!slot))
416 SETERR_RETURN(context.get(), AL_INVALID_NAME,, "Invalid effect slot ID %u", effectslot);
418 switch(param)
420 case AL_EFFECTSLOT_AUXILIARY_SEND_AUTO:
421 *value = slot->AuxSendAuto;
422 break;
424 default:
425 SETERR_RETURN(context.get(), AL_INVALID_ENUM,,
426 "Invalid effect slot integer property 0x%04x", param);
430 AL_API ALvoid AL_APIENTRY alGetAuxiliaryEffectSlotiv(ALuint effectslot, ALenum param, ALint *values)
432 switch(param)
434 case AL_EFFECTSLOT_EFFECT:
435 case AL_EFFECTSLOT_AUXILIARY_SEND_AUTO:
436 alGetAuxiliaryEffectSloti(effectslot, param, values);
437 return;
440 ContextRef context{GetContextRef()};
441 if(UNLIKELY(!context)) return;
443 std::lock_guard<std::mutex> _{context->EffectSlotLock};
444 ALeffectslot *slot = LookupEffectSlot(context.get(), effectslot);
445 if(UNLIKELY(!slot))
446 SETERR_RETURN(context.get(), AL_INVALID_NAME,, "Invalid effect slot ID %u", effectslot);
448 switch(param)
450 default:
451 SETERR_RETURN(context.get(), AL_INVALID_ENUM,,
452 "Invalid effect slot integer-vector property 0x%04x", param);
456 AL_API ALvoid AL_APIENTRY alGetAuxiliaryEffectSlotf(ALuint effectslot, ALenum param, ALfloat *value)
458 ContextRef context{GetContextRef()};
459 if(UNLIKELY(!context)) return;
461 std::lock_guard<std::mutex> _{context->EffectSlotLock};
462 ALeffectslot *slot = LookupEffectSlot(context.get(), effectslot);
463 if(UNLIKELY(!slot))
464 SETERR_RETURN(context.get(), AL_INVALID_NAME,, "Invalid effect slot ID %u", effectslot);
466 switch(param)
468 case AL_EFFECTSLOT_GAIN:
469 *value = slot->Gain;
470 break;
472 default:
473 SETERR_RETURN(context.get(), AL_INVALID_ENUM,,
474 "Invalid effect slot float property 0x%04x", param);
478 AL_API ALvoid AL_APIENTRY alGetAuxiliaryEffectSlotfv(ALuint effectslot, ALenum param, ALfloat *values)
480 switch(param)
482 case AL_EFFECTSLOT_GAIN:
483 alGetAuxiliaryEffectSlotf(effectslot, param, values);
484 return;
487 ContextRef context{GetContextRef()};
488 if(UNLIKELY(!context)) return;
490 std::lock_guard<std::mutex> _{context->EffectSlotLock};
491 ALeffectslot *slot = LookupEffectSlot(context.get(), effectslot);
492 if(UNLIKELY(!slot))
493 SETERR_RETURN(context.get(), AL_INVALID_NAME,, "Invalid effect slot ID %u", effectslot);
495 switch(param)
497 default:
498 SETERR_RETURN(context.get(), AL_INVALID_ENUM,,
499 "Invalid effect slot float-vector property 0x%04x", param);
504 ALenum InitializeEffect(ALCcontext *Context, ALeffectslot *EffectSlot, ALeffect *effect)
506 ALenum newtype{effect ? effect->type : AL_EFFECT_NULL};
507 if(newtype != EffectSlot->Effect.Type)
509 EffectStateFactory *factory{getFactoryByType(newtype)};
510 if(!factory)
512 ERR("Failed to find factory for effect type 0x%04x\n", newtype);
513 return AL_INVALID_ENUM;
515 EffectState *State{factory->create()};
516 if(!State) return AL_OUT_OF_MEMORY;
518 FPUCtl mixer_mode{};
519 ALCdevice *Device{Context->Device};
520 std::unique_lock<std::mutex> backlock{Device->BackendLock};
521 State->mOutBuffer = Device->Dry.Buffer;
522 State->mOutChannels = Device->Dry.NumChannels;
523 if(State->deviceUpdate(Device) == AL_FALSE)
525 backlock.unlock();
526 mixer_mode.leave();
527 State->DecRef();
528 return AL_OUT_OF_MEMORY;
530 mixer_mode.leave();
532 if(!effect)
534 EffectSlot->Effect.Type = AL_EFFECT_NULL;
535 memset(&EffectSlot->Effect.Props, 0, sizeof(EffectSlot->Effect.Props));
537 else
539 EffectSlot->Effect.Type = effect->type;
540 EffectSlot->Effect.Props = effect->Props;
543 EffectSlot->Effect.State->DecRef();
544 EffectSlot->Effect.State = State;
546 else if(effect)
547 EffectSlot->Effect.Props = effect->Props;
549 /* Remove state references from old effect slot property updates. */
550 ALeffectslotProps *props{Context->FreeEffectslotProps.load()};
551 while(props)
553 if(props->State)
554 props->State->DecRef();
555 props->State = nullptr;
556 props = props->next.load(std::memory_order_relaxed);
559 return AL_NO_ERROR;
563 void EffectState::IncRef() noexcept
565 auto ref = IncrementRef(&mRef);
566 TRACEREF("%p increasing refcount to %u\n", this, ref);
569 void EffectState::DecRef() noexcept
571 auto ref = DecrementRef(&mRef);
572 TRACEREF("%p decreasing refcount to %u\n", this, ref);
573 if(ref == 0) delete this;
577 ALenum InitEffectSlot(ALeffectslot *slot)
579 EffectStateFactory *factory{getFactoryByType(slot->Effect.Type)};
580 if(!factory) return AL_INVALID_VALUE;
581 slot->Effect.State = factory->create();
582 if(!slot->Effect.State) return AL_OUT_OF_MEMORY;
584 slot->Effect.State->IncRef();
585 slot->Params.mEffectState = slot->Effect.State;
586 return AL_NO_ERROR;
589 ALeffectslot::~ALeffectslot()
591 struct ALeffectslotProps *props{Update.load()};
592 if(props)
594 if(props->State) props->State->DecRef();
595 TRACE("Freed unapplied AuxiliaryEffectSlot update %p\n", props);
596 al_free(props);
599 if(Effect.State)
600 Effect.State->DecRef();
601 if(Params.mEffectState)
602 Params.mEffectState->DecRef();
605 void UpdateEffectSlotProps(ALeffectslot *slot, ALCcontext *context)
607 /* Get an unused property container, or allocate a new one as needed. */
608 ALeffectslotProps *props{context->FreeEffectslotProps.load(std::memory_order_relaxed)};
609 if(!props)
610 props = static_cast<ALeffectslotProps*>(al_calloc(16, sizeof(*props)));
611 else
613 struct ALeffectslotProps *next;
614 do {
615 next = props->next.load(std::memory_order_relaxed);
616 } while(context->FreeEffectslotProps.compare_exchange_weak(props, next,
617 std::memory_order_seq_cst, std::memory_order_acquire) == 0);
620 /* Copy in current property values. */
621 props->Gain = slot->Gain;
622 props->AuxSendAuto = slot->AuxSendAuto;
624 props->Type = slot->Effect.Type;
625 props->Props = slot->Effect.Props;
626 /* Swap out any stale effect state object there may be in the container, to
627 * delete it.
629 EffectState *oldstate{props->State};
630 slot->Effect.State->IncRef();
631 props->State = slot->Effect.State;
633 /* Set the new container for updating internal parameters. */
634 props = slot->Update.exchange(props, std::memory_order_acq_rel);
635 if(props)
637 /* If there was an unused update container, put it back in the
638 * freelist.
640 if(props->State)
641 props->State->DecRef();
642 props->State = nullptr;
643 AtomicReplaceHead(context->FreeEffectslotProps, props);
646 if(oldstate)
647 oldstate->DecRef();
650 void UpdateAllEffectSlotProps(ALCcontext *context)
652 std::lock_guard<std::mutex> _{context->EffectSlotLock};
653 ALeffectslotArray *auxslots{context->ActiveAuxSlots.load(std::memory_order_acquire)};
654 for(ALsizei i{0};i < auxslots->count;i++)
656 ALeffectslot *slot = auxslots->slot[i];
657 if(!slot->PropsClean.test_and_set(std::memory_order_acq_rel))
658 UpdateEffectSlotProps(slot, context);