Don't inline the utf8 converters
[openal-soft.git] / alc / alu.cpp
blob21eea1db750e77fc4aa2e99153a444b0b23dfa43
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 "alu.h"
25 #include <algorithm>
26 #include <array>
27 #include <atomic>
28 #include <cassert>
29 #include <chrono>
30 #include <climits>
31 #include <cmath>
32 #include <cstdarg>
33 #include <cstdio>
34 #include <cstdlib>
35 #include <cstring>
36 #include <functional>
37 #include <iterator>
38 #include <limits>
39 #include <memory>
40 #include <new>
41 #include <numeric>
42 #include <utility>
44 #include "AL/al.h"
45 #include "AL/alc.h"
46 #include "AL/efx.h"
48 #include "al/auxeffectslot.h"
49 #include "al/buffer.h"
50 #include "al/effect.h"
51 #include "al/event.h"
52 #include "al/listener.h"
53 #include "alcmain.h"
54 #include "alcontext.h"
55 #include "almalloc.h"
56 #include "alnumeric.h"
57 #include "alspan.h"
58 #include "alstring.h"
59 #include "ambidefs.h"
60 #include "atomic.h"
61 #include "bformatdec.h"
62 #include "bs2b.h"
63 #include "cpu_caps.h"
64 #include "devformat.h"
65 #include "effects/base.h"
66 #include "filters/biquad.h"
67 #include "filters/nfc.h"
68 #include "filters/splitter.h"
69 #include "fpu_modes.h"
70 #include "hrtf.h"
71 #include "inprogext.h"
72 #include "mastering.h"
73 #include "math_defs.h"
74 #include "mixer/defs.h"
75 #include "opthelpers.h"
76 #include "ringbuffer.h"
77 #include "strutils.h"
78 #include "threads.h"
79 #include "uhjfilter.h"
80 #include "vecmat.h"
82 #include "bsinc_inc.h"
85 static_assert(!(MAX_RESAMPLER_PADDING&1) && MAX_RESAMPLER_PADDING >= bsinc24.m[0],
86 "MAX_RESAMPLER_PADDING is not a multiple of two, or is too small");
89 namespace {
91 using namespace std::placeholders;
93 ALfloat InitConeScale()
95 ALfloat ret{1.0f};
96 if(auto optval = al::getenv("__ALSOFT_HALF_ANGLE_CONES"))
98 if(al::strcasecmp(optval->c_str(), "true") == 0
99 || strtol(optval->c_str(), nullptr, 0) == 1)
100 ret *= 0.5f;
102 return ret;
105 ALfloat InitZScale()
107 ALfloat ret{1.0f};
108 if(auto optval = al::getenv("__ALSOFT_REVERSE_Z"))
110 if(al::strcasecmp(optval->c_str(), "true") == 0
111 || strtol(optval->c_str(), nullptr, 0) == 1)
112 ret *= -1.0f;
114 return ret;
117 } // namespace
119 /* Cone scalar */
120 const ALfloat ConeScale{InitConeScale()};
122 /* Localized Z scalar for mono sources */
123 const ALfloat ZScale{InitZScale()};
126 namespace {
128 void ClearArray(ALfloat (&f)[MAX_OUTPUT_CHANNELS])
130 std::fill(std::begin(f), std::end(f), 0.0f);
133 struct ChanMap {
134 Channel channel;
135 ALfloat angle;
136 ALfloat elevation;
139 HrtfDirectMixerFunc MixDirectHrtf = MixDirectHrtf_<CTag>;
140 inline HrtfDirectMixerFunc SelectHrtfMixer(void)
142 #ifdef HAVE_NEON
143 if((CPUCapFlags&CPU_CAP_NEON))
144 return MixDirectHrtf_<NEONTag>;
145 #endif
146 #ifdef HAVE_SSE
147 if((CPUCapFlags&CPU_CAP_SSE))
148 return MixDirectHrtf_<SSETag>;
149 #endif
151 return MixDirectHrtf_<CTag>;
155 inline void BsincPrepare(const ALuint increment, BsincState *state, const BSincTable *table)
157 size_t si{BSINC_SCALE_COUNT - 1};
158 float sf{0.0f};
160 if(increment > FRACTIONONE)
162 sf = FRACTIONONE / static_cast<float>(increment);
163 sf = maxf(0.0f, (BSINC_SCALE_COUNT-1) * (sf-table->scaleBase) * table->scaleRange);
164 si = float2uint(sf);
165 /* The interpolation factor is fit to this diagonally-symmetric curve
166 * to reduce the transition ripple caused by interpolating different
167 * scales of the sinc function.
169 sf = 1.0f - std::cos(std::asin(sf - static_cast<float>(si)));
172 state->sf = sf;
173 state->m = table->m[si];
174 state->l = (state->m/2) - 1;
175 state->filter = table->Tab + table->filterOffset[si];
178 inline ResamplerFunc SelectResampler(Resampler resampler, ALuint increment)
180 switch(resampler)
182 case Resampler::Point:
183 return Resample_<PointTag,CTag>;
184 case Resampler::Linear:
185 #ifdef HAVE_NEON
186 if((CPUCapFlags&CPU_CAP_NEON))
187 return Resample_<LerpTag,NEONTag>;
188 #endif
189 #ifdef HAVE_SSE4_1
190 if((CPUCapFlags&CPU_CAP_SSE4_1))
191 return Resample_<LerpTag,SSE4Tag>;
192 #endif
193 #ifdef HAVE_SSE2
194 if((CPUCapFlags&CPU_CAP_SSE2))
195 return Resample_<LerpTag,SSE2Tag>;
196 #endif
197 return Resample_<LerpTag,CTag>;
198 case Resampler::Cubic:
199 return Resample_<CubicTag,CTag>;
200 case Resampler::BSinc12:
201 case Resampler::BSinc24:
202 if(increment <= FRACTIONONE)
204 /* fall-through */
205 case Resampler::FastBSinc12:
206 case Resampler::FastBSinc24:
207 #ifdef HAVE_NEON
208 if((CPUCapFlags&CPU_CAP_NEON))
209 return Resample_<FastBSincTag,NEONTag>;
210 #endif
211 #ifdef HAVE_SSE
212 if((CPUCapFlags&CPU_CAP_SSE))
213 return Resample_<FastBSincTag,SSETag>;
214 #endif
215 return Resample_<FastBSincTag,CTag>;
217 #ifdef HAVE_NEON
218 if((CPUCapFlags&CPU_CAP_NEON))
219 return Resample_<BSincTag,NEONTag>;
220 #endif
221 #ifdef HAVE_SSE
222 if((CPUCapFlags&CPU_CAP_SSE))
223 return Resample_<BSincTag,SSETag>;
224 #endif
225 return Resample_<BSincTag,CTag>;
228 return Resample_<PointTag,CTag>;
231 } // namespace
233 void aluInit(void)
235 MixDirectHrtf = SelectHrtfMixer();
239 ResamplerFunc PrepareResampler(Resampler resampler, ALuint increment, InterpState *state)
241 switch(resampler)
243 case Resampler::Point:
244 case Resampler::Linear:
245 case Resampler::Cubic:
246 break;
247 case Resampler::FastBSinc12:
248 case Resampler::BSinc12:
249 BsincPrepare(increment, &state->bsinc, &bsinc12);
250 break;
251 case Resampler::FastBSinc24:
252 case Resampler::BSinc24:
253 BsincPrepare(increment, &state->bsinc, &bsinc24);
254 break;
256 return SelectResampler(resampler, increment);
260 void ALCdevice::ProcessHrtf(const size_t SamplesToDo)
262 /* HRTF is stereo output only. */
263 const ALuint lidx{RealOut.ChannelIndex[FrontLeft]};
264 const ALuint ridx{RealOut.ChannelIndex[FrontRight]};
266 MixDirectHrtf(RealOut.Buffer[lidx], RealOut.Buffer[ridx], Dry.Buffer, HrtfAccumData,
267 mHrtfState.get(), SamplesToDo);
270 void ALCdevice::ProcessAmbiDec(const size_t SamplesToDo)
272 AmbiDecoder->process(RealOut.Buffer, Dry.Buffer.data(), SamplesToDo);
275 void ALCdevice::ProcessUhj(const size_t SamplesToDo)
277 /* UHJ is stereo output only. */
278 const ALuint lidx{RealOut.ChannelIndex[FrontLeft]};
279 const ALuint ridx{RealOut.ChannelIndex[FrontRight]};
281 /* Encode to stereo-compatible 2-channel UHJ output. */
282 Uhj_Encoder->encode(RealOut.Buffer[lidx], RealOut.Buffer[ridx], Dry.Buffer.data(),
283 SamplesToDo);
286 void ALCdevice::ProcessBs2b(const size_t SamplesToDo)
288 /* First, decode the ambisonic mix to the "real" output. */
289 AmbiDecoder->process(RealOut.Buffer, Dry.Buffer.data(), SamplesToDo);
291 /* BS2B is stereo output only. */
292 const ALuint lidx{RealOut.ChannelIndex[FrontLeft]};
293 const ALuint ridx{RealOut.ChannelIndex[FrontRight]};
295 /* Now apply the BS2B binaural/crossfeed filter. */
296 bs2b_cross_feed(Bs2b.get(), RealOut.Buffer[lidx].data(), RealOut.Buffer[ridx].data(),
297 SamplesToDo);
301 namespace {
303 /* This RNG method was created based on the math found in opusdec. It's quick,
304 * and starting with a seed value of 22222, is suitable for generating
305 * whitenoise.
307 inline ALuint dither_rng(ALuint *seed) noexcept
309 *seed = (*seed * 96314165) + 907633515;
310 return *seed;
314 inline alu::Vector aluCrossproduct(const alu::Vector &in1, const alu::Vector &in2)
316 return alu::Vector{
317 in1[1]*in2[2] - in1[2]*in2[1],
318 in1[2]*in2[0] - in1[0]*in2[2],
319 in1[0]*in2[1] - in1[1]*in2[0],
320 0.0f
324 inline ALfloat aluDotproduct(const alu::Vector &vec1, const alu::Vector &vec2)
326 return vec1[0]*vec2[0] + vec1[1]*vec2[1] + vec1[2]*vec2[2];
330 alu::Vector operator*(const alu::Matrix &mtx, const alu::Vector &vec) noexcept
332 return alu::Vector{
333 vec[0]*mtx[0][0] + vec[1]*mtx[1][0] + vec[2]*mtx[2][0] + vec[3]*mtx[3][0],
334 vec[0]*mtx[0][1] + vec[1]*mtx[1][1] + vec[2]*mtx[2][1] + vec[3]*mtx[3][1],
335 vec[0]*mtx[0][2] + vec[1]*mtx[1][2] + vec[2]*mtx[2][2] + vec[3]*mtx[3][2],
336 vec[0]*mtx[0][3] + vec[1]*mtx[1][3] + vec[2]*mtx[2][3] + vec[3]*mtx[3][3]
341 bool CalcContextParams(ALCcontext *Context)
343 ALcontextProps *props{Context->mUpdate.exchange(nullptr, std::memory_order_acq_rel)};
344 if(!props) return false;
346 ALlistener &Listener = Context->mListener;
347 Listener.Params.DopplerFactor = props->DopplerFactor;
348 Listener.Params.SpeedOfSound = props->SpeedOfSound * props->DopplerVelocity;
350 Listener.Params.SourceDistanceModel = props->SourceDistanceModel;
351 Listener.Params.mDistanceModel = props->mDistanceModel;
353 AtomicReplaceHead(Context->mFreeContextProps, props);
354 return true;
357 bool CalcListenerParams(ALCcontext *Context)
359 ALlistener &Listener = Context->mListener;
361 ALlistenerProps *props{Listener.Params.Update.exchange(nullptr, std::memory_order_acq_rel)};
362 if(!props) return false;
364 /* AT then UP */
365 alu::Vector N{props->OrientAt[0], props->OrientAt[1], props->OrientAt[2], 0.0f};
366 N.normalize();
367 alu::Vector V{props->OrientUp[0], props->OrientUp[1], props->OrientUp[2], 0.0f};
368 V.normalize();
369 /* Build and normalize right-vector */
370 alu::Vector U{aluCrossproduct(N, V)};
371 U.normalize();
373 Listener.Params.Matrix = alu::Matrix{
374 U[0], V[0], -N[0], 0.0f,
375 U[1], V[1], -N[1], 0.0f,
376 U[2], V[2], -N[2], 0.0f,
377 0.0f, 0.0f, 0.0f, 1.0f
380 const alu::Vector P{Listener.Params.Matrix *
381 alu::Vector{props->Position[0], props->Position[1], props->Position[2], 1.0f}};
382 Listener.Params.Matrix.setRow(3, -P[0], -P[1], -P[2], 1.0f);
384 const alu::Vector vel{props->Velocity[0], props->Velocity[1], props->Velocity[2], 0.0f};
385 Listener.Params.Velocity = Listener.Params.Matrix * vel;
387 Listener.Params.Gain = props->Gain * Context->mGainBoost;
388 Listener.Params.MetersPerUnit = props->MetersPerUnit;
390 AtomicReplaceHead(Context->mFreeListenerProps, props);
391 return true;
394 bool CalcEffectSlotParams(ALeffectslot *slot, ALCcontext *context)
396 ALeffectslotProps *props{slot->Params.Update.exchange(nullptr, std::memory_order_acq_rel)};
397 if(!props) return false;
399 slot->Params.Gain = props->Gain;
400 slot->Params.AuxSendAuto = props->AuxSendAuto;
401 slot->Params.Target = props->Target;
402 slot->Params.EffectType = props->Type;
403 slot->Params.mEffectProps = 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 EffectState *state{props->State};
424 props->State = nullptr;
425 EffectState *oldstate{slot->Params.mEffectState};
426 slot->Params.mEffectState = state;
428 /* Only release the old state if it won't get deleted, since we can't be
429 * deleting/freeing anything in the mixer.
431 if(!oldstate->releaseIfNoDelete())
433 /* Otherwise, if it would be deleted send it off with a release event. */
434 RingBuffer *ring{context->mAsyncEvents.get()};
435 auto evt_vec = ring->getWriteVector();
436 if LIKELY(evt_vec.first.len > 0)
438 AsyncEvent *evt{new (evt_vec.first.buf) AsyncEvent{EventType_ReleaseEffectState}};
439 evt->u.mEffectState = oldstate;
440 ring->writeAdvance(1);
441 context->mEventSem.post();
443 else
445 /* If writing the event failed, the queue was probably full. Store
446 * the old state in the property object where it can eventually be
447 * cleaned up sometime later (not ideal, but better than blocking
448 * or leaking).
450 props->State = oldstate;
454 AtomicReplaceHead(context->mFreeEffectslotProps, props);
456 EffectTarget output;
457 if(ALeffectslot *target{slot->Params.Target})
458 output = EffectTarget{&target->Wet, nullptr};
459 else
461 ALCdevice *device{context->mDevice.get()};
462 output = EffectTarget{&device->Dry, &device->RealOut};
464 state->update(context, slot, &slot->Params.mEffectProps, output);
465 return true;
469 /* Scales the given azimuth toward the side (+/- pi/2 radians) for positions in
470 * front.
472 inline float ScaleAzimuthFront(float azimuth, float scale)
474 const ALfloat abs_azi{std::fabs(azimuth)};
475 if(!(abs_azi >= al::MathDefs<float>::Pi()*0.5f))
476 return std::copysign(minf(abs_azi*scale, al::MathDefs<float>::Pi()*0.5f), azimuth);
477 return azimuth;
480 void CalcPanningAndFilters(ALvoice *voice, const ALfloat xpos, const ALfloat ypos,
481 const ALfloat zpos, const ALfloat Distance, const ALfloat Spread, const ALfloat DryGain,
482 const ALfloat DryGainHF, const ALfloat DryGainLF, const ALfloat (&WetGain)[MAX_SENDS],
483 const ALfloat (&WetGainLF)[MAX_SENDS], const ALfloat (&WetGainHF)[MAX_SENDS],
484 ALeffectslot *(&SendSlots)[MAX_SENDS], const ALvoicePropsBase *props,
485 const ALlistener &Listener, const ALCdevice *Device)
487 static constexpr ChanMap MonoMap[1]{
488 { FrontCenter, 0.0f, 0.0f }
489 }, RearMap[2]{
490 { BackLeft, Deg2Rad(-150.0f), Deg2Rad(0.0f) },
491 { BackRight, Deg2Rad( 150.0f), Deg2Rad(0.0f) }
492 }, QuadMap[4]{
493 { FrontLeft, Deg2Rad( -45.0f), Deg2Rad(0.0f) },
494 { FrontRight, Deg2Rad( 45.0f), Deg2Rad(0.0f) },
495 { BackLeft, Deg2Rad(-135.0f), Deg2Rad(0.0f) },
496 { BackRight, Deg2Rad( 135.0f), Deg2Rad(0.0f) }
497 }, X51Map[6]{
498 { FrontLeft, Deg2Rad( -30.0f), Deg2Rad(0.0f) },
499 { FrontRight, Deg2Rad( 30.0f), Deg2Rad(0.0f) },
500 { FrontCenter, Deg2Rad( 0.0f), Deg2Rad(0.0f) },
501 { LFE, 0.0f, 0.0f },
502 { SideLeft, Deg2Rad(-110.0f), Deg2Rad(0.0f) },
503 { SideRight, Deg2Rad( 110.0f), Deg2Rad(0.0f) }
504 }, X61Map[7]{
505 { FrontLeft, Deg2Rad(-30.0f), Deg2Rad(0.0f) },
506 { FrontRight, Deg2Rad( 30.0f), Deg2Rad(0.0f) },
507 { FrontCenter, Deg2Rad( 0.0f), Deg2Rad(0.0f) },
508 { LFE, 0.0f, 0.0f },
509 { BackCenter, Deg2Rad(180.0f), Deg2Rad(0.0f) },
510 { SideLeft, Deg2Rad(-90.0f), Deg2Rad(0.0f) },
511 { SideRight, Deg2Rad( 90.0f), Deg2Rad(0.0f) }
512 }, X71Map[8]{
513 { FrontLeft, Deg2Rad( -30.0f), Deg2Rad(0.0f) },
514 { FrontRight, Deg2Rad( 30.0f), Deg2Rad(0.0f) },
515 { FrontCenter, Deg2Rad( 0.0f), Deg2Rad(0.0f) },
516 { LFE, 0.0f, 0.0f },
517 { BackLeft, Deg2Rad(-150.0f), Deg2Rad(0.0f) },
518 { BackRight, Deg2Rad( 150.0f), Deg2Rad(0.0f) },
519 { SideLeft, Deg2Rad( -90.0f), Deg2Rad(0.0f) },
520 { SideRight, Deg2Rad( 90.0f), Deg2Rad(0.0f) }
523 ChanMap StereoMap[2]{
524 { FrontLeft, Deg2Rad(-30.0f), Deg2Rad(0.0f) },
525 { FrontRight, Deg2Rad( 30.0f), Deg2Rad(0.0f) }
528 const auto Frequency = static_cast<ALfloat>(Device->Frequency);
529 const ALuint NumSends{Device->NumAuxSends};
531 bool DirectChannels{props->DirectChannels != AL_FALSE};
532 const ChanMap *chans{nullptr};
533 ALuint num_channels{0};
534 bool isbformat{false};
535 ALfloat downmix_gain{1.0f};
536 switch(voice->mFmtChannels)
538 case FmtMono:
539 chans = MonoMap;
540 num_channels = 1;
541 /* Mono buffers are never played direct. */
542 DirectChannels = false;
543 break;
545 case FmtStereo:
546 /* Convert counter-clockwise to clockwise. */
547 StereoMap[0].angle = -props->StereoPan[0];
548 StereoMap[1].angle = -props->StereoPan[1];
550 chans = StereoMap;
551 num_channels = 2;
552 downmix_gain = 1.0f / 2.0f;
553 break;
555 case FmtRear:
556 chans = RearMap;
557 num_channels = 2;
558 downmix_gain = 1.0f / 2.0f;
559 break;
561 case FmtQuad:
562 chans = QuadMap;
563 num_channels = 4;
564 downmix_gain = 1.0f / 4.0f;
565 break;
567 case FmtX51:
568 chans = X51Map;
569 num_channels = 6;
570 /* NOTE: Excludes LFE. */
571 downmix_gain = 1.0f / 5.0f;
572 break;
574 case FmtX61:
575 chans = X61Map;
576 num_channels = 7;
577 /* NOTE: Excludes LFE. */
578 downmix_gain = 1.0f / 6.0f;
579 break;
581 case FmtX71:
582 chans = X71Map;
583 num_channels = 8;
584 /* NOTE: Excludes LFE. */
585 downmix_gain = 1.0f / 7.0f;
586 break;
588 case FmtBFormat2D:
589 num_channels = 3;
590 isbformat = true;
591 DirectChannels = false;
592 break;
594 case FmtBFormat3D:
595 num_channels = 4;
596 isbformat = true;
597 DirectChannels = false;
598 break;
600 ASSUME(num_channels > 0);
602 std::for_each(voice->mChans.begin(), voice->mChans.begin()+num_channels,
603 [NumSends](ALvoice::ChannelData &chandata) -> void
605 chandata.mDryParams.Hrtf.Target = HrtfFilter{};
606 ClearArray(chandata.mDryParams.Gains.Target);
607 std::for_each(chandata.mWetParams.begin(), chandata.mWetParams.begin()+NumSends,
608 [](SendParams &params) -> void { ClearArray(params.Gains.Target); });
611 voice->mFlags &= ~(VOICE_HAS_HRTF | VOICE_HAS_NFC);
612 if(isbformat)
614 /* Special handling for B-Format sources. */
616 if(Distance > std::numeric_limits<float>::epsilon())
618 /* Panning a B-Format sound toward some direction is easy. Just pan
619 * the first (W) channel as a normal mono sound and silence the
620 * others.
623 if(Device->AvgSpeakerDist > 0.0f)
625 /* Clamp the distance for really close sources, to prevent
626 * excessive bass.
628 const ALfloat mdist{maxf(Distance, Device->AvgSpeakerDist/4.0f)};
629 const ALfloat w0{SPEEDOFSOUNDMETRESPERSEC / (mdist * Frequency)};
631 /* Only need to adjust the first channel of a B-Format source. */
632 voice->mChans[0].mDryParams.NFCtrlFilter.adjust(w0);
634 voice->mFlags |= VOICE_HAS_NFC;
637 ALfloat coeffs[MAX_AMBI_CHANNELS];
638 if(Device->mRenderMode != StereoPair)
639 CalcDirectionCoeffs({xpos, ypos, zpos}, Spread, coeffs);
640 else
642 /* Clamp Y, in case rounding errors caused it to end up outside
643 * of -1...+1.
645 const ALfloat ev{std::asin(clampf(ypos, -1.0f, 1.0f))};
646 /* Negate Z for right-handed coords with -Z in front. */
647 const ALfloat az{std::atan2(xpos, -zpos)};
649 /* A scalar of 1.5 for plain stereo results in +/-60 degrees
650 * being moved to +/-90 degrees for direct right and left
651 * speaker responses.
653 CalcAngleCoeffs(ScaleAzimuthFront(az, 1.5f), ev, Spread, coeffs);
656 /* NOTE: W needs to be scaled due to FuMa normalization. */
657 const ALfloat &scale0 = AmbiScale::FromFuMa[0];
658 ComputePanGains(&Device->Dry, coeffs, DryGain*scale0,
659 voice->mChans[0].mDryParams.Gains.Target);
660 for(ALuint i{0};i < NumSends;i++)
662 if(const ALeffectslot *Slot{SendSlots[i]})
663 ComputePanGains(&Slot->Wet, coeffs, WetGain[i]*scale0,
664 voice->mChans[0].mWetParams[i].Gains.Target);
667 else
669 if(Device->AvgSpeakerDist > 0.0f)
671 /* NOTE: The NFCtrlFilters were created with a w0 of 0, which
672 * is what we want for FOA input. The first channel may have
673 * been previously re-adjusted if panned, so reset it.
675 voice->mChans[0].mDryParams.NFCtrlFilter.adjust(0.0f);
677 voice->mFlags |= VOICE_HAS_NFC;
680 /* Local B-Format sources have their XYZ channels rotated according
681 * to the orientation.
683 /* AT then UP */
684 alu::Vector N{props->OrientAt[0], props->OrientAt[1], props->OrientAt[2], 0.0f};
685 N.normalize();
686 alu::Vector V{props->OrientUp[0], props->OrientUp[1], props->OrientUp[2], 0.0f};
687 V.normalize();
688 if(!props->HeadRelative)
690 N = Listener.Params.Matrix * N;
691 V = Listener.Params.Matrix * V;
693 /* Build and normalize right-vector */
694 alu::Vector U{aluCrossproduct(N, V)};
695 U.normalize();
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 const ALfloat &wscale = AmbiScale::FromFuMa[0];
702 const ALfloat &yscale = AmbiScale::FromFuMa[1];
703 const ALfloat &zscale = AmbiScale::FromFuMa[2];
704 const ALfloat &xscale = AmbiScale::FromFuMa[3];
705 const ALfloat matrix[4][MAX_AMBI_CHANNELS]{
706 // ACN0 ACN1 ACN2 ACN3
707 { wscale, 0.0f, 0.0f, 0.0f }, // FuMa W
708 { 0.0f, -N[0]*xscale, N[1]*xscale, -N[2]*xscale }, // FuMa X
709 { 0.0f, U[0]*yscale, -U[1]*yscale, U[2]*yscale }, // FuMa Y
710 { 0.0f, -V[0]*zscale, V[1]*zscale, -V[2]*zscale } // FuMa Z
713 for(ALuint c{0};c < num_channels;c++)
715 ComputePanGains(&Device->Dry, matrix[c], DryGain,
716 voice->mChans[c].mDryParams.Gains.Target);
718 for(ALuint i{0};i < NumSends;i++)
720 if(const ALeffectslot *Slot{SendSlots[i]})
721 ComputePanGains(&Slot->Wet, matrix[c], WetGain[i],
722 voice->mChans[c].mWetParams[i].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->mDirect.Buffer = Device->RealOut.Buffer;
734 for(ALuint c{0};c < num_channels;c++)
736 const ALuint idx{GetChannelIdxByName(Device->RealOut, chans[c].channel)};
737 if(idx != INVALID_CHANNEL_INDEX)
738 voice->mChans[c].mDryParams.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(ALuint c{0};c < num_channels;c++)
746 ALfloat coeffs[MAX_AMBI_CHANNELS];
747 CalcAngleCoeffs(chans[c].angle, chans[c].elevation, 0.0f, coeffs);
749 for(ALuint i{0};i < NumSends;i++)
751 if(const ALeffectslot *Slot{SendSlots[i]})
752 ComputePanGains(&Slot->Wet, coeffs, WetGain[i],
753 voice->mChans[c].mWetParams[i].Gains.Target);
757 else if(Device->mRenderMode == HrtfRender)
759 /* Full HRTF rendering. Skip the virtual channels and render to the
760 * real outputs.
762 voice->mDirect.Buffer = Device->RealOut.Buffer;
764 if(Distance > std::numeric_limits<float>::epsilon())
766 const ALfloat ev{std::asin(clampf(ypos, -1.0f, 1.0f))};
767 const ALfloat az{std::atan2(xpos, -zpos)};
769 /* Get the HRIR coefficients and delays just once, for the given
770 * source direction.
772 GetHrtfCoeffs(Device->mHrtf, ev, az, Distance, Spread,
773 voice->mChans[0].mDryParams.Hrtf.Target.Coeffs,
774 voice->mChans[0].mDryParams.Hrtf.Target.Delay);
775 voice->mChans[0].mDryParams.Hrtf.Target.Gain = DryGain * downmix_gain;
777 /* Remaining channels use the same results as the first. */
778 for(ALuint c{1};c < num_channels;c++)
780 /* Skip LFE */
781 if(chans[c].channel == LFE) continue;
782 voice->mChans[c].mDryParams.Hrtf.Target = voice->mChans[0].mDryParams.Hrtf.Target;
785 /* Calculate the directional coefficients once, which apply to all
786 * input channels of the source sends.
788 ALfloat coeffs[MAX_AMBI_CHANNELS];
789 CalcDirectionCoeffs({xpos, ypos, zpos}, Spread, coeffs);
791 for(ALuint c{0};c < num_channels;c++)
793 /* Skip LFE */
794 if(chans[c].channel == LFE)
795 continue;
796 for(ALuint i{0};i < NumSends;i++)
798 if(const ALeffectslot *Slot{SendSlots[i]})
799 ComputePanGains(&Slot->Wet, coeffs, WetGain[i] * downmix_gain,
800 voice->mChans[c].mWetParams[i].Gains.Target);
804 else
806 /* Local sources on HRTF play with each channel panned to its
807 * relative location around the listener, providing "virtual
808 * speaker" responses.
810 for(ALuint c{0};c < num_channels;c++)
812 /* Skip LFE */
813 if(chans[c].channel == LFE)
814 continue;
816 /* Get the HRIR coefficients and delays for this channel
817 * position.
819 GetHrtfCoeffs(Device->mHrtf, chans[c].elevation, chans[c].angle,
820 std::numeric_limits<float>::infinity(), Spread,
821 voice->mChans[c].mDryParams.Hrtf.Target.Coeffs,
822 voice->mChans[c].mDryParams.Hrtf.Target.Delay);
823 voice->mChans[c].mDryParams.Hrtf.Target.Gain = DryGain;
825 /* Normal panning for auxiliary sends. */
826 ALfloat coeffs[MAX_AMBI_CHANNELS];
827 CalcAngleCoeffs(chans[c].angle, chans[c].elevation, Spread, coeffs);
829 for(ALuint i{0};i < NumSends;i++)
831 if(const ALeffectslot *Slot{SendSlots[i]})
832 ComputePanGains(&Slot->Wet, coeffs, WetGain[i],
833 voice->mChans[c].mWetParams[i].Gains.Target);
838 voice->mFlags |= VOICE_HAS_HRTF;
840 else
842 /* Non-HRTF rendering. Use normal panning to the output. */
844 if(Distance > std::numeric_limits<float>::epsilon())
846 /* Calculate NFC filter coefficient if needed. */
847 if(Device->AvgSpeakerDist > 0.0f)
849 /* Clamp the distance for really close sources, to prevent
850 * excessive bass.
852 const ALfloat mdist{maxf(Distance, Device->AvgSpeakerDist/4.0f)};
853 const ALfloat w0{SPEEDOFSOUNDMETRESPERSEC / (mdist * Frequency)};
855 /* Adjust NFC filters. */
856 for(ALuint c{0};c < num_channels;c++)
857 voice->mChans[c].mDryParams.NFCtrlFilter.adjust(w0);
859 voice->mFlags |= VOICE_HAS_NFC;
862 /* Calculate the directional coefficients once, which apply to all
863 * input channels.
865 ALfloat coeffs[MAX_AMBI_CHANNELS];
866 if(Device->mRenderMode != StereoPair)
867 CalcDirectionCoeffs({xpos, ypos, zpos}, Spread, coeffs);
868 else
870 const ALfloat ev{std::asin(clampf(ypos, -1.0f, 1.0f))};
871 const ALfloat az{std::atan2(xpos, -zpos)};
872 CalcAngleCoeffs(ScaleAzimuthFront(az, 1.5f), ev, Spread, coeffs);
875 for(ALuint c{0};c < num_channels;c++)
877 /* Special-case LFE */
878 if(chans[c].channel == LFE)
880 if(Device->Dry.Buffer.data() == Device->RealOut.Buffer.data())
882 const ALuint idx{GetChannelIdxByName(Device->RealOut, chans[c].channel)};
883 if(idx != INVALID_CHANNEL_INDEX)
884 voice->mChans[c].mDryParams.Gains.Target[idx] = DryGain;
886 continue;
889 ComputePanGains(&Device->Dry, coeffs, DryGain * downmix_gain,
890 voice->mChans[c].mDryParams.Gains.Target);
891 for(ALuint i{0};i < NumSends;i++)
893 if(const ALeffectslot *Slot{SendSlots[i]})
894 ComputePanGains(&Slot->Wet, coeffs, WetGain[i] * downmix_gain,
895 voice->mChans[c].mWetParams[i].Gains.Target);
899 else
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 const ALfloat w0{SPEEDOFSOUNDMETRESPERSEC / (Device->AvgSpeakerDist * Frequency)};
910 for(ALuint c{0};c < num_channels;c++)
911 voice->mChans[c].mDryParams.NFCtrlFilter.adjust(w0);
913 voice->mFlags |= VOICE_HAS_NFC;
916 for(ALuint c{0};c < num_channels;c++)
918 /* Special-case LFE */
919 if(chans[c].channel == LFE)
921 if(Device->Dry.Buffer.data() == Device->RealOut.Buffer.data())
923 const ALuint idx{GetChannelIdxByName(Device->RealOut, chans[c].channel)};
924 if(idx != INVALID_CHANNEL_INDEX)
925 voice->mChans[c].mDryParams.Gains.Target[idx] = DryGain;
927 continue;
930 ALfloat coeffs[MAX_AMBI_CHANNELS];
931 CalcAngleCoeffs(
932 (Device->mRenderMode==StereoPair) ? ScaleAzimuthFront(chans[c].angle, 3.0f)
933 : chans[c].angle,
934 chans[c].elevation, Spread, coeffs
937 ComputePanGains(&Device->Dry, coeffs, DryGain,
938 voice->mChans[c].mDryParams.Gains.Target);
939 for(ALuint i{0};i < NumSends;i++)
941 if(const ALeffectslot *Slot{SendSlots[i]})
942 ComputePanGains(&Slot->Wet, coeffs, WetGain[i],
943 voice->mChans[c].mWetParams[i].Gains.Target);
950 const ALfloat hfScale{props->Direct.HFReference / Frequency};
951 const ALfloat lfScale{props->Direct.LFReference / Frequency};
952 const ALfloat gainHF{maxf(DryGainHF, 0.001f)}; /* Limit -60dB */
953 const ALfloat gainLF{maxf(DryGainLF, 0.001f)};
955 voice->mDirect.FilterType = AF_None;
956 if(gainHF != 1.0f) voice->mDirect.FilterType |= AF_LowPass;
957 if(gainLF != 1.0f) voice->mDirect.FilterType |= AF_HighPass;
958 auto &lowpass = voice->mChans[0].mDryParams.LowPass;
959 auto &highpass = voice->mChans[0].mDryParams.HighPass;
960 lowpass.setParams(BiquadType::HighShelf, gainHF, hfScale,
961 lowpass.rcpQFromSlope(gainHF, 1.0f));
962 highpass.setParams(BiquadType::LowShelf, gainLF, lfScale,
963 highpass.rcpQFromSlope(gainLF, 1.0f));
964 for(ALuint c{1};c < num_channels;c++)
966 voice->mChans[c].mDryParams.LowPass.copyParamsFrom(lowpass);
967 voice->mChans[c].mDryParams.HighPass.copyParamsFrom(highpass);
970 for(ALuint i{0};i < NumSends;i++)
972 const ALfloat hfScale{props->Send[i].HFReference / Frequency};
973 const ALfloat lfScale{props->Send[i].LFReference / Frequency};
974 const ALfloat gainHF{maxf(WetGainHF[i], 0.001f)};
975 const ALfloat gainLF{maxf(WetGainLF[i], 0.001f)};
977 voice->mSend[i].FilterType = AF_None;
978 if(gainHF != 1.0f) voice->mSend[i].FilterType |= AF_LowPass;
979 if(gainLF != 1.0f) voice->mSend[i].FilterType |= AF_HighPass;
981 auto &lowpass = voice->mChans[0].mWetParams[i].LowPass;
982 auto &highpass = voice->mChans[0].mWetParams[i].HighPass;
983 lowpass.setParams(BiquadType::HighShelf, gainHF, hfScale,
984 lowpass.rcpQFromSlope(gainHF, 1.0f));
985 highpass.setParams(BiquadType::LowShelf, gainLF, lfScale,
986 highpass.rcpQFromSlope(gainLF, 1.0f));
987 for(ALuint c{1};c < num_channels;c++)
989 voice->mChans[c].mWetParams[i].LowPass.copyParamsFrom(lowpass);
990 voice->mChans[c].mWetParams[i].HighPass.copyParamsFrom(highpass);
995 void CalcNonAttnSourceParams(ALvoice *voice, const ALvoicePropsBase *props, const ALCcontext *ALContext)
997 const ALCdevice *Device{ALContext->mDevice.get()};
998 ALeffectslot *SendSlots[MAX_SENDS];
1000 voice->mDirect.Buffer = Device->Dry.Buffer;
1001 for(ALuint i{0};i < Device->NumAuxSends;i++)
1003 SendSlots[i] = props->Send[i].Slot;
1004 if(!SendSlots[i] && i == 0)
1005 SendSlots[i] = ALContext->mDefaultSlot.get();
1006 if(!SendSlots[i] || SendSlots[i]->Params.EffectType == AL_EFFECT_NULL)
1008 SendSlots[i] = nullptr;
1009 voice->mSend[i].Buffer = {};
1011 else
1012 voice->mSend[i].Buffer = SendSlots[i]->Wet.Buffer;
1015 /* Calculate the stepping value */
1016 const auto Pitch = static_cast<ALfloat>(voice->mFrequency) /
1017 static_cast<ALfloat>(Device->Frequency) * props->Pitch;
1018 if(Pitch > float{MAX_PITCH})
1019 voice->mStep = MAX_PITCH<<FRACTIONBITS;
1020 else
1021 voice->mStep = maxu(fastf2u(Pitch * FRACTIONONE), 1);
1022 voice->mResampler = PrepareResampler(props->mResampler, voice->mStep, &voice->mResampleState);
1024 /* Calculate gains */
1025 const ALlistener &Listener = ALContext->mListener;
1026 ALfloat DryGain{clampf(props->Gain, props->MinGain, props->MaxGain)};
1027 DryGain *= props->Direct.Gain * Listener.Params.Gain;
1028 DryGain = minf(DryGain, GAIN_MIX_MAX);
1029 ALfloat DryGainHF{props->Direct.GainHF};
1030 ALfloat DryGainLF{props->Direct.GainLF};
1031 ALfloat WetGain[MAX_SENDS], WetGainHF[MAX_SENDS], WetGainLF[MAX_SENDS];
1032 for(ALuint i{0};i < Device->NumAuxSends;i++)
1034 WetGain[i] = clampf(props->Gain, props->MinGain, props->MaxGain);
1035 WetGain[i] *= props->Send[i].Gain * Listener.Params.Gain;
1036 WetGain[i] = minf(WetGain[i], GAIN_MIX_MAX);
1037 WetGainHF[i] = props->Send[i].GainHF;
1038 WetGainLF[i] = props->Send[i].GainLF;
1041 CalcPanningAndFilters(voice, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, DryGain, DryGainHF, DryGainLF,
1042 WetGain, WetGainLF, WetGainHF, SendSlots, props, Listener, Device);
1045 void CalcAttnSourceParams(ALvoice *voice, const ALvoicePropsBase *props, const ALCcontext *ALContext)
1047 const ALCdevice *Device{ALContext->mDevice.get()};
1048 const ALuint NumSends{Device->NumAuxSends};
1049 const ALlistener &Listener = ALContext->mListener;
1051 /* Set mixing buffers and get send parameters. */
1052 voice->mDirect.Buffer = Device->Dry.Buffer;
1053 ALeffectslot *SendSlots[MAX_SENDS];
1054 ALfloat RoomRolloff[MAX_SENDS];
1055 ALfloat DecayDistance[MAX_SENDS];
1056 ALfloat DecayLFDistance[MAX_SENDS];
1057 ALfloat DecayHFDistance[MAX_SENDS];
1058 for(ALuint i{0};i < NumSends;i++)
1060 SendSlots[i] = props->Send[i].Slot;
1061 if(!SendSlots[i] && i == 0)
1062 SendSlots[i] = ALContext->mDefaultSlot.get();
1063 if(!SendSlots[i] || SendSlots[i]->Params.EffectType == AL_EFFECT_NULL)
1065 SendSlots[i] = nullptr;
1066 RoomRolloff[i] = 0.0f;
1067 DecayDistance[i] = 0.0f;
1068 DecayLFDistance[i] = 0.0f;
1069 DecayHFDistance[i] = 0.0f;
1071 else if(SendSlots[i]->Params.AuxSendAuto)
1073 RoomRolloff[i] = SendSlots[i]->Params.RoomRolloff + props->RoomRolloffFactor;
1074 /* Calculate the distances to where this effect's decay reaches
1075 * -60dB.
1077 DecayDistance[i] = SendSlots[i]->Params.DecayTime * SPEEDOFSOUNDMETRESPERSEC;
1078 DecayLFDistance[i] = DecayDistance[i] * SendSlots[i]->Params.DecayLFRatio;
1079 DecayHFDistance[i] = DecayDistance[i] * SendSlots[i]->Params.DecayHFRatio;
1080 if(SendSlots[i]->Params.DecayHFLimit)
1082 ALfloat airAbsorption{SendSlots[i]->Params.AirAbsorptionGainHF};
1083 if(airAbsorption < 1.0f)
1085 /* Calculate the distance to where this effect's air
1086 * absorption reaches -60dB, and limit the effect's HF
1087 * decay distance (so it doesn't take any longer to decay
1088 * than the air would allow).
1090 ALfloat absorb_dist{std::log10(REVERB_DECAY_GAIN) / std::log10(airAbsorption)};
1091 DecayHFDistance[i] = minf(absorb_dist, DecayHFDistance[i]);
1095 else
1097 /* If the slot's auxiliary send auto is off, the data sent to the
1098 * effect slot is the same as the dry path, sans filter effects */
1099 RoomRolloff[i] = props->RolloffFactor;
1100 DecayDistance[i] = 0.0f;
1101 DecayLFDistance[i] = 0.0f;
1102 DecayHFDistance[i] = 0.0f;
1105 if(!SendSlots[i])
1106 voice->mSend[i].Buffer = {};
1107 else
1108 voice->mSend[i].Buffer = SendSlots[i]->Wet.Buffer;
1111 /* Transform source to listener space (convert to head relative) */
1112 alu::Vector Position{props->Position[0], props->Position[1], props->Position[2], 1.0f};
1113 alu::Vector Velocity{props->Velocity[0], props->Velocity[1], props->Velocity[2], 0.0f};
1114 alu::Vector Direction{props->Direction[0], props->Direction[1], props->Direction[2], 0.0f};
1115 if(props->HeadRelative == AL_FALSE)
1117 /* Transform source vectors */
1118 Position = Listener.Params.Matrix * Position;
1119 Velocity = Listener.Params.Matrix * Velocity;
1120 Direction = Listener.Params.Matrix * Direction;
1122 else
1124 /* Offset the source velocity to be relative of the listener velocity */
1125 Velocity += Listener.Params.Velocity;
1128 const bool directional{Direction.normalize() > 0.0f};
1129 alu::Vector ToSource{Position[0], Position[1], Position[2], 0.0f};
1130 const ALfloat Distance{ToSource.normalize()};
1132 /* Initial source gain */
1133 ALfloat DryGain{props->Gain};
1134 ALfloat DryGainHF{1.0f};
1135 ALfloat DryGainLF{1.0f};
1136 ALfloat WetGain[MAX_SENDS], WetGainHF[MAX_SENDS], WetGainLF[MAX_SENDS];
1137 for(ALuint i{0};i < NumSends;i++)
1139 WetGain[i] = props->Gain;
1140 WetGainHF[i] = 1.0f;
1141 WetGainLF[i] = 1.0f;
1144 /* Calculate distance attenuation */
1145 ALfloat ClampedDist{Distance};
1147 switch(Listener.Params.SourceDistanceModel ?
1148 props->mDistanceModel : Listener.Params.mDistanceModel)
1150 case DistanceModel::InverseClamped:
1151 ClampedDist = clampf(ClampedDist, props->RefDistance, props->MaxDistance);
1152 if(props->MaxDistance < props->RefDistance) break;
1153 /*fall-through*/
1154 case DistanceModel::Inverse:
1155 if(!(props->RefDistance > 0.0f))
1156 ClampedDist = props->RefDistance;
1157 else
1159 ALfloat dist = lerp(props->RefDistance, ClampedDist, props->RolloffFactor);
1160 if(dist > 0.0f) DryGain *= props->RefDistance / dist;
1161 for(ALuint i{0};i < NumSends;i++)
1163 dist = lerp(props->RefDistance, ClampedDist, RoomRolloff[i]);
1164 if(dist > 0.0f) WetGain[i] *= props->RefDistance / dist;
1167 break;
1169 case DistanceModel::LinearClamped:
1170 ClampedDist = clampf(ClampedDist, props->RefDistance, props->MaxDistance);
1171 if(props->MaxDistance < props->RefDistance) break;
1172 /*fall-through*/
1173 case DistanceModel::Linear:
1174 if(!(props->MaxDistance != props->RefDistance))
1175 ClampedDist = props->RefDistance;
1176 else
1178 ALfloat attn = props->RolloffFactor * (ClampedDist-props->RefDistance) /
1179 (props->MaxDistance-props->RefDistance);
1180 DryGain *= maxf(1.0f - attn, 0.0f);
1181 for(ALuint i{0};i < NumSends;i++)
1183 attn = RoomRolloff[i] * (ClampedDist-props->RefDistance) /
1184 (props->MaxDistance-props->RefDistance);
1185 WetGain[i] *= maxf(1.0f - attn, 0.0f);
1188 break;
1190 case DistanceModel::ExponentClamped:
1191 ClampedDist = clampf(ClampedDist, props->RefDistance, props->MaxDistance);
1192 if(props->MaxDistance < props->RefDistance) break;
1193 /*fall-through*/
1194 case DistanceModel::Exponent:
1195 if(!(ClampedDist > 0.0f && props->RefDistance > 0.0f))
1196 ClampedDist = props->RefDistance;
1197 else
1199 DryGain *= std::pow(ClampedDist/props->RefDistance, -props->RolloffFactor);
1200 for(ALuint i{0};i < NumSends;i++)
1201 WetGain[i] *= std::pow(ClampedDist/props->RefDistance, -RoomRolloff[i]);
1203 break;
1205 case DistanceModel::Disable:
1206 ClampedDist = props->RefDistance;
1207 break;
1210 /* Calculate directional soundcones */
1211 if(directional && props->InnerAngle < 360.0f)
1213 const ALfloat Angle{Rad2Deg(std::acos(-aluDotproduct(Direction, ToSource)) *
1214 ConeScale * 2.0f)};
1216 ALfloat ConeVolume, ConeHF;
1217 if(!(Angle > props->InnerAngle))
1219 ConeVolume = 1.0f;
1220 ConeHF = 1.0f;
1222 else if(Angle < props->OuterAngle)
1224 ALfloat scale = ( Angle-props->InnerAngle) /
1225 (props->OuterAngle-props->InnerAngle);
1226 ConeVolume = lerp(1.0f, props->OuterGain, scale);
1227 ConeHF = lerp(1.0f, props->OuterGainHF, scale);
1229 else
1231 ConeVolume = props->OuterGain;
1232 ConeHF = props->OuterGainHF;
1235 DryGain *= ConeVolume;
1236 if(props->DryGainHFAuto)
1237 DryGainHF *= ConeHF;
1238 if(props->WetGainAuto)
1239 std::transform(std::begin(WetGain), std::begin(WetGain)+NumSends, std::begin(WetGain),
1240 [ConeVolume](ALfloat gain) noexcept -> ALfloat { return gain * ConeVolume; }
1242 if(props->WetGainHFAuto)
1243 std::transform(std::begin(WetGainHF), std::begin(WetGainHF)+NumSends,
1244 std::begin(WetGainHF),
1245 [ConeHF](ALfloat gain) noexcept -> ALfloat { return gain * ConeHF; }
1249 /* Apply gain and frequency filters */
1250 DryGain = clampf(DryGain, props->MinGain, props->MaxGain);
1251 DryGain = minf(DryGain*props->Direct.Gain*Listener.Params.Gain, GAIN_MIX_MAX);
1252 DryGainHF *= props->Direct.GainHF;
1253 DryGainLF *= props->Direct.GainLF;
1254 for(ALuint i{0};i < NumSends;i++)
1256 WetGain[i] = clampf(WetGain[i], props->MinGain, props->MaxGain);
1257 WetGain[i] = minf(WetGain[i]*props->Send[i].Gain*Listener.Params.Gain, GAIN_MIX_MAX);
1258 WetGainHF[i] *= props->Send[i].GainHF;
1259 WetGainLF[i] *= props->Send[i].GainLF;
1262 /* Distance-based air absorption and initial send decay. */
1263 if(ClampedDist > props->RefDistance && props->RolloffFactor > 0.0f)
1265 ALfloat meters_base{(ClampedDist-props->RefDistance) * props->RolloffFactor *
1266 Listener.Params.MetersPerUnit};
1267 if(props->AirAbsorptionFactor > 0.0f)
1269 ALfloat hfattn{std::pow(AIRABSORBGAINHF, meters_base * props->AirAbsorptionFactor)};
1270 DryGainHF *= hfattn;
1271 std::transform(std::begin(WetGainHF), std::begin(WetGainHF)+NumSends,
1272 std::begin(WetGainHF),
1273 [hfattn](ALfloat gain) noexcept -> ALfloat { return gain * hfattn; }
1277 if(props->WetGainAuto)
1279 /* Apply a decay-time transformation to the wet path, based on the
1280 * source distance in meters. The initial decay of the reverb
1281 * effect is calculated and applied to the wet path.
1283 for(ALuint i{0};i < NumSends;i++)
1285 if(!(DecayDistance[i] > 0.0f))
1286 continue;
1288 const ALfloat gain{std::pow(REVERB_DECAY_GAIN, meters_base/DecayDistance[i])};
1289 WetGain[i] *= gain;
1290 /* Yes, the wet path's air absorption is applied with
1291 * WetGainAuto on, rather than WetGainHFAuto.
1293 if(gain > 0.0f)
1295 ALfloat gainhf{std::pow(REVERB_DECAY_GAIN, meters_base/DecayHFDistance[i])};
1296 WetGainHF[i] *= minf(gainhf / gain, 1.0f);
1297 ALfloat gainlf{std::pow(REVERB_DECAY_GAIN, meters_base/DecayLFDistance[i])};
1298 WetGainLF[i] *= minf(gainlf / gain, 1.0f);
1305 /* Initial source pitch */
1306 ALfloat Pitch{props->Pitch};
1308 /* Calculate velocity-based doppler effect */
1309 ALfloat DopplerFactor{props->DopplerFactor * Listener.Params.DopplerFactor};
1310 if(DopplerFactor > 0.0f)
1312 const alu::Vector &lvelocity = Listener.Params.Velocity;
1313 ALfloat vss{aluDotproduct(Velocity, ToSource) * -DopplerFactor};
1314 ALfloat vls{aluDotproduct(lvelocity, ToSource) * -DopplerFactor};
1316 const ALfloat SpeedOfSound{Listener.Params.SpeedOfSound};
1317 if(!(vls < SpeedOfSound))
1319 /* Listener moving away from the source at the speed of sound.
1320 * Sound waves can't catch it.
1322 Pitch = 0.0f;
1324 else if(!(vss < SpeedOfSound))
1326 /* Source moving toward the listener at the speed of sound. Sound
1327 * waves bunch up to extreme frequencies.
1329 Pitch = std::numeric_limits<float>::infinity();
1331 else
1333 /* Source and listener movement is nominal. Calculate the proper
1334 * doppler shift.
1336 Pitch *= (SpeedOfSound-vls) / (SpeedOfSound-vss);
1340 /* Adjust pitch based on the buffer and output frequencies, and calculate
1341 * fixed-point stepping value.
1343 Pitch *= static_cast<ALfloat>(voice->mFrequency)/static_cast<ALfloat>(Device->Frequency);
1344 if(Pitch > float{MAX_PITCH})
1345 voice->mStep = MAX_PITCH<<FRACTIONBITS;
1346 else
1347 voice->mStep = maxu(fastf2u(Pitch * FRACTIONONE), 1);
1348 voice->mResampler = PrepareResampler(props->mResampler, voice->mStep, &voice->mResampleState);
1350 ALfloat spread{0.0f};
1351 if(props->Radius > Distance)
1352 spread = al::MathDefs<float>::Tau() - Distance/props->Radius*al::MathDefs<float>::Pi();
1353 else if(Distance > 0.0f)
1354 spread = std::asin(props->Radius/Distance) * 2.0f;
1356 CalcPanningAndFilters(voice, ToSource[0], ToSource[1], ToSource[2]*ZScale,
1357 Distance*Listener.Params.MetersPerUnit, spread, DryGain, DryGainHF, DryGainLF, WetGain,
1358 WetGainLF, WetGainHF, SendSlots, props, Listener, Device);
1361 void CalcSourceParams(ALvoice *voice, ALCcontext *context, bool force)
1363 ALvoiceProps *props{voice->mUpdate.exchange(nullptr, std::memory_order_acq_rel)};
1364 if(!props && !force) return;
1366 if(props)
1368 voice->mProps = *props;
1370 AtomicReplaceHead(context->mFreeVoiceProps, props);
1373 if((voice->mProps.mSpatializeMode == SpatializeAuto && voice->mFmtChannels == FmtMono) ||
1374 voice->mProps.mSpatializeMode == SpatializeOn)
1375 CalcAttnSourceParams(voice, &voice->mProps, context);
1376 else
1377 CalcNonAttnSourceParams(voice, &voice->mProps, context);
1381 void ProcessParamUpdates(ALCcontext *ctx, const ALeffectslotArray &slots,
1382 const al::span<ALvoice> voices)
1384 IncrementRef(ctx->mUpdateCount);
1385 if LIKELY(!ctx->mHoldUpdates.load(std::memory_order_acquire))
1387 bool force{CalcContextParams(ctx)};
1388 force |= CalcListenerParams(ctx);
1389 force = std::accumulate(slots.begin(), slots.end(), force,
1390 [ctx](const bool f, ALeffectslot *slot) -> bool
1391 { return CalcEffectSlotParams(slot, ctx) | f; }
1394 auto calc_params = [ctx,force](ALvoice &voice) -> void
1396 if(voice.mSourceID.load(std::memory_order_acquire) != 0)
1397 CalcSourceParams(&voice, ctx, force);
1399 std::for_each(voices.begin(), voices.end(), calc_params);
1401 IncrementRef(ctx->mUpdateCount);
1404 void ProcessContext(ALCcontext *ctx, const ALuint SamplesToDo)
1406 ASSUME(SamplesToDo > 0);
1408 const ALeffectslotArray &auxslots = *ctx->mActiveAuxSlots.load(std::memory_order_acquire);
1409 const al::span<ALvoice> voices{ctx->mVoices.data(), ctx->mVoices.size()};
1411 /* Process pending propery updates for objects on the context. */
1412 ProcessParamUpdates(ctx, auxslots, voices);
1414 /* Clear auxiliary effect slot mixing buffers. */
1415 std::for_each(auxslots.begin(), auxslots.end(),
1416 [SamplesToDo](ALeffectslot *slot) -> void
1418 for(auto &buffer : slot->MixBuffer)
1419 std::fill_n(buffer.begin(), SamplesToDo, 0.0f);
1423 /* Process voices that have a playing source. */
1424 std::for_each(voices.begin(), voices.end(),
1425 [SamplesToDo,ctx](ALvoice &voice) -> void
1427 const ALvoice::State vstate{voice.mPlayState.load(std::memory_order_acquire)};
1428 if(vstate != ALvoice::Stopped) voice.mix(vstate, ctx, SamplesToDo);
1432 /* Process effects. */
1433 if(auxslots.empty()) return;
1434 auto slots = auxslots.data();
1435 auto slots_end = slots + auxslots.size();
1437 /* First sort the slots into scratch storage, so that effects come before
1438 * their effect target (or their targets' target).
1440 auto sorted_slots = const_cast<ALeffectslot**>(slots_end);
1441 auto sorted_slots_end = sorted_slots;
1442 auto in_chain = [](const ALeffectslot *slot1, const ALeffectslot *slot2) noexcept -> bool
1444 while((slot1=slot1->Params.Target) != nullptr) {
1445 if(slot1 == slot2) return true;
1447 return false;
1450 *sorted_slots_end = *slots;
1451 ++sorted_slots_end;
1452 while(++slots != slots_end)
1454 /* If this effect slot targets an effect slot already in the list (i.e.
1455 * slots outputs to something in sorted_slots), directly or indirectly,
1456 * insert it prior to that element.
1458 auto checker = sorted_slots;
1459 do {
1460 if(in_chain(*slots, *checker)) break;
1461 } while(++checker != sorted_slots_end);
1463 checker = std::move_backward(checker, sorted_slots_end, sorted_slots_end+1);
1464 *--checker = *slots;
1465 ++sorted_slots_end;
1468 std::for_each(sorted_slots, sorted_slots_end,
1469 [SamplesToDo](const ALeffectslot *slot) -> void
1471 EffectState *state{slot->Params.mEffectState};
1472 state->process(SamplesToDo, slot->Wet.Buffer, state->mOutTarget);
1478 void ApplyStablizer(FrontStablizer *Stablizer, const al::span<FloatBufferLine> Buffer,
1479 const ALuint lidx, const ALuint ridx, const ALuint cidx, const ALuint SamplesToDo)
1481 ASSUME(SamplesToDo > 0);
1483 /* Apply a delay to all channels, except the front-left and front-right, so
1484 * they maintain correct timing.
1486 const size_t NumChannels{Buffer.size()};
1487 for(size_t i{0u};i < NumChannels;i++)
1489 if(i == lidx || i == ridx)
1490 continue;
1492 auto &DelayBuf = Stablizer->DelayBuf[i];
1493 auto buffer_end = Buffer[i].begin() + SamplesToDo;
1494 if LIKELY(SamplesToDo >= ALuint{FrontStablizer::DelayLength})
1496 auto delay_end = std::rotate(Buffer[i].begin(),
1497 buffer_end - FrontStablizer::DelayLength, buffer_end);
1498 std::swap_ranges(Buffer[i].begin(), delay_end, std::begin(DelayBuf));
1500 else
1502 auto delay_start = std::swap_ranges(Buffer[i].begin(), buffer_end,
1503 std::begin(DelayBuf));
1504 std::rotate(std::begin(DelayBuf), delay_start, std::end(DelayBuf));
1508 ALfloat (&lsplit)[2][BUFFERSIZE] = Stablizer->LSplit;
1509 ALfloat (&rsplit)[2][BUFFERSIZE] = Stablizer->RSplit;
1510 auto &tmpbuf = Stablizer->TempBuf;
1512 /* This applies the band-splitter, preserving phase at the cost of some
1513 * delay. The shorter the delay, the more error seeps into the result.
1515 auto apply_splitter = [&tmpbuf,SamplesToDo](const FloatBufferLine &InBuf,
1516 ALfloat (&DelayBuf)[FrontStablizer::DelayLength], BandSplitter &Filter,
1517 ALfloat (&splitbuf)[2][BUFFERSIZE]) -> void
1519 /* Combine the delayed samples and the input samples into the temp
1520 * buffer, in reverse. Then copy the final samples back into the delay
1521 * buffer for next time. Note that the delay buffer's samples are
1522 * stored backwards here.
1524 auto tmpbuf_end = std::begin(tmpbuf) + SamplesToDo;
1525 std::copy_n(std::begin(DelayBuf), FrontStablizer::DelayLength, tmpbuf_end);
1526 std::reverse_copy(InBuf.begin(), InBuf.begin()+SamplesToDo, std::begin(tmpbuf));
1527 std::copy_n(std::begin(tmpbuf), FrontStablizer::DelayLength, std::begin(DelayBuf));
1529 /* Apply an all-pass on the reversed signal, then reverse the samples
1530 * to get the forward signal with a reversed phase shift.
1532 Filter.applyAllpass(tmpbuf, SamplesToDo+FrontStablizer::DelayLength);
1533 std::reverse(std::begin(tmpbuf), tmpbuf_end+FrontStablizer::DelayLength);
1535 /* Now apply the band-splitter, combining its phase shift with the
1536 * reversed phase shift, restoring the original phase on the split
1537 * signal.
1539 Filter.process(splitbuf[1], splitbuf[0], tmpbuf, SamplesToDo);
1541 apply_splitter(Buffer[lidx], Stablizer->DelayBuf[lidx], Stablizer->LFilter, lsplit);
1542 apply_splitter(Buffer[ridx], Stablizer->DelayBuf[ridx], Stablizer->RFilter, rsplit);
1544 for(ALuint i{0};i < SamplesToDo;i++)
1546 ALfloat lfsum{lsplit[0][i] + rsplit[0][i]};
1547 ALfloat hfsum{lsplit[1][i] + rsplit[1][i]};
1548 ALfloat s{lsplit[0][i] + lsplit[1][i] - rsplit[0][i] - rsplit[1][i]};
1550 /* This pans the separate low- and high-frequency sums between being on
1551 * the center channel and the left/right channels. The low-frequency
1552 * sum is 1/3rd toward center (2/3rds on left/right) and the high-
1553 * frequency sum is 1/4th toward center (3/4ths on left/right). These
1554 * values can be tweaked.
1556 ALfloat m{lfsum*std::cos(1.0f/3.0f * (al::MathDefs<float>::Pi()*0.5f)) +
1557 hfsum*std::cos(1.0f/4.0f * (al::MathDefs<float>::Pi()*0.5f))};
1558 ALfloat c{lfsum*std::sin(1.0f/3.0f * (al::MathDefs<float>::Pi()*0.5f)) +
1559 hfsum*std::sin(1.0f/4.0f * (al::MathDefs<float>::Pi()*0.5f))};
1561 /* The generated center channel signal adds to the existing signal,
1562 * while the modified left and right channels replace.
1564 Buffer[lidx][i] = (m + s) * 0.5f;
1565 Buffer[ridx][i] = (m - s) * 0.5f;
1566 Buffer[cidx][i] += c * 0.5f;
1570 void ApplyDistanceComp(const al::span<FloatBufferLine> Samples, const ALuint SamplesToDo,
1571 const DistanceComp::DistData *distcomp)
1573 ASSUME(SamplesToDo > 0);
1575 for(auto &chanbuffer : Samples)
1577 const ALfloat gain{distcomp->Gain};
1578 const ALuint base{distcomp->Length};
1579 ALfloat *distbuf{al::assume_aligned<16>(distcomp->Buffer)};
1580 ++distcomp;
1582 if(base < 1)
1583 continue;
1585 ALfloat *inout{al::assume_aligned<16>(chanbuffer.data())};
1586 auto inout_end = inout + SamplesToDo;
1587 if LIKELY(SamplesToDo >= base)
1589 auto delay_end = std::rotate(inout, inout_end - base, inout_end);
1590 std::swap_ranges(inout, delay_end, distbuf);
1592 else
1594 auto delay_start = std::swap_ranges(inout, inout_end, distbuf);
1595 std::rotate(distbuf, delay_start, distbuf + base);
1597 std::transform(inout, inout_end, inout, std::bind(std::multiplies<float>{}, _1, gain));
1601 void ApplyDither(const al::span<FloatBufferLine> Samples, ALuint *dither_seed,
1602 const ALfloat quant_scale, const ALuint SamplesToDo)
1604 /* Dithering. Generate whitenoise (uniform distribution of random values
1605 * between -1 and +1) and add it to the sample values, after scaling up to
1606 * the desired quantization depth amd before rounding.
1608 const ALfloat invscale{1.0f / quant_scale};
1609 ALuint seed{*dither_seed};
1610 auto dither_channel = [&seed,invscale,quant_scale,SamplesToDo](FloatBufferLine &input) -> void
1612 ASSUME(SamplesToDo > 0);
1613 auto dither_sample = [&seed,invscale,quant_scale](const ALfloat sample) noexcept -> ALfloat
1615 ALfloat val{sample * quant_scale};
1616 ALuint rng0{dither_rng(&seed)};
1617 ALuint rng1{dither_rng(&seed)};
1618 val += static_cast<ALfloat>(rng0*(1.0/UINT_MAX) - rng1*(1.0/UINT_MAX));
1619 return fast_roundf(val) * invscale;
1621 std::transform(input.begin(), input.begin()+SamplesToDo, input.begin(), dither_sample);
1623 std::for_each(Samples.begin(), Samples.end(), dither_channel);
1624 *dither_seed = seed;
1628 /* Base template left undefined. Should be marked =delete, but Clang 3.8.1
1629 * chokes on that given the inline specializations.
1631 template<typename T>
1632 inline T SampleConv(ALfloat) noexcept;
1634 template<> inline ALfloat SampleConv(ALfloat val) noexcept
1635 { return val; }
1636 template<> inline ALint SampleConv(ALfloat val) noexcept
1638 /* Floats have a 23-bit mantissa, plus an implied 1 bit and a sign bit.
1639 * This means a normalized float has at most 25 bits of signed precision.
1640 * When scaling and clamping for a signed 32-bit integer, these following
1641 * values are the best a float can give.
1643 return fastf2i(clampf(val*2147483648.0f, -2147483648.0f, 2147483520.0f));
1645 template<> inline ALshort SampleConv(ALfloat val) noexcept
1646 { return static_cast<ALshort>(fastf2i(clampf(val*32768.0f, -32768.0f, 32767.0f))); }
1647 template<> inline ALbyte SampleConv(ALfloat val) noexcept
1648 { return static_cast<ALbyte>(fastf2i(clampf(val*128.0f, -128.0f, 127.0f))); }
1650 /* Define unsigned output variations. */
1651 template<> inline ALuint SampleConv(ALfloat val) noexcept
1652 { return static_cast<ALuint>(SampleConv<ALint>(val)) + 2147483648u; }
1653 template<> inline ALushort SampleConv(ALfloat val) noexcept
1654 { return static_cast<ALushort>(SampleConv<ALshort>(val) + 32768); }
1655 template<> inline ALubyte SampleConv(ALfloat val) noexcept
1656 { return static_cast<ALubyte>(SampleConv<ALbyte>(val) + 128); }
1658 template<DevFmtType T>
1659 void Write(const al::span<const FloatBufferLine> InBuffer, ALvoid *OutBuffer, const size_t Offset,
1660 const ALuint SamplesToDo)
1662 using SampleType = typename DevFmtTypeTraits<T>::Type;
1664 const size_t numchans{InBuffer.size()};
1665 ASSUME(numchans > 0);
1667 SampleType *outbase = static_cast<SampleType*>(OutBuffer) + Offset*numchans;
1668 auto conv_channel = [&outbase,SamplesToDo,numchans](const FloatBufferLine &inbuf) -> void
1670 ASSUME(SamplesToDo > 0);
1671 SampleType *out{outbase++};
1672 auto conv_sample = [numchans,&out](const ALfloat s) noexcept -> void
1674 *out = SampleConv<SampleType>(s);
1675 out += numchans;
1677 std::for_each(inbuf.begin(), inbuf.begin()+SamplesToDo, conv_sample);
1679 std::for_each(InBuffer.cbegin(), InBuffer.cend(), conv_channel);
1682 } // namespace
1684 void aluMixData(ALCdevice *device, ALvoid *OutBuffer, const ALuint NumSamples)
1686 FPUCtl mixer_mode{};
1687 for(ALuint SamplesDone{0u};SamplesDone < NumSamples;)
1689 const ALuint SamplesToDo{minu(NumSamples-SamplesDone, BUFFERSIZE)};
1691 /* Clear main mixing buffers. */
1692 std::for_each(device->MixBuffer.begin(), device->MixBuffer.end(),
1693 [SamplesToDo](std::array<ALfloat,BUFFERSIZE> &buffer) -> void
1694 { std::fill_n(buffer.begin(), SamplesToDo, 0.0f); }
1697 /* Increment the mix count at the start (lsb should now be 1). */
1698 IncrementRef(device->MixCount);
1700 /* For each context on this device, process and mix its sources and
1701 * effects.
1703 for(ALCcontext *ctx : *device->mContexts.load(std::memory_order_acquire))
1704 ProcessContext(ctx, SamplesToDo);
1706 /* Increment the clock time. Every second's worth of samples is
1707 * converted and added to clock base so that large sample counts don't
1708 * overflow during conversion. This also guarantees a stable
1709 * conversion.
1711 device->SamplesDone += SamplesToDo;
1712 device->ClockBase += std::chrono::seconds{device->SamplesDone / device->Frequency};
1713 device->SamplesDone %= device->Frequency;
1715 /* Increment the mix count at the end (lsb should now be 0). */
1716 IncrementRef(device->MixCount);
1718 /* Apply any needed post-process for finalizing the Dry mix to the
1719 * RealOut (Ambisonic decode, UHJ encode, etc).
1721 device->postProcess(SamplesToDo);
1723 const al::span<FloatBufferLine> RealOut{device->RealOut.Buffer};
1725 /* Apply front image stablization for surround sound, if applicable. */
1726 if(device->Stablizer)
1728 const ALuint lidx{GetChannelIdxByName(device->RealOut, FrontLeft)};
1729 const ALuint ridx{GetChannelIdxByName(device->RealOut, FrontRight)};
1730 const ALuint cidx{GetChannelIdxByName(device->RealOut, FrontCenter)};
1732 ApplyStablizer(device->Stablizer.get(), RealOut, lidx, ridx, cidx, SamplesToDo);
1735 /* Apply compression, limiting sample amplitude if needed or desired. */
1736 if(Compressor *comp{device->Limiter.get()})
1737 comp->process(SamplesToDo, RealOut.data());
1739 /* Apply delays and attenuation for mismatched speaker distances. */
1740 ApplyDistanceComp(RealOut, SamplesToDo, device->ChannelDelay.as_span().cbegin());
1742 /* Apply dithering. The compressor should have left enough headroom for
1743 * the dither noise to not saturate.
1745 if(device->DitherDepth > 0.0f)
1746 ApplyDither(RealOut, &device->DitherSeed, device->DitherDepth, SamplesToDo);
1748 if LIKELY(OutBuffer)
1750 /* Finally, interleave and convert samples, writing to the device's
1751 * output buffer.
1753 switch(device->FmtType)
1755 #define HANDLE_WRITE(T) case T: \
1756 Write<T>(RealOut, OutBuffer, SamplesDone, SamplesToDo); break;
1757 HANDLE_WRITE(DevFmtByte)
1758 HANDLE_WRITE(DevFmtUByte)
1759 HANDLE_WRITE(DevFmtShort)
1760 HANDLE_WRITE(DevFmtUShort)
1761 HANDLE_WRITE(DevFmtInt)
1762 HANDLE_WRITE(DevFmtUInt)
1763 HANDLE_WRITE(DevFmtFloat)
1764 #undef HANDLE_WRITE
1768 SamplesDone += SamplesToDo;
1773 void aluHandleDisconnect(ALCdevice *device, const char *msg, ...)
1775 if(!device->Connected.exchange(false, std::memory_order_acq_rel))
1776 return;
1778 AsyncEvent evt{EventType_Disconnected};
1779 evt.u.user.type = AL_EVENT_TYPE_DISCONNECTED_SOFT;
1780 evt.u.user.id = 0;
1781 evt.u.user.param = 0;
1783 va_list args;
1784 va_start(args, msg);
1785 int msglen{vsnprintf(evt.u.user.msg, sizeof(evt.u.user.msg), msg, args)};
1786 va_end(args);
1788 if(msglen < 0 || static_cast<size_t>(msglen) >= sizeof(evt.u.user.msg))
1789 evt.u.user.msg[sizeof(evt.u.user.msg)-1] = 0;
1791 IncrementRef(device->MixCount);
1792 for(ALCcontext *ctx : *device->mContexts.load())
1794 const ALbitfieldSOFT enabledevt{ctx->mEnabledEvts.load(std::memory_order_acquire)};
1795 if((enabledevt&EventType_Disconnected))
1797 RingBuffer *ring{ctx->mAsyncEvents.get()};
1798 auto evt_data = ring->getWriteVector().first;
1799 if(evt_data.len > 0)
1801 ::new (evt_data.buf) AsyncEvent{evt};
1802 ring->writeAdvance(1);
1803 ctx->mEventSem.post();
1807 auto stop_voice = [](ALvoice &voice) -> void
1809 voice.mCurrentBuffer.store(nullptr, std::memory_order_relaxed);
1810 voice.mLoopBuffer.store(nullptr, std::memory_order_relaxed);
1811 voice.mSourceID.store(0u, std::memory_order_relaxed);
1812 voice.mPlayState.store(ALvoice::Stopped, std::memory_order_release);
1814 std::for_each(ctx->mVoices.begin(), ctx->mVoices.end(), stop_voice);
1816 IncrementRef(device->MixCount);