aboutsummaryrefslogtreecommitdiffstats
path: root/OpenAL32/alAuxEffectSlot.cpp
blob: 07c6e69edb11084aa6d22bd98bcb359df82eb180 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
/**
 * OpenAL cross platform audio library
 * Copyright (C) 1999-2007 by authors.
 * This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Library General Public
 *  License as published by the Free Software Foundation; either
 *  version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 *  License along with this library; if not, write to the
 *  Free Software Foundation, Inc.,
 *  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 * Or go to http://www.gnu.org/copyleft/lgpl.html
 */

#include "config.h"

#include <cstdlib>
#include <cmath>

#include <thread>
#include <algorithm>

#include "AL/al.h"
#include "AL/alc.h"

#include "alMain.h"
#include "alcontext.h"
#include "alAuxEffectSlot.h"
#include "alError.h"
#include "alListener.h"
#include "alSource.h"

#include "fpu_modes.h"
#include "almalloc.h"


namespace {

inline ALeffectslot *LookupEffectSlot(ALCcontext *context, ALuint id) noexcept
{
    ALuint lidx = (id-1) >> 6;
    ALsizei slidx = (id-1) & 0x3f;

    if(UNLIKELY(lidx >= context->EffectSlotList.size()))
        return nullptr;
    EffectSlotSubList &sublist{context->EffectSlotList[lidx]};
    if(UNLIKELY(sublist.FreeMask & (1_u64 << slidx)))
        return nullptr;
    return sublist.EffectSlots + slidx;
}

inline ALeffect *LookupEffect(ALCdevice *device, ALuint id) noexcept
{
    ALuint lidx = (id-1) >> 6;
    ALsizei slidx = (id-1) & 0x3f;

    if(UNLIKELY(lidx >= device->EffectList.size()))
        return nullptr;
    EffectSubList &sublist = device->EffectList[lidx];
    if(UNLIKELY(sublist.FreeMask & (1_u64 << slidx)))
        return nullptr;
    return sublist.Effects + slidx;
}


void AddActiveEffectSlots(const ALuint *slotids, ALsizei count, ALCcontext *context)
{
    if(count < 1) return;
    ALeffectslotArray *curarray{context->ActiveAuxSlots.load(std::memory_order_acquire)};
    size_t newcount{curarray->size() + count};

    /* Insert the new effect slots into the head of the array, followed by the
     * existing ones.
     */
    ALeffectslotArray *newarray = ALeffectslot::CreatePtrArray(newcount);
    auto slotiter = std::transform(slotids, slotids+count, newarray->begin(),
        [context](ALuint id) noexcept -> ALeffectslot*
        { return LookupEffectSlot(context, id); }
    );
    std::copy(curarray->begin(), curarray->end(), slotiter);

    /* Remove any duplicates (first instance of each will be kept). */
    auto last = newarray->end();
    for(auto start=newarray->begin()+1;;)
    {
        last = std::remove(start, last, *(start-1));
        if(start == last) break;
        ++start;
    }
    newcount = static_cast<size_t>(std::distance(newarray->begin(), last));

    /* Reallocate newarray if the new size ended up smaller from duplicate
     * removal.
     */
    if(UNLIKELY(newcount < newarray->size()))
    {
        curarray = newarray;
        newarray = ALeffectslot::CreatePtrArray(newcount);
        std::copy_n(curarray->begin(), newcount, newarray->begin());
        delete curarray;
        curarray = nullptr;
    }

    curarray = context->ActiveAuxSlots.exchange(newarray, std::memory_order_acq_rel);
    ALCdevice *device{context->Device};
    while((device->MixCount.load(std::memory_order_acquire)&1))
        std::this_thread::yield();
    delete curarray;
}

void RemoveActiveEffectSlots(const ALuint *slotids, ALsizei count, ALCcontext *context)
{
    if(count < 1) return;
    ALeffectslotArray *curarray{context->ActiveAuxSlots.load(std::memory_order_acquire)};

    /* Don't shrink the allocated array size since we don't know how many (if
     * any) of the effect slots to remove are in the array.
     */
    ALeffectslotArray *newarray = ALeffectslot::CreatePtrArray(curarray->size());

    /* Copy each element in curarray to newarray whose ID is not in slotids. */
    const ALuint *slotids_end{slotids + count};
    auto slotiter = std::copy_if(curarray->begin(), curarray->end(), newarray->begin(),
        [slotids, slotids_end](const ALeffectslot *slot) -> bool
        { return std::find(slotids, slotids_end, slot->id) == slotids_end; }
    );

    /* Reallocate with the new size. */
    auto newsize = static_cast<size_t>(std::distance(newarray->begin(), slotiter));
    if(LIKELY(newsize != newarray->size()))
    {
        curarray = newarray;
        newarray = ALeffectslot::CreatePtrArray(newsize);
        std::copy_n(curarray->begin(), newsize, newarray->begin());

        delete curarray;
        curarray = nullptr;
    }

    curarray = context->ActiveAuxSlots.exchange(newarray, std::memory_order_acq_rel);
    ALCdevice *device{context->Device};
    while((device->MixCount.load(std::memory_order_acquire)&1))
        std::this_thread::yield();
    delete curarray;
}

constexpr struct FactoryItem {
    ALenum Type;
    EffectStateFactory* (&GetFactory)(void);
} FactoryList[] = {
    { AL_EFFECT_NULL, NullStateFactory_getFactory },
    { AL_EFFECT_EAXREVERB, ReverbStateFactory_getFactory },
    { AL_EFFECT_REVERB, ReverbStateFactory_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_DEDICATED_DIALOGUE, DedicatedStateFactory_getFactory },
    { AL_EFFECT_DEDICATED_LOW_FREQUENCY_EFFECT, DedicatedStateFactory_getFactory }
};

inline 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;
}


ALeffectslot *AllocEffectSlot(ALCcontext *context)
{
    ALCdevice *device{context->Device};
    std::lock_guard<std::mutex> _{context->EffectSlotLock};
    if(context->NumEffectSlots >= device->AuxiliaryEffectSlotMax)
    {
        alSetError(context, AL_OUT_OF_MEMORY, "Exceeding %u effect slot limit",
            device->AuxiliaryEffectSlotMax);
        return nullptr;
    }
    auto sublist = std::find_if(context->EffectSlotList.begin(), context->EffectSlotList.end(),
        [](const EffectSlotSubList &entry) noexcept -> bool
        { return entry.FreeMask != 0; }
    );
    auto lidx = static_cast<ALsizei>(std::distance(context->EffectSlotList.begin(), sublist));
    ALeffectslot *slot;
    ALsizei slidx;
    if(LIKELY(sublist != context->EffectSlotList.end()))
    {
        slidx = CTZ64(sublist->FreeMask);
        slot = sublist->EffectSlots + slidx;
    }
    else
    {
        /* Don't allocate so many list entries that the 32-bit ID could
         * overflow...
         */
        if(UNLIKELY(context->EffectSlotList.size() >= 1<<25))
        {
            alSetError(context, AL_OUT_OF_MEMORY, "Too many effect slots allocated");
            return nullptr;
        }
        context->EffectSlotList.emplace_back();
        sublist = context->EffectSlotList.end() - 1;

        sublist->FreeMask = ~0_u64;
        sublist->EffectSlots = static_cast<ALeffectslot*>(al_calloc(16, sizeof(ALeffectslot)*64));
        if(UNLIKELY(!sublist->EffectSlots))
        {
            context->EffectSlotList.pop_back();
            alSetError(context, AL_OUT_OF_MEMORY, "Failed to allocate effect slot batch");
            return nullptr;
        }

        slidx = 0;
        slot = sublist->EffectSlots + slidx;
    }

    slot = new (slot) ALeffectslot{};
    ALenum err{InitEffectSlot(slot)};
    if(err != AL_NO_ERROR)
    {
        slot->~ALeffectslot();
        alSetError(context, err, "Effect slot object initialization failed");
        return nullptr;
    }
    aluInitEffectPanning(slot);

    /* Add 1 to avoid source ID 0. */
    slot->id = ((lidx<<6) | slidx) + 1;

    context->NumEffectSlots += 1;
    sublist->FreeMask &= ~(1_u64 << slidx);

    return slot;
}

void FreeEffectSlot(ALCcontext *context, ALeffectslot *slot)
{
    ALuint id = slot->id - 1;
    ALsizei lidx = id >> 6;
    ALsizei slidx = id & 0x3f;

    slot->~ALeffectslot();

    context->EffectSlotList[lidx].FreeMask |= 1_u64 << slidx;
    context->NumEffectSlots--;
}


#define DO_UPDATEPROPS() do {                                                 \
    if(!context->DeferUpdates.load(std::memory_order_acquire))                \
        UpdateEffectSlotProps(slot, context.get());                           \
    else                                                                      \
        slot->PropsClean.clear(std::memory_order_release);                    \
} while(0)

} // namespace

ALeffectslotArray *ALeffectslot::CreatePtrArray(size_t count) noexcept
{
    /* Allocate space for twice as many pointers, so the mixer has scratch
     * space to store a sorted list during mixing.
     */
    void *ptr{al_calloc(DEF_ALIGN, ALeffectslotArray::Sizeof(count*2))};
    return new (ptr) ALeffectslotArray{count};
}


AL_API ALvoid AL_APIENTRY alGenAuxiliaryEffectSlots(ALsizei n, ALuint *effectslots)
{
    ContextRef context{GetContextRef()};
    if(UNLIKELY(!context)) return;

    if(n < 0)
        SETERR_RETURN(context.get(), AL_INVALID_VALUE,, "Generating %d effect slots", n);
    if(n == 0) return;

    if(n == 1)
    {
        ALeffectslot *slot{AllocEffectSlot(context.get())};
        if(!slot) return;
        effectslots[0] = slot->id;
    }
    else
    {
        auto tempids = al::vector<ALuint>(n);
        auto alloc_end = std::find_if_not(tempids.begin(), tempids.end(),
            [&context](ALuint &id) -> bool
            {
                ALeffectslot *slot{AllocEffectSlot(context.get())};
                if(!slot) return false;
                id = slot->id;
                return true;
            }
        );
        if(alloc_end != tempids.end())
        {
            auto count = static_cast<ALsizei>(std::distance(tempids.begin(), alloc_end));
            alDeleteAuxiliaryEffectSlots(count, tempids.data());
            return;
        }

        std::copy(tempids.cbegin(), tempids.cend(), effectslots);
    }

    std::unique_lock<std::mutex> slotlock{context->EffectSlotLock};
    AddActiveEffectSlots(effectslots, n, context.get());
}

AL_API ALvoid AL_APIENTRY alDeleteAuxiliaryEffectSlots(ALsizei n, const ALuint *effectslots)
{
    ContextRef context{GetContextRef()};
    if(UNLIKELY(!context)) return;

    if(n < 0)
        SETERR_RETURN(context.get(), AL_INVALID_VALUE,, "Deleting %d effect slots", n);
    if(n == 0) return;

    std::lock_guard<std::mutex> _{context->EffectSlotLock};
    auto effectslots_end = effectslots + n;
    auto bad_slot = std::find_if(effectslots, effectslots_end,
        [&context](ALuint id) -> bool
        {
            ALeffectslot *slot{LookupEffectSlot(context.get(), id)};
            if(!slot)
            {
                alSetError(context.get(), AL_INVALID_NAME, "Invalid effect slot ID %u", id);
                return true;
            }
            if(ReadRef(&slot->ref) != 0)
            {
                alSetError(context.get(), AL_INVALID_NAME, "Deleting in-use effect slot %u", id);
                return true;
            }
            return false;
        }
    );
    if(bad_slot != effectslots_end)
        return;

    // All effectslots are valid, remove and delete them
    RemoveActiveEffectSlots(effectslots, n, context.get());
    std::for_each(effectslots, effectslots_end,
        [&context](ALuint sid) -> void
        {
            ALeffectslot *slot{LookupEffectSlot(context.get(), sid)};
            if(slot) FreeEffectSlot(context.get(), slot);
        }
    );
}

AL_API ALboolean AL_APIENTRY alIsAuxiliaryEffectSlot(ALuint effectslot)
{
    ContextRef context{GetContextRef()};
    if(LIKELY(context))
    {
        std::lock_guard<std::mutex> _{context->EffectSlotLock};
        if(LookupEffectSlot(context.get(), effectslot) != nullptr)
            return AL_TRUE;
    }
    return AL_FALSE;
}

AL_API ALvoid AL_APIENTRY alAuxiliaryEffectSloti(ALuint effectslot, ALenum param, ALint value)
{
    ContextRef context{GetContextRef()};
    if(UNLIKELY(!context)) return;

    std::lock_guard<std::mutex> _{context->PropLock};
    std::lock_guard<std::mutex> __{context->EffectSlotLock};
    ALeffectslot *slot = LookupEffectSlot(context.get(), effectslot);
    if(UNLIKELY(!slot))
        SETERR_RETURN(context.get(), AL_INVALID_NAME,, "Invalid effect slot ID %u", effectslot);

    ALeffectslot *target{};
    ALCdevice *device{};
    ALenum err{};
    switch(param)
    {
    case AL_EFFECTSLOT_EFFECT:
        device = context->Device;

        { std::lock_guard<std::mutex> ___{device->EffectLock};
            ALeffect *effect{value ? LookupEffect(device, value) : nullptr};
            if(!(value == 0 || effect != nullptr))
                SETERR_RETURN(context.get(), AL_INVALID_VALUE,, "Invalid effect ID %u", value);
            err = InitializeEffect(context.get(), slot, effect);
        }
        if(err != AL_NO_ERROR)
        {
            alSetError(context.get(), err, "Effect initialization failed");
            return;
        }
        break;

    case AL_EFFECTSLOT_AUXILIARY_SEND_AUTO:
        if(!(value == AL_TRUE || value == AL_FALSE))
            SETERR_RETURN(context.get(), AL_INVALID_VALUE,,
                          "Effect slot auxiliary send auto out of range");
        slot->AuxSendAuto = value;
        break;

    case AL_EFFECTSLOT_TARGET_SOFT:
        target = (value ? LookupEffectSlot(context.get(), value) : nullptr);
        if(value && !target)
            SETERR_RETURN(context.get(), AL_INVALID_VALUE,, "Invalid effect slot target ID");
        if(target)
        {
            ALeffectslot *checker{target};
            while(checker && checker != slot)
                checker = checker->Target;
            if(checker)
                SETERR_RETURN(context.get(), AL_INVALID_OPERATION,,
                    "Setting target of effect slot ID %u to %u creates circular chain", slot->id,
                    target->id);
        }

        if(ALeffectslot *oldtarget{slot->Target})
        {
            /* We must force an update if there was an existing effect slot
             * target, in case it's about to be deleted.
             */
            if(target) IncrementRef(&target->ref);
            DecrementRef(&oldtarget->ref);
            slot->Target = target;
            UpdateEffectSlotProps(slot, context.get());
            return;
        }

        if(target) IncrementRef(&target->ref);
        slot->Target = target;
        break;

    default:
        SETERR_RETURN(context.get(), AL_INVALID_ENUM,,
                      "Invalid effect slot integer property 0x%04x", param);
    }
    DO_UPDATEPROPS();
}

AL_API ALvoid AL_APIENTRY alAuxiliaryEffectSlotiv(ALuint effectslot, ALenum param, const ALint *values)
{
    switch(param)
    {
    case AL_EFFECTSLOT_EFFECT:
    case AL_EFFECTSLOT_AUXILIARY_SEND_AUTO:
    case AL_EFFECTSLOT_TARGET_SOFT:
        alAuxiliaryEffectSloti(effectslot, param, values[0]);
        return;
    }

    ContextRef context{GetContextRef()};
    if(UNLIKELY(!context)) return;

    std::lock_guard<std::mutex> _{context->EffectSlotLock};
    ALeffectslot *slot = LookupEffectSlot(context.get(), effectslot);
    if(UNLIKELY(!slot))
        SETERR_RETURN(context.get(), AL_INVALID_NAME,, "Invalid effect slot ID %u", effectslot);

    switch(param)
    {
    default:
        SETERR_RETURN(context.get(), AL_INVALID_ENUM,,
                      "Invalid effect slot integer-vector property 0x%04x", param);
    }
}

AL_API ALvoid AL_APIENTRY alAuxiliaryEffectSlotf(ALuint effectslot, ALenum param, ALfloat value)
{
    ContextRef context{GetContextRef()};
    if(UNLIKELY(!context)) return;

    std::lock_guard<std::mutex> _{context->PropLock};
    std::lock_guard<std::mutex> __{context->EffectSlotLock};
    ALeffectslot *slot = LookupEffectSlot(context.get(), effectslot);
    if(UNLIKELY(!slot))
        SETERR_RETURN(context.get(), AL_INVALID_NAME,, "Invalid effect slot ID %u", effectslot);

    switch(param)
    {
    case AL_EFFECTSLOT_GAIN:
        if(!(value >= 0.0f && value <= 1.0f))
            SETERR_RETURN(context.get(), AL_INVALID_VALUE,, "Effect slot gain out of range");
        slot->Gain = value;
        break;

    default:
        SETERR_RETURN(context.get(), AL_INVALID_ENUM,, "Invalid effect slot float property 0x%04x",
                      param);
    }
    DO_UPDATEPROPS();
}

AL_API ALvoid AL_APIENTRY alAuxiliaryEffectSlotfv(ALuint effectslot, ALenum param, const ALfloat *values)
{
    switch(param)
    {
    case AL_EFFECTSLOT_GAIN:
        alAuxiliaryEffectSlotf(effectslot, param, values[0]);
        return;
    }

    ContextRef context{GetContextRef()};
    if(UNLIKELY(!context)) return;

    std::lock_guard<std::mutex> _{context->EffectSlotLock};
    ALeffectslot *slot = LookupEffectSlot(context.get(), effectslot);
    if(UNLIKELY(!slot))
        SETERR_RETURN(context.get(), AL_INVALID_NAME,, "Invalid effect slot ID %u", effectslot);

    switch(param)
    {
    default:
        SETERR_RETURN(context.get(), AL_INVALID_ENUM,,
                      "Invalid effect slot float-vector property 0x%04x", param);
    }
}

AL_API ALvoid AL_APIENTRY alGetAuxiliaryEffectSloti(ALuint effectslot, ALenum param, ALint *value)
{
    ContextRef context{GetContextRef()};
    if(UNLIKELY(!context)) return;

    std::lock_guard<std::mutex> _{context->EffectSlotLock};
    ALeffectslot *slot = LookupEffectSlot(context.get(), effectslot);
    if(UNLIKELY(!slot))
        SETERR_RETURN(context.get(), AL_INVALID_NAME,, "Invalid effect slot ID %u", effectslot);

    switch(param)
    {
    case AL_EFFECTSLOT_AUXILIARY_SEND_AUTO:
        *value = slot->AuxSendAuto;
        break;

    case AL_EFFECTSLOT_TARGET_SOFT:
        *value = slot->Target ? slot->Target->id : 0;
        break;

    default:
        SETERR_RETURN(context.get(), AL_INVALID_ENUM,,
                      "Invalid effect slot integer property 0x%04x", param);
    }
}

AL_API ALvoid AL_APIENTRY alGetAuxiliaryEffectSlotiv(ALuint effectslot, ALenum param, ALint *values)
{
    switch(param)
    {
    case AL_EFFECTSLOT_EFFECT:
    case AL_EFFECTSLOT_AUXILIARY_SEND_AUTO:
    case AL_EFFECTSLOT_TARGET_SOFT:
        alGetAuxiliaryEffectSloti(effectslot, param, values);
        return;
    }

    ContextRef context{GetContextRef()};
    if(UNLIKELY(!context)) return;

    std::lock_guard<std::mutex> _{context->EffectSlotLock};
    ALeffectslot *slot = LookupEffectSlot(context.get(), effectslot);
    if(UNLIKELY(!slot))
        SETERR_RETURN(context.get(), AL_INVALID_NAME,, "Invalid effect slot ID %u", effectslot);

    switch(param)
    {
    default:
        SETERR_RETURN(context.get(), AL_INVALID_ENUM,,
                      "Invalid effect slot integer-vector property 0x%04x", param);
    }
}

AL_API ALvoid AL_APIENTRY alGetAuxiliaryEffectSlotf(ALuint effectslot, ALenum param, ALfloat *value)
{
    ContextRef context{GetContextRef()};
    if(UNLIKELY(!context)) return;

    std::lock_guard<std::mutex> _{context->EffectSlotLock};
    ALeffectslot *slot = LookupEffectSlot(context.get(), effectslot);
    if(UNLIKELY(!slot))
        SETERR_RETURN(context.get(), AL_INVALID_NAME,, "Invalid effect slot ID %u", effectslot);

    switch(param)
    {
    case AL_EFFECTSLOT_GAIN:
        *value = slot->Gain;
        break;

    default:
        SETERR_RETURN(context.get(), AL_INVALID_ENUM,,
                      "Invalid effect slot float property 0x%04x", param);
    }
}

AL_API ALvoid AL_APIENTRY alGetAuxiliaryEffectSlotfv(ALuint effectslot, ALenum param, ALfloat *values)
{
    switch(param)
    {
    case AL_EFFECTSLOT_GAIN:
        alGetAuxiliaryEffectSlotf(effectslot, param, values);
        return;
    }

    ContextRef context{GetContextRef()};
    if(UNLIKELY(!context)) return;

    std::lock_guard<std::mutex> _{context->EffectSlotLock};
    ALeffectslot *slot = LookupEffectSlot(context.get(), effectslot);
    if(UNLIKELY(!slot))
        SETERR_RETURN(context.get(), AL_INVALID_NAME,, "Invalid effect slot ID %u", effectslot);

    switch(param)
    {
    default:
        SETERR_RETURN(context.get(), AL_INVALID_ENUM,,
                      "Invalid effect slot float-vector property 0x%04x", param);
    }
}


ALenum InitializeEffect(ALCcontext *Context, ALeffectslot *EffectSlot, ALeffect *effect)
{
    ALenum newtype{effect ? effect->type : AL_EFFECT_NULL};
    if(newtype != EffectSlot->Effect.Type)
    {
        EffectStateFactory *factory{getFactoryByType(newtype)};
        if(!factory)
        {
            ERR("Failed to find factory for effect type 0x%04x\n", newtype);
            return AL_INVALID_ENUM;
        }
        EffectState *State{factory->create()};
        if(!State) return AL_OUT_OF_MEMORY;

        FPUCtl mixer_mode{};
        ALCdevice *Device{Context->Device};
        std::unique_lock<std::mutex> statelock{Device->StateLock};
        State->mOutBuffer = Device->Dry.Buffer;
        State->mOutChannels = Device->Dry.NumChannels;
        if(State->deviceUpdate(Device) == AL_FALSE)
        {
            statelock.unlock();
            mixer_mode.leave();
            State->DecRef();
            return AL_OUT_OF_MEMORY;
        }
        mixer_mode.leave();

        if(!effect)
        {
            EffectSlot->Effect.Type = AL_EFFECT_NULL;
            EffectSlot->Effect.Props = ALeffectProps{};
        }
        else
        {
            EffectSlot->Effect.Type = effect->type;
            EffectSlot->Effect.Props = effect->Props;
        }

        EffectSlot->Effect.State->DecRef();
        EffectSlot->Effect.State = State;
    }
    else if(effect)
        EffectSlot->Effect.Props = effect->Props;

    /* Remove state references from old effect slot property updates. */
    ALeffectslotProps *props{Context->FreeEffectslotProps.load()};
    while(props)
    {
        if(props->State)
            props->State->DecRef();
        props->State = nullptr;
        props = props->next.load(std::memory_order_relaxed);
    }

    return AL_NO_ERROR;
}


void EffectState::IncRef() noexcept
{
    auto ref = IncrementRef(&mRef);
    TRACEREF("%p increasing refcount to %u\n", this, ref);
}

void EffectState::DecRef() noexcept
{
    auto ref = DecrementRef(&mRef);
    TRACEREF("%p decreasing refcount to %u\n", this, ref);
    if(ref == 0) delete this;
}


ALenum InitEffectSlot(ALeffectslot *slot)
{
    EffectStateFactory *factory{getFactoryByType(slot->Effect.Type)};
    if(!factory) return AL_INVALID_VALUE;
    slot->Effect.State = factory->create();
    if(!slot->Effect.State) return AL_OUT_OF_MEMORY;

    slot->Effect.State->IncRef();
    slot->Params.mEffectState = slot->Effect.State;
    return AL_NO_ERROR;
}

ALeffectslot::~ALeffectslot()
{
    if(Target)
        DecrementRef(&Target->ref);
    Target = nullptr;

    ALeffectslotProps *props{Update.load()};
    if(props)
    {
        if(props->State) props->State->DecRef();
        TRACE("Freed unapplied AuxiliaryEffectSlot update %p\n", props);
        al_free(props);
    }

    if(Effect.State)
        Effect.State->DecRef();
    if(Params.mEffectState)
        Params.mEffectState->DecRef();
}

void UpdateEffectSlotProps(ALeffectslot *slot, ALCcontext *context)
{
    /* Get an unused property container, or allocate a new one as needed. */
    ALeffectslotProps *props{context->FreeEffectslotProps.load(std::memory_order_relaxed)};
    if(!props)
        props = static_cast<ALeffectslotProps*>(al_calloc(16, sizeof(*props)));
    else
    {
        ALeffectslotProps *next;
        do {
            next = props->next.load(std::memory_order_relaxed);
        } while(context->FreeEffectslotProps.compare_exchange_weak(props, next,
                std::memory_order_seq_cst, std::memory_order_acquire) == 0);
    }

    /* Copy in current property values. */
    props->Gain = slot->Gain;
    props->AuxSendAuto = slot->AuxSendAuto;
    props->Target = slot->Target;

    props->Type = slot->Effect.Type;
    props->Props = slot->Effect.Props;
    /* Swap out any stale effect state object there may be in the container, to
     * delete it.
     */
    EffectState *oldstate{props->State};
    slot->Effect.State->IncRef();
    props->State = slot->Effect.State;

    /* Set the new container for updating internal parameters. */
    props = slot->Update.exchange(props, std::memory_order_acq_rel);
    if(props)
    {
        /* If there was an unused update container, put it back in the
         * freelist.
         */
        if(props->State)
            props->State->DecRef();
        props->State = nullptr;
        AtomicReplaceHead(context->FreeEffectslotProps, props);
    }

    if(oldstate)
        oldstate->DecRef();
}

void UpdateAllEffectSlotProps(ALCcontext *context)
{
    std::lock_guard<std::mutex> _{context->EffectSlotLock};
    ALeffectslotArray *auxslots{context->ActiveAuxSlots.load(std::memory_order_acquire)};
    for(ALeffectslot *slot : *auxslots)
    {
        if(!slot->PropsClean.test_and_set(std::memory_order_acq_rel))
            UpdateEffectSlotProps(slot, context);
    }
}

EffectSlotSubList::~EffectSlotSubList()
{
    uint64_t usemask{~FreeMask};
    while(usemask)
    {
        ALsizei idx{CTZ64(usemask)};
        EffectSlots[idx].~ALeffectslot();
        usemask &= ~(1_u64 << idx);
    }
    FreeMask = ~usemask;
    al_free(EffectSlots);
    EffectSlots = nullptr;
}