Avoid a separate function to clean up effect slots
[openal-soft.git] / OpenAL32 / alAuxEffectSlot.cpp
blobe7991ff061e677ef0c293a2e031bb5bbf4c1b262
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 <algorithm>
28 #include "AL/al.h"
29 #include "AL/alc.h"
31 #include "alMain.h"
32 #include "alcontext.h"
33 #include "alAuxEffectSlot.h"
34 #include "alError.h"
35 #include "alListener.h"
36 #include "alSource.h"
38 #include "fpu_modes.h"
39 #include "almalloc.h"
42 namespace {
44 inline ALeffectslot *LookupEffectSlot(ALCcontext *context, ALuint id) noexcept
46 --id;
47 if(UNLIKELY(id >= context->EffectSlotList.size()))
48 return nullptr;
49 return context->EffectSlotList[id].get();
52 inline ALeffect *LookupEffect(ALCdevice *device, ALuint id) noexcept
54 ALuint lidx = (id-1) >> 6;
55 ALsizei slidx = (id-1) & 0x3f;
57 if(UNLIKELY(lidx >= device->EffectList.size()))
58 return nullptr;
59 EffectSubList &sublist = device->EffectList[lidx];
60 if(UNLIKELY(sublist.FreeMask & (U64(1)<<slidx)))
61 return nullptr;
62 return sublist.Effects + slidx;
66 void AddActiveEffectSlots(const ALuint *slotids, ALsizei count, ALCcontext *context)
68 if(count < 1) return;
69 ALeffectslotArray *curarray{context->ActiveAuxSlots.load(std::memory_order_acquire)};
70 ALsizei newcount{curarray->count + count};
72 /* Insert the new effect slots into the head of the array, followed by the
73 * existing ones.
75 auto newarray = static_cast<ALeffectslotArray*>(al_calloc(DEF_ALIGN,
76 FAM_SIZE(ALeffectslotArray, slot, newcount)));
77 newarray->count = newcount;
78 auto slotiter = std::transform(slotids, slotids+count, newarray->slot,
79 [context](ALuint id) noexcept -> ALeffectslot*
80 { return LookupEffectSlot(context, id); }
82 std::copy_n(curarray->slot, curarray->count, slotiter);
84 /* Remove any duplicates (first instance of each will be kept). */
85 ALeffectslot **last = newarray->slot + newarray->count;
86 for(ALeffectslot **start=newarray->slot+1;;)
88 last = std::remove(start, last, *(start-1));
89 if(start == last) break;
90 ++start;
92 newcount = std::distance(newarray->slot, last);
94 /* Reallocate newarray if the new size ended up smaller from duplicate
95 * removal.
97 if(UNLIKELY(newcount < newarray->count))
99 curarray = newarray;
100 newarray = static_cast<ALeffectslotArray*>(al_calloc(DEF_ALIGN,
101 FAM_SIZE(ALeffectslotArray, slot, newcount)));
102 newarray->count = newcount;
103 std::copy_n(curarray->slot, newcount, newarray->slot);
104 al_free(curarray);
105 curarray = nullptr;
108 curarray = context->ActiveAuxSlots.exchange(newarray, std::memory_order_acq_rel);
109 ALCdevice *device{context->Device};
110 while((device->MixCount.load(std::memory_order_acquire)&1))
111 althrd_yield();
112 al_free(curarray);
115 void RemoveActiveEffectSlots(const ALuint *slotids, ALsizei count, ALCcontext *context)
117 if(count < 1) return;
118 ALeffectslotArray *curarray{context->ActiveAuxSlots.load(std::memory_order_acquire)};
120 /* Don't shrink the allocated array size since we don't know how many (if
121 * any) of the effect slots to remove are in the array.
123 auto newarray = static_cast<ALeffectslotArray*>(al_calloc(DEF_ALIGN,
124 FAM_SIZE(ALeffectslotArray, slot, curarray->count)));
126 /* Copy each element in curarray to newarray whose ID is not in slotids. */
127 const ALuint *slotids_end{slotids + count};
128 auto slotiter = std::copy_if(curarray->slot, curarray->slot+curarray->count, newarray->slot,
129 [slotids, slotids_end](const ALeffectslot *slot) -> bool
130 { return std::find(slotids, slotids_end, slot->id) == slotids_end; }
132 newarray->count = std::distance(newarray->slot, slotiter);
134 /* TODO: Could reallocate newarray now that we know it's needed size. */
136 curarray = context->ActiveAuxSlots.exchange(newarray, std::memory_order_acq_rel);
137 ALCdevice *device{context->Device};
138 while((device->MixCount.load(std::memory_order_acquire)&1))
139 althrd_yield();
140 al_free(curarray);
143 constexpr struct FactoryItem {
144 ALenum Type;
145 EffectStateFactory* (&GetFactory)(void);
146 } FactoryList[] = {
147 { AL_EFFECT_NULL, NullStateFactory_getFactory },
148 { AL_EFFECT_EAXREVERB, ReverbStateFactory_getFactory },
149 { AL_EFFECT_REVERB, ReverbStateFactory_getFactory },
150 { AL_EFFECT_AUTOWAH, AutowahStateFactory_getFactory },
151 { AL_EFFECT_CHORUS, ChorusStateFactory_getFactory },
152 { AL_EFFECT_COMPRESSOR, CompressorStateFactory_getFactory },
153 { AL_EFFECT_DISTORTION, DistortionStateFactory_getFactory },
154 { AL_EFFECT_ECHO, EchoStateFactory_getFactory },
155 { AL_EFFECT_EQUALIZER, EqualizerStateFactory_getFactory },
156 { AL_EFFECT_FLANGER, FlangerStateFactory_getFactory },
157 { AL_EFFECT_FREQUENCY_SHIFTER, FshifterStateFactory_getFactory },
158 { AL_EFFECT_RING_MODULATOR, ModulatorStateFactory_getFactory },
159 { AL_EFFECT_PITCH_SHIFTER, PshifterStateFactory_getFactory},
160 { AL_EFFECT_DEDICATED_DIALOGUE, DedicatedStateFactory_getFactory },
161 { AL_EFFECT_DEDICATED_LOW_FREQUENCY_EFFECT, DedicatedStateFactory_getFactory }
164 inline EffectStateFactory *getFactoryByType(ALenum type)
166 auto iter = std::find_if(std::begin(FactoryList), std::end(FactoryList),
167 [type](const FactoryItem &item) noexcept -> bool
168 { return item.Type == type; }
170 return (iter != std::end(FactoryList)) ? iter->GetFactory() : nullptr;
174 #define DO_UPDATEPROPS() do { \
175 if(!context->DeferUpdates.load(std::memory_order_acquire)) \
176 UpdateEffectSlotProps(slot, context.get()); \
177 else \
178 slot->PropsClean.clear(std::memory_order_release); \
179 } while(0)
181 } // namespace
183 AL_API ALvoid AL_APIENTRY alGenAuxiliaryEffectSlots(ALsizei n, ALuint *effectslots)
185 ContextRef context{GetContextRef()};
186 if(UNLIKELY(!context)) return;
188 if(n < 0)
189 SETERR_RETURN(context.get(), AL_INVALID_VALUE,, "Generating %d effect slots", n);
190 if(n == 0) return;
192 std::unique_lock<almtx_t> slotlock{context->EffectSlotLock};
193 ALCdevice *device{context->Device};
194 for(ALsizei cur{0};cur < n;cur++)
196 auto iter = std::find_if(context->EffectSlotList.begin(), context->EffectSlotList.end(),
197 [](const ALeffectslotPtr &entry) noexcept -> bool
198 { return !entry; }
200 if(iter == context->EffectSlotList.end())
202 if(UNLIKELY(device->AuxiliaryEffectSlotMax == context->EffectSlotList.size()))
204 slotlock.unlock();
205 alDeleteAuxiliaryEffectSlots(cur, effectslots);
206 alSetError(context.get(), AL_OUT_OF_MEMORY,
207 "Exceeding %u auxiliary effect slot limit", device->AuxiliaryEffectSlotMax);
208 return;
210 context->EffectSlotList.emplace_back(nullptr);
211 iter = context->EffectSlotList.end() - 1;
214 *iter = std::unique_ptr<ALeffectslot>(new ALeffectslot{});
215 ALenum err{InitEffectSlot(iter->get())};
216 if(err != AL_NO_ERROR)
218 *iter = nullptr;
219 slotlock.unlock();
221 alDeleteAuxiliaryEffectSlots(cur, effectslots);
222 alSetError(context.get(), err, "Effect slot object allocation failed");
223 return;
225 aluInitEffectPanning(iter->get());
227 ALuint id = std::distance(context->EffectSlotList.begin(), iter) + 1;
228 (*iter)->id = id;
229 effectslots[cur] = id;
231 AddActiveEffectSlots(effectslots, n, context.get());
234 AL_API ALvoid AL_APIENTRY alDeleteAuxiliaryEffectSlots(ALsizei n, const ALuint *effectslots)
236 ContextRef context{GetContextRef()};
237 if(UNLIKELY(!context)) return;
239 if(n < 0)
240 SETERR_RETURN(context.get(), AL_INVALID_VALUE,, "Deleting %d effect slots", n);
241 if(n == 0) return;
243 std::lock_guard<almtx_t> _{context->EffectSlotLock};
244 auto effectslots_end = effectslots + n;
245 auto bad_slot = std::find_if(effectslots, effectslots_end,
246 [&context](ALuint id) -> bool
248 ALeffectslot *slot{LookupEffectSlot(context.get(), id)};
249 if(!slot)
251 alSetError(context.get(), AL_INVALID_NAME, "Invalid effect slot ID %u", id);
252 return true;
254 if(ReadRef(&slot->ref) != 0)
256 alSetError(context.get(), AL_INVALID_NAME, "Deleting in-use effect slot %u", id);
257 return true;
259 return false;
262 if(bad_slot != effectslots_end)
263 return;
265 // All effectslots are valid, remove and delete them
266 RemoveActiveEffectSlots(effectslots, n, context.get());
267 std::for_each(effectslots, effectslots_end,
268 [&context](ALuint id) noexcept -> void
269 { context->EffectSlotList[id-1] = nullptr; }
273 AL_API ALboolean AL_APIENTRY alIsAuxiliaryEffectSlot(ALuint effectslot)
275 ContextRef context{GetContextRef()};
276 if(LIKELY(context))
278 std::lock_guard<almtx_t> _{context->EffectSlotLock};
279 if(LookupEffectSlot(context.get(), effectslot) != nullptr)
280 return AL_TRUE;
282 return AL_FALSE;
285 AL_API ALvoid AL_APIENTRY alAuxiliaryEffectSloti(ALuint effectslot, ALenum param, ALint value)
287 ContextRef context{GetContextRef()};
288 if(UNLIKELY(!context)) return;
290 std::lock_guard<almtx_t> _{context->PropLock};
291 std::lock_guard<almtx_t> __{context->EffectSlotLock};
292 ALeffectslot *slot = LookupEffectSlot(context.get(), effectslot);
293 if(UNLIKELY(!slot))
294 SETERR_RETURN(context.get(), AL_INVALID_NAME,, "Invalid effect slot ID %u", effectslot);
296 ALCdevice *device{};
297 ALenum err{};
298 switch(param)
300 case AL_EFFECTSLOT_EFFECT:
301 device = context->Device;
303 { std::lock_guard<almtx_t> ___{device->EffectLock};
304 ALeffect *effect{value ? LookupEffect(device, value) : nullptr};
305 if(!(value == 0 || effect != nullptr))
306 SETERR_RETURN(context.get(), AL_INVALID_VALUE,, "Invalid effect ID %u", value);
307 err = InitializeEffect(context.get(), slot, effect);
309 if(err != AL_NO_ERROR)
311 alSetError(context.get(), err, "Effect initialization failed");
312 return;
314 break;
316 case AL_EFFECTSLOT_AUXILIARY_SEND_AUTO:
317 if(!(value == AL_TRUE || value == AL_FALSE))
318 SETERR_RETURN(context.get(), AL_INVALID_VALUE,,
319 "Effect slot auxiliary send auto out of range");
320 slot->AuxSendAuto = value;
321 break;
323 default:
324 SETERR_RETURN(context.get(), AL_INVALID_ENUM,,
325 "Invalid effect slot integer property 0x%04x", param);
327 DO_UPDATEPROPS();
330 AL_API ALvoid AL_APIENTRY alAuxiliaryEffectSlotiv(ALuint effectslot, ALenum param, const ALint *values)
332 switch(param)
334 case AL_EFFECTSLOT_EFFECT:
335 case AL_EFFECTSLOT_AUXILIARY_SEND_AUTO:
336 alAuxiliaryEffectSloti(effectslot, param, values[0]);
337 return;
340 ContextRef context{GetContextRef()};
341 if(UNLIKELY(!context)) return;
343 std::lock_guard<almtx_t> __{context->EffectSlotLock};
344 ALeffectslot *slot = LookupEffectSlot(context.get(), effectslot);
345 if(UNLIKELY(!slot))
346 SETERR_RETURN(context.get(), AL_INVALID_NAME,, "Invalid effect slot ID %u", effectslot);
348 switch(param)
350 default:
351 SETERR_RETURN(context.get(), AL_INVALID_ENUM,,
352 "Invalid effect slot integer-vector property 0x%04x", param);
356 AL_API ALvoid AL_APIENTRY alAuxiliaryEffectSlotf(ALuint effectslot, ALenum param, ALfloat value)
358 ContextRef context{GetContextRef()};
359 if(UNLIKELY(!context)) return;
361 std::lock_guard<almtx_t> _{context->PropLock};
362 std::lock_guard<almtx_t> __{context->EffectSlotLock};
363 ALeffectslot *slot = LookupEffectSlot(context.get(), effectslot);
364 if(UNLIKELY(!slot))
365 SETERR_RETURN(context.get(), AL_INVALID_NAME,, "Invalid effect slot ID %u", effectslot);
367 switch(param)
369 case AL_EFFECTSLOT_GAIN:
370 if(!(value >= 0.0f && value <= 1.0f))
371 SETERR_RETURN(context.get(), AL_INVALID_VALUE,, "Effect slot gain out of range");
372 slot->Gain = value;
373 break;
375 default:
376 SETERR_RETURN(context.get(), AL_INVALID_ENUM,, "Invalid effect slot float property 0x%04x",
377 param);
379 DO_UPDATEPROPS();
382 AL_API ALvoid AL_APIENTRY alAuxiliaryEffectSlotfv(ALuint effectslot, ALenum param, const ALfloat *values)
384 switch(param)
386 case AL_EFFECTSLOT_GAIN:
387 alAuxiliaryEffectSlotf(effectslot, param, values[0]);
388 return;
391 ContextRef context{GetContextRef()};
392 if(UNLIKELY(!context)) return;
394 std::lock_guard<almtx_t> _{context->EffectSlotLock};
395 ALeffectslot *slot = LookupEffectSlot(context.get(), effectslot);
396 if(UNLIKELY(!slot))
397 SETERR_RETURN(context.get(), AL_INVALID_NAME,, "Invalid effect slot ID %u", effectslot);
399 switch(param)
401 default:
402 SETERR_RETURN(context.get(), AL_INVALID_ENUM,,
403 "Invalid effect slot float-vector property 0x%04x", param);
407 AL_API ALvoid AL_APIENTRY alGetAuxiliaryEffectSloti(ALuint effectslot, ALenum param, ALint *value)
409 ContextRef context{GetContextRef()};
410 if(UNLIKELY(!context)) return;
412 std::lock_guard<almtx_t> __{context->EffectSlotLock};
413 ALeffectslot *slot = LookupEffectSlot(context.get(), effectslot);
414 if(UNLIKELY(!slot))
415 SETERR_RETURN(context.get(), AL_INVALID_NAME,, "Invalid effect slot ID %u", effectslot);
417 switch(param)
419 case AL_EFFECTSLOT_AUXILIARY_SEND_AUTO:
420 *value = slot->AuxSendAuto;
421 break;
423 default:
424 SETERR_RETURN(context.get(), AL_INVALID_ENUM,,
425 "Invalid effect slot integer property 0x%04x", param);
429 AL_API ALvoid AL_APIENTRY alGetAuxiliaryEffectSlotiv(ALuint effectslot, ALenum param, ALint *values)
431 switch(param)
433 case AL_EFFECTSLOT_EFFECT:
434 case AL_EFFECTSLOT_AUXILIARY_SEND_AUTO:
435 alGetAuxiliaryEffectSloti(effectslot, param, values);
436 return;
439 ContextRef context{GetContextRef()};
440 if(UNLIKELY(!context)) return;
442 std::lock_guard<almtx_t> _{context->EffectSlotLock};
443 ALeffectslot *slot = LookupEffectSlot(context.get(), effectslot);
444 if(UNLIKELY(!slot))
445 SETERR_RETURN(context.get(), AL_INVALID_NAME,, "Invalid effect slot ID %u", effectslot);
447 switch(param)
449 default:
450 SETERR_RETURN(context.get(), AL_INVALID_ENUM,,
451 "Invalid effect slot integer-vector property 0x%04x", param);
455 AL_API ALvoid AL_APIENTRY alGetAuxiliaryEffectSlotf(ALuint effectslot, ALenum param, ALfloat *value)
457 ContextRef context{GetContextRef()};
458 if(UNLIKELY(!context)) return;
460 std::lock_guard<almtx_t> _{context->EffectSlotLock};
461 ALeffectslot *slot = LookupEffectSlot(context.get(), effectslot);
462 if(UNLIKELY(!slot))
463 SETERR_RETURN(context.get(), AL_INVALID_NAME,, "Invalid effect slot ID %u", effectslot);
465 switch(param)
467 case AL_EFFECTSLOT_GAIN:
468 *value = slot->Gain;
469 break;
471 default:
472 SETERR_RETURN(context.get(), AL_INVALID_ENUM,,
473 "Invalid effect slot float property 0x%04x", param);
477 AL_API ALvoid AL_APIENTRY alGetAuxiliaryEffectSlotfv(ALuint effectslot, ALenum param, ALfloat *values)
479 switch(param)
481 case AL_EFFECTSLOT_GAIN:
482 alGetAuxiliaryEffectSlotf(effectslot, param, values);
483 return;
486 ContextRef context{GetContextRef()};
487 if(UNLIKELY(!context)) return;
489 std::lock_guard<almtx_t> _{context->EffectSlotLock};
490 ALeffectslot *slot = LookupEffectSlot(context.get(), effectslot);
491 if(UNLIKELY(!slot))
492 SETERR_RETURN(context.get(), AL_INVALID_NAME,, "Invalid effect slot ID %u", effectslot);
494 switch(param)
496 default:
497 SETERR_RETURN(context.get(), AL_INVALID_ENUM,,
498 "Invalid effect slot float-vector property 0x%04x", param);
503 ALenum InitializeEffect(ALCcontext *Context, ALeffectslot *EffectSlot, ALeffect *effect)
505 ALenum newtype{effect ? effect->type : AL_EFFECT_NULL};
506 if(newtype != EffectSlot->Effect.Type)
508 EffectStateFactory *factory{getFactoryByType(newtype)};
509 if(!factory)
511 ERR("Failed to find factory for effect type 0x%04x\n", newtype);
512 return AL_INVALID_ENUM;
514 EffectState *State{factory->create()};
515 if(!State) return AL_OUT_OF_MEMORY;
517 FPUCtl mixer_mode{};
518 ALCdevice *Device{Context->Device};
519 std::unique_lock<almtx_t> backlock{Device->BackendLock};
520 State->mOutBuffer = Device->Dry.Buffer;
521 State->mOutChannels = Device->Dry.NumChannels;
522 if(State->deviceUpdate(Device) == AL_FALSE)
524 backlock.unlock();
525 mixer_mode.leave();
526 State->DecRef();
527 return AL_OUT_OF_MEMORY;
529 mixer_mode.leave();
531 if(!effect)
533 EffectSlot->Effect.Type = AL_EFFECT_NULL;
534 memset(&EffectSlot->Effect.Props, 0, sizeof(EffectSlot->Effect.Props));
536 else
538 EffectSlot->Effect.Type = effect->type;
539 EffectSlot->Effect.Props = effect->Props;
542 EffectSlot->Effect.State->DecRef();
543 EffectSlot->Effect.State = State;
545 else if(effect)
546 EffectSlot->Effect.Props = effect->Props;
548 /* Remove state references from old effect slot property updates. */
549 ALeffectslotProps *props{Context->FreeEffectslotProps.load()};
550 while(props)
552 if(props->State)
553 props->State->DecRef();
554 props->State = nullptr;
555 props = ATOMIC_LOAD(&props->next, almemory_order_relaxed);
558 return AL_NO_ERROR;
562 void EffectState::IncRef() noexcept
564 auto ref = IncrementRef(&mRef);
565 TRACEREF("%p increasing refcount to %u\n", this, ref);
568 void EffectState::DecRef() noexcept
570 auto ref = DecrementRef(&mRef);
571 TRACEREF("%p decreasing refcount to %u\n", this, ref);
572 if(ref == 0) delete this;
576 ALenum InitEffectSlot(ALeffectslot *slot)
578 EffectStateFactory *factory{getFactoryByType(slot->Effect.Type)};
579 slot->Effect.State = factory->create();
580 if(!slot->Effect.State) return AL_OUT_OF_MEMORY;
582 slot->Effect.State->IncRef();
583 slot->Params.mEffectState = slot->Effect.State;
584 return AL_NO_ERROR;
587 ALeffectslot::~ALeffectslot()
589 struct ALeffectslotProps *props{Update.load()};
590 if(props)
592 if(props->State) props->State->DecRef();
593 TRACE("Freed unapplied AuxiliaryEffectSlot update %p\n", props);
594 al_free(props);
597 if(Effect.State)
598 Effect.State->DecRef();
599 if(Params.mEffectState)
600 Params.mEffectState->DecRef();
603 void UpdateEffectSlotProps(ALeffectslot *slot, ALCcontext *context)
605 /* Get an unused property container, or allocate a new one as needed. */
606 ALeffectslotProps *props{context->FreeEffectslotProps.load(std::memory_order_relaxed)};
607 if(!props)
608 props = static_cast<ALeffectslotProps*>(al_calloc(16, sizeof(*props)));
609 else
611 struct ALeffectslotProps *next;
612 do {
613 next = props->next.load(std::memory_order_relaxed);
614 } while(context->FreeEffectslotProps.compare_exchange_weak(props, next,
615 std::memory_order_seq_cst, std::memory_order_acquire) == 0);
618 /* Copy in current property values. */
619 props->Gain = slot->Gain;
620 props->AuxSendAuto = slot->AuxSendAuto;
622 props->Type = slot->Effect.Type;
623 props->Props = slot->Effect.Props;
624 /* Swap out any stale effect state object there may be in the container, to
625 * delete it.
627 EffectState *oldstate{props->State};
628 slot->Effect.State->IncRef();
629 props->State = slot->Effect.State;
631 /* Set the new container for updating internal parameters. */
632 props = slot->Update.exchange(props, std::memory_order_acq_rel);
633 if(props)
635 /* If there was an unused update container, put it back in the
636 * freelist.
638 if(props->State)
639 props->State->DecRef();
640 props->State = nullptr;
641 AtomicReplaceHead(context->FreeEffectslotProps, props);
644 if(oldstate)
645 oldstate->DecRef();
648 void UpdateAllEffectSlotProps(ALCcontext *context)
650 std::lock_guard<almtx_t> _{context->EffectSlotLock};
651 ALeffectslotArray *auxslots{context->ActiveAuxSlots.load(std::memory_order_acquire)};
652 for(ALsizei i{0};i < auxslots->count;i++)
654 ALeffectslot *slot = auxslots->slot[i];
655 if(!slot->PropsClean.test_and_set(std::memory_order_acq_rel))
656 UpdateEffectSlotProps(slot, context);