Use C++ templates instead of macro-defined variations
[openal-soft.git] / Alc / alu.cpp
blobcc48a4bfb7b44e8f6b1868ab6345e32fe3a89d29
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 "alMain.h"
30 #include "alcontext.h"
31 #include "alSource.h"
32 #include "alBuffer.h"
33 #include "alListener.h"
34 #include "alAuxEffectSlot.h"
35 #include "alu.h"
36 #include "bs2b.h"
37 #include "hrtf.h"
38 #include "mastering.h"
39 #include "uhjfilter.h"
40 #include "bformatdec.h"
41 #include "ringbuffer.h"
42 #include "filters/splitter.h"
44 #include "mixer/defs.h"
45 #include "fpu_modes.h"
46 #include "cpu_caps.h"
47 #include "bsinc_inc.h"
50 /* Cone scalar */
51 ALfloat ConeScale = 1.0f;
53 /* Localized Z scalar for mono sources */
54 ALfloat ZScale = 1.0f;
56 /* Force default speed of sound for distance-related reverb decay. */
57 ALboolean OverrideReverbSpeedOfSound = AL_FALSE;
60 namespace {
62 void ClearArray(ALfloat f[MAX_OUTPUT_CHANNELS])
64 size_t i;
65 for(i = 0;i < MAX_OUTPUT_CHANNELS;i++)
66 f[i] = 0.0f;
69 struct ChanMap {
70 enum Channel channel;
71 ALfloat angle;
72 ALfloat elevation;
75 HrtfDirectMixerFunc MixDirectHrtf = MixDirectHrtf_C;
78 inline HrtfDirectMixerFunc SelectHrtfMixer(void)
80 #ifdef HAVE_NEON
81 if((CPUCapFlags&CPU_CAP_NEON))
82 return MixDirectHrtf_Neon;
83 #endif
84 #ifdef HAVE_SSE
85 if((CPUCapFlags&CPU_CAP_SSE))
86 return MixDirectHrtf_SSE;
87 #endif
89 return MixDirectHrtf_C;
92 } // namespace
94 void aluInit(void)
96 MixDirectHrtf = SelectHrtfMixer();
100 void DeinitVoice(ALvoice *voice)
102 al_free(voice->Update.exchange(nullptr));
106 namespace {
108 void ProcessHrtf(ALCdevice *device, ALsizei SamplesToDo)
110 DirectHrtfState *state;
111 int lidx, ridx;
112 ALsizei c;
114 if(device->AmbiUp)
115 ambiup_process(device->AmbiUp,
116 device->Dry.Buffer, device->Dry.NumChannels, device->FOAOut.Buffer,
117 SamplesToDo
120 lidx = GetChannelIdxByName(&device->RealOut, FrontLeft);
121 ridx = GetChannelIdxByName(&device->RealOut, FrontRight);
122 assert(lidx != -1 && ridx != -1);
124 state = device->Hrtf;
125 for(c = 0;c < device->Dry.NumChannels;c++)
127 MixDirectHrtf(device->RealOut.Buffer[lidx], device->RealOut.Buffer[ridx],
128 device->Dry.Buffer[c], state->Offset, state->IrSize,
129 state->Chan[c].Coeffs, state->Chan[c].Values, SamplesToDo
132 state->Offset += SamplesToDo;
135 void ProcessAmbiDec(ALCdevice *device, ALsizei SamplesToDo)
137 if(device->Dry.Buffer != device->FOAOut.Buffer)
138 bformatdec_upSample(device->AmbiDecoder,
139 device->Dry.Buffer, device->FOAOut.Buffer, device->FOAOut.NumChannels,
140 SamplesToDo
142 bformatdec_process(device->AmbiDecoder,
143 device->RealOut.Buffer, device->RealOut.NumChannels, device->Dry.Buffer,
144 SamplesToDo
148 void ProcessAmbiUp(ALCdevice *device, ALsizei SamplesToDo)
150 ambiup_process(device->AmbiUp,
151 device->RealOut.Buffer, device->RealOut.NumChannels, device->FOAOut.Buffer,
152 SamplesToDo
156 void ProcessUhj(ALCdevice *device, ALsizei SamplesToDo)
158 int lidx = GetChannelIdxByName(&device->RealOut, FrontLeft);
159 int ridx = GetChannelIdxByName(&device->RealOut, FrontRight);
160 assert(lidx != -1 && ridx != -1);
162 /* Encode to stereo-compatible 2-channel UHJ output. */
163 EncodeUhj2(device->Uhj_Encoder,
164 device->RealOut.Buffer[lidx], device->RealOut.Buffer[ridx],
165 device->Dry.Buffer, SamplesToDo
169 void ProcessBs2b(ALCdevice *device, ALsizei SamplesToDo)
171 int lidx = GetChannelIdxByName(&device->RealOut, FrontLeft);
172 int ridx = GetChannelIdxByName(&device->RealOut, FrontRight);
173 assert(lidx != -1 && ridx != -1);
175 /* Apply binaural/crossfeed filter */
176 bs2b_cross_feed(device->Bs2b, device->RealOut.Buffer[lidx],
177 device->RealOut.Buffer[ridx], SamplesToDo);
180 } // namespace
182 void aluSelectPostProcess(ALCdevice *device)
184 if(device->HrtfHandle)
185 device->PostProcess = ProcessHrtf;
186 else if(device->AmbiDecoder)
187 device->PostProcess = ProcessAmbiDec;
188 else if(device->AmbiUp)
189 device->PostProcess = ProcessAmbiUp;
190 else if(device->Uhj_Encoder)
191 device->PostProcess = ProcessUhj;
192 else if(device->Bs2b)
193 device->PostProcess = ProcessBs2b;
194 else
195 device->PostProcess = NULL;
199 /* Prepares the interpolator for a given rate (determined by increment).
201 * With a bit of work, and a trade of memory for CPU cost, this could be
202 * modified for use with an interpolated increment for buttery-smooth pitch
203 * changes.
205 void BsincPrepare(const ALuint increment, BsincState *state, const BSincTable *table)
207 ALfloat sf = 0.0f;
208 ALsizei si = BSINC_SCALE_COUNT-1;
210 if(increment > FRACTIONONE)
212 sf = (ALfloat)FRACTIONONE / increment;
213 sf = maxf(0.0f, (BSINC_SCALE_COUNT-1) * (sf-table->scaleBase) * table->scaleRange);
214 si = float2int(sf);
215 /* The interpolation factor is fit to this diagonally-symmetric curve
216 * to reduce the transition ripple caused by interpolating different
217 * scales of the sinc function.
219 sf = 1.0f - cosf(asinf(sf - si));
222 state->sf = sf;
223 state->m = table->m[si];
224 state->l = (state->m/2) - 1;
225 state->filter = table->Tab + table->filterOffset[si];
229 namespace {
231 /* This RNG method was created based on the math found in opusdec. It's quick,
232 * and starting with a seed value of 22222, is suitable for generating
233 * whitenoise.
235 inline ALuint dither_rng(ALuint *seed)
237 *seed = (*seed * 96314165) + 907633515;
238 return *seed;
242 inline void aluCrossproduct(const ALfloat *inVector1, const ALfloat *inVector2, ALfloat *outVector)
244 outVector[0] = inVector1[1]*inVector2[2] - inVector1[2]*inVector2[1];
245 outVector[1] = inVector1[2]*inVector2[0] - inVector1[0]*inVector2[2];
246 outVector[2] = inVector1[0]*inVector2[1] - inVector1[1]*inVector2[0];
249 inline ALfloat aluDotproduct(const aluVector *vec1, const aluVector *vec2)
251 return vec1->v[0]*vec2->v[0] + vec1->v[1]*vec2->v[1] + vec1->v[2]*vec2->v[2];
254 ALfloat aluNormalize(ALfloat *vec)
256 ALfloat length = sqrtf(vec[0]*vec[0] + vec[1]*vec[1] + vec[2]*vec[2]);
257 if(length > FLT_EPSILON)
259 ALfloat inv_length = 1.0f/length;
260 vec[0] *= inv_length;
261 vec[1] *= inv_length;
262 vec[2] *= inv_length;
263 return length;
265 vec[0] = vec[1] = vec[2] = 0.0f;
266 return 0.0f;
269 void aluMatrixfFloat3(ALfloat *vec, ALfloat w, const aluMatrixf *mtx)
271 ALfloat v[4] = { vec[0], vec[1], vec[2], w };
273 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];
274 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];
275 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];
278 aluVector aluMatrixfVector(const aluMatrixf *mtx, const aluVector *vec)
280 aluVector v;
281 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];
282 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];
283 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];
284 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];
285 return v;
289 void SendSourceStoppedEvent(ALCcontext *context, ALuint id)
291 AsyncEvent evt = ASYNC_EVENT(EventType_SourceStateChange);
292 ALbitfieldSOFT enabledevt;
293 size_t strpos;
294 ALuint scale;
296 enabledevt = ATOMIC_LOAD(&context->EnabledEvts, almemory_order_acquire);
297 if(!(enabledevt&EventType_SourceStateChange)) return;
299 evt.u.user.type = AL_EVENT_TYPE_SOURCE_STATE_CHANGED_SOFT;
300 evt.u.user.id = id;
301 evt.u.user.param = AL_STOPPED;
303 /* Normally snprintf would be used, but this is called from the mixer and
304 * that function's not real-time safe, so we have to construct it manually.
306 strcpy(evt.u.user.msg, "Source ID "); strpos = 10;
307 scale = 1000000000;
308 while(scale > 0 && scale > id)
309 scale /= 10;
310 while(scale > 0)
312 evt.u.user.msg[strpos++] = '0' + ((id/scale)%10);
313 scale /= 10;
315 strcpy(evt.u.user.msg+strpos, " state changed to AL_STOPPED");
317 if(ll_ringbuffer_write(context->AsyncEvents, &evt, 1) == 1)
318 alsem_post(&context->EventSem);
322 bool CalcContextParams(ALCcontext *Context)
324 ALlistener &Listener = Context->Listener;
325 struct ALcontextProps *props;
327 props = Context->Update.exchange(nullptr, std::memory_order_acq_rel);
328 if(!props) return false;
330 Listener.Params.MetersPerUnit = props->MetersPerUnit;
332 Listener.Params.DopplerFactor = props->DopplerFactor;
333 Listener.Params.SpeedOfSound = props->SpeedOfSound * props->DopplerVelocity;
334 if(!OverrideReverbSpeedOfSound)
335 Listener.Params.ReverbSpeedOfSound = Listener.Params.SpeedOfSound *
336 Listener.Params.MetersPerUnit;
338 Listener.Params.SourceDistanceModel = props->SourceDistanceModel;
339 Listener.Params.mDistanceModel = props->mDistanceModel;
341 AtomicReplaceHead(Context->FreeContextProps, props);
342 return true;
345 bool CalcListenerParams(ALCcontext *Context)
347 ALlistener &Listener = Context->Listener;
348 ALfloat N[3], V[3], U[3], P[3];
349 struct ALlistenerProps *props;
350 aluVector vel;
352 props = Listener.Update.exchange(nullptr, std::memory_order_acq_rel);
353 if(!props) return false;
355 /* AT then UP */
356 N[0] = props->Forward[0];
357 N[1] = props->Forward[1];
358 N[2] = props->Forward[2];
359 aluNormalize(N);
360 V[0] = props->Up[0];
361 V[1] = props->Up[1];
362 V[2] = props->Up[2];
363 aluNormalize(V);
364 /* Build and normalize right-vector */
365 aluCrossproduct(N, V, U);
366 aluNormalize(U);
368 aluMatrixfSet(&Listener.Params.Matrix,
369 U[0], V[0], -N[0], 0.0,
370 U[1], V[1], -N[1], 0.0,
371 U[2], V[2], -N[2], 0.0,
372 0.0, 0.0, 0.0, 1.0
375 P[0] = props->Position[0];
376 P[1] = props->Position[1];
377 P[2] = props->Position[2];
378 aluMatrixfFloat3(P, 1.0, &Listener.Params.Matrix);
379 aluMatrixfSetRow(&Listener.Params.Matrix, 3, -P[0], -P[1], -P[2], 1.0f);
381 aluVectorSet(&vel, props->Velocity[0], props->Velocity[1], props->Velocity[2], 0.0f);
382 Listener.Params.Velocity = aluMatrixfVector(&Listener.Params.Matrix, &vel);
384 Listener.Params.Gain = props->Gain * Context->GainBoost;
386 AtomicReplaceHead(Context->FreeListenerProps, props);
387 return true;
390 bool CalcEffectSlotParams(ALeffectslot *slot, ALCcontext *context, bool force)
392 struct ALeffectslotProps *props;
393 EffectState *state;
395 props = slot->Update.exchange(nullptr, std::memory_order_acq_rel);
396 if(!props && !force) return false;
398 if(props)
400 slot->Params.Gain = props->Gain;
401 slot->Params.AuxSendAuto = props->AuxSendAuto;
402 slot->Params.EffectType = props->Type;
403 slot->Params.EffectProps = props->Props;
404 if(IsReverbEffect(props->Type))
406 slot->Params.RoomRolloff = props->Props.Reverb.RoomRolloffFactor;
407 slot->Params.DecayTime = props->Props.Reverb.DecayTime;
408 slot->Params.DecayLFRatio = props->Props.Reverb.DecayLFRatio;
409 slot->Params.DecayHFRatio = props->Props.Reverb.DecayHFRatio;
410 slot->Params.DecayHFLimit = props->Props.Reverb.DecayHFLimit;
411 slot->Params.AirAbsorptionGainHF = props->Props.Reverb.AirAbsorptionGainHF;
413 else
415 slot->Params.RoomRolloff = 0.0f;
416 slot->Params.DecayTime = 0.0f;
417 slot->Params.DecayLFRatio = 0.0f;
418 slot->Params.DecayHFRatio = 0.0f;
419 slot->Params.DecayHFLimit = AL_FALSE;
420 slot->Params.AirAbsorptionGainHF = 1.0f;
423 state = props->State;
425 if(state == slot->Params.mEffectState)
427 /* If the effect state is the same as current, we can decrement its
428 * count safely to remove it from the update object (it can't reach
429 * 0 refs since the current params also hold a reference).
431 DecrementRef(&state->mRef);
432 props->State = nullptr;
434 else
436 /* Otherwise, replace it and send off the old one with a release
437 * event.
439 AsyncEvent evt = ASYNC_EVENT(EventType_ReleaseEffectState);
440 evt.u.mEffectState = slot->Params.mEffectState;
442 slot->Params.mEffectState = state;
443 props->State = NULL;
445 if(LIKELY(ll_ringbuffer_write(context->AsyncEvents, &evt, 1) != 0))
446 alsem_post(&context->EventSem);
447 else
449 /* If writing the event failed, the queue was probably full.
450 * Store the old state in the property object where it can
451 * eventually be cleaned up sometime later (not ideal, but
452 * better than blocking or leaking).
454 props->State = evt.u.mEffectState;
458 AtomicReplaceHead(context->FreeEffectslotProps, props);
460 else
461 state = slot->Params.mEffectState;
463 state->update(context, slot, &slot->Params.EffectProps);
464 return true;
468 constexpr struct ChanMap MonoMap[1] = {
469 { FrontCenter, 0.0f, 0.0f }
470 }, RearMap[2] = {
471 { BackLeft, DEG2RAD(-150.0f), DEG2RAD(0.0f) },
472 { BackRight, DEG2RAD( 150.0f), DEG2RAD(0.0f) }
473 }, QuadMap[4] = {
474 { FrontLeft, DEG2RAD( -45.0f), DEG2RAD(0.0f) },
475 { FrontRight, DEG2RAD( 45.0f), DEG2RAD(0.0f) },
476 { BackLeft, DEG2RAD(-135.0f), DEG2RAD(0.0f) },
477 { BackRight, DEG2RAD( 135.0f), DEG2RAD(0.0f) }
478 }, X51Map[6] = {
479 { FrontLeft, DEG2RAD( -30.0f), DEG2RAD(0.0f) },
480 { FrontRight, DEG2RAD( 30.0f), DEG2RAD(0.0f) },
481 { FrontCenter, DEG2RAD( 0.0f), DEG2RAD(0.0f) },
482 { LFE, 0.0f, 0.0f },
483 { SideLeft, DEG2RAD(-110.0f), DEG2RAD(0.0f) },
484 { SideRight, DEG2RAD( 110.0f), DEG2RAD(0.0f) }
485 }, X61Map[7] = {
486 { FrontLeft, DEG2RAD(-30.0f), DEG2RAD(0.0f) },
487 { FrontRight, DEG2RAD( 30.0f), DEG2RAD(0.0f) },
488 { FrontCenter, DEG2RAD( 0.0f), DEG2RAD(0.0f) },
489 { LFE, 0.0f, 0.0f },
490 { BackCenter, DEG2RAD(180.0f), DEG2RAD(0.0f) },
491 { SideLeft, DEG2RAD(-90.0f), DEG2RAD(0.0f) },
492 { SideRight, DEG2RAD( 90.0f), DEG2RAD(0.0f) }
493 }, X71Map[8] = {
494 { FrontLeft, DEG2RAD( -30.0f), DEG2RAD(0.0f) },
495 { FrontRight, DEG2RAD( 30.0f), DEG2RAD(0.0f) },
496 { FrontCenter, DEG2RAD( 0.0f), DEG2RAD(0.0f) },
497 { LFE, 0.0f, 0.0f },
498 { BackLeft, DEG2RAD(-150.0f), DEG2RAD(0.0f) },
499 { BackRight, DEG2RAD( 150.0f), DEG2RAD(0.0f) },
500 { SideLeft, DEG2RAD( -90.0f), DEG2RAD(0.0f) },
501 { SideRight, DEG2RAD( 90.0f), DEG2RAD(0.0f) }
504 void CalcPanningAndFilters(ALvoice *voice, const ALfloat Azi, const ALfloat Elev,
505 const ALfloat Distance, const ALfloat Spread,
506 const ALfloat DryGain, const ALfloat DryGainHF,
507 const ALfloat DryGainLF, const ALfloat *WetGain,
508 const ALfloat *WetGainLF, const ALfloat *WetGainHF,
509 ALeffectslot **SendSlots, const ALbuffer *Buffer,
510 const struct ALvoiceProps *props, const ALlistener &Listener,
511 const ALCdevice *Device)
513 struct ChanMap StereoMap[2] = {
514 { FrontLeft, DEG2RAD(-30.0f), DEG2RAD(0.0f) },
515 { FrontRight, DEG2RAD( 30.0f), DEG2RAD(0.0f) }
517 bool DirectChannels = props->DirectChannels;
518 const ALsizei NumSends = Device->NumAuxSends;
519 const ALuint Frequency = Device->Frequency;
520 const struct ChanMap *chans = NULL;
521 ALsizei num_channels = 0;
522 bool isbformat = false;
523 ALfloat downmix_gain = 1.0f;
524 ALsizei c, i;
526 switch(Buffer->FmtChannels)
528 case FmtMono:
529 chans = MonoMap;
530 num_channels = 1;
531 /* Mono buffers are never played direct. */
532 DirectChannels = false;
533 break;
535 case FmtStereo:
536 /* Convert counter-clockwise to clockwise. */
537 StereoMap[0].angle = -props->StereoPan[0];
538 StereoMap[1].angle = -props->StereoPan[1];
540 chans = StereoMap;
541 num_channels = 2;
542 downmix_gain = 1.0f / 2.0f;
543 break;
545 case FmtRear:
546 chans = RearMap;
547 num_channels = 2;
548 downmix_gain = 1.0f / 2.0f;
549 break;
551 case FmtQuad:
552 chans = QuadMap;
553 num_channels = 4;
554 downmix_gain = 1.0f / 4.0f;
555 break;
557 case FmtX51:
558 chans = X51Map;
559 num_channels = 6;
560 /* NOTE: Excludes LFE. */
561 downmix_gain = 1.0f / 5.0f;
562 break;
564 case FmtX61:
565 chans = X61Map;
566 num_channels = 7;
567 /* NOTE: Excludes LFE. */
568 downmix_gain = 1.0f / 6.0f;
569 break;
571 case FmtX71:
572 chans = X71Map;
573 num_channels = 8;
574 /* NOTE: Excludes LFE. */
575 downmix_gain = 1.0f / 7.0f;
576 break;
578 case FmtBFormat2D:
579 num_channels = 3;
580 isbformat = true;
581 DirectChannels = false;
582 break;
584 case FmtBFormat3D:
585 num_channels = 4;
586 isbformat = true;
587 DirectChannels = false;
588 break;
591 for(c = 0;c < num_channels;c++)
593 memset(&voice->Direct.Params[c].Hrtf.Target, 0,
594 sizeof(voice->Direct.Params[c].Hrtf.Target));
595 ClearArray(voice->Direct.Params[c].Gains.Target);
597 for(i = 0;i < NumSends;i++)
599 for(c = 0;c < num_channels;c++)
600 ClearArray(voice->Send[i].Params[c].Gains.Target);
603 voice->Flags &= ~(VOICE_HAS_HRTF | VOICE_HAS_NFC);
604 if(isbformat)
606 /* Special handling for B-Format sources. */
608 if(Distance > FLT_EPSILON)
610 /* Panning a B-Format sound toward some direction is easy. Just pan
611 * the first (W) channel as a normal mono sound and silence the
612 * others.
614 ALfloat coeffs[MAX_AMBI_COEFFS];
616 if(Device->AvgSpeakerDist > 0.0f)
618 ALfloat mdist = Distance * Listener.Params.MetersPerUnit;
619 ALfloat w0 = SPEEDOFSOUNDMETRESPERSEC /
620 (mdist * (ALfloat)Device->Frequency);
621 ALfloat w1 = SPEEDOFSOUNDMETRESPERSEC /
622 (Device->AvgSpeakerDist * (ALfloat)Device->Frequency);
623 /* Clamp w0 for really close distances, to prevent excessive
624 * bass.
626 w0 = minf(w0, w1*4.0f);
628 /* Only need to adjust the first channel of a B-Format source. */
629 NfcFilterAdjust(&voice->Direct.Params[0].NFCtrlFilter, w0);
631 for(i = 0;i < MAX_AMBI_ORDER+1;i++)
632 voice->Direct.ChannelsPerOrder[i] = Device->NumChannelsPerOrder[i];
633 voice->Flags |= VOICE_HAS_NFC;
636 /* A scalar of 1.5 for plain stereo results in +/-60 degrees being
637 * moved to +/-90 degrees for direct right and left speaker
638 * responses.
640 CalcAngleCoeffs((Device->Render_Mode==StereoPair) ? ScaleAzimuthFront(Azi, 1.5f) : Azi,
641 Elev, Spread, coeffs);
643 /* NOTE: W needs to be scaled by sqrt(2) due to FuMa normalization. */
644 ComputePanGains(&Device->Dry, coeffs, DryGain*SQRTF_2,
645 voice->Direct.Params[0].Gains.Target);
646 for(i = 0;i < NumSends;i++)
648 const ALeffectslot *Slot = SendSlots[i];
649 if(Slot)
650 ComputePanningGainsBF(Slot->ChanMap, Slot->NumChannels, coeffs,
651 WetGain[i]*SQRTF_2, voice->Send[i].Params[0].Gains.Target
655 else
657 /* Local B-Format sources have their XYZ channels rotated according
658 * to the orientation.
660 ALfloat N[3], V[3], U[3];
661 aluMatrixf matrix;
663 if(Device->AvgSpeakerDist > 0.0f)
665 /* NOTE: The NFCtrlFilters were created with a w0 of 0, which
666 * is what we want for FOA input. The first channel may have
667 * been previously re-adjusted if panned, so reset it.
669 NfcFilterAdjust(&voice->Direct.Params[0].NFCtrlFilter, 0.0f);
671 voice->Direct.ChannelsPerOrder[0] = 1;
672 voice->Direct.ChannelsPerOrder[1] = mini(voice->Direct.Channels-1, 3);
673 for(i = 2;i < MAX_AMBI_ORDER+1;i++)
674 voice->Direct.ChannelsPerOrder[i] = 0;
675 voice->Flags |= VOICE_HAS_NFC;
678 /* AT then UP */
679 N[0] = props->Orientation[0][0];
680 N[1] = props->Orientation[0][1];
681 N[2] = props->Orientation[0][2];
682 aluNormalize(N);
683 V[0] = props->Orientation[1][0];
684 V[1] = props->Orientation[1][1];
685 V[2] = props->Orientation[1][2];
686 aluNormalize(V);
687 if(!props->HeadRelative)
689 const aluMatrixf *lmatrix = &Listener.Params.Matrix;
690 aluMatrixfFloat3(N, 0.0f, lmatrix);
691 aluMatrixfFloat3(V, 0.0f, lmatrix);
693 /* Build and normalize right-vector */
694 aluCrossproduct(N, V, U);
695 aluNormalize(U);
697 /* Build a rotate + conversion matrix (FuMa -> ACN+N3D). NOTE: This
698 * matrix is transposed, for the inputs to align on the rows and
699 * outputs on the columns.
701 aluMatrixfSet(&matrix,
702 // ACN0 ACN1 ACN2 ACN3
703 SQRTF_2, 0.0f, 0.0f, 0.0f, // Ambi W
704 0.0f, -N[0]*SQRTF_3, N[1]*SQRTF_3, -N[2]*SQRTF_3, // Ambi X
705 0.0f, U[0]*SQRTF_3, -U[1]*SQRTF_3, U[2]*SQRTF_3, // Ambi Y
706 0.0f, -V[0]*SQRTF_3, V[1]*SQRTF_3, -V[2]*SQRTF_3 // Ambi Z
709 voice->Direct.Buffer = Device->FOAOut.Buffer;
710 voice->Direct.Channels = Device->FOAOut.NumChannels;
711 for(c = 0;c < num_channels;c++)
712 ComputePanGains(&Device->FOAOut, matrix.m[c], DryGain,
713 voice->Direct.Params[c].Gains.Target);
714 for(i = 0;i < NumSends;i++)
716 const ALeffectslot *Slot = SendSlots[i];
717 if(Slot)
719 for(c = 0;c < num_channels;c++)
720 ComputePanningGainsBF(Slot->ChanMap, Slot->NumChannels,
721 matrix.m[c], WetGain[i], voice->Send[i].Params[c].Gains.Target
727 else if(DirectChannels)
729 /* Direct source channels always play local. Skip the virtual channels
730 * and write inputs to the matching real outputs.
732 voice->Direct.Buffer = Device->RealOut.Buffer;
733 voice->Direct.Channels = Device->RealOut.NumChannels;
735 for(c = 0;c < num_channels;c++)
737 int idx = GetChannelIdxByName(&Device->RealOut, chans[c].channel);
738 if(idx != -1) voice->Direct.Params[c].Gains.Target[idx] = DryGain;
741 /* Auxiliary sends still use normal channel panning since they mix to
742 * B-Format, which can't channel-match.
744 for(c = 0;c < num_channels;c++)
746 ALfloat coeffs[MAX_AMBI_COEFFS];
747 CalcAngleCoeffs(chans[c].angle, chans[c].elevation, 0.0f, coeffs);
749 for(i = 0;i < NumSends;i++)
751 const ALeffectslot *Slot = SendSlots[i];
752 if(Slot)
753 ComputePanningGainsBF(Slot->ChanMap, Slot->NumChannels,
754 coeffs, WetGain[i], voice->Send[i].Params[c].Gains.Target
759 else if(Device->Render_Mode == HrtfRender)
761 /* Full HRTF rendering. Skip the virtual channels and render to the
762 * real outputs.
764 voice->Direct.Buffer = Device->RealOut.Buffer;
765 voice->Direct.Channels = Device->RealOut.NumChannels;
767 if(Distance > FLT_EPSILON)
769 ALfloat coeffs[MAX_AMBI_COEFFS];
771 /* Get the HRIR coefficients and delays just once, for the given
772 * source direction.
774 GetHrtfCoeffs(Device->HrtfHandle, Elev, Azi, Spread,
775 voice->Direct.Params[0].Hrtf.Target.Coeffs,
776 voice->Direct.Params[0].Hrtf.Target.Delay);
777 voice->Direct.Params[0].Hrtf.Target.Gain = DryGain * downmix_gain;
779 /* Remaining channels use the same results as the first. */
780 for(c = 1;c < num_channels;c++)
782 /* Skip LFE */
783 if(chans[c].channel != LFE)
784 voice->Direct.Params[c].Hrtf.Target = voice->Direct.Params[0].Hrtf.Target;
787 /* Calculate the directional coefficients once, which apply to all
788 * input channels of the source sends.
790 CalcAngleCoeffs(Azi, Elev, Spread, coeffs);
792 for(i = 0;i < NumSends;i++)
794 const ALeffectslot *Slot = SendSlots[i];
795 if(Slot)
796 for(c = 0;c < num_channels;c++)
798 /* Skip LFE */
799 if(chans[c].channel != LFE)
800 ComputePanningGainsBF(Slot->ChanMap,
801 Slot->NumChannels, coeffs, WetGain[i] * downmix_gain,
802 voice->Send[i].Params[c].Gains.Target
807 else
809 /* Local sources on HRTF play with each channel panned to its
810 * relative location around the listener, providing "virtual
811 * speaker" responses.
813 for(c = 0;c < num_channels;c++)
815 ALfloat coeffs[MAX_AMBI_COEFFS];
817 if(chans[c].channel == LFE)
819 /* Skip LFE */
820 continue;
823 /* Get the HRIR coefficients and delays for this channel
824 * position.
826 GetHrtfCoeffs(Device->HrtfHandle,
827 chans[c].elevation, chans[c].angle, Spread,
828 voice->Direct.Params[c].Hrtf.Target.Coeffs,
829 voice->Direct.Params[c].Hrtf.Target.Delay
831 voice->Direct.Params[c].Hrtf.Target.Gain = DryGain;
833 /* Normal panning for auxiliary sends. */
834 CalcAngleCoeffs(chans[c].angle, chans[c].elevation, Spread, coeffs);
836 for(i = 0;i < NumSends;i++)
838 const ALeffectslot *Slot = SendSlots[i];
839 if(Slot)
840 ComputePanningGainsBF(Slot->ChanMap, Slot->NumChannels,
841 coeffs, WetGain[i], voice->Send[i].Params[c].Gains.Target
847 voice->Flags |= VOICE_HAS_HRTF;
849 else
851 /* Non-HRTF rendering. Use normal panning to the output. */
853 if(Distance > FLT_EPSILON)
855 ALfloat coeffs[MAX_AMBI_COEFFS];
856 ALfloat w0 = 0.0f;
858 /* Calculate NFC filter coefficient if needed. */
859 if(Device->AvgSpeakerDist > 0.0f)
861 ALfloat mdist = Distance * Listener.Params.MetersPerUnit;
862 ALfloat w1 = SPEEDOFSOUNDMETRESPERSEC /
863 (Device->AvgSpeakerDist * (ALfloat)Device->Frequency);
864 w0 = SPEEDOFSOUNDMETRESPERSEC /
865 (mdist * (ALfloat)Device->Frequency);
866 /* Clamp w0 for really close distances, to prevent excessive
867 * bass.
869 w0 = minf(w0, w1*4.0f);
871 /* Adjust NFC filters. */
872 for(c = 0;c < num_channels;c++)
873 NfcFilterAdjust(&voice->Direct.Params[c].NFCtrlFilter, w0);
875 for(i = 0;i < MAX_AMBI_ORDER+1;i++)
876 voice->Direct.ChannelsPerOrder[i] = Device->NumChannelsPerOrder[i];
877 voice->Flags |= VOICE_HAS_NFC;
880 /* Calculate the directional coefficients once, which apply to all
881 * input channels.
883 CalcAngleCoeffs((Device->Render_Mode==StereoPair) ? ScaleAzimuthFront(Azi, 1.5f) : Azi,
884 Elev, Spread, coeffs);
886 for(c = 0;c < num_channels;c++)
888 /* Special-case LFE */
889 if(chans[c].channel == LFE)
891 if(Device->Dry.Buffer == Device->RealOut.Buffer)
893 int idx = GetChannelIdxByName(&Device->RealOut, chans[c].channel);
894 if(idx != -1) voice->Direct.Params[c].Gains.Target[idx] = DryGain;
896 continue;
899 ComputePanGains(&Device->Dry, coeffs, DryGain * downmix_gain,
900 voice->Direct.Params[c].Gains.Target);
903 for(i = 0;i < NumSends;i++)
905 const ALeffectslot *Slot = SendSlots[i];
906 if(Slot)
907 for(c = 0;c < num_channels;c++)
909 /* Skip LFE */
910 if(chans[c].channel != LFE)
911 ComputePanningGainsBF(Slot->ChanMap,
912 Slot->NumChannels, coeffs, WetGain[i] * downmix_gain,
913 voice->Send[i].Params[c].Gains.Target
918 else
920 ALfloat w0 = 0.0f;
922 if(Device->AvgSpeakerDist > 0.0f)
924 /* If the source distance is 0, set w0 to w1 to act as a pass-
925 * through. We still want to pass the signal through the
926 * filters so they keep an appropriate history, in case the
927 * source moves away from the listener.
929 w0 = SPEEDOFSOUNDMETRESPERSEC /
930 (Device->AvgSpeakerDist * (ALfloat)Device->Frequency);
932 for(c = 0;c < num_channels;c++)
933 NfcFilterAdjust(&voice->Direct.Params[c].NFCtrlFilter, w0);
935 for(i = 0;i < MAX_AMBI_ORDER+1;i++)
936 voice->Direct.ChannelsPerOrder[i] = Device->NumChannelsPerOrder[i];
937 voice->Flags |= VOICE_HAS_NFC;
940 for(c = 0;c < num_channels;c++)
942 ALfloat coeffs[MAX_AMBI_COEFFS];
944 /* Special-case LFE */
945 if(chans[c].channel == LFE)
947 if(Device->Dry.Buffer == Device->RealOut.Buffer)
949 int idx = GetChannelIdxByName(&Device->RealOut, chans[c].channel);
950 if(idx != -1) voice->Direct.Params[c].Gains.Target[idx] = DryGain;
952 continue;
955 CalcAngleCoeffs(
956 (Device->Render_Mode==StereoPair) ? ScaleAzimuthFront(chans[c].angle, 3.0f)
957 : chans[c].angle,
958 chans[c].elevation, Spread, coeffs
961 ComputePanGains(&Device->Dry, coeffs, DryGain,
962 voice->Direct.Params[c].Gains.Target);
963 for(i = 0;i < NumSends;i++)
965 const ALeffectslot *Slot = SendSlots[i];
966 if(Slot)
967 ComputePanningGainsBF(Slot->ChanMap, Slot->NumChannels,
968 coeffs, WetGain[i], voice->Send[i].Params[c].Gains.Target
976 ALfloat hfScale = props->Direct.HFReference / Frequency;
977 ALfloat lfScale = props->Direct.LFReference / Frequency;
978 ALfloat gainHF = maxf(DryGainHF, 0.001f); /* Limit -60dB */
979 ALfloat gainLF = maxf(DryGainLF, 0.001f);
981 voice->Direct.FilterType = AF_None;
982 if(gainHF != 1.0f) voice->Direct.FilterType |= AF_LowPass;
983 if(gainLF != 1.0f) voice->Direct.FilterType |= AF_HighPass;
984 BiquadFilter_setParams(
985 &voice->Direct.Params[0].LowPass, BiquadType::HighShelf,
986 gainHF, hfScale, calc_rcpQ_from_slope(gainHF, 1.0f)
988 BiquadFilter_setParams(
989 &voice->Direct.Params[0].HighPass, BiquadType::LowShelf,
990 gainLF, lfScale, calc_rcpQ_from_slope(gainLF, 1.0f)
992 for(c = 1;c < num_channels;c++)
994 BiquadFilter_copyParams(&voice->Direct.Params[c].LowPass,
995 &voice->Direct.Params[0].LowPass);
996 BiquadFilter_copyParams(&voice->Direct.Params[c].HighPass,
997 &voice->Direct.Params[0].HighPass);
1000 for(i = 0;i < NumSends;i++)
1002 ALfloat hfScale = props->Send[i].HFReference / Frequency;
1003 ALfloat lfScale = props->Send[i].LFReference / Frequency;
1004 ALfloat gainHF = maxf(WetGainHF[i], 0.001f);
1005 ALfloat gainLF = maxf(WetGainLF[i], 0.001f);
1007 voice->Send[i].FilterType = AF_None;
1008 if(gainHF != 1.0f) voice->Send[i].FilterType |= AF_LowPass;
1009 if(gainLF != 1.0f) voice->Send[i].FilterType |= AF_HighPass;
1010 BiquadFilter_setParams(
1011 &voice->Send[i].Params[0].LowPass, BiquadType::HighShelf,
1012 gainHF, hfScale, calc_rcpQ_from_slope(gainHF, 1.0f)
1014 BiquadFilter_setParams(
1015 &voice->Send[i].Params[0].HighPass, BiquadType::LowShelf,
1016 gainLF, lfScale, calc_rcpQ_from_slope(gainLF, 1.0f)
1018 for(c = 1;c < num_channels;c++)
1020 BiquadFilter_copyParams(&voice->Send[i].Params[c].LowPass,
1021 &voice->Send[i].Params[0].LowPass);
1022 BiquadFilter_copyParams(&voice->Send[i].Params[c].HighPass,
1023 &voice->Send[i].Params[0].HighPass);
1028 void CalcNonAttnSourceParams(ALvoice *voice, const struct ALvoiceProps *props, const ALbuffer *ALBuffer, const ALCcontext *ALContext)
1030 const ALCdevice *Device = ALContext->Device;
1031 const ALlistener &Listener = ALContext->Listener;
1032 ALfloat DryGain, DryGainHF, DryGainLF;
1033 ALfloat WetGain[MAX_SENDS];
1034 ALfloat WetGainHF[MAX_SENDS];
1035 ALfloat WetGainLF[MAX_SENDS];
1036 ALeffectslot *SendSlots[MAX_SENDS];
1037 ALfloat Pitch;
1038 ALsizei i;
1040 voice->Direct.Buffer = Device->Dry.Buffer;
1041 voice->Direct.Channels = Device->Dry.NumChannels;
1042 for(i = 0;i < Device->NumAuxSends;i++)
1044 SendSlots[i] = props->Send[i].Slot;
1045 if(!SendSlots[i] && i == 0)
1046 SendSlots[i] = ALContext->DefaultSlot;
1047 if(!SendSlots[i] || SendSlots[i]->Params.EffectType == AL_EFFECT_NULL)
1049 SendSlots[i] = NULL;
1050 voice->Send[i].Buffer = NULL;
1051 voice->Send[i].Channels = 0;
1053 else
1055 voice->Send[i].Buffer = SendSlots[i]->WetBuffer;
1056 voice->Send[i].Channels = SendSlots[i]->NumChannels;
1060 /* Calculate the stepping value */
1061 Pitch = (ALfloat)ALBuffer->Frequency/(ALfloat)Device->Frequency * props->Pitch;
1062 if(Pitch > (ALfloat)MAX_PITCH)
1063 voice->Step = MAX_PITCH<<FRACTIONBITS;
1064 else
1065 voice->Step = maxi(fastf2i(Pitch * FRACTIONONE), 1);
1066 if(props->Resampler == BSinc24Resampler)
1067 BsincPrepare(voice->Step, &voice->ResampleState.bsinc, &bsinc24);
1068 else if(props->Resampler == BSinc12Resampler)
1069 BsincPrepare(voice->Step, &voice->ResampleState.bsinc, &bsinc12);
1070 voice->Resampler = SelectResampler(props->Resampler);
1072 /* Calculate gains */
1073 DryGain = clampf(props->Gain, props->MinGain, props->MaxGain);
1074 DryGain *= props->Direct.Gain * Listener.Params.Gain;
1075 DryGain = minf(DryGain, GAIN_MIX_MAX);
1076 DryGainHF = props->Direct.GainHF;
1077 DryGainLF = props->Direct.GainLF;
1078 for(i = 0;i < Device->NumAuxSends;i++)
1080 WetGain[i] = clampf(props->Gain, props->MinGain, props->MaxGain);
1081 WetGain[i] *= props->Send[i].Gain * Listener.Params.Gain;
1082 WetGain[i] = minf(WetGain[i], GAIN_MIX_MAX);
1083 WetGainHF[i] = props->Send[i].GainHF;
1084 WetGainLF[i] = props->Send[i].GainLF;
1087 CalcPanningAndFilters(voice, 0.0f, 0.0f, 0.0f, 0.0f, DryGain, DryGainHF, DryGainLF, WetGain,
1088 WetGainLF, WetGainHF, SendSlots, ALBuffer, props, Listener, Device);
1091 void CalcAttnSourceParams(ALvoice *voice, const struct ALvoiceProps *props, const ALbuffer *ALBuffer, const ALCcontext *ALContext)
1093 const ALCdevice *Device = ALContext->Device;
1094 const ALlistener &Listener = ALContext->Listener;
1095 const ALsizei NumSends = Device->NumAuxSends;
1096 aluVector Position, Velocity, Direction, SourceToListener;
1097 ALfloat Distance, ClampedDist, DopplerFactor;
1098 ALeffectslot *SendSlots[MAX_SENDS];
1099 ALfloat RoomRolloff[MAX_SENDS];
1100 ALfloat DecayDistance[MAX_SENDS];
1101 ALfloat DecayLFDistance[MAX_SENDS];
1102 ALfloat DecayHFDistance[MAX_SENDS];
1103 ALfloat DryGain, DryGainHF, DryGainLF;
1104 ALfloat WetGain[MAX_SENDS];
1105 ALfloat WetGainHF[MAX_SENDS];
1106 ALfloat WetGainLF[MAX_SENDS];
1107 bool directional;
1108 ALfloat ev, az;
1109 ALfloat spread;
1110 ALfloat Pitch;
1111 ALint i;
1113 /* Set mixing buffers and get send parameters. */
1114 voice->Direct.Buffer = Device->Dry.Buffer;
1115 voice->Direct.Channels = Device->Dry.NumChannels;
1116 for(i = 0;i < NumSends;i++)
1118 SendSlots[i] = props->Send[i].Slot;
1119 if(!SendSlots[i] && i == 0)
1120 SendSlots[i] = ALContext->DefaultSlot;
1121 if(!SendSlots[i] || SendSlots[i]->Params.EffectType == AL_EFFECT_NULL)
1123 SendSlots[i] = NULL;
1124 RoomRolloff[i] = 0.0f;
1125 DecayDistance[i] = 0.0f;
1126 DecayLFDistance[i] = 0.0f;
1127 DecayHFDistance[i] = 0.0f;
1129 else if(SendSlots[i]->Params.AuxSendAuto)
1131 RoomRolloff[i] = SendSlots[i]->Params.RoomRolloff + props->RoomRolloffFactor;
1132 /* Calculate the distances to where this effect's decay reaches
1133 * -60dB.
1135 DecayDistance[i] = SendSlots[i]->Params.DecayTime *
1136 Listener.Params.ReverbSpeedOfSound;
1137 DecayLFDistance[i] = DecayDistance[i] * SendSlots[i]->Params.DecayLFRatio;
1138 DecayHFDistance[i] = DecayDistance[i] * SendSlots[i]->Params.DecayHFRatio;
1139 if(SendSlots[i]->Params.DecayHFLimit)
1141 ALfloat airAbsorption = SendSlots[i]->Params.AirAbsorptionGainHF;
1142 if(airAbsorption < 1.0f)
1144 /* Calculate the distance to where this effect's air
1145 * absorption reaches -60dB, and limit the effect's HF
1146 * decay distance (so it doesn't take any longer to decay
1147 * than the air would allow).
1149 ALfloat absorb_dist = log10f(REVERB_DECAY_GAIN) / log10f(airAbsorption);
1150 DecayHFDistance[i] = minf(absorb_dist, DecayHFDistance[i]);
1154 else
1156 /* If the slot's auxiliary send auto is off, the data sent to the
1157 * effect slot is the same as the dry path, sans filter effects */
1158 RoomRolloff[i] = props->RolloffFactor;
1159 DecayDistance[i] = 0.0f;
1160 DecayLFDistance[i] = 0.0f;
1161 DecayHFDistance[i] = 0.0f;
1164 if(!SendSlots[i])
1166 voice->Send[i].Buffer = NULL;
1167 voice->Send[i].Channels = 0;
1169 else
1171 voice->Send[i].Buffer = SendSlots[i]->WetBuffer;
1172 voice->Send[i].Channels = SendSlots[i]->NumChannels;
1176 /* Transform source to listener space (convert to head relative) */
1177 aluVectorSet(&Position, props->Position[0], props->Position[1], props->Position[2], 1.0f);
1178 aluVectorSet(&Direction, props->Direction[0], props->Direction[1], props->Direction[2], 0.0f);
1179 aluVectorSet(&Velocity, props->Velocity[0], props->Velocity[1], props->Velocity[2], 0.0f);
1180 if(props->HeadRelative == AL_FALSE)
1182 const aluMatrixf *Matrix = &Listener.Params.Matrix;
1183 /* Transform source vectors */
1184 Position = aluMatrixfVector(Matrix, &Position);
1185 Velocity = aluMatrixfVector(Matrix, &Velocity);
1186 Direction = aluMatrixfVector(Matrix, &Direction);
1188 else
1190 const aluVector *lvelocity = &Listener.Params.Velocity;
1191 /* Offset the source velocity to be relative of the listener velocity */
1192 Velocity.v[0] += lvelocity->v[0];
1193 Velocity.v[1] += lvelocity->v[1];
1194 Velocity.v[2] += lvelocity->v[2];
1197 directional = aluNormalize(Direction.v) > 0.0f;
1198 SourceToListener.v[0] = -Position.v[0];
1199 SourceToListener.v[1] = -Position.v[1];
1200 SourceToListener.v[2] = -Position.v[2];
1201 SourceToListener.v[3] = 0.0f;
1202 Distance = aluNormalize(SourceToListener.v);
1204 /* Initial source gain */
1205 DryGain = props->Gain;
1206 DryGainHF = 1.0f;
1207 DryGainLF = 1.0f;
1208 for(i = 0;i < NumSends;i++)
1210 WetGain[i] = props->Gain;
1211 WetGainHF[i] = 1.0f;
1212 WetGainLF[i] = 1.0f;
1215 /* Calculate distance attenuation */
1216 ClampedDist = Distance;
1218 switch(Listener.Params.SourceDistanceModel ?
1219 props->mDistanceModel : Listener.Params.mDistanceModel)
1221 case DistanceModel::InverseClamped:
1222 ClampedDist = clampf(ClampedDist, props->RefDistance, props->MaxDistance);
1223 if(props->MaxDistance < props->RefDistance)
1224 break;
1225 /*fall-through*/
1226 case DistanceModel::Inverse:
1227 if(!(props->RefDistance > 0.0f))
1228 ClampedDist = props->RefDistance;
1229 else
1231 ALfloat dist = lerp(props->RefDistance, ClampedDist, props->RolloffFactor);
1232 if(dist > 0.0f) DryGain *= props->RefDistance / dist;
1233 for(i = 0;i < NumSends;i++)
1235 dist = lerp(props->RefDistance, ClampedDist, RoomRolloff[i]);
1236 if(dist > 0.0f) WetGain[i] *= props->RefDistance / dist;
1239 break;
1241 case DistanceModel::LinearClamped:
1242 ClampedDist = clampf(ClampedDist, props->RefDistance, props->MaxDistance);
1243 if(props->MaxDistance < props->RefDistance)
1244 break;
1245 /*fall-through*/
1246 case DistanceModel::Linear:
1247 if(!(props->MaxDistance != props->RefDistance))
1248 ClampedDist = props->RefDistance;
1249 else
1251 ALfloat attn = props->RolloffFactor * (ClampedDist-props->RefDistance) /
1252 (props->MaxDistance-props->RefDistance);
1253 DryGain *= maxf(1.0f - attn, 0.0f);
1254 for(i = 0;i < NumSends;i++)
1256 attn = RoomRolloff[i] * (ClampedDist-props->RefDistance) /
1257 (props->MaxDistance-props->RefDistance);
1258 WetGain[i] *= maxf(1.0f - attn, 0.0f);
1261 break;
1263 case DistanceModel::ExponentClamped:
1264 ClampedDist = clampf(ClampedDist, props->RefDistance, props->MaxDistance);
1265 if(props->MaxDistance < props->RefDistance)
1266 break;
1267 /*fall-through*/
1268 case DistanceModel::Exponent:
1269 if(!(ClampedDist > 0.0f && props->RefDistance > 0.0f))
1270 ClampedDist = props->RefDistance;
1271 else
1273 DryGain *= powf(ClampedDist/props->RefDistance, -props->RolloffFactor);
1274 for(i = 0;i < NumSends;i++)
1275 WetGain[i] *= powf(ClampedDist/props->RefDistance, -RoomRolloff[i]);
1277 break;
1279 case DistanceModel::Disable:
1280 ClampedDist = props->RefDistance;
1281 break;
1284 /* Calculate directional soundcones */
1285 if(directional && props->InnerAngle < 360.0f)
1287 ALfloat ConeVolume;
1288 ALfloat ConeHF;
1289 ALfloat Angle;
1291 Angle = acosf(aluDotproduct(&Direction, &SourceToListener));
1292 Angle = RAD2DEG(Angle * ConeScale * 2.0f);
1293 if(!(Angle > props->InnerAngle))
1295 ConeVolume = 1.0f;
1296 ConeHF = 1.0f;
1298 else if(Angle < props->OuterAngle)
1300 ALfloat scale = ( Angle-props->InnerAngle) /
1301 (props->OuterAngle-props->InnerAngle);
1302 ConeVolume = lerp(1.0f, props->OuterGain, scale);
1303 ConeHF = lerp(1.0f, props->OuterGainHF, scale);
1305 else
1307 ConeVolume = props->OuterGain;
1308 ConeHF = props->OuterGainHF;
1311 DryGain *= ConeVolume;
1312 if(props->DryGainHFAuto)
1313 DryGainHF *= ConeHF;
1314 if(props->WetGainAuto)
1316 for(i = 0;i < NumSends;i++)
1317 WetGain[i] *= ConeVolume;
1319 if(props->WetGainHFAuto)
1321 for(i = 0;i < NumSends;i++)
1322 WetGainHF[i] *= ConeHF;
1326 /* Apply gain and frequency filters */
1327 DryGain = clampf(DryGain, props->MinGain, props->MaxGain);
1328 DryGain = minf(DryGain*props->Direct.Gain*Listener.Params.Gain, GAIN_MIX_MAX);
1329 DryGainHF *= props->Direct.GainHF;
1330 DryGainLF *= props->Direct.GainLF;
1331 for(i = 0;i < NumSends;i++)
1333 WetGain[i] = clampf(WetGain[i], props->MinGain, props->MaxGain);
1334 WetGain[i] = minf(WetGain[i]*props->Send[i].Gain*Listener.Params.Gain, GAIN_MIX_MAX);
1335 WetGainHF[i] *= props->Send[i].GainHF;
1336 WetGainLF[i] *= props->Send[i].GainLF;
1339 /* Distance-based air absorption and initial send decay. */
1340 if(ClampedDist > props->RefDistance && props->RolloffFactor > 0.0f)
1342 ALfloat meters_base = (ClampedDist-props->RefDistance) * props->RolloffFactor *
1343 Listener.Params.MetersPerUnit;
1344 if(props->AirAbsorptionFactor > 0.0f)
1346 ALfloat hfattn = powf(AIRABSORBGAINHF, meters_base * props->AirAbsorptionFactor);
1347 DryGainHF *= hfattn;
1348 for(i = 0;i < NumSends;i++)
1349 WetGainHF[i] *= hfattn;
1352 if(props->WetGainAuto)
1354 /* Apply a decay-time transformation to the wet path, based on the
1355 * source distance in meters. The initial decay of the reverb
1356 * effect is calculated and applied to the wet path.
1358 for(i = 0;i < NumSends;i++)
1360 ALfloat gain, gainhf, gainlf;
1362 if(!(DecayDistance[i] > 0.0f))
1363 continue;
1365 gain = powf(REVERB_DECAY_GAIN, meters_base/DecayDistance[i]);
1366 WetGain[i] *= gain;
1367 /* Yes, the wet path's air absorption is applied with
1368 * WetGainAuto on, rather than WetGainHFAuto.
1370 if(gain > 0.0f)
1372 gainhf = powf(REVERB_DECAY_GAIN, meters_base/DecayHFDistance[i]);
1373 WetGainHF[i] *= minf(gainhf / gain, 1.0f);
1374 gainlf = powf(REVERB_DECAY_GAIN, meters_base/DecayLFDistance[i]);
1375 WetGainLF[i] *= minf(gainlf / gain, 1.0f);
1382 /* Initial source pitch */
1383 Pitch = props->Pitch;
1385 /* Calculate velocity-based doppler effect */
1386 DopplerFactor = props->DopplerFactor * Listener.Params.DopplerFactor;
1387 if(DopplerFactor > 0.0f)
1389 const aluVector *lvelocity = &Listener.Params.Velocity;
1390 const ALfloat SpeedOfSound = Listener.Params.SpeedOfSound;
1391 ALfloat vss, vls;
1393 vss = aluDotproduct(&Velocity, &SourceToListener) * DopplerFactor;
1394 vls = aluDotproduct(lvelocity, &SourceToListener) * DopplerFactor;
1396 if(!(vls < SpeedOfSound))
1398 /* Listener moving away from the source at the speed of sound.
1399 * Sound waves can't catch it.
1401 Pitch = 0.0f;
1403 else if(!(vss < SpeedOfSound))
1405 /* Source moving toward the listener at the speed of sound. Sound
1406 * waves bunch up to extreme frequencies.
1408 Pitch = HUGE_VALF;
1410 else
1412 /* Source and listener movement is nominal. Calculate the proper
1413 * doppler shift.
1415 Pitch *= (SpeedOfSound-vls) / (SpeedOfSound-vss);
1419 /* Adjust pitch based on the buffer and output frequencies, and calculate
1420 * fixed-point stepping value.
1422 Pitch *= (ALfloat)ALBuffer->Frequency/(ALfloat)Device->Frequency;
1423 if(Pitch > (ALfloat)MAX_PITCH)
1424 voice->Step = MAX_PITCH<<FRACTIONBITS;
1425 else
1426 voice->Step = maxi(fastf2i(Pitch * FRACTIONONE), 1);
1427 if(props->Resampler == BSinc24Resampler)
1428 BsincPrepare(voice->Step, &voice->ResampleState.bsinc, &bsinc24);
1429 else if(props->Resampler == BSinc12Resampler)
1430 BsincPrepare(voice->Step, &voice->ResampleState.bsinc, &bsinc12);
1431 voice->Resampler = SelectResampler(props->Resampler);
1433 if(Distance > 0.0f)
1435 /* Clamp Y, in case rounding errors caused it to end up outside of
1436 * -1...+1.
1438 ev = asinf(clampf(-SourceToListener.v[1], -1.0f, 1.0f));
1439 /* Double negation on Z cancels out; negate once for changing source-
1440 * to-listener to listener-to-source, and again for right-handed coords
1441 * with -Z in front.
1443 az = atan2f(-SourceToListener.v[0], SourceToListener.v[2]*ZScale);
1445 else
1446 ev = az = 0.0f;
1448 if(props->Radius > Distance)
1449 spread = F_TAU - Distance/props->Radius*F_PI;
1450 else if(Distance > 0.0f)
1451 spread = asinf(props->Radius / Distance) * 2.0f;
1452 else
1453 spread = 0.0f;
1455 CalcPanningAndFilters(voice, az, ev, Distance, spread, DryGain, DryGainHF, DryGainLF, WetGain,
1456 WetGainLF, WetGainHF, SendSlots, ALBuffer, props, Listener, Device);
1459 void CalcSourceParams(ALvoice *voice, ALCcontext *context, bool force)
1461 ALbufferlistitem *BufferListItem;
1462 struct ALvoiceProps *props;
1464 props = voice->Update.exchange(nullptr, std::memory_order_acq_rel);
1465 if(!props && !force) return;
1467 if(props)
1469 memcpy(voice->Props, props,
1470 FAM_SIZE(struct ALvoiceProps, Send, context->Device->NumAuxSends)
1473 AtomicReplaceHead(context->FreeVoiceProps, props);
1475 props = voice->Props;
1477 BufferListItem = ATOMIC_LOAD(&voice->current_buffer, almemory_order_relaxed);
1478 while(BufferListItem != NULL)
1480 const ALbuffer *buffer = NULL;
1481 ALsizei i = 0;
1482 while(!buffer && i < BufferListItem->num_buffers)
1483 buffer = BufferListItem->buffers[i];
1484 if(LIKELY(buffer))
1486 if(props->SpatializeMode == SpatializeOn ||
1487 (props->SpatializeMode == SpatializeAuto && buffer->FmtChannels == FmtMono))
1488 CalcAttnSourceParams(voice, props, buffer, context);
1489 else
1490 CalcNonAttnSourceParams(voice, props, buffer, context);
1491 break;
1493 BufferListItem = ATOMIC_LOAD(&BufferListItem->next, almemory_order_acquire);
1498 void ProcessParamUpdates(ALCcontext *ctx, const struct ALeffectslotArray *slots)
1500 ALvoice **voice, **voice_end;
1501 ALsource *source;
1502 ALsizei i;
1504 IncrementRef(&ctx->UpdateCount);
1505 if(!ATOMIC_LOAD(&ctx->HoldUpdates, almemory_order_acquire))
1507 bool cforce = CalcContextParams(ctx);
1508 bool force = CalcListenerParams(ctx) | cforce;
1509 for(i = 0;i < slots->count;i++)
1510 force |= CalcEffectSlotParams(slots->slot[i], ctx, cforce);
1512 voice = ctx->Voices;
1513 voice_end = voice + ctx->VoiceCount;
1514 for(;voice != voice_end;++voice)
1516 source = ATOMIC_LOAD(&(*voice)->Source, almemory_order_acquire);
1517 if(source) CalcSourceParams(*voice, ctx, force);
1520 IncrementRef(&ctx->UpdateCount);
1524 void ApplyStablizer(FrontStablizer *Stablizer, ALfloat (*RESTRICT Buffer)[BUFFERSIZE],
1525 int lidx, int ridx, int cidx, ALsizei SamplesToDo, ALsizei NumChannels)
1527 ALfloat (*RESTRICT lsplit)[BUFFERSIZE] = Stablizer->LSplit;
1528 ALfloat (*RESTRICT rsplit)[BUFFERSIZE] = Stablizer->RSplit;
1529 ALsizei i;
1531 /* Apply an all-pass to all channels, except the front-left and front-
1532 * right, so they maintain the same relative phase.
1534 for(i = 0;i < NumChannels;i++)
1536 if(i == lidx || i == ridx)
1537 continue;
1538 splitterap_process(&Stablizer->APFilter[i], Buffer[i], SamplesToDo);
1541 bandsplit_process(&Stablizer->LFilter, lsplit[1], lsplit[0], Buffer[lidx], SamplesToDo);
1542 bandsplit_process(&Stablizer->RFilter, rsplit[1], rsplit[0], Buffer[ridx], SamplesToDo);
1544 for(i = 0;i < SamplesToDo;i++)
1546 ALfloat lfsum, hfsum;
1547 ALfloat m, s, c;
1549 lfsum = lsplit[0][i] + rsplit[0][i];
1550 hfsum = lsplit[1][i] + rsplit[1][i];
1551 s = lsplit[0][i] + lsplit[1][i] - rsplit[0][i] - rsplit[1][i];
1553 /* This pans the separate low- and high-frequency sums between being on
1554 * the center channel and the left/right channels. The low-frequency
1555 * sum is 1/3rd toward center (2/3rds on left/right) and the high-
1556 * frequency sum is 1/4th toward center (3/4ths on left/right). These
1557 * values can be tweaked.
1559 m = lfsum*cosf(1.0f/3.0f * F_PI_2) + hfsum*cosf(1.0f/4.0f * F_PI_2);
1560 c = lfsum*sinf(1.0f/3.0f * F_PI_2) + hfsum*sinf(1.0f/4.0f * F_PI_2);
1562 /* The generated center channel signal adds to the existing signal,
1563 * while the modified left and right channels replace.
1565 Buffer[lidx][i] = (m + s) * 0.5f;
1566 Buffer[ridx][i] = (m - s) * 0.5f;
1567 Buffer[cidx][i] += c * 0.5f;
1571 void ApplyDistanceComp(ALfloat (*RESTRICT Samples)[BUFFERSIZE], DistanceComp *distcomp,
1572 ALfloat *RESTRICT Values, ALsizei SamplesToDo, ALsizei numchans)
1574 ALsizei i, c;
1576 for(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)
1587 for(i = 0;i < SamplesToDo;i++)
1588 inout[i] *= gain;
1590 continue;
1593 if(LIKELY(SamplesToDo >= base))
1595 for(i = 0;i < base;i++)
1596 Values[i] = distbuf[i];
1597 for(;i < SamplesToDo;i++)
1598 Values[i] = inout[i-base];
1599 memcpy(distbuf, &inout[SamplesToDo-base], base*sizeof(ALfloat));
1601 else
1603 for(i = 0;i < SamplesToDo;i++)
1604 Values[i] = distbuf[i];
1605 memmove(distbuf, distbuf+SamplesToDo, (base-SamplesToDo)*sizeof(ALfloat));
1606 memcpy(distbuf+base-SamplesToDo, inout, SamplesToDo*sizeof(ALfloat));
1608 for(i = 0;i < SamplesToDo;i++)
1609 inout[i] = Values[i]*gain;
1613 void ApplyDither(ALfloat (*RESTRICT Samples)[BUFFERSIZE], ALuint *dither_seed,
1614 const ALfloat quant_scale, const ALsizei SamplesToDo, const ALsizei numchans)
1616 const ALfloat invscale = 1.0f / quant_scale;
1617 ALuint seed = *dither_seed;
1618 ALsizei c, i;
1620 ASSUME(numchans > 0);
1621 ASSUME(SamplesToDo > 0);
1623 /* Dithering. Step 1, generate whitenoise (uniform distribution of random
1624 * values between -1 and +1). Step 2 is to add the noise to the samples,
1625 * before rounding and after scaling up to the desired quantization depth.
1627 for(c = 0;c < numchans;c++)
1629 ALfloat *RESTRICT samples = Samples[c];
1630 for(i = 0;i < SamplesToDo;i++)
1632 ALfloat val = samples[i] * quant_scale;
1633 ALuint rng0 = dither_rng(&seed);
1634 ALuint rng1 = dither_rng(&seed);
1635 val += (ALfloat)(rng0*(1.0/UINT_MAX) - rng1*(1.0/UINT_MAX));
1636 samples[i] = fast_roundf(val) * invscale;
1639 *dither_seed = seed;
1643 /* Base template left undefined. Should be marked =delete, but Clang 3.8.1
1644 * chokes on that given the inline specializations.
1646 template<typename T>
1647 inline T SampleConv(ALfloat);
1649 template<> inline ALfloat SampleConv(ALfloat val)
1650 { return val; }
1651 template<> inline ALint SampleConv(ALfloat val)
1653 /* Floats have a 23-bit mantissa. There is an implied 1 bit in the mantissa
1654 * along with the sign bit, giving 25 bits total, so [-16777216, +16777216]
1655 * is the max value a normalized float can be scaled to before losing
1656 * precision.
1658 return fastf2i(clampf(val*16777216.0f, -16777216.0f, 16777215.0f))<<7;
1660 template<> inline ALshort SampleConv(ALfloat val)
1661 { return fastf2i(clampf(val*32768.0f, -32768.0f, 32767.0f)); }
1662 template<> inline ALbyte SampleConv(ALfloat val)
1663 { return fastf2i(clampf(val*128.0f, -128.0f, 127.0f)); }
1665 /* Define unsigned output variations. */
1666 template<> inline ALuint SampleConv(ALfloat val)
1667 { return SampleConv<ALint>(val) + 2147483648u; }
1668 template<> inline ALushort SampleConv(ALfloat val)
1669 { return SampleConv<ALshort>(val) + 32768; }
1670 template<> inline ALubyte SampleConv(ALfloat val)
1671 { return SampleConv<ALbyte>(val) + 128; }
1673 template<DevFmtType T>
1674 void Write(const ALfloat (*RESTRICT InBuffer)[BUFFERSIZE], ALvoid *OutBuffer,
1675 ALsizei Offset, ALsizei SamplesToDo, ALsizei numchans)
1677 using SampleType = typename DevFmtTypeTraits<T>::Type;
1679 ASSUME(numchans > 0);
1680 ASSUME(SamplesToDo > 0);
1682 for(ALsizei j{0};j < numchans;j++)
1684 const ALfloat *RESTRICT in = InBuffer[j];
1685 SampleType *RESTRICT out = static_cast<SampleType*>(OutBuffer) + Offset*numchans + j;
1687 for(ALsizei i{0};i < SamplesToDo;i++)
1688 out[i*numchans] = SampleConv<SampleType>(in[i]);
1692 } // namespace
1694 void aluMixData(ALCdevice *device, ALvoid *OutBuffer, ALsizei NumSamples)
1696 ALsizei SamplesToDo;
1697 ALsizei SamplesDone;
1698 ALCcontext *ctx;
1699 ALsizei i, c;
1701 START_MIXER_MODE();
1702 for(SamplesDone = 0;SamplesDone < NumSamples;)
1704 SamplesToDo = mini(NumSamples-SamplesDone, BUFFERSIZE);
1705 for(c = 0;c < device->Dry.NumChannels;c++)
1706 memset(device->Dry.Buffer[c], 0, SamplesToDo*sizeof(ALfloat));
1707 if(device->Dry.Buffer != device->FOAOut.Buffer)
1708 for(c = 0;c < device->FOAOut.NumChannels;c++)
1709 memset(device->FOAOut.Buffer[c], 0, SamplesToDo*sizeof(ALfloat));
1710 if(device->Dry.Buffer != device->RealOut.Buffer)
1711 for(c = 0;c < device->RealOut.NumChannels;c++)
1712 memset(device->RealOut.Buffer[c], 0, SamplesToDo*sizeof(ALfloat));
1714 IncrementRef(&device->MixCount);
1716 ctx = ATOMIC_LOAD(&device->ContextList, almemory_order_acquire);
1717 while(ctx)
1719 const struct ALeffectslotArray *auxslots;
1721 auxslots = ATOMIC_LOAD(&ctx->ActiveAuxSlots, almemory_order_acquire);
1722 ProcessParamUpdates(ctx, auxslots);
1724 for(i = 0;i < auxslots->count;i++)
1726 ALeffectslot *slot = auxslots->slot[i];
1727 for(c = 0;c < slot->NumChannels;c++)
1728 memset(slot->WetBuffer[c], 0, SamplesToDo*sizeof(ALfloat));
1731 /* source processing */
1732 for(i = 0;i < ctx->VoiceCount;i++)
1734 ALvoice *voice = ctx->Voices[i];
1735 ALsource *source = ATOMIC_LOAD(&voice->Source, almemory_order_acquire);
1736 if(source && ATOMIC_LOAD(&voice->Playing, almemory_order_relaxed) &&
1737 voice->Step > 0)
1739 if(!MixSource(voice, source->id, ctx, SamplesToDo))
1741 ATOMIC_STORE(&voice->Source, static_cast<ALsource*>(nullptr),
1742 almemory_order_relaxed);
1743 ATOMIC_STORE(&voice->Playing, false, almemory_order_release);
1744 SendSourceStoppedEvent(ctx, source->id);
1749 /* effect slot processing */
1750 for(i = 0;i < auxslots->count;i++)
1752 const ALeffectslot *slot = auxslots->slot[i];
1753 EffectState *state = slot->Params.mEffectState;
1754 state->process(SamplesToDo, slot->WetBuffer, state->mOutBuffer,
1755 state->mOutChannels);
1758 ctx = ATOMIC_LOAD(&ctx->next, almemory_order_relaxed);
1761 /* Increment the clock time. Every second's worth of samples is
1762 * converted and added to clock base so that large sample counts don't
1763 * overflow during conversion. This also guarantees an exact, stable
1764 * conversion. */
1765 device->SamplesDone += SamplesToDo;
1766 device->ClockBase += (device->SamplesDone/device->Frequency) * DEVICE_CLOCK_RES;
1767 device->SamplesDone %= device->Frequency;
1768 IncrementRef(&device->MixCount);
1770 /* Apply post-process for finalizing the Dry mix to the RealOut
1771 * (Ambisonic decode, UHJ encode, etc).
1773 if(LIKELY(device->PostProcess))
1774 device->PostProcess(device, SamplesToDo);
1776 if(device->Stablizer)
1778 int lidx = GetChannelIdxByName(&device->RealOut, FrontLeft);
1779 int ridx = GetChannelIdxByName(&device->RealOut, FrontRight);
1780 int cidx = GetChannelIdxByName(&device->RealOut, FrontCenter);
1781 assert(lidx >= 0 && ridx >= 0 && cidx >= 0);
1783 ApplyStablizer(device->Stablizer, device->RealOut.Buffer, lidx, ridx, cidx,
1784 SamplesToDo, device->RealOut.NumChannels);
1787 ApplyDistanceComp(device->RealOut.Buffer, device->ChannelDelay, device->TempBuffer[0],
1788 SamplesToDo, device->RealOut.NumChannels);
1790 if(device->Limiter)
1791 ApplyCompression(device->Limiter, SamplesToDo, device->RealOut.Buffer);
1793 if(device->DitherDepth > 0.0f)
1794 ApplyDither(device->RealOut.Buffer, &device->DitherSeed, device->DitherDepth,
1795 SamplesToDo, device->RealOut.NumChannels);
1797 if(LIKELY(OutBuffer))
1799 ALfloat (*Buffer)[BUFFERSIZE] = device->RealOut.Buffer;
1800 ALsizei Channels = device->RealOut.NumChannels;
1802 switch(device->FmtType)
1804 #define HANDLE_WRITE(T) case T: \
1805 Write<T>(Buffer, OutBuffer, SamplesDone, SamplesToDo, Channels); break;
1806 HANDLE_WRITE(DevFmtByte)
1807 HANDLE_WRITE(DevFmtUByte)
1808 HANDLE_WRITE(DevFmtShort)
1809 HANDLE_WRITE(DevFmtUShort)
1810 HANDLE_WRITE(DevFmtInt)
1811 HANDLE_WRITE(DevFmtUInt)
1812 HANDLE_WRITE(DevFmtFloat)
1813 #undef HANDLE_WRITE
1817 SamplesDone += SamplesToDo;
1819 END_MIXER_MODE();
1823 void aluHandleDisconnect(ALCdevice *device, const char *msg, ...)
1825 AsyncEvent evt = ASYNC_EVENT(EventType_Disconnected);
1826 ALCcontext *ctx;
1827 va_list args;
1828 int msglen;
1830 if(!device->Connected.exchange(AL_FALSE, std::memory_order_acq_rel))
1831 return;
1833 evt.u.user.type = AL_EVENT_TYPE_DISCONNECTED_SOFT;
1834 evt.u.user.id = 0;
1835 evt.u.user.param = 0;
1837 va_start(args, msg);
1838 msglen = vsnprintf(evt.u.user.msg, sizeof(evt.u.user.msg), msg, args);
1839 va_end(args);
1841 if(msglen < 0 || (size_t)msglen >= sizeof(evt.u.user.msg))
1842 evt.u.user.msg[sizeof(evt.u.user.msg)-1] = 0;
1844 ctx = ATOMIC_LOAD_SEQ(&device->ContextList);
1845 while(ctx)
1847 ALbitfieldSOFT enabledevt = ATOMIC_LOAD(&ctx->EnabledEvts, almemory_order_acquire);
1848 ALsizei i;
1850 if((enabledevt&EventType_Disconnected) &&
1851 ll_ringbuffer_write(ctx->AsyncEvents, &evt, 1) == 1)
1852 alsem_post(&ctx->EventSem);
1854 for(i = 0;i < ctx->VoiceCount;i++)
1856 ALvoice *voice = ctx->Voices[i];
1857 ALsource *source = voice->Source.exchange(nullptr, std::memory_order_relaxed);
1858 if(source && voice->Playing.load(std::memory_order_relaxed))
1860 /* If the source's voice was playing, it's now effectively
1861 * stopped (the source state will be updated the next time it's
1862 * checked).
1864 SendSourceStoppedEvent(ctx, source->id);
1866 voice->Playing.store(false, std::memory_order_release);
1869 ctx = ATOMIC_LOAD(&ctx->next, almemory_order_relaxed);