Use a unique_ptr for the Compressor
[openal-soft.git] / Alc / alu.cpp
blob4d3ad9b2287efd4a56e6a9409d1f6f0d0a0ba0b0
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 <math.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <ctype.h>
27 #include <assert.h>
29 #include <algorithm>
31 #include "alMain.h"
32 #include "alcontext.h"
33 #include "alSource.h"
34 #include "alBuffer.h"
35 #include "alListener.h"
36 #include "alAuxEffectSlot.h"
37 #include "alu.h"
38 #include "bs2b.h"
39 #include "hrtf.h"
40 #include "mastering.h"
41 #include "uhjfilter.h"
42 #include "bformatdec.h"
43 #include "ringbuffer.h"
44 #include "filters/splitter.h"
46 #include "mixer/defs.h"
47 #include "fpu_modes.h"
48 #include "cpu_caps.h"
49 #include "bsinc_inc.h"
52 /* Cone scalar */
53 ALfloat ConeScale = 1.0f;
55 /* Localized Z scalar for mono sources */
56 ALfloat ZScale = 1.0f;
58 /* Force default speed of sound for distance-related reverb decay. */
59 ALboolean OverrideReverbSpeedOfSound = AL_FALSE;
62 namespace {
64 void ClearArray(ALfloat f[MAX_OUTPUT_CHANNELS])
66 size_t i;
67 for(i = 0;i < MAX_OUTPUT_CHANNELS;i++)
68 f[i] = 0.0f;
71 struct ChanMap {
72 enum Channel channel;
73 ALfloat angle;
74 ALfloat elevation;
77 HrtfDirectMixerFunc MixDirectHrtf = MixDirectHrtf_C;
80 inline HrtfDirectMixerFunc SelectHrtfMixer(void)
82 #ifdef HAVE_NEON
83 if((CPUCapFlags&CPU_CAP_NEON))
84 return MixDirectHrtf_Neon;
85 #endif
86 #ifdef HAVE_SSE
87 if((CPUCapFlags&CPU_CAP_SSE))
88 return MixDirectHrtf_SSE;
89 #endif
91 return MixDirectHrtf_C;
94 } // namespace
96 void aluInit(void)
98 MixDirectHrtf = SelectHrtfMixer();
102 void DeinitVoice(ALvoice *voice)
104 al_free(voice->Update.exchange(nullptr));
108 namespace {
110 void ProcessHrtf(ALCdevice *device, ALsizei SamplesToDo)
112 DirectHrtfState *state;
113 int lidx, ridx;
114 ALsizei c;
116 if(device->AmbiUp)
117 ambiup_process(device->AmbiUp,
118 device->Dry.Buffer, device->Dry.NumChannels, device->FOAOut.Buffer,
119 SamplesToDo
122 lidx = GetChannelIdxByName(&device->RealOut, FrontLeft);
123 ridx = GetChannelIdxByName(&device->RealOut, FrontRight);
124 assert(lidx != -1 && ridx != -1);
126 state = device->Hrtf;
127 for(c = 0;c < device->Dry.NumChannels;c++)
129 MixDirectHrtf(device->RealOut.Buffer[lidx], device->RealOut.Buffer[ridx],
130 device->Dry.Buffer[c], state->Offset, state->IrSize,
131 state->Chan[c].Coeffs, state->Chan[c].Values, SamplesToDo
134 state->Offset += SamplesToDo;
137 void ProcessAmbiDec(ALCdevice *device, ALsizei SamplesToDo)
139 if(device->Dry.Buffer != device->FOAOut.Buffer)
140 bformatdec_upSample(device->AmbiDecoder,
141 device->Dry.Buffer, device->FOAOut.Buffer, device->FOAOut.NumChannels,
142 SamplesToDo
144 bformatdec_process(device->AmbiDecoder,
145 device->RealOut.Buffer, device->RealOut.NumChannels, device->Dry.Buffer,
146 SamplesToDo
150 void ProcessAmbiUp(ALCdevice *device, ALsizei SamplesToDo)
152 ambiup_process(device->AmbiUp,
153 device->RealOut.Buffer, device->RealOut.NumChannels, device->FOAOut.Buffer,
154 SamplesToDo
158 void ProcessUhj(ALCdevice *device, ALsizei SamplesToDo)
160 int lidx = GetChannelIdxByName(&device->RealOut, FrontLeft);
161 int ridx = GetChannelIdxByName(&device->RealOut, FrontRight);
162 assert(lidx != -1 && ridx != -1);
164 /* Encode to stereo-compatible 2-channel UHJ output. */
165 EncodeUhj2(device->Uhj_Encoder.get(),
166 device->RealOut.Buffer[lidx], device->RealOut.Buffer[ridx],
167 device->Dry.Buffer, SamplesToDo
171 void ProcessBs2b(ALCdevice *device, ALsizei SamplesToDo)
173 int lidx = GetChannelIdxByName(&device->RealOut, FrontLeft);
174 int ridx = GetChannelIdxByName(&device->RealOut, FrontRight);
175 assert(lidx != -1 && ridx != -1);
177 /* Apply binaural/crossfeed filter */
178 bs2b_cross_feed(device->Bs2b, device->RealOut.Buffer[lidx],
179 device->RealOut.Buffer[ridx], SamplesToDo);
182 } // namespace
184 void aluSelectPostProcess(ALCdevice *device)
186 if(device->HrtfHandle)
187 device->PostProcess = ProcessHrtf;
188 else if(device->AmbiDecoder)
189 device->PostProcess = ProcessAmbiDec;
190 else if(device->AmbiUp)
191 device->PostProcess = ProcessAmbiUp;
192 else if(device->Uhj_Encoder)
193 device->PostProcess = ProcessUhj;
194 else if(device->Bs2b)
195 device->PostProcess = ProcessBs2b;
196 else
197 device->PostProcess = NULL;
201 /* Prepares the interpolator for a given rate (determined by increment).
203 * With a bit of work, and a trade of memory for CPU cost, this could be
204 * modified for use with an interpolated increment for buttery-smooth pitch
205 * changes.
207 void BsincPrepare(const ALuint increment, BsincState *state, const BSincTable *table)
209 ALfloat sf = 0.0f;
210 ALsizei si = BSINC_SCALE_COUNT-1;
212 if(increment > FRACTIONONE)
214 sf = (ALfloat)FRACTIONONE / increment;
215 sf = maxf(0.0f, (BSINC_SCALE_COUNT-1) * (sf-table->scaleBase) * table->scaleRange);
216 si = float2int(sf);
217 /* The interpolation factor is fit to this diagonally-symmetric curve
218 * to reduce the transition ripple caused by interpolating different
219 * scales of the sinc function.
221 sf = 1.0f - cosf(asinf(sf - si));
224 state->sf = sf;
225 state->m = table->m[si];
226 state->l = (state->m/2) - 1;
227 state->filter = table->Tab + table->filterOffset[si];
231 namespace {
233 /* This RNG method was created based on the math found in opusdec. It's quick,
234 * and starting with a seed value of 22222, is suitable for generating
235 * whitenoise.
237 inline ALuint dither_rng(ALuint *seed)
239 *seed = (*seed * 96314165) + 907633515;
240 return *seed;
244 inline void aluCrossproduct(const ALfloat *inVector1, const ALfloat *inVector2, ALfloat *outVector)
246 outVector[0] = inVector1[1]*inVector2[2] - inVector1[2]*inVector2[1];
247 outVector[1] = inVector1[2]*inVector2[0] - inVector1[0]*inVector2[2];
248 outVector[2] = inVector1[0]*inVector2[1] - inVector1[1]*inVector2[0];
251 inline ALfloat aluDotproduct(const aluVector *vec1, const aluVector *vec2)
253 return vec1->v[0]*vec2->v[0] + vec1->v[1]*vec2->v[1] + vec1->v[2]*vec2->v[2];
256 ALfloat aluNormalize(ALfloat *vec)
258 ALfloat length = sqrtf(vec[0]*vec[0] + vec[1]*vec[1] + vec[2]*vec[2]);
259 if(length > FLT_EPSILON)
261 ALfloat inv_length = 1.0f/length;
262 vec[0] *= inv_length;
263 vec[1] *= inv_length;
264 vec[2] *= inv_length;
265 return length;
267 vec[0] = vec[1] = vec[2] = 0.0f;
268 return 0.0f;
271 void aluMatrixfFloat3(ALfloat *vec, ALfloat w, const aluMatrixf *mtx)
273 ALfloat v[4] = { vec[0], vec[1], vec[2], w };
275 vec[0] = v[0]*mtx->m[0][0] + v[1]*mtx->m[1][0] + v[2]*mtx->m[2][0] + v[3]*mtx->m[3][0];
276 vec[1] = v[0]*mtx->m[0][1] + v[1]*mtx->m[1][1] + v[2]*mtx->m[2][1] + v[3]*mtx->m[3][1];
277 vec[2] = v[0]*mtx->m[0][2] + v[1]*mtx->m[1][2] + v[2]*mtx->m[2][2] + v[3]*mtx->m[3][2];
280 aluVector aluMatrixfVector(const aluMatrixf *mtx, const aluVector *vec)
282 aluVector v;
283 v.v[0] = vec->v[0]*mtx->m[0][0] + vec->v[1]*mtx->m[1][0] + vec->v[2]*mtx->m[2][0] + vec->v[3]*mtx->m[3][0];
284 v.v[1] = vec->v[0]*mtx->m[0][1] + vec->v[1]*mtx->m[1][1] + vec->v[2]*mtx->m[2][1] + vec->v[3]*mtx->m[3][1];
285 v.v[2] = vec->v[0]*mtx->m[0][2] + vec->v[1]*mtx->m[1][2] + vec->v[2]*mtx->m[2][2] + vec->v[3]*mtx->m[3][2];
286 v.v[3] = vec->v[0]*mtx->m[0][3] + vec->v[1]*mtx->m[1][3] + vec->v[2]*mtx->m[2][3] + vec->v[3]*mtx->m[3][3];
287 return v;
291 void SendSourceStoppedEvent(ALCcontext *context, ALuint id)
293 AsyncEvent evt = ASYNC_EVENT(EventType_SourceStateChange);
294 ALbitfieldSOFT enabledevt;
295 size_t strpos;
296 ALuint scale;
298 enabledevt = ATOMIC_LOAD(&context->EnabledEvts, almemory_order_acquire);
299 if(!(enabledevt&EventType_SourceStateChange)) return;
301 evt.u.user.type = AL_EVENT_TYPE_SOURCE_STATE_CHANGED_SOFT;
302 evt.u.user.id = id;
303 evt.u.user.param = AL_STOPPED;
305 /* Normally snprintf would be used, but this is called from the mixer and
306 * that function's not real-time safe, so we have to construct it manually.
308 strcpy(evt.u.user.msg, "Source ID "); strpos = 10;
309 scale = 1000000000;
310 while(scale > 0 && scale > id)
311 scale /= 10;
312 while(scale > 0)
314 evt.u.user.msg[strpos++] = '0' + ((id/scale)%10);
315 scale /= 10;
317 strcpy(evt.u.user.msg+strpos, " state changed to AL_STOPPED");
319 if(ll_ringbuffer_write(context->AsyncEvents, &evt, 1) == 1)
320 alsem_post(&context->EventSem);
324 bool CalcContextParams(ALCcontext *Context)
326 ALlistener &Listener = Context->Listener;
327 struct ALcontextProps *props;
329 props = Context->Update.exchange(nullptr, std::memory_order_acq_rel);
330 if(!props) return false;
332 Listener.Params.MetersPerUnit = props->MetersPerUnit;
334 Listener.Params.DopplerFactor = props->DopplerFactor;
335 Listener.Params.SpeedOfSound = props->SpeedOfSound * props->DopplerVelocity;
336 if(!OverrideReverbSpeedOfSound)
337 Listener.Params.ReverbSpeedOfSound = Listener.Params.SpeedOfSound *
338 Listener.Params.MetersPerUnit;
340 Listener.Params.SourceDistanceModel = props->SourceDistanceModel;
341 Listener.Params.mDistanceModel = props->mDistanceModel;
343 AtomicReplaceHead(Context->FreeContextProps, props);
344 return true;
347 bool CalcListenerParams(ALCcontext *Context)
349 ALlistener &Listener = Context->Listener;
350 ALfloat N[3], V[3], U[3], P[3];
351 struct ALlistenerProps *props;
352 aluVector vel;
354 props = Listener.Update.exchange(nullptr, std::memory_order_acq_rel);
355 if(!props) return false;
357 /* AT then UP */
358 N[0] = props->Forward[0];
359 N[1] = props->Forward[1];
360 N[2] = props->Forward[2];
361 aluNormalize(N);
362 V[0] = props->Up[0];
363 V[1] = props->Up[1];
364 V[2] = props->Up[2];
365 aluNormalize(V);
366 /* Build and normalize right-vector */
367 aluCrossproduct(N, V, U);
368 aluNormalize(U);
370 aluMatrixfSet(&Listener.Params.Matrix,
371 U[0], V[0], -N[0], 0.0,
372 U[1], V[1], -N[1], 0.0,
373 U[2], V[2], -N[2], 0.0,
374 0.0, 0.0, 0.0, 1.0
377 P[0] = props->Position[0];
378 P[1] = props->Position[1];
379 P[2] = props->Position[2];
380 aluMatrixfFloat3(P, 1.0, &Listener.Params.Matrix);
381 aluMatrixfSetRow(&Listener.Params.Matrix, 3, -P[0], -P[1], -P[2], 1.0f);
383 aluVectorSet(&vel, props->Velocity[0], props->Velocity[1], props->Velocity[2], 0.0f);
384 Listener.Params.Velocity = aluMatrixfVector(&Listener.Params.Matrix, &vel);
386 Listener.Params.Gain = props->Gain * Context->GainBoost;
388 AtomicReplaceHead(Context->FreeListenerProps, props);
389 return true;
392 bool CalcEffectSlotParams(ALeffectslot *slot, ALCcontext *context, bool force)
394 struct ALeffectslotProps *props;
395 EffectState *state;
397 props = slot->Update.exchange(nullptr, std::memory_order_acq_rel);
398 if(!props && !force) return false;
400 if(props)
402 slot->Params.Gain = props->Gain;
403 slot->Params.AuxSendAuto = props->AuxSendAuto;
404 slot->Params.EffectType = props->Type;
405 slot->Params.EffectProps = props->Props;
406 if(IsReverbEffect(props->Type))
408 slot->Params.RoomRolloff = props->Props.Reverb.RoomRolloffFactor;
409 slot->Params.DecayTime = props->Props.Reverb.DecayTime;
410 slot->Params.DecayLFRatio = props->Props.Reverb.DecayLFRatio;
411 slot->Params.DecayHFRatio = props->Props.Reverb.DecayHFRatio;
412 slot->Params.DecayHFLimit = props->Props.Reverb.DecayHFLimit;
413 slot->Params.AirAbsorptionGainHF = props->Props.Reverb.AirAbsorptionGainHF;
415 else
417 slot->Params.RoomRolloff = 0.0f;
418 slot->Params.DecayTime = 0.0f;
419 slot->Params.DecayLFRatio = 0.0f;
420 slot->Params.DecayHFRatio = 0.0f;
421 slot->Params.DecayHFLimit = AL_FALSE;
422 slot->Params.AirAbsorptionGainHF = 1.0f;
425 state = props->State;
427 if(state == slot->Params.mEffectState)
429 /* If the effect state is the same as current, we can decrement its
430 * count safely to remove it from the update object (it can't reach
431 * 0 refs since the current params also hold a reference).
433 DecrementRef(&state->mRef);
434 props->State = nullptr;
436 else
438 /* Otherwise, replace it and send off the old one with a release
439 * event.
441 AsyncEvent evt = ASYNC_EVENT(EventType_ReleaseEffectState);
442 evt.u.mEffectState = slot->Params.mEffectState;
444 slot->Params.mEffectState = state;
445 props->State = NULL;
447 if(LIKELY(ll_ringbuffer_write(context->AsyncEvents, &evt, 1) != 0))
448 alsem_post(&context->EventSem);
449 else
451 /* If writing the event failed, the queue was probably full.
452 * Store the old state in the property object where it can
453 * eventually be cleaned up sometime later (not ideal, but
454 * better than blocking or leaking).
456 props->State = evt.u.mEffectState;
460 AtomicReplaceHead(context->FreeEffectslotProps, props);
462 else
463 state = slot->Params.mEffectState;
465 state->update(context, slot, &slot->Params.EffectProps);
466 return true;
470 constexpr struct ChanMap MonoMap[1] = {
471 { FrontCenter, 0.0f, 0.0f }
472 }, RearMap[2] = {
473 { BackLeft, DEG2RAD(-150.0f), DEG2RAD(0.0f) },
474 { BackRight, DEG2RAD( 150.0f), DEG2RAD(0.0f) }
475 }, QuadMap[4] = {
476 { FrontLeft, DEG2RAD( -45.0f), DEG2RAD(0.0f) },
477 { FrontRight, DEG2RAD( 45.0f), DEG2RAD(0.0f) },
478 { BackLeft, DEG2RAD(-135.0f), DEG2RAD(0.0f) },
479 { BackRight, DEG2RAD( 135.0f), DEG2RAD(0.0f) }
480 }, X51Map[6] = {
481 { FrontLeft, DEG2RAD( -30.0f), DEG2RAD(0.0f) },
482 { FrontRight, DEG2RAD( 30.0f), DEG2RAD(0.0f) },
483 { FrontCenter, DEG2RAD( 0.0f), DEG2RAD(0.0f) },
484 { LFE, 0.0f, 0.0f },
485 { SideLeft, DEG2RAD(-110.0f), DEG2RAD(0.0f) },
486 { SideRight, DEG2RAD( 110.0f), DEG2RAD(0.0f) }
487 }, X61Map[7] = {
488 { FrontLeft, DEG2RAD(-30.0f), DEG2RAD(0.0f) },
489 { FrontRight, DEG2RAD( 30.0f), DEG2RAD(0.0f) },
490 { FrontCenter, DEG2RAD( 0.0f), DEG2RAD(0.0f) },
491 { LFE, 0.0f, 0.0f },
492 { BackCenter, DEG2RAD(180.0f), DEG2RAD(0.0f) },
493 { SideLeft, DEG2RAD(-90.0f), DEG2RAD(0.0f) },
494 { SideRight, DEG2RAD( 90.0f), DEG2RAD(0.0f) }
495 }, X71Map[8] = {
496 { FrontLeft, DEG2RAD( -30.0f), DEG2RAD(0.0f) },
497 { FrontRight, DEG2RAD( 30.0f), DEG2RAD(0.0f) },
498 { FrontCenter, DEG2RAD( 0.0f), DEG2RAD(0.0f) },
499 { LFE, 0.0f, 0.0f },
500 { BackLeft, DEG2RAD(-150.0f), DEG2RAD(0.0f) },
501 { BackRight, DEG2RAD( 150.0f), DEG2RAD(0.0f) },
502 { SideLeft, DEG2RAD( -90.0f), DEG2RAD(0.0f) },
503 { SideRight, DEG2RAD( 90.0f), DEG2RAD(0.0f) }
506 void CalcPanningAndFilters(ALvoice *voice, const ALfloat Azi, const ALfloat Elev,
507 const ALfloat Distance, const ALfloat Spread,
508 const ALfloat DryGain, const ALfloat DryGainHF,
509 const ALfloat DryGainLF, const ALfloat *WetGain,
510 const ALfloat *WetGainLF, const ALfloat *WetGainHF,
511 ALeffectslot **SendSlots, const ALbuffer *Buffer,
512 const struct ALvoiceProps *props, const ALlistener &Listener,
513 const ALCdevice *Device)
515 struct ChanMap StereoMap[2] = {
516 { FrontLeft, DEG2RAD(-30.0f), DEG2RAD(0.0f) },
517 { FrontRight, DEG2RAD( 30.0f), DEG2RAD(0.0f) }
519 bool DirectChannels = props->DirectChannels;
520 const ALsizei NumSends = Device->NumAuxSends;
521 const ALuint Frequency = Device->Frequency;
522 const struct ChanMap *chans = NULL;
523 ALsizei num_channels = 0;
524 bool isbformat = false;
525 ALfloat downmix_gain = 1.0f;
526 ALsizei c, i;
528 switch(Buffer->FmtChannels)
530 case FmtMono:
531 chans = MonoMap;
532 num_channels = 1;
533 /* Mono buffers are never played direct. */
534 DirectChannels = false;
535 break;
537 case FmtStereo:
538 /* Convert counter-clockwise to clockwise. */
539 StereoMap[0].angle = -props->StereoPan[0];
540 StereoMap[1].angle = -props->StereoPan[1];
542 chans = StereoMap;
543 num_channels = 2;
544 downmix_gain = 1.0f / 2.0f;
545 break;
547 case FmtRear:
548 chans = RearMap;
549 num_channels = 2;
550 downmix_gain = 1.0f / 2.0f;
551 break;
553 case FmtQuad:
554 chans = QuadMap;
555 num_channels = 4;
556 downmix_gain = 1.0f / 4.0f;
557 break;
559 case FmtX51:
560 chans = X51Map;
561 num_channels = 6;
562 /* NOTE: Excludes LFE. */
563 downmix_gain = 1.0f / 5.0f;
564 break;
566 case FmtX61:
567 chans = X61Map;
568 num_channels = 7;
569 /* NOTE: Excludes LFE. */
570 downmix_gain = 1.0f / 6.0f;
571 break;
573 case FmtX71:
574 chans = X71Map;
575 num_channels = 8;
576 /* NOTE: Excludes LFE. */
577 downmix_gain = 1.0f / 7.0f;
578 break;
580 case FmtBFormat2D:
581 num_channels = 3;
582 isbformat = true;
583 DirectChannels = false;
584 break;
586 case FmtBFormat3D:
587 num_channels = 4;
588 isbformat = true;
589 DirectChannels = false;
590 break;
593 for(c = 0;c < num_channels;c++)
595 memset(&voice->Direct.Params[c].Hrtf.Target, 0,
596 sizeof(voice->Direct.Params[c].Hrtf.Target));
597 ClearArray(voice->Direct.Params[c].Gains.Target);
599 for(i = 0;i < NumSends;i++)
601 for(c = 0;c < num_channels;c++)
602 ClearArray(voice->Send[i].Params[c].Gains.Target);
605 voice->Flags &= ~(VOICE_HAS_HRTF | VOICE_HAS_NFC);
606 if(isbformat)
608 /* Special handling for B-Format sources. */
610 if(Distance > FLT_EPSILON)
612 /* Panning a B-Format sound toward some direction is easy. Just pan
613 * the first (W) channel as a normal mono sound and silence the
614 * others.
616 ALfloat coeffs[MAX_AMBI_COEFFS];
618 if(Device->AvgSpeakerDist > 0.0f)
620 ALfloat mdist = Distance * Listener.Params.MetersPerUnit;
621 ALfloat w0 = SPEEDOFSOUNDMETRESPERSEC /
622 (mdist * (ALfloat)Device->Frequency);
623 ALfloat w1 = SPEEDOFSOUNDMETRESPERSEC /
624 (Device->AvgSpeakerDist * (ALfloat)Device->Frequency);
625 /* Clamp w0 for really close distances, to prevent excessive
626 * bass.
628 w0 = minf(w0, w1*4.0f);
630 /* Only need to adjust the first channel of a B-Format source. */
631 NfcFilterAdjust(&voice->Direct.Params[0].NFCtrlFilter, w0);
633 for(i = 0;i < MAX_AMBI_ORDER+1;i++)
634 voice->Direct.ChannelsPerOrder[i] = Device->NumChannelsPerOrder[i];
635 voice->Flags |= VOICE_HAS_NFC;
638 /* A scalar of 1.5 for plain stereo results in +/-60 degrees being
639 * moved to +/-90 degrees for direct right and left speaker
640 * responses.
642 CalcAngleCoeffs((Device->Render_Mode==StereoPair) ? ScaleAzimuthFront(Azi, 1.5f) : Azi,
643 Elev, Spread, coeffs);
645 /* NOTE: W needs to be scaled by sqrt(2) due to FuMa normalization. */
646 ComputePanGains(&Device->Dry, coeffs, DryGain*SQRTF_2,
647 voice->Direct.Params[0].Gains.Target);
648 for(i = 0;i < NumSends;i++)
650 const ALeffectslot *Slot = SendSlots[i];
651 if(Slot)
652 ComputePanningGainsBF(Slot->ChanMap, Slot->NumChannels, coeffs,
653 WetGain[i]*SQRTF_2, voice->Send[i].Params[0].Gains.Target
657 else
659 /* Local B-Format sources have their XYZ channels rotated according
660 * to the orientation.
662 ALfloat N[3], V[3], U[3];
663 aluMatrixf matrix;
665 if(Device->AvgSpeakerDist > 0.0f)
667 /* NOTE: The NFCtrlFilters were created with a w0 of 0, which
668 * is what we want for FOA input. The first channel may have
669 * been previously re-adjusted if panned, so reset it.
671 NfcFilterAdjust(&voice->Direct.Params[0].NFCtrlFilter, 0.0f);
673 voice->Direct.ChannelsPerOrder[0] = 1;
674 voice->Direct.ChannelsPerOrder[1] = mini(voice->Direct.Channels-1, 3);
675 for(i = 2;i < MAX_AMBI_ORDER+1;i++)
676 voice->Direct.ChannelsPerOrder[i] = 0;
677 voice->Flags |= VOICE_HAS_NFC;
680 /* AT then UP */
681 N[0] = props->Orientation[0][0];
682 N[1] = props->Orientation[0][1];
683 N[2] = props->Orientation[0][2];
684 aluNormalize(N);
685 V[0] = props->Orientation[1][0];
686 V[1] = props->Orientation[1][1];
687 V[2] = props->Orientation[1][2];
688 aluNormalize(V);
689 if(!props->HeadRelative)
691 const aluMatrixf *lmatrix = &Listener.Params.Matrix;
692 aluMatrixfFloat3(N, 0.0f, lmatrix);
693 aluMatrixfFloat3(V, 0.0f, lmatrix);
695 /* Build and normalize right-vector */
696 aluCrossproduct(N, V, U);
697 aluNormalize(U);
699 /* Build a rotate + conversion matrix (FuMa -> ACN+N3D). NOTE: This
700 * matrix is transposed, for the inputs to align on the rows and
701 * outputs on the columns.
703 aluMatrixfSet(&matrix,
704 // ACN0 ACN1 ACN2 ACN3
705 SQRTF_2, 0.0f, 0.0f, 0.0f, // Ambi W
706 0.0f, -N[0]*SQRTF_3, N[1]*SQRTF_3, -N[2]*SQRTF_3, // Ambi X
707 0.0f, U[0]*SQRTF_3, -U[1]*SQRTF_3, U[2]*SQRTF_3, // Ambi Y
708 0.0f, -V[0]*SQRTF_3, V[1]*SQRTF_3, -V[2]*SQRTF_3 // Ambi Z
711 voice->Direct.Buffer = Device->FOAOut.Buffer;
712 voice->Direct.Channels = Device->FOAOut.NumChannels;
713 for(c = 0;c < num_channels;c++)
714 ComputePanGains(&Device->FOAOut, matrix.m[c], DryGain,
715 voice->Direct.Params[c].Gains.Target);
716 for(i = 0;i < NumSends;i++)
718 const ALeffectslot *Slot = SendSlots[i];
719 if(Slot)
721 for(c = 0;c < num_channels;c++)
722 ComputePanningGainsBF(Slot->ChanMap, Slot->NumChannels,
723 matrix.m[c], WetGain[i], voice->Send[i].Params[c].Gains.Target
729 else if(DirectChannels)
731 /* Direct source channels always play local. Skip the virtual channels
732 * and write inputs to the matching real outputs.
734 voice->Direct.Buffer = Device->RealOut.Buffer;
735 voice->Direct.Channels = Device->RealOut.NumChannels;
737 for(c = 0;c < num_channels;c++)
739 int idx = GetChannelIdxByName(&Device->RealOut, chans[c].channel);
740 if(idx != -1) voice->Direct.Params[c].Gains.Target[idx] = DryGain;
743 /* Auxiliary sends still use normal channel panning since they mix to
744 * B-Format, which can't channel-match.
746 for(c = 0;c < num_channels;c++)
748 ALfloat coeffs[MAX_AMBI_COEFFS];
749 CalcAngleCoeffs(chans[c].angle, chans[c].elevation, 0.0f, coeffs);
751 for(i = 0;i < NumSends;i++)
753 const ALeffectslot *Slot = SendSlots[i];
754 if(Slot)
755 ComputePanningGainsBF(Slot->ChanMap, Slot->NumChannels,
756 coeffs, WetGain[i], voice->Send[i].Params[c].Gains.Target
761 else if(Device->Render_Mode == HrtfRender)
763 /* Full HRTF rendering. Skip the virtual channels and render to the
764 * real outputs.
766 voice->Direct.Buffer = Device->RealOut.Buffer;
767 voice->Direct.Channels = Device->RealOut.NumChannels;
769 if(Distance > FLT_EPSILON)
771 ALfloat coeffs[MAX_AMBI_COEFFS];
773 /* Get the HRIR coefficients and delays just once, for the given
774 * source direction.
776 GetHrtfCoeffs(Device->HrtfHandle, Elev, Azi, Spread,
777 voice->Direct.Params[0].Hrtf.Target.Coeffs,
778 voice->Direct.Params[0].Hrtf.Target.Delay);
779 voice->Direct.Params[0].Hrtf.Target.Gain = DryGain * downmix_gain;
781 /* Remaining channels use the same results as the first. */
782 for(c = 1;c < num_channels;c++)
784 /* Skip LFE */
785 if(chans[c].channel != LFE)
786 voice->Direct.Params[c].Hrtf.Target = voice->Direct.Params[0].Hrtf.Target;
789 /* Calculate the directional coefficients once, which apply to all
790 * input channels of the source sends.
792 CalcAngleCoeffs(Azi, Elev, Spread, coeffs);
794 for(i = 0;i < NumSends;i++)
796 const ALeffectslot *Slot = SendSlots[i];
797 if(Slot)
798 for(c = 0;c < num_channels;c++)
800 /* Skip LFE */
801 if(chans[c].channel != LFE)
802 ComputePanningGainsBF(Slot->ChanMap,
803 Slot->NumChannels, coeffs, WetGain[i] * downmix_gain,
804 voice->Send[i].Params[c].Gains.Target
809 else
811 /* Local sources on HRTF play with each channel panned to its
812 * relative location around the listener, providing "virtual
813 * speaker" responses.
815 for(c = 0;c < num_channels;c++)
817 ALfloat coeffs[MAX_AMBI_COEFFS];
819 if(chans[c].channel == LFE)
821 /* Skip LFE */
822 continue;
825 /* Get the HRIR coefficients and delays for this channel
826 * position.
828 GetHrtfCoeffs(Device->HrtfHandle,
829 chans[c].elevation, chans[c].angle, Spread,
830 voice->Direct.Params[c].Hrtf.Target.Coeffs,
831 voice->Direct.Params[c].Hrtf.Target.Delay
833 voice->Direct.Params[c].Hrtf.Target.Gain = DryGain;
835 /* Normal panning for auxiliary sends. */
836 CalcAngleCoeffs(chans[c].angle, chans[c].elevation, Spread, coeffs);
838 for(i = 0;i < NumSends;i++)
840 const ALeffectslot *Slot = SendSlots[i];
841 if(Slot)
842 ComputePanningGainsBF(Slot->ChanMap, Slot->NumChannels,
843 coeffs, WetGain[i], voice->Send[i].Params[c].Gains.Target
849 voice->Flags |= VOICE_HAS_HRTF;
851 else
853 /* Non-HRTF rendering. Use normal panning to the output. */
855 if(Distance > FLT_EPSILON)
857 ALfloat coeffs[MAX_AMBI_COEFFS];
858 ALfloat w0 = 0.0f;
860 /* Calculate NFC filter coefficient if needed. */
861 if(Device->AvgSpeakerDist > 0.0f)
863 ALfloat mdist = Distance * Listener.Params.MetersPerUnit;
864 ALfloat w1 = SPEEDOFSOUNDMETRESPERSEC /
865 (Device->AvgSpeakerDist * (ALfloat)Device->Frequency);
866 w0 = SPEEDOFSOUNDMETRESPERSEC /
867 (mdist * (ALfloat)Device->Frequency);
868 /* Clamp w0 for really close distances, to prevent excessive
869 * bass.
871 w0 = minf(w0, w1*4.0f);
873 /* Adjust NFC filters. */
874 for(c = 0;c < num_channels;c++)
875 NfcFilterAdjust(&voice->Direct.Params[c].NFCtrlFilter, w0);
877 for(i = 0;i < MAX_AMBI_ORDER+1;i++)
878 voice->Direct.ChannelsPerOrder[i] = Device->NumChannelsPerOrder[i];
879 voice->Flags |= VOICE_HAS_NFC;
882 /* Calculate the directional coefficients once, which apply to all
883 * input channels.
885 CalcAngleCoeffs((Device->Render_Mode==StereoPair) ? ScaleAzimuthFront(Azi, 1.5f) : Azi,
886 Elev, Spread, coeffs);
888 for(c = 0;c < num_channels;c++)
890 /* Special-case LFE */
891 if(chans[c].channel == LFE)
893 if(Device->Dry.Buffer == Device->RealOut.Buffer)
895 int idx = GetChannelIdxByName(&Device->RealOut, chans[c].channel);
896 if(idx != -1) voice->Direct.Params[c].Gains.Target[idx] = DryGain;
898 continue;
901 ComputePanGains(&Device->Dry, coeffs, DryGain * downmix_gain,
902 voice->Direct.Params[c].Gains.Target);
905 for(i = 0;i < NumSends;i++)
907 const ALeffectslot *Slot = SendSlots[i];
908 if(Slot)
909 for(c = 0;c < num_channels;c++)
911 /* Skip LFE */
912 if(chans[c].channel != LFE)
913 ComputePanningGainsBF(Slot->ChanMap,
914 Slot->NumChannels, coeffs, WetGain[i] * downmix_gain,
915 voice->Send[i].Params[c].Gains.Target
920 else
922 ALfloat w0 = 0.0f;
924 if(Device->AvgSpeakerDist > 0.0f)
926 /* If the source distance is 0, set w0 to w1 to act as a pass-
927 * through. We still want to pass the signal through the
928 * filters so they keep an appropriate history, in case the
929 * source moves away from the listener.
931 w0 = SPEEDOFSOUNDMETRESPERSEC /
932 (Device->AvgSpeakerDist * (ALfloat)Device->Frequency);
934 for(c = 0;c < num_channels;c++)
935 NfcFilterAdjust(&voice->Direct.Params[c].NFCtrlFilter, w0);
937 for(i = 0;i < MAX_AMBI_ORDER+1;i++)
938 voice->Direct.ChannelsPerOrder[i] = Device->NumChannelsPerOrder[i];
939 voice->Flags |= VOICE_HAS_NFC;
942 for(c = 0;c < num_channels;c++)
944 ALfloat coeffs[MAX_AMBI_COEFFS];
946 /* Special-case LFE */
947 if(chans[c].channel == LFE)
949 if(Device->Dry.Buffer == Device->RealOut.Buffer)
951 int idx = GetChannelIdxByName(&Device->RealOut, chans[c].channel);
952 if(idx != -1) voice->Direct.Params[c].Gains.Target[idx] = DryGain;
954 continue;
957 CalcAngleCoeffs(
958 (Device->Render_Mode==StereoPair) ? ScaleAzimuthFront(chans[c].angle, 3.0f)
959 : chans[c].angle,
960 chans[c].elevation, Spread, coeffs
963 ComputePanGains(&Device->Dry, coeffs, DryGain,
964 voice->Direct.Params[c].Gains.Target);
965 for(i = 0;i < NumSends;i++)
967 const ALeffectslot *Slot = SendSlots[i];
968 if(Slot)
969 ComputePanningGainsBF(Slot->ChanMap, Slot->NumChannels,
970 coeffs, WetGain[i], voice->Send[i].Params[c].Gains.Target
978 ALfloat hfScale = props->Direct.HFReference / Frequency;
979 ALfloat lfScale = props->Direct.LFReference / Frequency;
980 ALfloat gainHF = maxf(DryGainHF, 0.001f); /* Limit -60dB */
981 ALfloat gainLF = maxf(DryGainLF, 0.001f);
983 voice->Direct.FilterType = AF_None;
984 if(gainHF != 1.0f) voice->Direct.FilterType |= AF_LowPass;
985 if(gainLF != 1.0f) voice->Direct.FilterType |= AF_HighPass;
986 BiquadFilter_setParams(
987 &voice->Direct.Params[0].LowPass, BiquadType::HighShelf,
988 gainHF, hfScale, calc_rcpQ_from_slope(gainHF, 1.0f)
990 BiquadFilter_setParams(
991 &voice->Direct.Params[0].HighPass, BiquadType::LowShelf,
992 gainLF, lfScale, calc_rcpQ_from_slope(gainLF, 1.0f)
994 for(c = 1;c < num_channels;c++)
996 BiquadFilter_copyParams(&voice->Direct.Params[c].LowPass,
997 &voice->Direct.Params[0].LowPass);
998 BiquadFilter_copyParams(&voice->Direct.Params[c].HighPass,
999 &voice->Direct.Params[0].HighPass);
1002 for(i = 0;i < NumSends;i++)
1004 ALfloat hfScale = props->Send[i].HFReference / Frequency;
1005 ALfloat lfScale = props->Send[i].LFReference / Frequency;
1006 ALfloat gainHF = maxf(WetGainHF[i], 0.001f);
1007 ALfloat gainLF = maxf(WetGainLF[i], 0.001f);
1009 voice->Send[i].FilterType = AF_None;
1010 if(gainHF != 1.0f) voice->Send[i].FilterType |= AF_LowPass;
1011 if(gainLF != 1.0f) voice->Send[i].FilterType |= AF_HighPass;
1012 BiquadFilter_setParams(
1013 &voice->Send[i].Params[0].LowPass, BiquadType::HighShelf,
1014 gainHF, hfScale, calc_rcpQ_from_slope(gainHF, 1.0f)
1016 BiquadFilter_setParams(
1017 &voice->Send[i].Params[0].HighPass, BiquadType::LowShelf,
1018 gainLF, lfScale, calc_rcpQ_from_slope(gainLF, 1.0f)
1020 for(c = 1;c < num_channels;c++)
1022 BiquadFilter_copyParams(&voice->Send[i].Params[c].LowPass,
1023 &voice->Send[i].Params[0].LowPass);
1024 BiquadFilter_copyParams(&voice->Send[i].Params[c].HighPass,
1025 &voice->Send[i].Params[0].HighPass);
1030 void CalcNonAttnSourceParams(ALvoice *voice, const struct ALvoiceProps *props, const ALbuffer *ALBuffer, const ALCcontext *ALContext)
1032 const ALCdevice *Device = ALContext->Device;
1033 const ALlistener &Listener = ALContext->Listener;
1034 ALfloat DryGain, DryGainHF, DryGainLF;
1035 ALfloat WetGain[MAX_SENDS];
1036 ALfloat WetGainHF[MAX_SENDS];
1037 ALfloat WetGainLF[MAX_SENDS];
1038 ALeffectslot *SendSlots[MAX_SENDS];
1039 ALfloat Pitch;
1040 ALsizei i;
1042 voice->Direct.Buffer = Device->Dry.Buffer;
1043 voice->Direct.Channels = Device->Dry.NumChannels;
1044 for(i = 0;i < Device->NumAuxSends;i++)
1046 SendSlots[i] = props->Send[i].Slot;
1047 if(!SendSlots[i] && i == 0)
1048 SendSlots[i] = ALContext->DefaultSlot.get();
1049 if(!SendSlots[i] || SendSlots[i]->Params.EffectType == AL_EFFECT_NULL)
1051 SendSlots[i] = NULL;
1052 voice->Send[i].Buffer = NULL;
1053 voice->Send[i].Channels = 0;
1055 else
1057 voice->Send[i].Buffer = SendSlots[i]->WetBuffer;
1058 voice->Send[i].Channels = SendSlots[i]->NumChannels;
1062 /* Calculate the stepping value */
1063 Pitch = (ALfloat)ALBuffer->Frequency/(ALfloat)Device->Frequency * props->Pitch;
1064 if(Pitch > (ALfloat)MAX_PITCH)
1065 voice->Step = MAX_PITCH<<FRACTIONBITS;
1066 else
1067 voice->Step = maxi(fastf2i(Pitch * FRACTIONONE), 1);
1068 if(props->Resampler == BSinc24Resampler)
1069 BsincPrepare(voice->Step, &voice->ResampleState.bsinc, &bsinc24);
1070 else if(props->Resampler == BSinc12Resampler)
1071 BsincPrepare(voice->Step, &voice->ResampleState.bsinc, &bsinc12);
1072 voice->Resampler = SelectResampler(props->Resampler);
1074 /* Calculate gains */
1075 DryGain = clampf(props->Gain, props->MinGain, props->MaxGain);
1076 DryGain *= props->Direct.Gain * Listener.Params.Gain;
1077 DryGain = minf(DryGain, GAIN_MIX_MAX);
1078 DryGainHF = props->Direct.GainHF;
1079 DryGainLF = props->Direct.GainLF;
1080 for(i = 0;i < Device->NumAuxSends;i++)
1082 WetGain[i] = clampf(props->Gain, props->MinGain, props->MaxGain);
1083 WetGain[i] *= props->Send[i].Gain * Listener.Params.Gain;
1084 WetGain[i] = minf(WetGain[i], GAIN_MIX_MAX);
1085 WetGainHF[i] = props->Send[i].GainHF;
1086 WetGainLF[i] = props->Send[i].GainLF;
1089 CalcPanningAndFilters(voice, 0.0f, 0.0f, 0.0f, 0.0f, DryGain, DryGainHF, DryGainLF, WetGain,
1090 WetGainLF, WetGainHF, SendSlots, ALBuffer, props, Listener, Device);
1093 void CalcAttnSourceParams(ALvoice *voice, const struct ALvoiceProps *props, const ALbuffer *ALBuffer, const ALCcontext *ALContext)
1095 const ALCdevice *Device = ALContext->Device;
1096 const ALlistener &Listener = ALContext->Listener;
1097 const ALsizei NumSends = Device->NumAuxSends;
1098 aluVector Position, Velocity, Direction, SourceToListener;
1099 ALfloat Distance, ClampedDist, DopplerFactor;
1100 ALeffectslot *SendSlots[MAX_SENDS];
1101 ALfloat RoomRolloff[MAX_SENDS];
1102 ALfloat DecayDistance[MAX_SENDS];
1103 ALfloat DecayLFDistance[MAX_SENDS];
1104 ALfloat DecayHFDistance[MAX_SENDS];
1105 ALfloat DryGain, DryGainHF, DryGainLF;
1106 ALfloat WetGain[MAX_SENDS];
1107 ALfloat WetGainHF[MAX_SENDS];
1108 ALfloat WetGainLF[MAX_SENDS];
1109 bool directional;
1110 ALfloat ev, az;
1111 ALfloat spread;
1112 ALfloat Pitch;
1113 ALint i;
1115 /* Set mixing buffers and get send parameters. */
1116 voice->Direct.Buffer = Device->Dry.Buffer;
1117 voice->Direct.Channels = Device->Dry.NumChannels;
1118 for(i = 0;i < NumSends;i++)
1120 SendSlots[i] = props->Send[i].Slot;
1121 if(!SendSlots[i] && i == 0)
1122 SendSlots[i] = ALContext->DefaultSlot.get();
1123 if(!SendSlots[i] || SendSlots[i]->Params.EffectType == AL_EFFECT_NULL)
1125 SendSlots[i] = NULL;
1126 RoomRolloff[i] = 0.0f;
1127 DecayDistance[i] = 0.0f;
1128 DecayLFDistance[i] = 0.0f;
1129 DecayHFDistance[i] = 0.0f;
1131 else if(SendSlots[i]->Params.AuxSendAuto)
1133 RoomRolloff[i] = SendSlots[i]->Params.RoomRolloff + props->RoomRolloffFactor;
1134 /* Calculate the distances to where this effect's decay reaches
1135 * -60dB.
1137 DecayDistance[i] = SendSlots[i]->Params.DecayTime *
1138 Listener.Params.ReverbSpeedOfSound;
1139 DecayLFDistance[i] = DecayDistance[i] * SendSlots[i]->Params.DecayLFRatio;
1140 DecayHFDistance[i] = DecayDistance[i] * SendSlots[i]->Params.DecayHFRatio;
1141 if(SendSlots[i]->Params.DecayHFLimit)
1143 ALfloat airAbsorption = SendSlots[i]->Params.AirAbsorptionGainHF;
1144 if(airAbsorption < 1.0f)
1146 /* Calculate the distance to where this effect's air
1147 * absorption reaches -60dB, and limit the effect's HF
1148 * decay distance (so it doesn't take any longer to decay
1149 * than the air would allow).
1151 ALfloat absorb_dist = log10f(REVERB_DECAY_GAIN) / log10f(airAbsorption);
1152 DecayHFDistance[i] = minf(absorb_dist, DecayHFDistance[i]);
1156 else
1158 /* If the slot's auxiliary send auto is off, the data sent to the
1159 * effect slot is the same as the dry path, sans filter effects */
1160 RoomRolloff[i] = props->RolloffFactor;
1161 DecayDistance[i] = 0.0f;
1162 DecayLFDistance[i] = 0.0f;
1163 DecayHFDistance[i] = 0.0f;
1166 if(!SendSlots[i])
1168 voice->Send[i].Buffer = NULL;
1169 voice->Send[i].Channels = 0;
1171 else
1173 voice->Send[i].Buffer = SendSlots[i]->WetBuffer;
1174 voice->Send[i].Channels = SendSlots[i]->NumChannels;
1178 /* Transform source to listener space (convert to head relative) */
1179 aluVectorSet(&Position, props->Position[0], props->Position[1], props->Position[2], 1.0f);
1180 aluVectorSet(&Direction, props->Direction[0], props->Direction[1], props->Direction[2], 0.0f);
1181 aluVectorSet(&Velocity, props->Velocity[0], props->Velocity[1], props->Velocity[2], 0.0f);
1182 if(props->HeadRelative == AL_FALSE)
1184 const aluMatrixf *Matrix = &Listener.Params.Matrix;
1185 /* Transform source vectors */
1186 Position = aluMatrixfVector(Matrix, &Position);
1187 Velocity = aluMatrixfVector(Matrix, &Velocity);
1188 Direction = aluMatrixfVector(Matrix, &Direction);
1190 else
1192 const aluVector *lvelocity = &Listener.Params.Velocity;
1193 /* Offset the source velocity to be relative of the listener velocity */
1194 Velocity.v[0] += lvelocity->v[0];
1195 Velocity.v[1] += lvelocity->v[1];
1196 Velocity.v[2] += lvelocity->v[2];
1199 directional = aluNormalize(Direction.v) > 0.0f;
1200 SourceToListener.v[0] = -Position.v[0];
1201 SourceToListener.v[1] = -Position.v[1];
1202 SourceToListener.v[2] = -Position.v[2];
1203 SourceToListener.v[3] = 0.0f;
1204 Distance = aluNormalize(SourceToListener.v);
1206 /* Initial source gain */
1207 DryGain = props->Gain;
1208 DryGainHF = 1.0f;
1209 DryGainLF = 1.0f;
1210 for(i = 0;i < NumSends;i++)
1212 WetGain[i] = props->Gain;
1213 WetGainHF[i] = 1.0f;
1214 WetGainLF[i] = 1.0f;
1217 /* Calculate distance attenuation */
1218 ClampedDist = Distance;
1220 switch(Listener.Params.SourceDistanceModel ?
1221 props->mDistanceModel : Listener.Params.mDistanceModel)
1223 case DistanceModel::InverseClamped:
1224 ClampedDist = clampf(ClampedDist, props->RefDistance, props->MaxDistance);
1225 if(props->MaxDistance < props->RefDistance)
1226 break;
1227 /*fall-through*/
1228 case DistanceModel::Inverse:
1229 if(!(props->RefDistance > 0.0f))
1230 ClampedDist = props->RefDistance;
1231 else
1233 ALfloat dist = lerp(props->RefDistance, ClampedDist, props->RolloffFactor);
1234 if(dist > 0.0f) DryGain *= props->RefDistance / dist;
1235 for(i = 0;i < NumSends;i++)
1237 dist = lerp(props->RefDistance, ClampedDist, RoomRolloff[i]);
1238 if(dist > 0.0f) WetGain[i] *= props->RefDistance / dist;
1241 break;
1243 case DistanceModel::LinearClamped:
1244 ClampedDist = clampf(ClampedDist, props->RefDistance, props->MaxDistance);
1245 if(props->MaxDistance < props->RefDistance)
1246 break;
1247 /*fall-through*/
1248 case DistanceModel::Linear:
1249 if(!(props->MaxDistance != props->RefDistance))
1250 ClampedDist = props->RefDistance;
1251 else
1253 ALfloat attn = props->RolloffFactor * (ClampedDist-props->RefDistance) /
1254 (props->MaxDistance-props->RefDistance);
1255 DryGain *= maxf(1.0f - attn, 0.0f);
1256 for(i = 0;i < NumSends;i++)
1258 attn = RoomRolloff[i] * (ClampedDist-props->RefDistance) /
1259 (props->MaxDistance-props->RefDistance);
1260 WetGain[i] *= maxf(1.0f - attn, 0.0f);
1263 break;
1265 case DistanceModel::ExponentClamped:
1266 ClampedDist = clampf(ClampedDist, props->RefDistance, props->MaxDistance);
1267 if(props->MaxDistance < props->RefDistance)
1268 break;
1269 /*fall-through*/
1270 case DistanceModel::Exponent:
1271 if(!(ClampedDist > 0.0f && props->RefDistance > 0.0f))
1272 ClampedDist = props->RefDistance;
1273 else
1275 DryGain *= powf(ClampedDist/props->RefDistance, -props->RolloffFactor);
1276 for(i = 0;i < NumSends;i++)
1277 WetGain[i] *= powf(ClampedDist/props->RefDistance, -RoomRolloff[i]);
1279 break;
1281 case DistanceModel::Disable:
1282 ClampedDist = props->RefDistance;
1283 break;
1286 /* Calculate directional soundcones */
1287 if(directional && props->InnerAngle < 360.0f)
1289 ALfloat ConeVolume;
1290 ALfloat ConeHF;
1291 ALfloat Angle;
1293 Angle = acosf(aluDotproduct(&Direction, &SourceToListener));
1294 Angle = RAD2DEG(Angle * ConeScale * 2.0f);
1295 if(!(Angle > props->InnerAngle))
1297 ConeVolume = 1.0f;
1298 ConeHF = 1.0f;
1300 else if(Angle < props->OuterAngle)
1302 ALfloat scale = ( Angle-props->InnerAngle) /
1303 (props->OuterAngle-props->InnerAngle);
1304 ConeVolume = lerp(1.0f, props->OuterGain, scale);
1305 ConeHF = lerp(1.0f, props->OuterGainHF, scale);
1307 else
1309 ConeVolume = props->OuterGain;
1310 ConeHF = props->OuterGainHF;
1313 DryGain *= ConeVolume;
1314 if(props->DryGainHFAuto)
1315 DryGainHF *= ConeHF;
1316 if(props->WetGainAuto)
1318 for(i = 0;i < NumSends;i++)
1319 WetGain[i] *= ConeVolume;
1321 if(props->WetGainHFAuto)
1323 for(i = 0;i < NumSends;i++)
1324 WetGainHF[i] *= ConeHF;
1328 /* Apply gain and frequency filters */
1329 DryGain = clampf(DryGain, props->MinGain, props->MaxGain);
1330 DryGain = minf(DryGain*props->Direct.Gain*Listener.Params.Gain, GAIN_MIX_MAX);
1331 DryGainHF *= props->Direct.GainHF;
1332 DryGainLF *= props->Direct.GainLF;
1333 for(i = 0;i < NumSends;i++)
1335 WetGain[i] = clampf(WetGain[i], props->MinGain, props->MaxGain);
1336 WetGain[i] = minf(WetGain[i]*props->Send[i].Gain*Listener.Params.Gain, GAIN_MIX_MAX);
1337 WetGainHF[i] *= props->Send[i].GainHF;
1338 WetGainLF[i] *= props->Send[i].GainLF;
1341 /* Distance-based air absorption and initial send decay. */
1342 if(ClampedDist > props->RefDistance && props->RolloffFactor > 0.0f)
1344 ALfloat meters_base = (ClampedDist-props->RefDistance) * props->RolloffFactor *
1345 Listener.Params.MetersPerUnit;
1346 if(props->AirAbsorptionFactor > 0.0f)
1348 ALfloat hfattn = powf(AIRABSORBGAINHF, meters_base * props->AirAbsorptionFactor);
1349 DryGainHF *= hfattn;
1350 for(i = 0;i < NumSends;i++)
1351 WetGainHF[i] *= hfattn;
1354 if(props->WetGainAuto)
1356 /* Apply a decay-time transformation to the wet path, based on the
1357 * source distance in meters. The initial decay of the reverb
1358 * effect is calculated and applied to the wet path.
1360 for(i = 0;i < NumSends;i++)
1362 ALfloat gain, gainhf, gainlf;
1364 if(!(DecayDistance[i] > 0.0f))
1365 continue;
1367 gain = powf(REVERB_DECAY_GAIN, meters_base/DecayDistance[i]);
1368 WetGain[i] *= gain;
1369 /* Yes, the wet path's air absorption is applied with
1370 * WetGainAuto on, rather than WetGainHFAuto.
1372 if(gain > 0.0f)
1374 gainhf = powf(REVERB_DECAY_GAIN, meters_base/DecayHFDistance[i]);
1375 WetGainHF[i] *= minf(gainhf / gain, 1.0f);
1376 gainlf = powf(REVERB_DECAY_GAIN, meters_base/DecayLFDistance[i]);
1377 WetGainLF[i] *= minf(gainlf / gain, 1.0f);
1384 /* Initial source pitch */
1385 Pitch = props->Pitch;
1387 /* Calculate velocity-based doppler effect */
1388 DopplerFactor = props->DopplerFactor * Listener.Params.DopplerFactor;
1389 if(DopplerFactor > 0.0f)
1391 const aluVector *lvelocity = &Listener.Params.Velocity;
1392 const ALfloat SpeedOfSound = Listener.Params.SpeedOfSound;
1393 ALfloat vss, vls;
1395 vss = aluDotproduct(&Velocity, &SourceToListener) * DopplerFactor;
1396 vls = aluDotproduct(lvelocity, &SourceToListener) * DopplerFactor;
1398 if(!(vls < SpeedOfSound))
1400 /* Listener moving away from the source at the speed of sound.
1401 * Sound waves can't catch it.
1403 Pitch = 0.0f;
1405 else if(!(vss < SpeedOfSound))
1407 /* Source moving toward the listener at the speed of sound. Sound
1408 * waves bunch up to extreme frequencies.
1410 Pitch = HUGE_VALF;
1412 else
1414 /* Source and listener movement is nominal. Calculate the proper
1415 * doppler shift.
1417 Pitch *= (SpeedOfSound-vls) / (SpeedOfSound-vss);
1421 /* Adjust pitch based on the buffer and output frequencies, and calculate
1422 * fixed-point stepping value.
1424 Pitch *= (ALfloat)ALBuffer->Frequency/(ALfloat)Device->Frequency;
1425 if(Pitch > (ALfloat)MAX_PITCH)
1426 voice->Step = MAX_PITCH<<FRACTIONBITS;
1427 else
1428 voice->Step = maxi(fastf2i(Pitch * FRACTIONONE), 1);
1429 if(props->Resampler == BSinc24Resampler)
1430 BsincPrepare(voice->Step, &voice->ResampleState.bsinc, &bsinc24);
1431 else if(props->Resampler == BSinc12Resampler)
1432 BsincPrepare(voice->Step, &voice->ResampleState.bsinc, &bsinc12);
1433 voice->Resampler = SelectResampler(props->Resampler);
1435 if(Distance > 0.0f)
1437 /* Clamp Y, in case rounding errors caused it to end up outside of
1438 * -1...+1.
1440 ev = asinf(clampf(-SourceToListener.v[1], -1.0f, 1.0f));
1441 /* Double negation on Z cancels out; negate once for changing source-
1442 * to-listener to listener-to-source, and again for right-handed coords
1443 * with -Z in front.
1445 az = atan2f(-SourceToListener.v[0], SourceToListener.v[2]*ZScale);
1447 else
1448 ev = az = 0.0f;
1450 if(props->Radius > Distance)
1451 spread = F_TAU - Distance/props->Radius*F_PI;
1452 else if(Distance > 0.0f)
1453 spread = asinf(props->Radius / Distance) * 2.0f;
1454 else
1455 spread = 0.0f;
1457 CalcPanningAndFilters(voice, az, ev, Distance, spread, DryGain, DryGainHF, DryGainLF, WetGain,
1458 WetGainLF, WetGainHF, SendSlots, ALBuffer, props, Listener, Device);
1461 void CalcSourceParams(ALvoice *voice, ALCcontext *context, bool force)
1463 ALbufferlistitem *BufferListItem;
1464 struct ALvoiceProps *props;
1466 props = voice->Update.exchange(nullptr, std::memory_order_acq_rel);
1467 if(!props && !force) return;
1469 if(props)
1471 memcpy(voice->Props, props,
1472 FAM_SIZE(struct ALvoiceProps, Send, context->Device->NumAuxSends)
1475 AtomicReplaceHead(context->FreeVoiceProps, props);
1477 props = voice->Props;
1479 BufferListItem = ATOMIC_LOAD(&voice->current_buffer, almemory_order_relaxed);
1480 while(BufferListItem != NULL)
1482 const ALbuffer *buffer = NULL;
1483 ALsizei i = 0;
1484 while(!buffer && i < BufferListItem->num_buffers)
1485 buffer = BufferListItem->buffers[i];
1486 if(LIKELY(buffer))
1488 if(props->SpatializeMode == SpatializeOn ||
1489 (props->SpatializeMode == SpatializeAuto && buffer->FmtChannels == FmtMono))
1490 CalcAttnSourceParams(voice, props, buffer, context);
1491 else
1492 CalcNonAttnSourceParams(voice, props, buffer, context);
1493 break;
1495 BufferListItem = ATOMIC_LOAD(&BufferListItem->next, almemory_order_acquire);
1500 void ProcessParamUpdates(ALCcontext *ctx, const struct ALeffectslotArray *slots)
1502 ALvoice **voice, **voice_end;
1503 ALsource *source;
1504 ALsizei i;
1506 IncrementRef(&ctx->UpdateCount);
1507 if(!ATOMIC_LOAD(&ctx->HoldUpdates, almemory_order_acquire))
1509 bool cforce = CalcContextParams(ctx);
1510 bool force = CalcListenerParams(ctx) | cforce;
1511 for(i = 0;i < slots->count;i++)
1512 force |= CalcEffectSlotParams(slots->slot[i], ctx, cforce);
1514 voice = ctx->Voices;
1515 voice_end = voice + ctx->VoiceCount;
1516 for(;voice != voice_end;++voice)
1518 source = ATOMIC_LOAD(&(*voice)->Source, almemory_order_acquire);
1519 if(source) CalcSourceParams(*voice, ctx, force);
1522 IncrementRef(&ctx->UpdateCount);
1526 void ApplyStablizer(FrontStablizer *Stablizer, ALfloat (*RESTRICT Buffer)[BUFFERSIZE],
1527 int lidx, int ridx, int cidx, ALsizei SamplesToDo, ALsizei NumChannels)
1529 ALfloat (*RESTRICT lsplit)[BUFFERSIZE] = Stablizer->LSplit;
1530 ALfloat (*RESTRICT rsplit)[BUFFERSIZE] = Stablizer->RSplit;
1531 ALsizei i;
1533 /* Apply an all-pass to all channels, except the front-left and front-
1534 * right, so they maintain the same relative phase.
1536 for(i = 0;i < NumChannels;i++)
1538 if(i == lidx || i == ridx)
1539 continue;
1540 splitterap_process(&Stablizer->APFilter[i], Buffer[i], SamplesToDo);
1543 bandsplit_process(&Stablizer->LFilter, lsplit[1], lsplit[0], Buffer[lidx], SamplesToDo);
1544 bandsplit_process(&Stablizer->RFilter, rsplit[1], rsplit[0], Buffer[ridx], SamplesToDo);
1546 for(i = 0;i < SamplesToDo;i++)
1548 ALfloat lfsum, hfsum;
1549 ALfloat m, s, c;
1551 lfsum = lsplit[0][i] + rsplit[0][i];
1552 hfsum = lsplit[1][i] + rsplit[1][i];
1553 s = lsplit[0][i] + lsplit[1][i] - rsplit[0][i] - rsplit[1][i];
1555 /* This pans the separate low- and high-frequency sums between being on
1556 * the center channel and the left/right channels. The low-frequency
1557 * sum is 1/3rd toward center (2/3rds on left/right) and the high-
1558 * frequency sum is 1/4th toward center (3/4ths on left/right). These
1559 * values can be tweaked.
1561 m = lfsum*cosf(1.0f/3.0f * F_PI_2) + hfsum*cosf(1.0f/4.0f * F_PI_2);
1562 c = lfsum*sinf(1.0f/3.0f * F_PI_2) + hfsum*sinf(1.0f/4.0f * F_PI_2);
1564 /* The generated center channel signal adds to the existing signal,
1565 * while the modified left and right channels replace.
1567 Buffer[lidx][i] = (m + s) * 0.5f;
1568 Buffer[ridx][i] = (m - s) * 0.5f;
1569 Buffer[cidx][i] += c * 0.5f;
1573 void ApplyDistanceComp(ALfloat (*RESTRICT Samples)[BUFFERSIZE], const DistanceComp &distcomp,
1574 ALfloat *RESTRICT Values, ALsizei SamplesToDo, ALsizei numchans)
1576 for(ALsizei c{0};c < numchans;c++)
1578 ALfloat *RESTRICT inout = Samples[c];
1579 const ALfloat gain = distcomp[c].Gain;
1580 const ALsizei base = distcomp[c].Length;
1581 ALfloat *RESTRICT distbuf = distcomp[c].Buffer;
1583 if(base == 0)
1585 if(gain < 1.0f)
1586 std::for_each(inout, inout+SamplesToDo,
1587 [gain](ALfloat &in) noexcept -> void
1588 { in *= gain; }
1590 continue;
1593 if(LIKELY(SamplesToDo >= base))
1595 auto out = std::copy_n(distbuf, base, Values);
1596 std::copy_n(inout, SamplesToDo-base, out);
1597 std::copy_n(inout+SamplesToDo-base, base, distbuf);
1599 else
1601 std::copy_n(distbuf, SamplesToDo, Values);
1602 auto out = std::copy(distbuf+SamplesToDo, distbuf+base, distbuf);
1603 std::copy_n(inout, SamplesToDo, out);
1605 std::transform(Values, Values+SamplesToDo, inout,
1606 [gain](ALfloat in) noexcept -> ALfloat
1607 { return in * gain; }
1612 void ApplyDither(ALfloat (*RESTRICT Samples)[BUFFERSIZE], ALuint *dither_seed,
1613 const ALfloat quant_scale, const ALsizei SamplesToDo, const ALsizei numchans)
1615 const ALfloat invscale = 1.0f / quant_scale;
1616 ALuint seed = *dither_seed;
1617 ALsizei c, i;
1619 ASSUME(numchans > 0);
1620 ASSUME(SamplesToDo > 0);
1622 /* Dithering. Step 1, generate whitenoise (uniform distribution of random
1623 * values between -1 and +1). Step 2 is to add the noise to the samples,
1624 * before rounding and after scaling up to the desired quantization depth.
1626 for(c = 0;c < numchans;c++)
1628 ALfloat *RESTRICT samples = Samples[c];
1629 for(i = 0;i < SamplesToDo;i++)
1631 ALfloat val = samples[i] * quant_scale;
1632 ALuint rng0 = dither_rng(&seed);
1633 ALuint rng1 = dither_rng(&seed);
1634 val += (ALfloat)(rng0*(1.0/UINT_MAX) - rng1*(1.0/UINT_MAX));
1635 samples[i] = fast_roundf(val) * invscale;
1638 *dither_seed = seed;
1642 /* Base template left undefined. Should be marked =delete, but Clang 3.8.1
1643 * chokes on that given the inline specializations.
1645 template<typename T>
1646 inline T SampleConv(ALfloat);
1648 template<> inline ALfloat SampleConv(ALfloat val)
1649 { return val; }
1650 template<> inline ALint SampleConv(ALfloat val)
1652 /* Floats have a 23-bit mantissa. There is an implied 1 bit in the mantissa
1653 * along with the sign bit, giving 25 bits total, so [-16777216, +16777216]
1654 * is the max value a normalized float can be scaled to before losing
1655 * precision.
1657 return fastf2i(clampf(val*16777216.0f, -16777216.0f, 16777215.0f))<<7;
1659 template<> inline ALshort SampleConv(ALfloat val)
1660 { return fastf2i(clampf(val*32768.0f, -32768.0f, 32767.0f)); }
1661 template<> inline ALbyte SampleConv(ALfloat val)
1662 { return fastf2i(clampf(val*128.0f, -128.0f, 127.0f)); }
1664 /* Define unsigned output variations. */
1665 template<> inline ALuint SampleConv(ALfloat val)
1666 { return SampleConv<ALint>(val) + 2147483648u; }
1667 template<> inline ALushort SampleConv(ALfloat val)
1668 { return SampleConv<ALshort>(val) + 32768; }
1669 template<> inline ALubyte SampleConv(ALfloat val)
1670 { return SampleConv<ALbyte>(val) + 128; }
1672 template<DevFmtType T>
1673 void Write(const ALfloat (*RESTRICT InBuffer)[BUFFERSIZE], ALvoid *OutBuffer,
1674 ALsizei Offset, ALsizei SamplesToDo, ALsizei numchans)
1676 using SampleType = typename DevFmtTypeTraits<T>::Type;
1678 ASSUME(numchans > 0);
1679 ASSUME(SamplesToDo > 0);
1681 for(ALsizei j{0};j < numchans;j++)
1683 const ALfloat *RESTRICT in = InBuffer[j];
1684 SampleType *RESTRICT out = static_cast<SampleType*>(OutBuffer) + Offset*numchans + j;
1686 for(ALsizei i{0};i < SamplesToDo;i++)
1687 out[i*numchans] = SampleConv<SampleType>(in[i]);
1691 } // namespace
1693 void aluMixData(ALCdevice *device, ALvoid *OutBuffer, ALsizei NumSamples)
1695 ALsizei SamplesToDo;
1696 ALsizei SamplesDone;
1697 ALCcontext *ctx;
1698 ALsizei i, c;
1700 FPUCtl mixer_mode{};
1701 for(SamplesDone = 0;SamplesDone < NumSamples;)
1703 SamplesToDo = mini(NumSamples-SamplesDone, BUFFERSIZE);
1704 for(c = 0;c < device->Dry.NumChannels;c++)
1705 memset(device->Dry.Buffer[c], 0, SamplesToDo*sizeof(ALfloat));
1706 if(device->Dry.Buffer != device->FOAOut.Buffer)
1707 for(c = 0;c < device->FOAOut.NumChannels;c++)
1708 memset(device->FOAOut.Buffer[c], 0, SamplesToDo*sizeof(ALfloat));
1709 if(device->Dry.Buffer != device->RealOut.Buffer)
1710 for(c = 0;c < device->RealOut.NumChannels;c++)
1711 memset(device->RealOut.Buffer[c], 0, SamplesToDo*sizeof(ALfloat));
1713 IncrementRef(&device->MixCount);
1715 ctx = ATOMIC_LOAD(&device->ContextList, almemory_order_acquire);
1716 while(ctx)
1718 const struct ALeffectslotArray *auxslots;
1720 auxslots = ATOMIC_LOAD(&ctx->ActiveAuxSlots, almemory_order_acquire);
1721 ProcessParamUpdates(ctx, auxslots);
1723 for(i = 0;i < auxslots->count;i++)
1725 ALeffectslot *slot = auxslots->slot[i];
1726 for(c = 0;c < slot->NumChannels;c++)
1727 memset(slot->WetBuffer[c], 0, SamplesToDo*sizeof(ALfloat));
1730 /* source processing */
1731 for(i = 0;i < ctx->VoiceCount;i++)
1733 ALvoice *voice = ctx->Voices[i];
1734 ALsource *source = ATOMIC_LOAD(&voice->Source, almemory_order_acquire);
1735 if(source && ATOMIC_LOAD(&voice->Playing, almemory_order_relaxed) &&
1736 voice->Step > 0)
1738 if(!MixSource(voice, source->id, ctx, SamplesToDo))
1740 ATOMIC_STORE(&voice->Source, static_cast<ALsource*>(nullptr),
1741 almemory_order_relaxed);
1742 ATOMIC_STORE(&voice->Playing, false, almemory_order_release);
1743 SendSourceStoppedEvent(ctx, source->id);
1748 /* effect slot processing */
1749 for(i = 0;i < auxslots->count;i++)
1751 const ALeffectslot *slot = auxslots->slot[i];
1752 EffectState *state = slot->Params.mEffectState;
1753 state->process(SamplesToDo, slot->WetBuffer, state->mOutBuffer,
1754 state->mOutChannels);
1757 ctx = ATOMIC_LOAD(&ctx->next, almemory_order_relaxed);
1760 /* Increment the clock time. Every second's worth of samples is
1761 * converted and added to clock base so that large sample counts don't
1762 * overflow during conversion. This also guarantees an exact, stable
1763 * conversion. */
1764 device->SamplesDone += SamplesToDo;
1765 device->ClockBase += (device->SamplesDone/device->Frequency) * DEVICE_CLOCK_RES;
1766 device->SamplesDone %= device->Frequency;
1767 IncrementRef(&device->MixCount);
1769 /* Apply post-process for finalizing the Dry mix to the RealOut
1770 * (Ambisonic decode, UHJ encode, etc).
1772 if(LIKELY(device->PostProcess))
1773 device->PostProcess(device, SamplesToDo);
1775 if(device->Stablizer)
1777 int lidx = GetChannelIdxByName(&device->RealOut, FrontLeft);
1778 int ridx = GetChannelIdxByName(&device->RealOut, FrontRight);
1779 int cidx = GetChannelIdxByName(&device->RealOut, FrontCenter);
1780 assert(lidx >= 0 && ridx >= 0 && cidx >= 0);
1782 ApplyStablizer(device->Stablizer, device->RealOut.Buffer, lidx, ridx, cidx,
1783 SamplesToDo, device->RealOut.NumChannels);
1786 ApplyDistanceComp(device->RealOut.Buffer, device->ChannelDelay, device->TempBuffer[0],
1787 SamplesToDo, device->RealOut.NumChannels);
1789 if(device->Limiter)
1790 ApplyCompression(device->Limiter.get(), SamplesToDo, device->RealOut.Buffer);
1792 if(device->DitherDepth > 0.0f)
1793 ApplyDither(device->RealOut.Buffer, &device->DitherSeed, device->DitherDepth,
1794 SamplesToDo, device->RealOut.NumChannels);
1796 if(LIKELY(OutBuffer))
1798 ALfloat (*Buffer)[BUFFERSIZE] = device->RealOut.Buffer;
1799 ALsizei Channels = device->RealOut.NumChannels;
1801 switch(device->FmtType)
1803 #define HANDLE_WRITE(T) case T: \
1804 Write<T>(Buffer, OutBuffer, SamplesDone, SamplesToDo, Channels); break;
1805 HANDLE_WRITE(DevFmtByte)
1806 HANDLE_WRITE(DevFmtUByte)
1807 HANDLE_WRITE(DevFmtShort)
1808 HANDLE_WRITE(DevFmtUShort)
1809 HANDLE_WRITE(DevFmtInt)
1810 HANDLE_WRITE(DevFmtUInt)
1811 HANDLE_WRITE(DevFmtFloat)
1812 #undef HANDLE_WRITE
1816 SamplesDone += SamplesToDo;
1821 void aluHandleDisconnect(ALCdevice *device, const char *msg, ...)
1823 AsyncEvent evt = ASYNC_EVENT(EventType_Disconnected);
1824 ALCcontext *ctx;
1825 va_list args;
1826 int msglen;
1828 if(!device->Connected.exchange(AL_FALSE, std::memory_order_acq_rel))
1829 return;
1831 evt.u.user.type = AL_EVENT_TYPE_DISCONNECTED_SOFT;
1832 evt.u.user.id = 0;
1833 evt.u.user.param = 0;
1835 va_start(args, msg);
1836 msglen = vsnprintf(evt.u.user.msg, sizeof(evt.u.user.msg), msg, args);
1837 va_end(args);
1839 if(msglen < 0 || (size_t)msglen >= sizeof(evt.u.user.msg))
1840 evt.u.user.msg[sizeof(evt.u.user.msg)-1] = 0;
1842 ctx = ATOMIC_LOAD_SEQ(&device->ContextList);
1843 while(ctx)
1845 ALbitfieldSOFT enabledevt = ATOMIC_LOAD(&ctx->EnabledEvts, almemory_order_acquire);
1846 ALsizei i;
1848 if((enabledevt&EventType_Disconnected) &&
1849 ll_ringbuffer_write(ctx->AsyncEvents, &evt, 1) == 1)
1850 alsem_post(&ctx->EventSem);
1852 for(i = 0;i < ctx->VoiceCount;i++)
1854 ALvoice *voice = ctx->Voices[i];
1855 ALsource *source = voice->Source.exchange(nullptr, std::memory_order_relaxed);
1856 if(source && voice->Playing.load(std::memory_order_relaxed))
1858 /* If the source's voice was playing, it's now effectively
1859 * stopped (the source state will be updated the next time it's
1860 * checked).
1862 SendSourceStoppedEvent(ctx, source->id);
1864 voice->Playing.store(false, std::memory_order_release);
1867 ctx = ATOMIC_LOAD(&ctx->next, almemory_order_relaxed);