Use member functions for BFormatDec and AmbiUpsampler
[openal-soft.git] / Alc / alu.cpp
blob34634983c5ff73b56228453c34e531a38937d5ca
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 std::fill(std::begin(f), std::end(f), 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) noexcept
102 delete voice->Update.exchange(nullptr, std::memory_order_acq_rel);
103 voice->~ALvoice();
107 namespace {
109 void ProcessHrtf(ALCdevice *device, ALsizei SamplesToDo)
111 if(device->AmbiUp)
112 device->AmbiUp->process(device->Dry.Buffer, device->Dry.NumChannels,
113 device->FOAOut.Buffer, SamplesToDo
116 int lidx{GetChannelIdxByName(&device->RealOut, FrontLeft)};
117 int ridx{GetChannelIdxByName(&device->RealOut, FrontRight)};
118 assert(lidx != -1 && ridx != -1);
120 DirectHrtfState *state{device->mHrtfState.get()};
121 for(ALsizei c{0};c < device->Dry.NumChannels;c++)
123 MixDirectHrtf(device->RealOut.Buffer[lidx], device->RealOut.Buffer[ridx],
124 device->Dry.Buffer[c], state->Offset, state->IrSize,
125 state->Chan[c].Coeffs, state->Chan[c].Values, SamplesToDo
128 state->Offset += SamplesToDo;
131 void ProcessAmbiDec(ALCdevice *device, ALsizei SamplesToDo)
133 if(device->Dry.Buffer != device->FOAOut.Buffer)
134 device->AmbiDecoder->upSample(device->Dry.Buffer, device->FOAOut.Buffer,
135 device->FOAOut.NumChannels, SamplesToDo
137 device->AmbiDecoder->process(device->RealOut.Buffer, device->RealOut.NumChannels,
138 device->Dry.Buffer, SamplesToDo
142 void ProcessAmbiUp(ALCdevice *device, ALsizei SamplesToDo)
144 device->AmbiUp->process(device->RealOut.Buffer, device->RealOut.NumChannels,
145 device->FOAOut.Buffer, SamplesToDo
149 void ProcessUhj(ALCdevice *device, ALsizei SamplesToDo)
151 int lidx = GetChannelIdxByName(&device->RealOut, FrontLeft);
152 int ridx = GetChannelIdxByName(&device->RealOut, FrontRight);
153 assert(lidx != -1 && ridx != -1);
155 /* Encode to stereo-compatible 2-channel UHJ output. */
156 EncodeUhj2(device->Uhj_Encoder.get(),
157 device->RealOut.Buffer[lidx], device->RealOut.Buffer[ridx],
158 device->Dry.Buffer, SamplesToDo
162 void ProcessBs2b(ALCdevice *device, ALsizei SamplesToDo)
164 int lidx = GetChannelIdxByName(&device->RealOut, FrontLeft);
165 int ridx = GetChannelIdxByName(&device->RealOut, FrontRight);
166 assert(lidx != -1 && ridx != -1);
168 /* Apply binaural/crossfeed filter */
169 bs2b_cross_feed(device->Bs2b.get(), device->RealOut.Buffer[lidx],
170 device->RealOut.Buffer[ridx], SamplesToDo);
173 } // namespace
175 void aluSelectPostProcess(ALCdevice *device)
177 if(device->HrtfHandle)
178 device->PostProcess = ProcessHrtf;
179 else if(device->AmbiDecoder)
180 device->PostProcess = ProcessAmbiDec;
181 else if(device->AmbiUp)
182 device->PostProcess = ProcessAmbiUp;
183 else if(device->Uhj_Encoder)
184 device->PostProcess = ProcessUhj;
185 else if(device->Bs2b)
186 device->PostProcess = ProcessBs2b;
187 else
188 device->PostProcess = NULL;
192 /* Prepares the interpolator for a given rate (determined by increment).
194 * With a bit of work, and a trade of memory for CPU cost, this could be
195 * modified for use with an interpolated increment for buttery-smooth pitch
196 * changes.
198 void BsincPrepare(const ALuint increment, BsincState *state, const BSincTable *table)
200 ALfloat sf = 0.0f;
201 ALsizei si = BSINC_SCALE_COUNT-1;
203 if(increment > FRACTIONONE)
205 sf = (ALfloat)FRACTIONONE / increment;
206 sf = maxf(0.0f, (BSINC_SCALE_COUNT-1) * (sf-table->scaleBase) * table->scaleRange);
207 si = float2int(sf);
208 /* The interpolation factor is fit to this diagonally-symmetric curve
209 * to reduce the transition ripple caused by interpolating different
210 * scales of the sinc function.
212 sf = 1.0f - cosf(asinf(sf - si));
215 state->sf = sf;
216 state->m = table->m[si];
217 state->l = (state->m/2) - 1;
218 state->filter = table->Tab + table->filterOffset[si];
222 namespace {
224 /* This RNG method was created based on the math found in opusdec. It's quick,
225 * and starting with a seed value of 22222, is suitable for generating
226 * whitenoise.
228 inline ALuint dither_rng(ALuint *seed) noexcept
230 *seed = (*seed * 96314165) + 907633515;
231 return *seed;
235 inline void aluCrossproduct(const ALfloat *inVector1, const ALfloat *inVector2, ALfloat *outVector)
237 outVector[0] = inVector1[1]*inVector2[2] - inVector1[2]*inVector2[1];
238 outVector[1] = inVector1[2]*inVector2[0] - inVector1[0]*inVector2[2];
239 outVector[2] = inVector1[0]*inVector2[1] - inVector1[1]*inVector2[0];
242 inline ALfloat aluDotproduct(const aluVector *vec1, const aluVector *vec2)
244 return vec1->v[0]*vec2->v[0] + vec1->v[1]*vec2->v[1] + vec1->v[2]*vec2->v[2];
247 ALfloat aluNormalize(ALfloat *vec)
249 ALfloat length = sqrtf(vec[0]*vec[0] + vec[1]*vec[1] + vec[2]*vec[2]);
250 if(length > FLT_EPSILON)
252 ALfloat inv_length = 1.0f/length;
253 vec[0] *= inv_length;
254 vec[1] *= inv_length;
255 vec[2] *= inv_length;
256 return length;
258 vec[0] = vec[1] = vec[2] = 0.0f;
259 return 0.0f;
262 void aluMatrixfFloat3(ALfloat *vec, ALfloat w, const aluMatrixf *mtx)
264 ALfloat v[4] = { vec[0], vec[1], vec[2], w };
266 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];
267 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];
268 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];
271 aluVector aluMatrixfVector(const aluMatrixf *mtx, const aluVector *vec)
273 aluVector v;
274 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];
275 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];
276 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];
277 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];
278 return v;
282 void SendSourceStoppedEvent(ALCcontext *context, ALuint id)
284 ALbitfieldSOFT enabledevt{context->EnabledEvts.load(std::memory_order_acquire)};
285 if(!(enabledevt&EventType_SourceStateChange)) return;
287 AsyncEvent evt{EventType_SourceStateChange};
288 evt.u.srcstate.id = id;
289 evt.u.srcstate.state = AL_STOPPED;
291 if(ll_ringbuffer_write(context->AsyncEvents, &evt, 1) == 1)
292 context->EventSem.post();
296 bool CalcContextParams(ALCcontext *Context)
298 ALlistener &Listener = Context->Listener;
299 struct ALcontextProps *props;
301 props = Context->Update.exchange(nullptr, std::memory_order_acq_rel);
302 if(!props) return false;
304 Listener.Params.MetersPerUnit = props->MetersPerUnit;
306 Listener.Params.DopplerFactor = props->DopplerFactor;
307 Listener.Params.SpeedOfSound = props->SpeedOfSound * props->DopplerVelocity;
308 if(!OverrideReverbSpeedOfSound)
309 Listener.Params.ReverbSpeedOfSound = Listener.Params.SpeedOfSound *
310 Listener.Params.MetersPerUnit;
312 Listener.Params.SourceDistanceModel = props->SourceDistanceModel;
313 Listener.Params.mDistanceModel = props->mDistanceModel;
315 AtomicReplaceHead(Context->FreeContextProps, props);
316 return true;
319 bool CalcListenerParams(ALCcontext *Context)
321 ALlistener &Listener = Context->Listener;
322 ALfloat N[3], V[3], U[3], P[3];
323 struct ALlistenerProps *props;
324 aluVector vel;
326 props = Listener.Update.exchange(nullptr, std::memory_order_acq_rel);
327 if(!props) return false;
329 /* AT then UP */
330 N[0] = props->Forward[0];
331 N[1] = props->Forward[1];
332 N[2] = props->Forward[2];
333 aluNormalize(N);
334 V[0] = props->Up[0];
335 V[1] = props->Up[1];
336 V[2] = props->Up[2];
337 aluNormalize(V);
338 /* Build and normalize right-vector */
339 aluCrossproduct(N, V, U);
340 aluNormalize(U);
342 aluMatrixfSet(&Listener.Params.Matrix,
343 U[0], V[0], -N[0], 0.0,
344 U[1], V[1], -N[1], 0.0,
345 U[2], V[2], -N[2], 0.0,
346 0.0, 0.0, 0.0, 1.0
349 P[0] = props->Position[0];
350 P[1] = props->Position[1];
351 P[2] = props->Position[2];
352 aluMatrixfFloat3(P, 1.0, &Listener.Params.Matrix);
353 aluMatrixfSetRow(&Listener.Params.Matrix, 3, -P[0], -P[1], -P[2], 1.0f);
355 aluVectorSet(&vel, props->Velocity[0], props->Velocity[1], props->Velocity[2], 0.0f);
356 Listener.Params.Velocity = aluMatrixfVector(&Listener.Params.Matrix, &vel);
358 Listener.Params.Gain = props->Gain * Context->GainBoost;
360 AtomicReplaceHead(Context->FreeListenerProps, props);
361 return true;
364 bool CalcEffectSlotParams(ALeffectslot *slot, ALCcontext *context, bool force)
366 struct ALeffectslotProps *props;
367 EffectState *state;
369 props = slot->Update.exchange(nullptr, std::memory_order_acq_rel);
370 if(!props && !force) return false;
372 if(props)
374 slot->Params.Gain = props->Gain;
375 slot->Params.AuxSendAuto = props->AuxSendAuto;
376 slot->Params.EffectType = props->Type;
377 slot->Params.EffectProps = props->Props;
378 if(IsReverbEffect(props->Type))
380 slot->Params.RoomRolloff = props->Props.Reverb.RoomRolloffFactor;
381 slot->Params.DecayTime = props->Props.Reverb.DecayTime;
382 slot->Params.DecayLFRatio = props->Props.Reverb.DecayLFRatio;
383 slot->Params.DecayHFRatio = props->Props.Reverb.DecayHFRatio;
384 slot->Params.DecayHFLimit = props->Props.Reverb.DecayHFLimit;
385 slot->Params.AirAbsorptionGainHF = props->Props.Reverb.AirAbsorptionGainHF;
387 else
389 slot->Params.RoomRolloff = 0.0f;
390 slot->Params.DecayTime = 0.0f;
391 slot->Params.DecayLFRatio = 0.0f;
392 slot->Params.DecayHFRatio = 0.0f;
393 slot->Params.DecayHFLimit = AL_FALSE;
394 slot->Params.AirAbsorptionGainHF = 1.0f;
397 state = props->State;
399 if(state == slot->Params.mEffectState)
401 /* If the effect state is the same as current, we can decrement its
402 * count safely to remove it from the update object (it can't reach
403 * 0 refs since the current params also hold a reference).
405 DecrementRef(&state->mRef);
406 props->State = nullptr;
408 else
410 /* Otherwise, replace it and send off the old one with a release
411 * event.
413 AsyncEvent evt{EventType_ReleaseEffectState};
414 evt.u.mEffectState = slot->Params.mEffectState;
416 slot->Params.mEffectState = state;
417 props->State = NULL;
419 if(LIKELY(ll_ringbuffer_write(context->AsyncEvents, &evt, 1) != 0))
420 context->EventSem.post();
421 else
423 /* If writing the event failed, the queue was probably full.
424 * Store the old state in the property object where it can
425 * eventually be cleaned up sometime later (not ideal, but
426 * better than blocking or leaking).
428 props->State = evt.u.mEffectState;
432 AtomicReplaceHead(context->FreeEffectslotProps, props);
434 else
435 state = slot->Params.mEffectState;
437 state->update(context, slot, &slot->Params.EffectProps);
438 return true;
442 constexpr struct ChanMap MonoMap[1] = {
443 { FrontCenter, 0.0f, 0.0f }
444 }, RearMap[2] = {
445 { BackLeft, DEG2RAD(-150.0f), DEG2RAD(0.0f) },
446 { BackRight, DEG2RAD( 150.0f), DEG2RAD(0.0f) }
447 }, QuadMap[4] = {
448 { FrontLeft, DEG2RAD( -45.0f), DEG2RAD(0.0f) },
449 { FrontRight, DEG2RAD( 45.0f), DEG2RAD(0.0f) },
450 { BackLeft, DEG2RAD(-135.0f), DEG2RAD(0.0f) },
451 { BackRight, DEG2RAD( 135.0f), DEG2RAD(0.0f) }
452 }, X51Map[6] = {
453 { FrontLeft, DEG2RAD( -30.0f), DEG2RAD(0.0f) },
454 { FrontRight, DEG2RAD( 30.0f), DEG2RAD(0.0f) },
455 { FrontCenter, DEG2RAD( 0.0f), DEG2RAD(0.0f) },
456 { LFE, 0.0f, 0.0f },
457 { SideLeft, DEG2RAD(-110.0f), DEG2RAD(0.0f) },
458 { SideRight, DEG2RAD( 110.0f), DEG2RAD(0.0f) }
459 }, X61Map[7] = {
460 { FrontLeft, DEG2RAD(-30.0f), DEG2RAD(0.0f) },
461 { FrontRight, DEG2RAD( 30.0f), DEG2RAD(0.0f) },
462 { FrontCenter, DEG2RAD( 0.0f), DEG2RAD(0.0f) },
463 { LFE, 0.0f, 0.0f },
464 { BackCenter, DEG2RAD(180.0f), DEG2RAD(0.0f) },
465 { SideLeft, DEG2RAD(-90.0f), DEG2RAD(0.0f) },
466 { SideRight, DEG2RAD( 90.0f), DEG2RAD(0.0f) }
467 }, X71Map[8] = {
468 { FrontLeft, DEG2RAD( -30.0f), DEG2RAD(0.0f) },
469 { FrontRight, DEG2RAD( 30.0f), DEG2RAD(0.0f) },
470 { FrontCenter, DEG2RAD( 0.0f), DEG2RAD(0.0f) },
471 { LFE, 0.0f, 0.0f },
472 { BackLeft, DEG2RAD(-150.0f), DEG2RAD(0.0f) },
473 { BackRight, DEG2RAD( 150.0f), DEG2RAD(0.0f) },
474 { SideLeft, DEG2RAD( -90.0f), DEG2RAD(0.0f) },
475 { SideRight, DEG2RAD( 90.0f), DEG2RAD(0.0f) }
478 void CalcPanningAndFilters(ALvoice *voice, const ALfloat Azi, const ALfloat Elev,
479 const ALfloat Distance, const ALfloat Spread,
480 const ALfloat DryGain, const ALfloat DryGainHF,
481 const ALfloat DryGainLF, const ALfloat *WetGain,
482 const ALfloat *WetGainLF, const ALfloat *WetGainHF,
483 ALeffectslot **SendSlots, const ALbuffer *Buffer,
484 const ALvoicePropsBase *props, const ALlistener &Listener,
485 const ALCdevice *Device)
487 struct ChanMap StereoMap[2] = {
488 { FrontLeft, DEG2RAD(-30.0f), DEG2RAD(0.0f) },
489 { FrontRight, DEG2RAD( 30.0f), DEG2RAD(0.0f) }
491 bool DirectChannels = props->DirectChannels;
492 const ALsizei NumSends = Device->NumAuxSends;
493 const ALuint Frequency = Device->Frequency;
494 const struct ChanMap *chans = NULL;
495 ALsizei num_channels = 0;
496 bool isbformat = false;
497 ALfloat downmix_gain = 1.0f;
498 ALsizei c, i;
500 switch(Buffer->FmtChannels)
502 case FmtMono:
503 chans = MonoMap;
504 num_channels = 1;
505 /* Mono buffers are never played direct. */
506 DirectChannels = false;
507 break;
509 case FmtStereo:
510 /* Convert counter-clockwise to clockwise. */
511 StereoMap[0].angle = -props->StereoPan[0];
512 StereoMap[1].angle = -props->StereoPan[1];
514 chans = StereoMap;
515 num_channels = 2;
516 downmix_gain = 1.0f / 2.0f;
517 break;
519 case FmtRear:
520 chans = RearMap;
521 num_channels = 2;
522 downmix_gain = 1.0f / 2.0f;
523 break;
525 case FmtQuad:
526 chans = QuadMap;
527 num_channels = 4;
528 downmix_gain = 1.0f / 4.0f;
529 break;
531 case FmtX51:
532 chans = X51Map;
533 num_channels = 6;
534 /* NOTE: Excludes LFE. */
535 downmix_gain = 1.0f / 5.0f;
536 break;
538 case FmtX61:
539 chans = X61Map;
540 num_channels = 7;
541 /* NOTE: Excludes LFE. */
542 downmix_gain = 1.0f / 6.0f;
543 break;
545 case FmtX71:
546 chans = X71Map;
547 num_channels = 8;
548 /* NOTE: Excludes LFE. */
549 downmix_gain = 1.0f / 7.0f;
550 break;
552 case FmtBFormat2D:
553 num_channels = 3;
554 isbformat = true;
555 DirectChannels = false;
556 break;
558 case FmtBFormat3D:
559 num_channels = 4;
560 isbformat = true;
561 DirectChannels = false;
562 break;
565 std::for_each(std::begin(voice->Direct.Params), std::begin(voice->Direct.Params)+num_channels,
566 [](DirectParams &params) -> void
568 params.Hrtf.Target = HrtfParams{};
569 ClearArray(params.Gains.Target);
572 std::for_each(voice->Send+0, voice->Send+NumSends,
573 [num_channels](ALvoice::SendData &send) -> void
575 std::for_each(std::begin(send.Params), std::begin(send.Params)+num_channels,
576 [](SendParams &params) -> void { ClearArray(params.Gains.Target); }
581 voice->Flags &= ~(VOICE_HAS_HRTF | VOICE_HAS_NFC);
582 if(isbformat)
584 /* Special handling for B-Format sources. */
586 if(Distance > FLT_EPSILON)
588 /* Panning a B-Format sound toward some direction is easy. Just pan
589 * the first (W) channel as a normal mono sound and silence the
590 * others.
592 ALfloat coeffs[MAX_AMBI_COEFFS];
594 if(Device->AvgSpeakerDist > 0.0f)
596 ALfloat mdist = Distance * Listener.Params.MetersPerUnit;
597 ALfloat w0 = SPEEDOFSOUNDMETRESPERSEC /
598 (mdist * (ALfloat)Device->Frequency);
599 ALfloat w1 = SPEEDOFSOUNDMETRESPERSEC /
600 (Device->AvgSpeakerDist * (ALfloat)Device->Frequency);
601 /* Clamp w0 for really close distances, to prevent excessive
602 * bass.
604 w0 = minf(w0, w1*4.0f);
606 /* Only need to adjust the first channel of a B-Format source. */
607 voice->Direct.Params[0].NFCtrlFilter.adjust(w0);
609 std::copy(std::begin(Device->NumChannelsPerOrder),
610 std::end(Device->NumChannelsPerOrder),
611 std::begin(voice->Direct.ChannelsPerOrder));
612 voice->Flags |= VOICE_HAS_NFC;
615 /* A scalar of 1.5 for plain stereo results in +/-60 degrees being
616 * moved to +/-90 degrees for direct right and left speaker
617 * responses.
619 CalcAngleCoeffs((Device->Render_Mode==StereoPair) ? ScaleAzimuthFront(Azi, 1.5f) : Azi,
620 Elev, Spread, coeffs);
622 /* NOTE: W needs to be scaled by sqrt(2) due to FuMa normalization. */
623 ComputePanGains(&Device->Dry, coeffs, DryGain*SQRTF_2,
624 voice->Direct.Params[0].Gains.Target);
625 for(i = 0;i < NumSends;i++)
627 const ALeffectslot *Slot = SendSlots[i];
628 if(Slot)
629 ComputePanningGainsBF(Slot->ChanMap, Slot->NumChannels, coeffs,
630 WetGain[i]*SQRTF_2, voice->Send[i].Params[0].Gains.Target
634 else
636 /* Local B-Format sources have their XYZ channels rotated according
637 * to the orientation.
639 ALfloat N[3], V[3], U[3];
640 aluMatrixf matrix;
642 if(Device->AvgSpeakerDist > 0.0f)
644 /* NOTE: The NFCtrlFilters were created with a w0 of 0, which
645 * is what we want for FOA input. The first channel may have
646 * been previously re-adjusted if panned, so reset it.
648 voice->Direct.Params[0].NFCtrlFilter.adjust(0.0f);
650 voice->Direct.ChannelsPerOrder[0] = 1;
651 voice->Direct.ChannelsPerOrder[1] = mini(voice->Direct.Channels-1, 3);
652 std::fill(std::begin(voice->Direct.ChannelsPerOrder)+2,
653 std::end(voice->Direct.ChannelsPerOrder), 0);
654 voice->Flags |= VOICE_HAS_NFC;
657 /* AT then UP */
658 N[0] = props->Orientation[0][0];
659 N[1] = props->Orientation[0][1];
660 N[2] = props->Orientation[0][2];
661 aluNormalize(N);
662 V[0] = props->Orientation[1][0];
663 V[1] = props->Orientation[1][1];
664 V[2] = props->Orientation[1][2];
665 aluNormalize(V);
666 if(!props->HeadRelative)
668 const aluMatrixf *lmatrix = &Listener.Params.Matrix;
669 aluMatrixfFloat3(N, 0.0f, lmatrix);
670 aluMatrixfFloat3(V, 0.0f, lmatrix);
672 /* Build and normalize right-vector */
673 aluCrossproduct(N, V, U);
674 aluNormalize(U);
676 /* Build a rotate + conversion matrix (FuMa -> ACN+N3D). NOTE: This
677 * matrix is transposed, for the inputs to align on the rows and
678 * outputs on the columns.
680 aluMatrixfSet(&matrix,
681 // ACN0 ACN1 ACN2 ACN3
682 SQRTF_2, 0.0f, 0.0f, 0.0f, // Ambi W
683 0.0f, -N[0]*SQRTF_3, N[1]*SQRTF_3, -N[2]*SQRTF_3, // Ambi X
684 0.0f, U[0]*SQRTF_3, -U[1]*SQRTF_3, U[2]*SQRTF_3, // Ambi Y
685 0.0f, -V[0]*SQRTF_3, V[1]*SQRTF_3, -V[2]*SQRTF_3 // Ambi Z
688 voice->Direct.Buffer = Device->FOAOut.Buffer;
689 voice->Direct.Channels = Device->FOAOut.NumChannels;
690 for(c = 0;c < num_channels;c++)
691 ComputePanGains(&Device->FOAOut, matrix.m[c], DryGain,
692 voice->Direct.Params[c].Gains.Target);
693 for(i = 0;i < NumSends;i++)
695 const ALeffectslot *Slot = SendSlots[i];
696 if(Slot)
698 for(c = 0;c < num_channels;c++)
699 ComputePanningGainsBF(Slot->ChanMap, Slot->NumChannels,
700 matrix.m[c], WetGain[i], voice->Send[i].Params[c].Gains.Target
706 else if(DirectChannels)
708 /* Direct source channels always play local. Skip the virtual channels
709 * and write inputs to the matching real outputs.
711 voice->Direct.Buffer = Device->RealOut.Buffer;
712 voice->Direct.Channels = Device->RealOut.NumChannels;
714 for(c = 0;c < num_channels;c++)
716 int idx = GetChannelIdxByName(&Device->RealOut, chans[c].channel);
717 if(idx != -1) voice->Direct.Params[c].Gains.Target[idx] = DryGain;
720 /* Auxiliary sends still use normal channel panning since they mix to
721 * B-Format, which can't channel-match.
723 for(c = 0;c < num_channels;c++)
725 ALfloat coeffs[MAX_AMBI_COEFFS];
726 CalcAngleCoeffs(chans[c].angle, chans[c].elevation, 0.0f, coeffs);
728 for(i = 0;i < NumSends;i++)
730 const ALeffectslot *Slot = SendSlots[i];
731 if(Slot)
732 ComputePanningGainsBF(Slot->ChanMap, Slot->NumChannels,
733 coeffs, WetGain[i], voice->Send[i].Params[c].Gains.Target
738 else if(Device->Render_Mode == HrtfRender)
740 /* Full HRTF rendering. Skip the virtual channels and render to the
741 * real outputs.
743 voice->Direct.Buffer = Device->RealOut.Buffer;
744 voice->Direct.Channels = Device->RealOut.NumChannels;
746 if(Distance > FLT_EPSILON)
748 ALfloat coeffs[MAX_AMBI_COEFFS];
750 /* Get the HRIR coefficients and delays just once, for the given
751 * source direction.
753 GetHrtfCoeffs(Device->HrtfHandle, Elev, Azi, Spread,
754 voice->Direct.Params[0].Hrtf.Target.Coeffs,
755 voice->Direct.Params[0].Hrtf.Target.Delay);
756 voice->Direct.Params[0].Hrtf.Target.Gain = DryGain * downmix_gain;
758 /* Remaining channels use the same results as the first. */
759 for(c = 1;c < num_channels;c++)
761 /* Skip LFE */
762 if(chans[c].channel != LFE)
763 voice->Direct.Params[c].Hrtf.Target = voice->Direct.Params[0].Hrtf.Target;
766 /* Calculate the directional coefficients once, which apply to all
767 * input channels of the source sends.
769 CalcAngleCoeffs(Azi, Elev, Spread, coeffs);
771 for(i = 0;i < NumSends;i++)
773 const ALeffectslot *Slot = SendSlots[i];
774 if(Slot)
775 for(c = 0;c < num_channels;c++)
777 /* Skip LFE */
778 if(chans[c].channel != LFE)
779 ComputePanningGainsBF(Slot->ChanMap,
780 Slot->NumChannels, coeffs, WetGain[i] * downmix_gain,
781 voice->Send[i].Params[c].Gains.Target
786 else
788 /* Local sources on HRTF play with each channel panned to its
789 * relative location around the listener, providing "virtual
790 * speaker" responses.
792 for(c = 0;c < num_channels;c++)
794 ALfloat coeffs[MAX_AMBI_COEFFS];
796 if(chans[c].channel == LFE)
798 /* Skip LFE */
799 continue;
802 /* Get the HRIR coefficients and delays for this channel
803 * position.
805 GetHrtfCoeffs(Device->HrtfHandle,
806 chans[c].elevation, chans[c].angle, Spread,
807 voice->Direct.Params[c].Hrtf.Target.Coeffs,
808 voice->Direct.Params[c].Hrtf.Target.Delay
810 voice->Direct.Params[c].Hrtf.Target.Gain = DryGain;
812 /* Normal panning for auxiliary sends. */
813 CalcAngleCoeffs(chans[c].angle, chans[c].elevation, Spread, coeffs);
815 for(i = 0;i < NumSends;i++)
817 const ALeffectslot *Slot = SendSlots[i];
818 if(Slot)
819 ComputePanningGainsBF(Slot->ChanMap, Slot->NumChannels,
820 coeffs, WetGain[i], voice->Send[i].Params[c].Gains.Target
826 voice->Flags |= VOICE_HAS_HRTF;
828 else
830 /* Non-HRTF rendering. Use normal panning to the output. */
832 if(Distance > FLT_EPSILON)
834 ALfloat coeffs[MAX_AMBI_COEFFS];
835 ALfloat w0 = 0.0f;
837 /* Calculate NFC filter coefficient if needed. */
838 if(Device->AvgSpeakerDist > 0.0f)
840 ALfloat mdist = Distance * Listener.Params.MetersPerUnit;
841 ALfloat w1 = SPEEDOFSOUNDMETRESPERSEC /
842 (Device->AvgSpeakerDist * (ALfloat)Device->Frequency);
843 w0 = SPEEDOFSOUNDMETRESPERSEC /
844 (mdist * (ALfloat)Device->Frequency);
845 /* Clamp w0 for really close distances, to prevent excessive
846 * bass.
848 w0 = minf(w0, w1*4.0f);
850 /* Adjust NFC filters. */
851 for(c = 0;c < num_channels;c++)
852 voice->Direct.Params[c].NFCtrlFilter.adjust(w0);
854 for(i = 0;i < MAX_AMBI_ORDER+1;i++)
855 voice->Direct.ChannelsPerOrder[i] = Device->NumChannelsPerOrder[i];
856 voice->Flags |= VOICE_HAS_NFC;
859 /* Calculate the directional coefficients once, which apply to all
860 * input channels.
862 CalcAngleCoeffs((Device->Render_Mode==StereoPair) ? ScaleAzimuthFront(Azi, 1.5f) : Azi,
863 Elev, Spread, coeffs);
865 for(c = 0;c < num_channels;c++)
867 /* Special-case LFE */
868 if(chans[c].channel == LFE)
870 if(Device->Dry.Buffer == Device->RealOut.Buffer)
872 int idx = GetChannelIdxByName(&Device->RealOut, chans[c].channel);
873 if(idx != -1) voice->Direct.Params[c].Gains.Target[idx] = DryGain;
875 continue;
878 ComputePanGains(&Device->Dry, coeffs, DryGain * downmix_gain,
879 voice->Direct.Params[c].Gains.Target);
882 for(i = 0;i < NumSends;i++)
884 const ALeffectslot *Slot = SendSlots[i];
885 if(Slot)
886 for(c = 0;c < num_channels;c++)
888 /* Skip LFE */
889 if(chans[c].channel != LFE)
890 ComputePanningGainsBF(Slot->ChanMap,
891 Slot->NumChannels, coeffs, WetGain[i] * downmix_gain,
892 voice->Send[i].Params[c].Gains.Target
897 else
899 ALfloat w0 = 0.0f;
901 if(Device->AvgSpeakerDist > 0.0f)
903 /* If the source distance is 0, set w0 to w1 to act as a pass-
904 * through. We still want to pass the signal through the
905 * filters so they keep an appropriate history, in case the
906 * source moves away from the listener.
908 w0 = SPEEDOFSOUNDMETRESPERSEC /
909 (Device->AvgSpeakerDist * (ALfloat)Device->Frequency);
911 for(c = 0;c < num_channels;c++)
912 voice->Direct.Params[c].NFCtrlFilter.adjust(w0);
914 for(i = 0;i < MAX_AMBI_ORDER+1;i++)
915 voice->Direct.ChannelsPerOrder[i] = Device->NumChannelsPerOrder[i];
916 voice->Flags |= VOICE_HAS_NFC;
919 for(c = 0;c < num_channels;c++)
921 ALfloat coeffs[MAX_AMBI_COEFFS];
923 /* Special-case LFE */
924 if(chans[c].channel == LFE)
926 if(Device->Dry.Buffer == Device->RealOut.Buffer)
928 int idx = GetChannelIdxByName(&Device->RealOut, chans[c].channel);
929 if(idx != -1) voice->Direct.Params[c].Gains.Target[idx] = DryGain;
931 continue;
934 CalcAngleCoeffs(
935 (Device->Render_Mode==StereoPair) ? ScaleAzimuthFront(chans[c].angle, 3.0f)
936 : chans[c].angle,
937 chans[c].elevation, Spread, coeffs
940 ComputePanGains(&Device->Dry, coeffs, DryGain,
941 voice->Direct.Params[c].Gains.Target);
942 for(i = 0;i < NumSends;i++)
944 const ALeffectslot *Slot = SendSlots[i];
945 if(Slot)
946 ComputePanningGainsBF(Slot->ChanMap, Slot->NumChannels,
947 coeffs, WetGain[i], voice->Send[i].Params[c].Gains.Target
955 ALfloat hfScale = props->Direct.HFReference / Frequency;
956 ALfloat lfScale = props->Direct.LFReference / Frequency;
957 ALfloat gainHF = maxf(DryGainHF, 0.001f); /* Limit -60dB */
958 ALfloat gainLF = maxf(DryGainLF, 0.001f);
960 voice->Direct.FilterType = AF_None;
961 if(gainHF != 1.0f) voice->Direct.FilterType |= AF_LowPass;
962 if(gainLF != 1.0f) voice->Direct.FilterType |= AF_HighPass;
963 voice->Direct.Params[0].LowPass.setParams(BiquadType::HighShelf,
964 gainHF, hfScale, calc_rcpQ_from_slope(gainHF, 1.0f)
966 voice->Direct.Params[0].HighPass.setParams(BiquadType::LowShelf,
967 gainLF, lfScale, calc_rcpQ_from_slope(gainLF, 1.0f)
969 for(c = 1;c < num_channels;c++)
971 voice->Direct.Params[c].LowPass.copyParamsFrom(voice->Direct.Params[0].LowPass);
972 voice->Direct.Params[c].HighPass.copyParamsFrom(voice->Direct.Params[0].HighPass);
975 for(i = 0;i < NumSends;i++)
977 ALfloat hfScale = props->Send[i].HFReference / Frequency;
978 ALfloat lfScale = props->Send[i].LFReference / Frequency;
979 ALfloat gainHF = maxf(WetGainHF[i], 0.001f);
980 ALfloat gainLF = maxf(WetGainLF[i], 0.001f);
982 voice->Send[i].FilterType = AF_None;
983 if(gainHF != 1.0f) voice->Send[i].FilterType |= AF_LowPass;
984 if(gainLF != 1.0f) voice->Send[i].FilterType |= AF_HighPass;
985 voice->Send[i].Params[0].LowPass.setParams(BiquadType::HighShelf,
986 gainHF, hfScale, calc_rcpQ_from_slope(gainHF, 1.0f)
988 voice->Send[i].Params[0].HighPass.setParams(BiquadType::LowShelf,
989 gainLF, lfScale, calc_rcpQ_from_slope(gainLF, 1.0f)
991 for(c = 1;c < num_channels;c++)
993 voice->Send[i].Params[c].LowPass.copyParamsFrom(voice->Send[i].Params[0].LowPass);
994 voice->Send[i].Params[c].HighPass.copyParamsFrom(voice->Send[i].Params[0].HighPass);
999 void CalcNonAttnSourceParams(ALvoice *voice, const ALvoicePropsBase *props, const ALbuffer *ALBuffer, const ALCcontext *ALContext)
1001 const ALCdevice *Device = ALContext->Device;
1002 const ALlistener &Listener = ALContext->Listener;
1003 ALfloat DryGain, DryGainHF, DryGainLF;
1004 ALfloat WetGain[MAX_SENDS];
1005 ALfloat WetGainHF[MAX_SENDS];
1006 ALfloat WetGainLF[MAX_SENDS];
1007 ALeffectslot *SendSlots[MAX_SENDS];
1008 ALfloat Pitch;
1009 ALsizei i;
1011 voice->Direct.Buffer = Device->Dry.Buffer;
1012 voice->Direct.Channels = Device->Dry.NumChannels;
1013 for(i = 0;i < Device->NumAuxSends;i++)
1015 SendSlots[i] = props->Send[i].Slot;
1016 if(!SendSlots[i] && i == 0)
1017 SendSlots[i] = ALContext->DefaultSlot.get();
1018 if(!SendSlots[i] || SendSlots[i]->Params.EffectType == AL_EFFECT_NULL)
1020 SendSlots[i] = NULL;
1021 voice->Send[i].Buffer = NULL;
1022 voice->Send[i].Channels = 0;
1024 else
1026 voice->Send[i].Buffer = SendSlots[i]->WetBuffer;
1027 voice->Send[i].Channels = SendSlots[i]->NumChannels;
1031 /* Calculate the stepping value */
1032 Pitch = (ALfloat)ALBuffer->Frequency/(ALfloat)Device->Frequency * props->Pitch;
1033 if(Pitch > (ALfloat)MAX_PITCH)
1034 voice->Step = MAX_PITCH<<FRACTIONBITS;
1035 else
1036 voice->Step = maxi(fastf2i(Pitch * FRACTIONONE), 1);
1037 if(props->Resampler == BSinc24Resampler)
1038 BsincPrepare(voice->Step, &voice->ResampleState.bsinc, &bsinc24);
1039 else if(props->Resampler == BSinc12Resampler)
1040 BsincPrepare(voice->Step, &voice->ResampleState.bsinc, &bsinc12);
1041 voice->Resampler = SelectResampler(props->Resampler);
1043 /* Calculate gains */
1044 DryGain = clampf(props->Gain, props->MinGain, props->MaxGain);
1045 DryGain *= props->Direct.Gain * Listener.Params.Gain;
1046 DryGain = minf(DryGain, GAIN_MIX_MAX);
1047 DryGainHF = props->Direct.GainHF;
1048 DryGainLF = props->Direct.GainLF;
1049 for(i = 0;i < Device->NumAuxSends;i++)
1051 WetGain[i] = clampf(props->Gain, props->MinGain, props->MaxGain);
1052 WetGain[i] *= props->Send[i].Gain * Listener.Params.Gain;
1053 WetGain[i] = minf(WetGain[i], GAIN_MIX_MAX);
1054 WetGainHF[i] = props->Send[i].GainHF;
1055 WetGainLF[i] = props->Send[i].GainLF;
1058 CalcPanningAndFilters(voice, 0.0f, 0.0f, 0.0f, 0.0f, DryGain, DryGainHF, DryGainLF, WetGain,
1059 WetGainLF, WetGainHF, SendSlots, ALBuffer, props, Listener, Device);
1062 void CalcAttnSourceParams(ALvoice *voice, const ALvoicePropsBase *props, const ALbuffer *ALBuffer, const ALCcontext *ALContext)
1064 const ALCdevice *Device = ALContext->Device;
1065 const ALlistener &Listener = ALContext->Listener;
1066 const ALsizei NumSends = Device->NumAuxSends;
1067 aluVector Position, Velocity, Direction, SourceToListener;
1068 ALfloat Distance, ClampedDist, DopplerFactor;
1069 ALeffectslot *SendSlots[MAX_SENDS];
1070 ALfloat RoomRolloff[MAX_SENDS];
1071 ALfloat DecayDistance[MAX_SENDS];
1072 ALfloat DecayLFDistance[MAX_SENDS];
1073 ALfloat DecayHFDistance[MAX_SENDS];
1074 ALfloat DryGain, DryGainHF, DryGainLF;
1075 ALfloat WetGain[MAX_SENDS];
1076 ALfloat WetGainHF[MAX_SENDS];
1077 ALfloat WetGainLF[MAX_SENDS];
1078 bool directional;
1079 ALfloat ev, az;
1080 ALfloat spread;
1081 ALfloat Pitch;
1082 ALint i;
1084 /* Set mixing buffers and get send parameters. */
1085 voice->Direct.Buffer = Device->Dry.Buffer;
1086 voice->Direct.Channels = Device->Dry.NumChannels;
1087 for(i = 0;i < NumSends;i++)
1089 SendSlots[i] = props->Send[i].Slot;
1090 if(!SendSlots[i] && i == 0)
1091 SendSlots[i] = ALContext->DefaultSlot.get();
1092 if(!SendSlots[i] || SendSlots[i]->Params.EffectType == AL_EFFECT_NULL)
1094 SendSlots[i] = NULL;
1095 RoomRolloff[i] = 0.0f;
1096 DecayDistance[i] = 0.0f;
1097 DecayLFDistance[i] = 0.0f;
1098 DecayHFDistance[i] = 0.0f;
1100 else if(SendSlots[i]->Params.AuxSendAuto)
1102 RoomRolloff[i] = SendSlots[i]->Params.RoomRolloff + props->RoomRolloffFactor;
1103 /* Calculate the distances to where this effect's decay reaches
1104 * -60dB.
1106 DecayDistance[i] = SendSlots[i]->Params.DecayTime *
1107 Listener.Params.ReverbSpeedOfSound;
1108 DecayLFDistance[i] = DecayDistance[i] * SendSlots[i]->Params.DecayLFRatio;
1109 DecayHFDistance[i] = DecayDistance[i] * SendSlots[i]->Params.DecayHFRatio;
1110 if(SendSlots[i]->Params.DecayHFLimit)
1112 ALfloat airAbsorption = SendSlots[i]->Params.AirAbsorptionGainHF;
1113 if(airAbsorption < 1.0f)
1115 /* Calculate the distance to where this effect's air
1116 * absorption reaches -60dB, and limit the effect's HF
1117 * decay distance (so it doesn't take any longer to decay
1118 * than the air would allow).
1120 ALfloat absorb_dist = log10f(REVERB_DECAY_GAIN) / log10f(airAbsorption);
1121 DecayHFDistance[i] = minf(absorb_dist, DecayHFDistance[i]);
1125 else
1127 /* If the slot's auxiliary send auto is off, the data sent to the
1128 * effect slot is the same as the dry path, sans filter effects */
1129 RoomRolloff[i] = props->RolloffFactor;
1130 DecayDistance[i] = 0.0f;
1131 DecayLFDistance[i] = 0.0f;
1132 DecayHFDistance[i] = 0.0f;
1135 if(!SendSlots[i])
1137 voice->Send[i].Buffer = NULL;
1138 voice->Send[i].Channels = 0;
1140 else
1142 voice->Send[i].Buffer = SendSlots[i]->WetBuffer;
1143 voice->Send[i].Channels = SendSlots[i]->NumChannels;
1147 /* Transform source to listener space (convert to head relative) */
1148 aluVectorSet(&Position, props->Position[0], props->Position[1], props->Position[2], 1.0f);
1149 aluVectorSet(&Direction, props->Direction[0], props->Direction[1], props->Direction[2], 0.0f);
1150 aluVectorSet(&Velocity, props->Velocity[0], props->Velocity[1], props->Velocity[2], 0.0f);
1151 if(props->HeadRelative == AL_FALSE)
1153 const aluMatrixf *Matrix = &Listener.Params.Matrix;
1154 /* Transform source vectors */
1155 Position = aluMatrixfVector(Matrix, &Position);
1156 Velocity = aluMatrixfVector(Matrix, &Velocity);
1157 Direction = aluMatrixfVector(Matrix, &Direction);
1159 else
1161 const aluVector *lvelocity = &Listener.Params.Velocity;
1162 /* Offset the source velocity to be relative of the listener velocity */
1163 Velocity.v[0] += lvelocity->v[0];
1164 Velocity.v[1] += lvelocity->v[1];
1165 Velocity.v[2] += lvelocity->v[2];
1168 directional = aluNormalize(Direction.v) > 0.0f;
1169 SourceToListener.v[0] = -Position.v[0];
1170 SourceToListener.v[1] = -Position.v[1];
1171 SourceToListener.v[2] = -Position.v[2];
1172 SourceToListener.v[3] = 0.0f;
1173 Distance = aluNormalize(SourceToListener.v);
1175 /* Initial source gain */
1176 DryGain = props->Gain;
1177 DryGainHF = 1.0f;
1178 DryGainLF = 1.0f;
1179 for(i = 0;i < NumSends;i++)
1181 WetGain[i] = props->Gain;
1182 WetGainHF[i] = 1.0f;
1183 WetGainLF[i] = 1.0f;
1186 /* Calculate distance attenuation */
1187 ClampedDist = Distance;
1189 switch(Listener.Params.SourceDistanceModel ?
1190 props->mDistanceModel : Listener.Params.mDistanceModel)
1192 case DistanceModel::InverseClamped:
1193 ClampedDist = clampf(ClampedDist, props->RefDistance, props->MaxDistance);
1194 if(props->MaxDistance < props->RefDistance)
1195 break;
1196 /*fall-through*/
1197 case DistanceModel::Inverse:
1198 if(!(props->RefDistance > 0.0f))
1199 ClampedDist = props->RefDistance;
1200 else
1202 ALfloat dist = lerp(props->RefDistance, ClampedDist, props->RolloffFactor);
1203 if(dist > 0.0f) DryGain *= props->RefDistance / dist;
1204 for(i = 0;i < NumSends;i++)
1206 dist = lerp(props->RefDistance, ClampedDist, RoomRolloff[i]);
1207 if(dist > 0.0f) WetGain[i] *= props->RefDistance / dist;
1210 break;
1212 case DistanceModel::LinearClamped:
1213 ClampedDist = clampf(ClampedDist, props->RefDistance, props->MaxDistance);
1214 if(props->MaxDistance < props->RefDistance)
1215 break;
1216 /*fall-through*/
1217 case DistanceModel::Linear:
1218 if(!(props->MaxDistance != props->RefDistance))
1219 ClampedDist = props->RefDistance;
1220 else
1222 ALfloat attn = props->RolloffFactor * (ClampedDist-props->RefDistance) /
1223 (props->MaxDistance-props->RefDistance);
1224 DryGain *= maxf(1.0f - attn, 0.0f);
1225 for(i = 0;i < NumSends;i++)
1227 attn = RoomRolloff[i] * (ClampedDist-props->RefDistance) /
1228 (props->MaxDistance-props->RefDistance);
1229 WetGain[i] *= maxf(1.0f - attn, 0.0f);
1232 break;
1234 case DistanceModel::ExponentClamped:
1235 ClampedDist = clampf(ClampedDist, props->RefDistance, props->MaxDistance);
1236 if(props->MaxDistance < props->RefDistance)
1237 break;
1238 /*fall-through*/
1239 case DistanceModel::Exponent:
1240 if(!(ClampedDist > 0.0f && props->RefDistance > 0.0f))
1241 ClampedDist = props->RefDistance;
1242 else
1244 DryGain *= powf(ClampedDist/props->RefDistance, -props->RolloffFactor);
1245 for(i = 0;i < NumSends;i++)
1246 WetGain[i] *= powf(ClampedDist/props->RefDistance, -RoomRolloff[i]);
1248 break;
1250 case DistanceModel::Disable:
1251 ClampedDist = props->RefDistance;
1252 break;
1255 /* Calculate directional soundcones */
1256 if(directional && props->InnerAngle < 360.0f)
1258 ALfloat ConeVolume;
1259 ALfloat ConeHF;
1260 ALfloat Angle;
1262 Angle = acosf(aluDotproduct(&Direction, &SourceToListener));
1263 Angle = RAD2DEG(Angle * ConeScale * 2.0f);
1264 if(!(Angle > props->InnerAngle))
1266 ConeVolume = 1.0f;
1267 ConeHF = 1.0f;
1269 else if(Angle < props->OuterAngle)
1271 ALfloat scale = ( Angle-props->InnerAngle) /
1272 (props->OuterAngle-props->InnerAngle);
1273 ConeVolume = lerp(1.0f, props->OuterGain, scale);
1274 ConeHF = lerp(1.0f, props->OuterGainHF, scale);
1276 else
1278 ConeVolume = props->OuterGain;
1279 ConeHF = props->OuterGainHF;
1282 DryGain *= ConeVolume;
1283 if(props->DryGainHFAuto)
1284 DryGainHF *= ConeHF;
1285 if(props->WetGainAuto)
1287 for(i = 0;i < NumSends;i++)
1288 WetGain[i] *= ConeVolume;
1290 if(props->WetGainHFAuto)
1292 for(i = 0;i < NumSends;i++)
1293 WetGainHF[i] *= ConeHF;
1297 /* Apply gain and frequency filters */
1298 DryGain = clampf(DryGain, props->MinGain, props->MaxGain);
1299 DryGain = minf(DryGain*props->Direct.Gain*Listener.Params.Gain, GAIN_MIX_MAX);
1300 DryGainHF *= props->Direct.GainHF;
1301 DryGainLF *= props->Direct.GainLF;
1302 for(i = 0;i < NumSends;i++)
1304 WetGain[i] = clampf(WetGain[i], props->MinGain, props->MaxGain);
1305 WetGain[i] = minf(WetGain[i]*props->Send[i].Gain*Listener.Params.Gain, GAIN_MIX_MAX);
1306 WetGainHF[i] *= props->Send[i].GainHF;
1307 WetGainLF[i] *= props->Send[i].GainLF;
1310 /* Distance-based air absorption and initial send decay. */
1311 if(ClampedDist > props->RefDistance && props->RolloffFactor > 0.0f)
1313 ALfloat meters_base = (ClampedDist-props->RefDistance) * props->RolloffFactor *
1314 Listener.Params.MetersPerUnit;
1315 if(props->AirAbsorptionFactor > 0.0f)
1317 ALfloat hfattn = powf(AIRABSORBGAINHF, meters_base * props->AirAbsorptionFactor);
1318 DryGainHF *= hfattn;
1319 for(i = 0;i < NumSends;i++)
1320 WetGainHF[i] *= hfattn;
1323 if(props->WetGainAuto)
1325 /* Apply a decay-time transformation to the wet path, based on the
1326 * source distance in meters. The initial decay of the reverb
1327 * effect is calculated and applied to the wet path.
1329 for(i = 0;i < NumSends;i++)
1331 ALfloat gain, gainhf, gainlf;
1333 if(!(DecayDistance[i] > 0.0f))
1334 continue;
1336 gain = powf(REVERB_DECAY_GAIN, meters_base/DecayDistance[i]);
1337 WetGain[i] *= gain;
1338 /* Yes, the wet path's air absorption is applied with
1339 * WetGainAuto on, rather than WetGainHFAuto.
1341 if(gain > 0.0f)
1343 gainhf = powf(REVERB_DECAY_GAIN, meters_base/DecayHFDistance[i]);
1344 WetGainHF[i] *= minf(gainhf / gain, 1.0f);
1345 gainlf = powf(REVERB_DECAY_GAIN, meters_base/DecayLFDistance[i]);
1346 WetGainLF[i] *= minf(gainlf / gain, 1.0f);
1353 /* Initial source pitch */
1354 Pitch = props->Pitch;
1356 /* Calculate velocity-based doppler effect */
1357 DopplerFactor = props->DopplerFactor * Listener.Params.DopplerFactor;
1358 if(DopplerFactor > 0.0f)
1360 const aluVector *lvelocity = &Listener.Params.Velocity;
1361 const ALfloat SpeedOfSound = Listener.Params.SpeedOfSound;
1362 ALfloat vss, vls;
1364 vss = aluDotproduct(&Velocity, &SourceToListener) * DopplerFactor;
1365 vls = aluDotproduct(lvelocity, &SourceToListener) * DopplerFactor;
1367 if(!(vls < SpeedOfSound))
1369 /* Listener moving away from the source at the speed of sound.
1370 * Sound waves can't catch it.
1372 Pitch = 0.0f;
1374 else if(!(vss < SpeedOfSound))
1376 /* Source moving toward the listener at the speed of sound. Sound
1377 * waves bunch up to extreme frequencies.
1379 Pitch = HUGE_VALF;
1381 else
1383 /* Source and listener movement is nominal. Calculate the proper
1384 * doppler shift.
1386 Pitch *= (SpeedOfSound-vls) / (SpeedOfSound-vss);
1390 /* Adjust pitch based on the buffer and output frequencies, and calculate
1391 * fixed-point stepping value.
1393 Pitch *= (ALfloat)ALBuffer->Frequency/(ALfloat)Device->Frequency;
1394 if(Pitch > (ALfloat)MAX_PITCH)
1395 voice->Step = MAX_PITCH<<FRACTIONBITS;
1396 else
1397 voice->Step = maxi(fastf2i(Pitch * FRACTIONONE), 1);
1398 if(props->Resampler == BSinc24Resampler)
1399 BsincPrepare(voice->Step, &voice->ResampleState.bsinc, &bsinc24);
1400 else if(props->Resampler == BSinc12Resampler)
1401 BsincPrepare(voice->Step, &voice->ResampleState.bsinc, &bsinc12);
1402 voice->Resampler = SelectResampler(props->Resampler);
1404 if(Distance > 0.0f)
1406 /* Clamp Y, in case rounding errors caused it to end up outside of
1407 * -1...+1.
1409 ev = asinf(clampf(-SourceToListener.v[1], -1.0f, 1.0f));
1410 /* Double negation on Z cancels out; negate once for changing source-
1411 * to-listener to listener-to-source, and again for right-handed coords
1412 * with -Z in front.
1414 az = atan2f(-SourceToListener.v[0], SourceToListener.v[2]*ZScale);
1416 else
1417 ev = az = 0.0f;
1419 if(props->Radius > Distance)
1420 spread = F_TAU - Distance/props->Radius*F_PI;
1421 else if(Distance > 0.0f)
1422 spread = asinf(props->Radius / Distance) * 2.0f;
1423 else
1424 spread = 0.0f;
1426 CalcPanningAndFilters(voice, az, ev, Distance, spread, DryGain, DryGainHF, DryGainLF, WetGain,
1427 WetGainLF, WetGainHF, SendSlots, ALBuffer, props, Listener, Device);
1430 void CalcSourceParams(ALvoice *voice, ALCcontext *context, bool force)
1432 ALvoiceProps *props{voice->Update.exchange(nullptr, std::memory_order_acq_rel)};
1433 if(!props && !force) return;
1435 if(props)
1437 voice->Props = *props;
1439 AtomicReplaceHead(context->FreeVoiceProps, props);
1442 ALbufferlistitem *BufferListItem{voice->current_buffer.load(std::memory_order_relaxed)};
1443 while(BufferListItem)
1445 auto buffers_end = BufferListItem->buffers+BufferListItem->num_buffers;
1446 auto buffer = std::find_if(BufferListItem->buffers, buffers_end,
1447 [](const ALbuffer *buffer) noexcept -> bool
1448 { return buffer != nullptr; }
1450 if(LIKELY(buffer != buffers_end))
1452 if(voice->Props.SpatializeMode == SpatializeOn ||
1453 (voice->Props.SpatializeMode == SpatializeAuto && (*buffer)->FmtChannels == FmtMono))
1454 CalcAttnSourceParams(voice, &voice->Props, *buffer, context);
1455 else
1456 CalcNonAttnSourceParams(voice, &voice->Props, *buffer, context);
1457 break;
1459 BufferListItem = BufferListItem->next.load(std::memory_order_acquire);
1464 void ProcessParamUpdates(ALCcontext *ctx, const ALeffectslotArray *slots)
1466 IncrementRef(&ctx->UpdateCount);
1467 if(LIKELY(!ctx->HoldUpdates.load(std::memory_order_acquire)))
1469 bool cforce = CalcContextParams(ctx);
1470 bool force = CalcListenerParams(ctx) | cforce;
1471 std::for_each(slots->slot, slots->slot+slots->count,
1472 [ctx,cforce,&force](ALeffectslot *slot) -> void
1473 { force |= CalcEffectSlotParams(slot, ctx, cforce); }
1476 std::for_each(ctx->Voices, ctx->Voices+ctx->VoiceCount.load(std::memory_order_acquire),
1477 [ctx,force](ALvoice *voice) -> void
1479 ALuint sid{voice->SourceID.load(std::memory_order_acquire)};
1480 if(sid) CalcSourceParams(voice, ctx, force);
1484 IncrementRef(&ctx->UpdateCount);
1487 void ProcessContext(ALCcontext *ctx, ALsizei SamplesToDo)
1489 const ALeffectslotArray *auxslots{ctx->ActiveAuxSlots.load(std::memory_order_acquire)};
1491 /* Process pending propery updates for objects on the context. */
1492 ProcessParamUpdates(ctx, auxslots);
1494 /* Clear auxiliary effect slot mixing buffers. */
1495 std::for_each(auxslots->slot, auxslots->slot+auxslots->count,
1496 [SamplesToDo](ALeffectslot *slot) -> void
1498 std::for_each(slot->WetBuffer, slot->WetBuffer+slot->NumChannels,
1499 [SamplesToDo](ALfloat *buffer) -> void
1500 { std::fill_n(buffer, SamplesToDo, 0.0f); }
1505 /* Process voices that have a playing source. */
1506 std::for_each(ctx->Voices, ctx->Voices+ctx->VoiceCount.load(std::memory_order_acquire),
1507 [SamplesToDo,ctx](ALvoice *voice) -> void
1509 if(!voice->Playing.load(std::memory_order_acquire)) return;
1510 ALuint sid{voice->SourceID.load(std::memory_order_relaxed)};
1511 if(!sid || voice->Step < 1) return;
1513 if(!MixSource(voice, sid, ctx, SamplesToDo))
1515 voice->SourceID.store(0u, std::memory_order_relaxed);
1516 voice->Playing.store(false, std::memory_order_release);
1517 SendSourceStoppedEvent(ctx, sid);
1522 /* Process effects. */
1523 std::for_each(auxslots->slot, auxslots->slot+auxslots->count,
1524 [SamplesToDo](const ALeffectslot *slot) -> void
1526 EffectState *state{slot->Params.mEffectState};
1527 state->process(SamplesToDo, slot->WetBuffer, state->mOutBuffer,
1528 state->mOutChannels);
1534 void ApplyStablizer(FrontStablizer *Stablizer, ALfloat (*RESTRICT Buffer)[BUFFERSIZE],
1535 int lidx, int ridx, int cidx, ALsizei SamplesToDo, ALsizei NumChannels)
1537 ALfloat (*RESTRICT lsplit)[BUFFERSIZE] = Stablizer->LSplit;
1538 ALfloat (*RESTRICT rsplit)[BUFFERSIZE] = Stablizer->RSplit;
1539 ALsizei i;
1541 /* Apply an all-pass to all channels, except the front-left and front-
1542 * right, so they maintain the same relative phase.
1544 for(i = 0;i < NumChannels;i++)
1546 if(i == lidx || i == ridx)
1547 continue;
1548 Stablizer->APFilter[i].process(Buffer[i], SamplesToDo);
1551 Stablizer->LFilter.process(lsplit[1], lsplit[0], Buffer[lidx], SamplesToDo);
1552 Stablizer->RFilter.process(rsplit[1], rsplit[0], Buffer[ridx], SamplesToDo);
1554 for(i = 0;i < SamplesToDo;i++)
1556 ALfloat lfsum, hfsum;
1557 ALfloat m, s, c;
1559 lfsum = lsplit[0][i] + rsplit[0][i];
1560 hfsum = lsplit[1][i] + rsplit[1][i];
1561 s = lsplit[0][i] + lsplit[1][i] - rsplit[0][i] - rsplit[1][i];
1563 /* This pans the separate low- and high-frequency sums between being on
1564 * the center channel and the left/right channels. The low-frequency
1565 * sum is 1/3rd toward center (2/3rds on left/right) and the high-
1566 * frequency sum is 1/4th toward center (3/4ths on left/right). These
1567 * values can be tweaked.
1569 m = lfsum*cosf(1.0f/3.0f * F_PI_2) + hfsum*cosf(1.0f/4.0f * F_PI_2);
1570 c = lfsum*sinf(1.0f/3.0f * F_PI_2) + hfsum*sinf(1.0f/4.0f * F_PI_2);
1572 /* The generated center channel signal adds to the existing signal,
1573 * while the modified left and right channels replace.
1575 Buffer[lidx][i] = (m + s) * 0.5f;
1576 Buffer[ridx][i] = (m - s) * 0.5f;
1577 Buffer[cidx][i] += c * 0.5f;
1581 void ApplyDistanceComp(ALfloat (*RESTRICT Samples)[BUFFERSIZE], const DistanceComp &distcomp,
1582 ALfloat *RESTRICT Values, ALsizei SamplesToDo, ALsizei numchans)
1584 for(ALsizei c{0};c < numchans;c++)
1586 ALfloat *RESTRICT inout = Samples[c];
1587 const ALfloat gain = distcomp[c].Gain;
1588 const ALsizei base = distcomp[c].Length;
1589 ALfloat *RESTRICT distbuf = distcomp[c].Buffer;
1591 if(base == 0)
1593 if(gain < 1.0f)
1594 std::for_each(inout, inout+SamplesToDo,
1595 [gain](ALfloat &in) noexcept -> void
1596 { in *= gain; }
1598 continue;
1601 if(LIKELY(SamplesToDo >= base))
1603 auto out = std::copy_n(distbuf, base, Values);
1604 std::copy_n(inout, SamplesToDo-base, out);
1605 std::copy_n(inout+SamplesToDo-base, base, distbuf);
1607 else
1609 std::copy_n(distbuf, SamplesToDo, Values);
1610 auto out = std::copy(distbuf+SamplesToDo, distbuf+base, distbuf);
1611 std::copy_n(inout, SamplesToDo, out);
1613 std::transform<ALfloat*RESTRICT>(Values, Values+SamplesToDo, inout,
1614 [gain](ALfloat in) noexcept -> ALfloat
1615 { return in * gain; }
1620 void ApplyDither(ALfloat (*RESTRICT Samples)[BUFFERSIZE], ALuint *dither_seed,
1621 const ALfloat quant_scale, const ALsizei SamplesToDo, const ALsizei numchans)
1623 ASSUME(numchans > 0);
1625 /* Dithering. Generate whitenoise (uniform distribution of random values
1626 * between -1 and +1) and add it to the sample values, after scaling up to
1627 * the desired quantization depth amd before rounding.
1629 const ALfloat invscale = 1.0f / quant_scale;
1630 ALuint seed = *dither_seed;
1631 auto dither_channel = [&seed,invscale,quant_scale,SamplesToDo](ALfloat *buffer) -> void
1633 ASSUME(SamplesToDo > 0);
1634 std::transform(buffer, buffer+SamplesToDo, buffer,
1635 [&seed,invscale,quant_scale](ALfloat sample) noexcept -> ALfloat
1637 ALfloat val = sample * quant_scale;
1638 ALuint rng0 = dither_rng(&seed);
1639 ALuint rng1 = dither_rng(&seed);
1640 val += (ALfloat)(rng0*(1.0/UINT_MAX) - rng1*(1.0/UINT_MAX));
1641 return fast_roundf(val) * invscale;
1645 std::for_each(Samples, Samples+numchans, dither_channel);
1646 *dither_seed = seed;
1650 /* Base template left undefined. Should be marked =delete, but Clang 3.8.1
1651 * chokes on that given the inline specializations.
1653 template<typename T>
1654 inline T SampleConv(ALfloat) noexcept;
1656 template<> inline ALfloat SampleConv(ALfloat val) noexcept
1657 { return val; }
1658 template<> inline ALint SampleConv(ALfloat val) noexcept
1660 /* Floats have a 23-bit mantissa. There is an implied 1 bit in the mantissa
1661 * along with the sign bit, giving 25 bits total, so [-16777216, +16777216]
1662 * is the max value a normalized float can be scaled to before losing
1663 * precision.
1665 return fastf2i(clampf(val*16777216.0f, -16777216.0f, 16777215.0f))<<7;
1667 template<> inline ALshort SampleConv(ALfloat val) noexcept
1668 { return fastf2i(clampf(val*32768.0f, -32768.0f, 32767.0f)); }
1669 template<> inline ALbyte SampleConv(ALfloat val) noexcept
1670 { return fastf2i(clampf(val*128.0f, -128.0f, 127.0f)); }
1672 /* Define unsigned output variations. */
1673 template<> inline ALuint SampleConv(ALfloat val) noexcept
1674 { return SampleConv<ALint>(val) + 2147483648u; }
1675 template<> inline ALushort SampleConv(ALfloat val) noexcept
1676 { return SampleConv<ALshort>(val) + 32768; }
1677 template<> inline ALubyte SampleConv(ALfloat val) noexcept
1678 { return SampleConv<ALbyte>(val) + 128; }
1680 template<DevFmtType T>
1681 void Write(const ALfloat (*RESTRICT InBuffer)[BUFFERSIZE], ALvoid *OutBuffer,
1682 ALsizei Offset, ALsizei SamplesToDo, ALsizei numchans)
1684 using SampleType = typename DevFmtTypeTraits<T>::Type;
1686 ASSUME(numchans > 0);
1687 SampleType *outbase = static_cast<SampleType*>(OutBuffer) + Offset*numchans;
1688 auto conv_channel = [&outbase,SamplesToDo,numchans](const ALfloat *inbuf) -> void
1690 ASSUME(SamplesToDo > 0);
1691 SampleType *out{outbase++};
1692 std::for_each<const ALfloat*RESTRICT>(inbuf, inbuf+SamplesToDo,
1693 [numchans,&out](const ALfloat s) noexcept -> void
1695 *out = SampleConv<SampleType>(s);
1696 out += numchans;
1700 std::for_each(InBuffer, InBuffer+numchans, conv_channel);
1703 } // namespace
1705 void aluMixData(ALCdevice *device, ALvoid *OutBuffer, ALsizei NumSamples)
1707 FPUCtl mixer_mode{};
1708 for(ALsizei SamplesDone{0};SamplesDone < NumSamples;)
1710 const ALsizei SamplesToDo{mini(NumSamples-SamplesDone, BUFFERSIZE)};
1712 /* Clear main mixing buffers. */
1713 std::for_each(device->MixBuffer.begin(), device->MixBuffer.end(),
1714 [SamplesToDo](std::array<ALfloat,BUFFERSIZE> &buffer) -> void
1715 { std::fill_n(buffer.begin(), SamplesToDo, 0.0f); }
1718 /* Increment the mix count at the start (lsb should now be 1). */
1719 IncrementRef(&device->MixCount);
1721 /* For each context on this device, process and mix its sources and
1722 * effects.
1724 ALCcontext *ctx{device->ContextList.load(std::memory_order_acquire)};
1725 while(ctx)
1727 ProcessContext(ctx, SamplesToDo);
1729 ctx = ctx->next.load(std::memory_order_relaxed);
1732 /* Increment the clock time. Every second's worth of samples is
1733 * converted and added to clock base so that large sample counts don't
1734 * overflow during conversion. This also guarantees a stable
1735 * conversion.
1737 device->SamplesDone += SamplesToDo;
1738 device->ClockBase += std::chrono::seconds{device->SamplesDone / device->Frequency};
1739 device->SamplesDone %= device->Frequency;
1741 /* Increment the mix count at the end (lsb should now be 0). */
1742 IncrementRef(&device->MixCount);
1744 /* Apply any needed post-process for finalizing the Dry mix to the
1745 * RealOut (Ambisonic decode, UHJ encode, etc).
1747 if(LIKELY(device->PostProcess))
1748 device->PostProcess(device, SamplesToDo);
1750 /* Apply front image stablization for surround sound, if applicable. */
1751 if(device->Stablizer)
1753 int lidx = GetChannelIdxByName(&device->RealOut, FrontLeft);
1754 int ridx = GetChannelIdxByName(&device->RealOut, FrontRight);
1755 int cidx = GetChannelIdxByName(&device->RealOut, FrontCenter);
1756 assert(lidx >= 0 && ridx >= 0 && cidx >= 0);
1758 ApplyStablizer(device->Stablizer.get(), device->RealOut.Buffer, lidx, ridx, cidx,
1759 SamplesToDo, device->RealOut.NumChannels);
1762 /* Apply delays and attenuation for mismatched speaker distances. */
1763 ApplyDistanceComp(device->RealOut.Buffer, device->ChannelDelay, device->TempBuffer[0],
1764 SamplesToDo, device->RealOut.NumChannels);
1766 /* Apply compression, limiting final sample amplitude, if desired. */
1767 if(device->Limiter)
1768 ApplyCompression(device->Limiter.get(), SamplesToDo, device->RealOut.Buffer);
1770 /* Apply dithering. The compressor should have left enough headroom for
1771 * the dither noise to not saturate.
1773 if(device->DitherDepth > 0.0f)
1774 ApplyDither(device->RealOut.Buffer, &device->DitherSeed, device->DitherDepth,
1775 SamplesToDo, device->RealOut.NumChannels);
1777 if(LIKELY(OutBuffer))
1779 ALfloat (*Buffer)[BUFFERSIZE] = device->RealOut.Buffer;
1780 ALsizei Channels = device->RealOut.NumChannels;
1782 /* Finally, interleave and convert samples, writing to the device's
1783 * output buffer.
1785 switch(device->FmtType)
1787 #define HANDLE_WRITE(T) case T: \
1788 Write<T>(Buffer, OutBuffer, SamplesDone, SamplesToDo, Channels); break;
1789 HANDLE_WRITE(DevFmtByte)
1790 HANDLE_WRITE(DevFmtUByte)
1791 HANDLE_WRITE(DevFmtShort)
1792 HANDLE_WRITE(DevFmtUShort)
1793 HANDLE_WRITE(DevFmtInt)
1794 HANDLE_WRITE(DevFmtUInt)
1795 HANDLE_WRITE(DevFmtFloat)
1796 #undef HANDLE_WRITE
1800 SamplesDone += SamplesToDo;
1805 void aluHandleDisconnect(ALCdevice *device, const char *msg, ...)
1807 if(!device->Connected.exchange(AL_FALSE, std::memory_order_acq_rel))
1808 return;
1810 AsyncEvent evt{EventType_Disconnected};
1811 evt.u.user.type = AL_EVENT_TYPE_DISCONNECTED_SOFT;
1812 evt.u.user.id = 0;
1813 evt.u.user.param = 0;
1815 va_list args;
1816 va_start(args, msg);
1817 int msglen{vsnprintf(evt.u.user.msg, sizeof(evt.u.user.msg), msg, args)};
1818 va_end(args);
1820 if(msglen < 0 || (size_t)msglen >= sizeof(evt.u.user.msg))
1821 evt.u.user.msg[sizeof(evt.u.user.msg)-1] = 0;
1823 ALCcontext *ctx{device->ContextList.load()};
1824 while(ctx)
1826 ALbitfieldSOFT enabledevt = ctx->EnabledEvts.load(std::memory_order_acquire);
1827 if((enabledevt&EventType_Disconnected) &&
1828 ll_ringbuffer_write(ctx->AsyncEvents, &evt, 1) == 1)
1829 ctx->EventSem.post();
1831 std::for_each(ctx->Voices, ctx->Voices+ctx->VoiceCount.load(std::memory_order_acquire),
1832 [ctx](ALvoice *voice) -> void
1834 if(!voice->Playing.load(std::memory_order_acquire)) return;
1835 ALuint sid{voice->SourceID.load(std::memory_order_relaxed)};
1836 if(!sid) return;
1838 voice->SourceID.store(0u, std::memory_order_relaxed);
1839 voice->Playing.store(false, std::memory_order_release);
1840 /* If the source's voice was playing, it's now effectively
1841 * stopped (the source state will be updated the next time it's
1842 * checked).
1844 SendSourceStoppedEvent(ctx, sid);
1848 ctx = ctx->next.load(std::memory_order_relaxed);