Use istream for makemhr input
[openal-soft.git] / alc / alu.cpp
blob8affbde4716e1e3e1fed83f008c6125031cf855e
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 namespace {
87 using namespace std::placeholders;
89 ALfloat InitConeScale()
91 ALfloat ret{1.0f};
92 if(auto optval = al::getenv("__ALSOFT_HALF_ANGLE_CONES"))
94 if(al::strcasecmp(optval->c_str(), "true") == 0
95 || strtol(optval->c_str(), nullptr, 0) == 1)
96 ret *= 0.5f;
98 return ret;
101 ALfloat InitZScale()
103 ALfloat ret{1.0f};
104 if(auto optval = al::getenv("__ALSOFT_REVERSE_Z"))
106 if(al::strcasecmp(optval->c_str(), "true") == 0
107 || strtol(optval->c_str(), nullptr, 0) == 1)
108 ret *= -1.0f;
110 return ret;
113 } // namespace
115 /* Cone scalar */
116 const ALfloat ConeScale{InitConeScale()};
118 /* Localized Z scalar for mono sources */
119 const ALfloat ZScale{InitZScale()};
122 namespace {
124 void ClearArray(ALfloat (&f)[MAX_OUTPUT_CHANNELS])
126 std::fill(std::begin(f), std::end(f), 0.0f);
129 struct ChanMap {
130 Channel channel;
131 ALfloat angle;
132 ALfloat elevation;
135 HrtfDirectMixerFunc MixDirectHrtf = MixDirectHrtf_<CTag>;
136 inline HrtfDirectMixerFunc SelectHrtfMixer(void)
138 #ifdef HAVE_NEON
139 if((CPUCapFlags&CPU_CAP_NEON))
140 return MixDirectHrtf_<NEONTag>;
141 #endif
142 #ifdef HAVE_SSE
143 if((CPUCapFlags&CPU_CAP_SSE))
144 return MixDirectHrtf_<SSETag>;
145 #endif
147 return MixDirectHrtf_<CTag>;
150 } // namespace
152 void aluInit(void)
154 MixDirectHrtf = SelectHrtfMixer();
158 void ALCdevice::ProcessHrtf(const size_t SamplesToDo)
160 /* HRTF is stereo output only. */
161 const ALuint lidx{RealOut.ChannelIndex[FrontLeft]};
162 const ALuint ridx{RealOut.ChannelIndex[FrontRight]};
164 MixDirectHrtf(RealOut.Buffer[lidx], RealOut.Buffer[ridx], Dry.Buffer, HrtfAccumData,
165 mHrtfState.get(), SamplesToDo);
168 void ALCdevice::ProcessAmbiDec(const size_t SamplesToDo)
170 AmbiDecoder->process(RealOut.Buffer, Dry.Buffer.data(), SamplesToDo);
173 void ALCdevice::ProcessUhj(const size_t SamplesToDo)
175 /* UHJ is stereo output only. */
176 const ALuint lidx{RealOut.ChannelIndex[FrontLeft]};
177 const ALuint ridx{RealOut.ChannelIndex[FrontRight]};
179 /* Encode to stereo-compatible 2-channel UHJ output. */
180 Uhj_Encoder->encode(RealOut.Buffer[lidx], RealOut.Buffer[ridx], Dry.Buffer.data(),
181 SamplesToDo);
184 void ALCdevice::ProcessBs2b(const size_t SamplesToDo)
186 /* First, decode the ambisonic mix to the "real" output. */
187 AmbiDecoder->process(RealOut.Buffer, Dry.Buffer.data(), SamplesToDo);
189 /* BS2B is stereo output only. */
190 const ALuint lidx{RealOut.ChannelIndex[FrontLeft]};
191 const ALuint ridx{RealOut.ChannelIndex[FrontRight]};
193 /* Now apply the BS2B binaural/crossfeed filter. */
194 bs2b_cross_feed(Bs2b.get(), RealOut.Buffer[lidx].data(), RealOut.Buffer[ridx].data(),
195 SamplesToDo);
199 /* Prepares the interpolator for a given rate (determined by increment).
201 * With a bit of work, and a trade of memory for CPU cost, this could be
202 * modified for use with an interpolated increment for buttery-smooth pitch
203 * changes.
205 void BsincPrepare(const ALuint increment, BsincState *state, const BSincTable *table)
207 size_t si{BSINC_SCALE_COUNT - 1};
208 float sf{0.0f};
210 if(increment > FRACTIONONE)
212 sf = FRACTIONONE / static_cast<float>(increment);
213 sf = maxf(0.0f, (BSINC_SCALE_COUNT-1) * (sf-table->scaleBase) * table->scaleRange);
214 si = float2uint(sf);
215 /* The interpolation factor is fit to this diagonally-symmetric curve
216 * to reduce the transition ripple caused by interpolating different
217 * scales of the sinc function.
219 sf = 1.0f - std::cos(std::asin(sf - static_cast<float>(si)));
222 state->sf = sf;
223 state->m = table->m[si];
224 state->l = (state->m/2) - 1;
225 state->filter = table->Tab + table->filterOffset[si];
229 namespace {
231 /* This RNG method was created based on the math found in opusdec. It's quick,
232 * and starting with a seed value of 22222, is suitable for generating
233 * whitenoise.
235 inline ALuint dither_rng(ALuint *seed) noexcept
237 *seed = (*seed * 96314165) + 907633515;
238 return *seed;
242 inline alu::Vector aluCrossproduct(const alu::Vector &in1, const alu::Vector &in2)
244 return alu::Vector{
245 in1[1]*in2[2] - in1[2]*in2[1],
246 in1[2]*in2[0] - in1[0]*in2[2],
247 in1[0]*in2[1] - in1[1]*in2[0],
248 0.0f
252 inline ALfloat aluDotproduct(const alu::Vector &vec1, const alu::Vector &vec2)
254 return vec1[0]*vec2[0] + vec1[1]*vec2[1] + vec1[2]*vec2[2];
258 alu::Vector operator*(const alu::Matrix &mtx, const alu::Vector &vec) noexcept
260 return alu::Vector{
261 vec[0]*mtx[0][0] + vec[1]*mtx[1][0] + vec[2]*mtx[2][0] + vec[3]*mtx[3][0],
262 vec[0]*mtx[0][1] + vec[1]*mtx[1][1] + vec[2]*mtx[2][1] + vec[3]*mtx[3][1],
263 vec[0]*mtx[0][2] + vec[1]*mtx[1][2] + vec[2]*mtx[2][2] + vec[3]*mtx[3][2],
264 vec[0]*mtx[0][3] + vec[1]*mtx[1][3] + vec[2]*mtx[2][3] + vec[3]*mtx[3][3]
269 bool CalcContextParams(ALCcontext *Context)
271 ALcontextProps *props{Context->mUpdate.exchange(nullptr, std::memory_order_acq_rel)};
272 if(!props) return false;
274 ALlistener &Listener = Context->mListener;
275 Listener.Params.DopplerFactor = props->DopplerFactor;
276 Listener.Params.SpeedOfSound = props->SpeedOfSound * props->DopplerVelocity;
278 Listener.Params.SourceDistanceModel = props->SourceDistanceModel;
279 Listener.Params.mDistanceModel = props->mDistanceModel;
281 AtomicReplaceHead(Context->mFreeContextProps, props);
282 return true;
285 bool CalcListenerParams(ALCcontext *Context)
287 ALlistener &Listener = Context->mListener;
289 ALlistenerProps *props{Listener.Params.Update.exchange(nullptr, std::memory_order_acq_rel)};
290 if(!props) return false;
292 /* AT then UP */
293 alu::Vector N{props->OrientAt[0], props->OrientAt[1], props->OrientAt[2], 0.0f};
294 N.normalize();
295 alu::Vector V{props->OrientUp[0], props->OrientUp[1], props->OrientUp[2], 0.0f};
296 V.normalize();
297 /* Build and normalize right-vector */
298 alu::Vector U{aluCrossproduct(N, V)};
299 U.normalize();
301 Listener.Params.Matrix = alu::Matrix{
302 U[0], V[0], -N[0], 0.0f,
303 U[1], V[1], -N[1], 0.0f,
304 U[2], V[2], -N[2], 0.0f,
305 0.0f, 0.0f, 0.0f, 1.0f
308 const alu::Vector P{Listener.Params.Matrix *
309 alu::Vector{props->Position[0], props->Position[1], props->Position[2], 1.0f}};
310 Listener.Params.Matrix.setRow(3, -P[0], -P[1], -P[2], 1.0f);
312 const alu::Vector vel{props->Velocity[0], props->Velocity[1], props->Velocity[2], 0.0f};
313 Listener.Params.Velocity = Listener.Params.Matrix * vel;
315 Listener.Params.Gain = props->Gain * Context->mGainBoost;
316 Listener.Params.MetersPerUnit = props->MetersPerUnit;
318 AtomicReplaceHead(Context->mFreeListenerProps, props);
319 return true;
322 bool CalcEffectSlotParams(ALeffectslot *slot, ALCcontext *context)
324 ALeffectslotProps *props{slot->Params.Update.exchange(nullptr, std::memory_order_acq_rel)};
325 if(!props) return false;
327 slot->Params.Gain = props->Gain;
328 slot->Params.AuxSendAuto = props->AuxSendAuto;
329 slot->Params.Target = props->Target;
330 slot->Params.EffectType = props->Type;
331 slot->Params.mEffectProps = props->Props;
332 if(IsReverbEffect(props->Type))
334 slot->Params.RoomRolloff = props->Props.Reverb.RoomRolloffFactor;
335 slot->Params.DecayTime = props->Props.Reverb.DecayTime;
336 slot->Params.DecayLFRatio = props->Props.Reverb.DecayLFRatio;
337 slot->Params.DecayHFRatio = props->Props.Reverb.DecayHFRatio;
338 slot->Params.DecayHFLimit = props->Props.Reverb.DecayHFLimit;
339 slot->Params.AirAbsorptionGainHF = props->Props.Reverb.AirAbsorptionGainHF;
341 else
343 slot->Params.RoomRolloff = 0.0f;
344 slot->Params.DecayTime = 0.0f;
345 slot->Params.DecayLFRatio = 0.0f;
346 slot->Params.DecayHFRatio = 0.0f;
347 slot->Params.DecayHFLimit = AL_FALSE;
348 slot->Params.AirAbsorptionGainHF = 1.0f;
351 EffectState *state{props->State};
352 props->State = nullptr;
353 EffectState *oldstate{slot->Params.mEffectState};
354 slot->Params.mEffectState = state;
356 /* Only release the old state if it won't get deleted, since we can't be
357 * deleting/freeing anything in the mixer.
359 if(!oldstate->releaseIfNoDelete())
361 /* Otherwise, if it would be deleted send it off with a release event. */
362 RingBuffer *ring{context->mAsyncEvents.get()};
363 auto evt_vec = ring->getWriteVector();
364 if LIKELY(evt_vec.first.len > 0)
366 AsyncEvent *evt{new (evt_vec.first.buf) AsyncEvent{EventType_ReleaseEffectState}};
367 evt->u.mEffectState = oldstate;
368 ring->writeAdvance(1);
369 context->mEventSem.post();
371 else
373 /* If writing the event failed, the queue was probably full. Store
374 * the old state in the property object where it can eventually be
375 * cleaned up sometime later (not ideal, but better than blocking
376 * or leaking).
378 props->State = oldstate;
382 AtomicReplaceHead(context->mFreeEffectslotProps, props);
384 EffectTarget output;
385 if(ALeffectslot *target{slot->Params.Target})
386 output = EffectTarget{&target->Wet, nullptr};
387 else
389 ALCdevice *device{context->mDevice.get()};
390 output = EffectTarget{&device->Dry, &device->RealOut};
392 state->update(context, slot, &slot->Params.mEffectProps, output);
393 return true;
397 /* Scales the given azimuth toward the side (+/- pi/2 radians) for positions in
398 * front.
400 inline float ScaleAzimuthFront(float azimuth, float scale)
402 const ALfloat abs_azi{std::fabs(azimuth)};
403 if(!(abs_azi >= al::MathDefs<float>::Pi()*0.5f))
404 return std::copysign(minf(abs_azi*scale, al::MathDefs<float>::Pi()*0.5f), azimuth);
405 return azimuth;
408 void CalcPanningAndFilters(ALvoice *voice, const ALfloat xpos, const ALfloat ypos,
409 const ALfloat zpos, const ALfloat Distance, const ALfloat Spread, const ALfloat DryGain,
410 const ALfloat DryGainHF, const ALfloat DryGainLF, const ALfloat (&WetGain)[MAX_SENDS],
411 const ALfloat (&WetGainLF)[MAX_SENDS], const ALfloat (&WetGainHF)[MAX_SENDS],
412 ALeffectslot *(&SendSlots)[MAX_SENDS], const ALvoicePropsBase *props,
413 const ALlistener &Listener, const ALCdevice *Device)
415 static constexpr ChanMap MonoMap[1]{
416 { FrontCenter, 0.0f, 0.0f }
417 }, RearMap[2]{
418 { BackLeft, Deg2Rad(-150.0f), Deg2Rad(0.0f) },
419 { BackRight, Deg2Rad( 150.0f), Deg2Rad(0.0f) }
420 }, QuadMap[4]{
421 { FrontLeft, Deg2Rad( -45.0f), Deg2Rad(0.0f) },
422 { FrontRight, Deg2Rad( 45.0f), Deg2Rad(0.0f) },
423 { BackLeft, Deg2Rad(-135.0f), Deg2Rad(0.0f) },
424 { BackRight, Deg2Rad( 135.0f), Deg2Rad(0.0f) }
425 }, X51Map[6]{
426 { FrontLeft, Deg2Rad( -30.0f), Deg2Rad(0.0f) },
427 { FrontRight, Deg2Rad( 30.0f), Deg2Rad(0.0f) },
428 { FrontCenter, Deg2Rad( 0.0f), Deg2Rad(0.0f) },
429 { LFE, 0.0f, 0.0f },
430 { SideLeft, Deg2Rad(-110.0f), Deg2Rad(0.0f) },
431 { SideRight, Deg2Rad( 110.0f), Deg2Rad(0.0f) }
432 }, X61Map[7]{
433 { FrontLeft, Deg2Rad(-30.0f), Deg2Rad(0.0f) },
434 { FrontRight, Deg2Rad( 30.0f), Deg2Rad(0.0f) },
435 { FrontCenter, Deg2Rad( 0.0f), Deg2Rad(0.0f) },
436 { LFE, 0.0f, 0.0f },
437 { BackCenter, Deg2Rad(180.0f), Deg2Rad(0.0f) },
438 { SideLeft, Deg2Rad(-90.0f), Deg2Rad(0.0f) },
439 { SideRight, Deg2Rad( 90.0f), Deg2Rad(0.0f) }
440 }, X71Map[8]{
441 { FrontLeft, Deg2Rad( -30.0f), Deg2Rad(0.0f) },
442 { FrontRight, Deg2Rad( 30.0f), Deg2Rad(0.0f) },
443 { FrontCenter, Deg2Rad( 0.0f), Deg2Rad(0.0f) },
444 { LFE, 0.0f, 0.0f },
445 { BackLeft, Deg2Rad(-150.0f), Deg2Rad(0.0f) },
446 { BackRight, Deg2Rad( 150.0f), Deg2Rad(0.0f) },
447 { SideLeft, Deg2Rad( -90.0f), Deg2Rad(0.0f) },
448 { SideRight, Deg2Rad( 90.0f), Deg2Rad(0.0f) }
451 ChanMap StereoMap[2]{
452 { FrontLeft, Deg2Rad(-30.0f), Deg2Rad(0.0f) },
453 { FrontRight, Deg2Rad( 30.0f), Deg2Rad(0.0f) }
456 const auto Frequency = static_cast<ALfloat>(Device->Frequency);
457 const ALuint NumSends{Device->NumAuxSends};
459 bool DirectChannels{props->DirectChannels != AL_FALSE};
460 const ChanMap *chans{nullptr};
461 ALuint num_channels{0};
462 bool isbformat{false};
463 ALfloat downmix_gain{1.0f};
464 switch(voice->mFmtChannels)
466 case FmtMono:
467 chans = MonoMap;
468 num_channels = 1;
469 /* Mono buffers are never played direct. */
470 DirectChannels = false;
471 break;
473 case FmtStereo:
474 /* Convert counter-clockwise to clockwise. */
475 StereoMap[0].angle = -props->StereoPan[0];
476 StereoMap[1].angle = -props->StereoPan[1];
478 chans = StereoMap;
479 num_channels = 2;
480 downmix_gain = 1.0f / 2.0f;
481 break;
483 case FmtRear:
484 chans = RearMap;
485 num_channels = 2;
486 downmix_gain = 1.0f / 2.0f;
487 break;
489 case FmtQuad:
490 chans = QuadMap;
491 num_channels = 4;
492 downmix_gain = 1.0f / 4.0f;
493 break;
495 case FmtX51:
496 chans = X51Map;
497 num_channels = 6;
498 /* NOTE: Excludes LFE. */
499 downmix_gain = 1.0f / 5.0f;
500 break;
502 case FmtX61:
503 chans = X61Map;
504 num_channels = 7;
505 /* NOTE: Excludes LFE. */
506 downmix_gain = 1.0f / 6.0f;
507 break;
509 case FmtX71:
510 chans = X71Map;
511 num_channels = 8;
512 /* NOTE: Excludes LFE. */
513 downmix_gain = 1.0f / 7.0f;
514 break;
516 case FmtBFormat2D:
517 num_channels = 3;
518 isbformat = true;
519 DirectChannels = false;
520 break;
522 case FmtBFormat3D:
523 num_channels = 4;
524 isbformat = true;
525 DirectChannels = false;
526 break;
528 ASSUME(num_channels > 0);
530 std::for_each(voice->mChans.begin(), voice->mChans.begin()+num_channels,
531 [NumSends](ALvoice::ChannelData &chandata) -> void
533 chandata.mDryParams.Hrtf.Target = HrtfFilter{};
534 ClearArray(chandata.mDryParams.Gains.Target);
535 std::for_each(chandata.mWetParams.begin(), chandata.mWetParams.begin()+NumSends,
536 [](SendParams &params) -> void { ClearArray(params.Gains.Target); });
539 voice->mFlags &= ~(VOICE_HAS_HRTF | VOICE_HAS_NFC);
540 if(isbformat)
542 /* Special handling for B-Format sources. */
544 if(Distance > std::numeric_limits<float>::epsilon())
546 /* Panning a B-Format sound toward some direction is easy. Just pan
547 * the first (W) channel as a normal mono sound and silence the
548 * others.
551 if(Device->AvgSpeakerDist > 0.0f)
553 /* Clamp the distance for really close sources, to prevent
554 * excessive bass.
556 const ALfloat mdist{maxf(Distance, Device->AvgSpeakerDist/4.0f)};
557 const ALfloat w0{SPEEDOFSOUNDMETRESPERSEC / (mdist * Frequency)};
559 /* Only need to adjust the first channel of a B-Format source. */
560 voice->mChans[0].mDryParams.NFCtrlFilter.adjust(w0);
562 voice->mFlags |= VOICE_HAS_NFC;
565 ALfloat coeffs[MAX_AMBI_CHANNELS];
566 if(Device->mRenderMode != StereoPair)
567 CalcDirectionCoeffs({xpos, ypos, zpos}, Spread, coeffs);
568 else
570 /* Clamp Y, in case rounding errors caused it to end up outside
571 * of -1...+1.
573 const ALfloat ev{std::asin(clampf(ypos, -1.0f, 1.0f))};
574 /* Negate Z for right-handed coords with -Z in front. */
575 const ALfloat az{std::atan2(xpos, -zpos)};
577 /* A scalar of 1.5 for plain stereo results in +/-60 degrees
578 * being moved to +/-90 degrees for direct right and left
579 * speaker responses.
581 CalcAngleCoeffs(ScaleAzimuthFront(az, 1.5f), ev, Spread, coeffs);
584 /* NOTE: W needs to be scaled due to FuMa normalization. */
585 const ALfloat &scale0 = AmbiScale::FromFuMa[0];
586 ComputePanGains(&Device->Dry, coeffs, DryGain*scale0,
587 voice->mChans[0].mDryParams.Gains.Target);
588 for(ALuint i{0};i < NumSends;i++)
590 if(const ALeffectslot *Slot{SendSlots[i]})
591 ComputePanGains(&Slot->Wet, coeffs, WetGain[i]*scale0,
592 voice->mChans[0].mWetParams[i].Gains.Target);
595 else
597 if(Device->AvgSpeakerDist > 0.0f)
599 /* NOTE: The NFCtrlFilters were created with a w0 of 0, which
600 * is what we want for FOA input. The first channel may have
601 * been previously re-adjusted if panned, so reset it.
603 voice->mChans[0].mDryParams.NFCtrlFilter.adjust(0.0f);
605 voice->mFlags |= VOICE_HAS_NFC;
608 /* Local B-Format sources have their XYZ channels rotated according
609 * to the orientation.
611 /* AT then UP */
612 alu::Vector N{props->OrientAt[0], props->OrientAt[1], props->OrientAt[2], 0.0f};
613 N.normalize();
614 alu::Vector V{props->OrientUp[0], props->OrientUp[1], props->OrientUp[2], 0.0f};
615 V.normalize();
616 if(!props->HeadRelative)
618 N = Listener.Params.Matrix * N;
619 V = Listener.Params.Matrix * V;
621 /* Build and normalize right-vector */
622 alu::Vector U{aluCrossproduct(N, V)};
623 U.normalize();
625 /* Build a rotate + conversion matrix (FuMa -> ACN+N3D). NOTE: This
626 * matrix is transposed, for the inputs to align on the rows and
627 * outputs on the columns.
629 const ALfloat &wscale = AmbiScale::FromFuMa[0];
630 const ALfloat &yscale = AmbiScale::FromFuMa[1];
631 const ALfloat &zscale = AmbiScale::FromFuMa[2];
632 const ALfloat &xscale = AmbiScale::FromFuMa[3];
633 const ALfloat matrix[4][MAX_AMBI_CHANNELS]{
634 // ACN0 ACN1 ACN2 ACN3
635 { wscale, 0.0f, 0.0f, 0.0f }, // FuMa W
636 { 0.0f, -N[0]*xscale, N[1]*xscale, -N[2]*xscale }, // FuMa X
637 { 0.0f, U[0]*yscale, -U[1]*yscale, U[2]*yscale }, // FuMa Y
638 { 0.0f, -V[0]*zscale, V[1]*zscale, -V[2]*zscale } // FuMa Z
641 for(ALuint c{0};c < num_channels;c++)
643 ComputePanGains(&Device->Dry, matrix[c], DryGain,
644 voice->mChans[c].mDryParams.Gains.Target);
646 for(ALuint i{0};i < NumSends;i++)
648 if(const ALeffectslot *Slot{SendSlots[i]})
649 ComputePanGains(&Slot->Wet, matrix[c], WetGain[i],
650 voice->mChans[c].mWetParams[i].Gains.Target);
655 else if(DirectChannels)
657 /* Direct source channels always play local. Skip the virtual channels
658 * and write inputs to the matching real outputs.
660 voice->mDirect.Buffer = Device->RealOut.Buffer;
662 for(ALuint c{0};c < num_channels;c++)
664 const ALuint idx{GetChannelIdxByName(Device->RealOut, chans[c].channel)};
665 if(idx != INVALID_CHANNEL_INDEX)
666 voice->mChans[c].mDryParams.Gains.Target[idx] = DryGain;
669 /* Auxiliary sends still use normal channel panning since they mix to
670 * B-Format, which can't channel-match.
672 for(ALuint c{0};c < num_channels;c++)
674 ALfloat coeffs[MAX_AMBI_CHANNELS];
675 CalcAngleCoeffs(chans[c].angle, chans[c].elevation, 0.0f, coeffs);
677 for(ALuint i{0};i < NumSends;i++)
679 if(const ALeffectslot *Slot{SendSlots[i]})
680 ComputePanGains(&Slot->Wet, coeffs, WetGain[i],
681 voice->mChans[c].mWetParams[i].Gains.Target);
685 else if(Device->mRenderMode == HrtfRender)
687 /* Full HRTF rendering. Skip the virtual channels and render to the
688 * real outputs.
690 voice->mDirect.Buffer = Device->RealOut.Buffer;
692 if(Distance > std::numeric_limits<float>::epsilon())
694 const ALfloat ev{std::asin(clampf(ypos, -1.0f, 1.0f))};
695 const ALfloat az{std::atan2(xpos, -zpos)};
697 /* Get the HRIR coefficients and delays just once, for the given
698 * source direction.
700 GetHrtfCoeffs(Device->mHrtf, ev, az, Distance, Spread,
701 voice->mChans[0].mDryParams.Hrtf.Target.Coeffs,
702 voice->mChans[0].mDryParams.Hrtf.Target.Delay);
703 voice->mChans[0].mDryParams.Hrtf.Target.Gain = DryGain * downmix_gain;
705 /* Remaining channels use the same results as the first. */
706 for(ALuint c{1};c < num_channels;c++)
708 /* Skip LFE */
709 if(chans[c].channel == LFE) continue;
710 voice->mChans[c].mDryParams.Hrtf.Target = voice->mChans[0].mDryParams.Hrtf.Target;
713 /* Calculate the directional coefficients once, which apply to all
714 * input channels of the source sends.
716 ALfloat coeffs[MAX_AMBI_CHANNELS];
717 CalcDirectionCoeffs({xpos, ypos, zpos}, Spread, coeffs);
719 for(ALuint c{0};c < num_channels;c++)
721 /* Skip LFE */
722 if(chans[c].channel == LFE)
723 continue;
724 for(ALuint i{0};i < NumSends;i++)
726 if(const ALeffectslot *Slot{SendSlots[i]})
727 ComputePanGains(&Slot->Wet, coeffs, WetGain[i] * downmix_gain,
728 voice->mChans[c].mWetParams[i].Gains.Target);
732 else
734 /* Local sources on HRTF play with each channel panned to its
735 * relative location around the listener, providing "virtual
736 * speaker" responses.
738 for(ALuint c{0};c < num_channels;c++)
740 /* Skip LFE */
741 if(chans[c].channel == LFE)
742 continue;
744 /* Get the HRIR coefficients and delays for this channel
745 * position.
747 GetHrtfCoeffs(Device->mHrtf, chans[c].elevation, chans[c].angle,
748 std::numeric_limits<float>::infinity(), Spread,
749 voice->mChans[c].mDryParams.Hrtf.Target.Coeffs,
750 voice->mChans[c].mDryParams.Hrtf.Target.Delay);
751 voice->mChans[c].mDryParams.Hrtf.Target.Gain = DryGain;
753 /* Normal panning for auxiliary sends. */
754 ALfloat coeffs[MAX_AMBI_CHANNELS];
755 CalcAngleCoeffs(chans[c].angle, chans[c].elevation, Spread, coeffs);
757 for(ALuint i{0};i < NumSends;i++)
759 if(const ALeffectslot *Slot{SendSlots[i]})
760 ComputePanGains(&Slot->Wet, coeffs, WetGain[i],
761 voice->mChans[c].mWetParams[i].Gains.Target);
766 voice->mFlags |= VOICE_HAS_HRTF;
768 else
770 /* Non-HRTF rendering. Use normal panning to the output. */
772 if(Distance > std::numeric_limits<float>::epsilon())
774 /* Calculate NFC filter coefficient if needed. */
775 if(Device->AvgSpeakerDist > 0.0f)
777 /* Clamp the distance for really close sources, to prevent
778 * excessive bass.
780 const ALfloat mdist{maxf(Distance, Device->AvgSpeakerDist/4.0f)};
781 const ALfloat w0{SPEEDOFSOUNDMETRESPERSEC / (mdist * Frequency)};
783 /* Adjust NFC filters. */
784 for(ALuint c{0};c < num_channels;c++)
785 voice->mChans[c].mDryParams.NFCtrlFilter.adjust(w0);
787 voice->mFlags |= VOICE_HAS_NFC;
790 /* Calculate the directional coefficients once, which apply to all
791 * input channels.
793 ALfloat coeffs[MAX_AMBI_CHANNELS];
794 if(Device->mRenderMode != StereoPair)
795 CalcDirectionCoeffs({xpos, ypos, zpos}, Spread, coeffs);
796 else
798 const ALfloat ev{std::asin(clampf(ypos, -1.0f, 1.0f))};
799 const ALfloat az{std::atan2(xpos, -zpos)};
800 CalcAngleCoeffs(ScaleAzimuthFront(az, 1.5f), ev, Spread, coeffs);
803 for(ALuint c{0};c < num_channels;c++)
805 /* Special-case LFE */
806 if(chans[c].channel == LFE)
808 if(Device->Dry.Buffer.data() == Device->RealOut.Buffer.data())
810 const ALuint idx{GetChannelIdxByName(Device->RealOut, chans[c].channel)};
811 if(idx != INVALID_CHANNEL_INDEX)
812 voice->mChans[c].mDryParams.Gains.Target[idx] = DryGain;
814 continue;
817 ComputePanGains(&Device->Dry, coeffs, DryGain * downmix_gain,
818 voice->mChans[c].mDryParams.Gains.Target);
819 for(ALuint i{0};i < NumSends;i++)
821 if(const ALeffectslot *Slot{SendSlots[i]})
822 ComputePanGains(&Slot->Wet, coeffs, WetGain[i] * downmix_gain,
823 voice->mChans[c].mWetParams[i].Gains.Target);
827 else
829 if(Device->AvgSpeakerDist > 0.0f)
831 /* If the source distance is 0, set w0 to w1 to act as a pass-
832 * through. We still want to pass the signal through the
833 * filters so they keep an appropriate history, in case the
834 * source moves away from the listener.
836 const ALfloat w0{SPEEDOFSOUNDMETRESPERSEC / (Device->AvgSpeakerDist * Frequency)};
838 for(ALuint c{0};c < num_channels;c++)
839 voice->mChans[c].mDryParams.NFCtrlFilter.adjust(w0);
841 voice->mFlags |= VOICE_HAS_NFC;
844 for(ALuint c{0};c < num_channels;c++)
846 /* Special-case LFE */
847 if(chans[c].channel == LFE)
849 if(Device->Dry.Buffer.data() == Device->RealOut.Buffer.data())
851 const ALuint idx{GetChannelIdxByName(Device->RealOut, chans[c].channel)};
852 if(idx != INVALID_CHANNEL_INDEX)
853 voice->mChans[c].mDryParams.Gains.Target[idx] = DryGain;
855 continue;
858 ALfloat coeffs[MAX_AMBI_CHANNELS];
859 CalcAngleCoeffs(
860 (Device->mRenderMode==StereoPair) ? ScaleAzimuthFront(chans[c].angle, 3.0f)
861 : chans[c].angle,
862 chans[c].elevation, Spread, coeffs
865 ComputePanGains(&Device->Dry, coeffs, DryGain,
866 voice->mChans[c].mDryParams.Gains.Target);
867 for(ALuint i{0};i < NumSends;i++)
869 if(const ALeffectslot *Slot{SendSlots[i]})
870 ComputePanGains(&Slot->Wet, coeffs, WetGain[i],
871 voice->mChans[c].mWetParams[i].Gains.Target);
878 const ALfloat hfScale{props->Direct.HFReference / Frequency};
879 const ALfloat lfScale{props->Direct.LFReference / Frequency};
880 const ALfloat gainHF{maxf(DryGainHF, 0.001f)}; /* Limit -60dB */
881 const ALfloat gainLF{maxf(DryGainLF, 0.001f)};
883 voice->mDirect.FilterType = AF_None;
884 if(gainHF != 1.0f) voice->mDirect.FilterType |= AF_LowPass;
885 if(gainLF != 1.0f) voice->mDirect.FilterType |= AF_HighPass;
886 auto &lowpass = voice->mChans[0].mDryParams.LowPass;
887 auto &highpass = voice->mChans[0].mDryParams.HighPass;
888 lowpass.setParams(BiquadType::HighShelf, gainHF, hfScale,
889 lowpass.rcpQFromSlope(gainHF, 1.0f));
890 highpass.setParams(BiquadType::LowShelf, gainLF, lfScale,
891 highpass.rcpQFromSlope(gainLF, 1.0f));
892 for(ALuint c{1};c < num_channels;c++)
894 voice->mChans[c].mDryParams.LowPass.copyParamsFrom(lowpass);
895 voice->mChans[c].mDryParams.HighPass.copyParamsFrom(highpass);
898 for(ALuint i{0};i < NumSends;i++)
900 const ALfloat hfScale{props->Send[i].HFReference / Frequency};
901 const ALfloat lfScale{props->Send[i].LFReference / Frequency};
902 const ALfloat gainHF{maxf(WetGainHF[i], 0.001f)};
903 const ALfloat gainLF{maxf(WetGainLF[i], 0.001f)};
905 voice->mSend[i].FilterType = AF_None;
906 if(gainHF != 1.0f) voice->mSend[i].FilterType |= AF_LowPass;
907 if(gainLF != 1.0f) voice->mSend[i].FilterType |= AF_HighPass;
909 auto &lowpass = voice->mChans[0].mWetParams[i].LowPass;
910 auto &highpass = voice->mChans[0].mWetParams[i].HighPass;
911 lowpass.setParams(BiquadType::HighShelf, gainHF, hfScale,
912 lowpass.rcpQFromSlope(gainHF, 1.0f));
913 highpass.setParams(BiquadType::LowShelf, gainLF, lfScale,
914 highpass.rcpQFromSlope(gainLF, 1.0f));
915 for(ALuint c{1};c < num_channels;c++)
917 voice->mChans[c].mWetParams[i].LowPass.copyParamsFrom(lowpass);
918 voice->mChans[c].mWetParams[i].HighPass.copyParamsFrom(highpass);
923 void CalcNonAttnSourceParams(ALvoice *voice, const ALvoicePropsBase *props, const ALCcontext *ALContext)
925 const ALCdevice *Device{ALContext->mDevice.get()};
926 ALeffectslot *SendSlots[MAX_SENDS];
928 voice->mDirect.Buffer = Device->Dry.Buffer;
929 for(ALuint i{0};i < Device->NumAuxSends;i++)
931 SendSlots[i] = props->Send[i].Slot;
932 if(!SendSlots[i] && i == 0)
933 SendSlots[i] = ALContext->mDefaultSlot.get();
934 if(!SendSlots[i] || SendSlots[i]->Params.EffectType == AL_EFFECT_NULL)
936 SendSlots[i] = nullptr;
937 voice->mSend[i].Buffer = {};
939 else
940 voice->mSend[i].Buffer = SendSlots[i]->Wet.Buffer;
943 /* Calculate the stepping value */
944 const auto Pitch = static_cast<ALfloat>(voice->mFrequency) /
945 static_cast<ALfloat>(Device->Frequency) * props->Pitch;
946 if(Pitch > static_cast<ALfloat>(MAX_PITCH))
947 voice->mStep = MAX_PITCH<<FRACTIONBITS;
948 else
949 voice->mStep = maxu(fastf2u(Pitch * FRACTIONONE), 1);
950 if(props->mResampler == Resampler::BSinc24)
951 BsincPrepare(voice->mStep, &voice->mResampleState.bsinc, &bsinc24);
952 else if(props->mResampler == Resampler::BSinc12)
953 BsincPrepare(voice->mStep, &voice->mResampleState.bsinc, &bsinc12);
954 voice->mResampler = SelectResampler(props->mResampler);
956 /* Calculate gains */
957 const ALlistener &Listener = ALContext->mListener;
958 ALfloat DryGain{clampf(props->Gain, props->MinGain, props->MaxGain)};
959 DryGain *= props->Direct.Gain * Listener.Params.Gain;
960 DryGain = minf(DryGain, GAIN_MIX_MAX);
961 ALfloat DryGainHF{props->Direct.GainHF};
962 ALfloat DryGainLF{props->Direct.GainLF};
963 ALfloat WetGain[MAX_SENDS], WetGainHF[MAX_SENDS], WetGainLF[MAX_SENDS];
964 for(ALuint i{0};i < Device->NumAuxSends;i++)
966 WetGain[i] = clampf(props->Gain, props->MinGain, props->MaxGain);
967 WetGain[i] *= props->Send[i].Gain * Listener.Params.Gain;
968 WetGain[i] = minf(WetGain[i], GAIN_MIX_MAX);
969 WetGainHF[i] = props->Send[i].GainHF;
970 WetGainLF[i] = props->Send[i].GainLF;
973 CalcPanningAndFilters(voice, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, DryGain, DryGainHF, DryGainLF,
974 WetGain, WetGainLF, WetGainHF, SendSlots, props, Listener, Device);
977 void CalcAttnSourceParams(ALvoice *voice, const ALvoicePropsBase *props, const ALCcontext *ALContext)
979 const ALCdevice *Device{ALContext->mDevice.get()};
980 const ALuint NumSends{Device->NumAuxSends};
981 const ALlistener &Listener = ALContext->mListener;
983 /* Set mixing buffers and get send parameters. */
984 voice->mDirect.Buffer = Device->Dry.Buffer;
985 ALeffectslot *SendSlots[MAX_SENDS];
986 ALfloat RoomRolloff[MAX_SENDS];
987 ALfloat DecayDistance[MAX_SENDS];
988 ALfloat DecayLFDistance[MAX_SENDS];
989 ALfloat DecayHFDistance[MAX_SENDS];
990 for(ALuint i{0};i < NumSends;i++)
992 SendSlots[i] = props->Send[i].Slot;
993 if(!SendSlots[i] && i == 0)
994 SendSlots[i] = ALContext->mDefaultSlot.get();
995 if(!SendSlots[i] || SendSlots[i]->Params.EffectType == AL_EFFECT_NULL)
997 SendSlots[i] = nullptr;
998 RoomRolloff[i] = 0.0f;
999 DecayDistance[i] = 0.0f;
1000 DecayLFDistance[i] = 0.0f;
1001 DecayHFDistance[i] = 0.0f;
1003 else if(SendSlots[i]->Params.AuxSendAuto)
1005 RoomRolloff[i] = SendSlots[i]->Params.RoomRolloff + props->RoomRolloffFactor;
1006 /* Calculate the distances to where this effect's decay reaches
1007 * -60dB.
1009 DecayDistance[i] = SendSlots[i]->Params.DecayTime * SPEEDOFSOUNDMETRESPERSEC;
1010 DecayLFDistance[i] = DecayDistance[i] * SendSlots[i]->Params.DecayLFRatio;
1011 DecayHFDistance[i] = DecayDistance[i] * SendSlots[i]->Params.DecayHFRatio;
1012 if(SendSlots[i]->Params.DecayHFLimit)
1014 ALfloat airAbsorption{SendSlots[i]->Params.AirAbsorptionGainHF};
1015 if(airAbsorption < 1.0f)
1017 /* Calculate the distance to where this effect's air
1018 * absorption reaches -60dB, and limit the effect's HF
1019 * decay distance (so it doesn't take any longer to decay
1020 * than the air would allow).
1022 ALfloat absorb_dist{std::log10(REVERB_DECAY_GAIN) / std::log10(airAbsorption)};
1023 DecayHFDistance[i] = minf(absorb_dist, DecayHFDistance[i]);
1027 else
1029 /* If the slot's auxiliary send auto is off, the data sent to the
1030 * effect slot is the same as the dry path, sans filter effects */
1031 RoomRolloff[i] = props->RolloffFactor;
1032 DecayDistance[i] = 0.0f;
1033 DecayLFDistance[i] = 0.0f;
1034 DecayHFDistance[i] = 0.0f;
1037 if(!SendSlots[i])
1038 voice->mSend[i].Buffer = {};
1039 else
1040 voice->mSend[i].Buffer = SendSlots[i]->Wet.Buffer;
1043 /* Transform source to listener space (convert to head relative) */
1044 alu::Vector Position{props->Position[0], props->Position[1], props->Position[2], 1.0f};
1045 alu::Vector Velocity{props->Velocity[0], props->Velocity[1], props->Velocity[2], 0.0f};
1046 alu::Vector Direction{props->Direction[0], props->Direction[1], props->Direction[2], 0.0f};
1047 if(props->HeadRelative == AL_FALSE)
1049 /* Transform source vectors */
1050 Position = Listener.Params.Matrix * Position;
1051 Velocity = Listener.Params.Matrix * Velocity;
1052 Direction = Listener.Params.Matrix * Direction;
1054 else
1056 /* Offset the source velocity to be relative of the listener velocity */
1057 Velocity += Listener.Params.Velocity;
1060 const bool directional{Direction.normalize() > 0.0f};
1061 alu::Vector ToSource{Position[0], Position[1], Position[2], 0.0f};
1062 const ALfloat Distance{ToSource.normalize()};
1064 /* Initial source gain */
1065 ALfloat DryGain{props->Gain};
1066 ALfloat DryGainHF{1.0f};
1067 ALfloat DryGainLF{1.0f};
1068 ALfloat WetGain[MAX_SENDS], WetGainHF[MAX_SENDS], WetGainLF[MAX_SENDS];
1069 for(ALuint i{0};i < NumSends;i++)
1071 WetGain[i] = props->Gain;
1072 WetGainHF[i] = 1.0f;
1073 WetGainLF[i] = 1.0f;
1076 /* Calculate distance attenuation */
1077 ALfloat ClampedDist{Distance};
1079 switch(Listener.Params.SourceDistanceModel ?
1080 props->mDistanceModel : Listener.Params.mDistanceModel)
1082 case DistanceModel::InverseClamped:
1083 ClampedDist = clampf(ClampedDist, props->RefDistance, props->MaxDistance);
1084 if(props->MaxDistance < props->RefDistance) break;
1085 /*fall-through*/
1086 case DistanceModel::Inverse:
1087 if(!(props->RefDistance > 0.0f))
1088 ClampedDist = props->RefDistance;
1089 else
1091 ALfloat dist = lerp(props->RefDistance, ClampedDist, props->RolloffFactor);
1092 if(dist > 0.0f) DryGain *= props->RefDistance / dist;
1093 for(ALuint i{0};i < NumSends;i++)
1095 dist = lerp(props->RefDistance, ClampedDist, RoomRolloff[i]);
1096 if(dist > 0.0f) WetGain[i] *= props->RefDistance / dist;
1099 break;
1101 case DistanceModel::LinearClamped:
1102 ClampedDist = clampf(ClampedDist, props->RefDistance, props->MaxDistance);
1103 if(props->MaxDistance < props->RefDistance) break;
1104 /*fall-through*/
1105 case DistanceModel::Linear:
1106 if(!(props->MaxDistance != props->RefDistance))
1107 ClampedDist = props->RefDistance;
1108 else
1110 ALfloat attn = props->RolloffFactor * (ClampedDist-props->RefDistance) /
1111 (props->MaxDistance-props->RefDistance);
1112 DryGain *= maxf(1.0f - attn, 0.0f);
1113 for(ALuint i{0};i < NumSends;i++)
1115 attn = RoomRolloff[i] * (ClampedDist-props->RefDistance) /
1116 (props->MaxDistance-props->RefDistance);
1117 WetGain[i] *= maxf(1.0f - attn, 0.0f);
1120 break;
1122 case DistanceModel::ExponentClamped:
1123 ClampedDist = clampf(ClampedDist, props->RefDistance, props->MaxDistance);
1124 if(props->MaxDistance < props->RefDistance) break;
1125 /*fall-through*/
1126 case DistanceModel::Exponent:
1127 if(!(ClampedDist > 0.0f && props->RefDistance > 0.0f))
1128 ClampedDist = props->RefDistance;
1129 else
1131 DryGain *= std::pow(ClampedDist/props->RefDistance, -props->RolloffFactor);
1132 for(ALuint i{0};i < NumSends;i++)
1133 WetGain[i] *= std::pow(ClampedDist/props->RefDistance, -RoomRolloff[i]);
1135 break;
1137 case DistanceModel::Disable:
1138 ClampedDist = props->RefDistance;
1139 break;
1142 /* Calculate directional soundcones */
1143 if(directional && props->InnerAngle < 360.0f)
1145 const ALfloat Angle{Rad2Deg(std::acos(-aluDotproduct(Direction, ToSource)) *
1146 ConeScale * 2.0f)};
1148 ALfloat ConeVolume, ConeHF;
1149 if(!(Angle > props->InnerAngle))
1151 ConeVolume = 1.0f;
1152 ConeHF = 1.0f;
1154 else if(Angle < props->OuterAngle)
1156 ALfloat scale = ( Angle-props->InnerAngle) /
1157 (props->OuterAngle-props->InnerAngle);
1158 ConeVolume = lerp(1.0f, props->OuterGain, scale);
1159 ConeHF = lerp(1.0f, props->OuterGainHF, scale);
1161 else
1163 ConeVolume = props->OuterGain;
1164 ConeHF = props->OuterGainHF;
1167 DryGain *= ConeVolume;
1168 if(props->DryGainHFAuto)
1169 DryGainHF *= ConeHF;
1170 if(props->WetGainAuto)
1171 std::transform(std::begin(WetGain), std::begin(WetGain)+NumSends, std::begin(WetGain),
1172 [ConeVolume](ALfloat gain) noexcept -> ALfloat { return gain * ConeVolume; }
1174 if(props->WetGainHFAuto)
1175 std::transform(std::begin(WetGainHF), std::begin(WetGainHF)+NumSends,
1176 std::begin(WetGainHF),
1177 [ConeHF](ALfloat gain) noexcept -> ALfloat { return gain * ConeHF; }
1181 /* Apply gain and frequency filters */
1182 DryGain = clampf(DryGain, props->MinGain, props->MaxGain);
1183 DryGain = minf(DryGain*props->Direct.Gain*Listener.Params.Gain, GAIN_MIX_MAX);
1184 DryGainHF *= props->Direct.GainHF;
1185 DryGainLF *= props->Direct.GainLF;
1186 for(ALuint i{0};i < NumSends;i++)
1188 WetGain[i] = clampf(WetGain[i], props->MinGain, props->MaxGain);
1189 WetGain[i] = minf(WetGain[i]*props->Send[i].Gain*Listener.Params.Gain, GAIN_MIX_MAX);
1190 WetGainHF[i] *= props->Send[i].GainHF;
1191 WetGainLF[i] *= props->Send[i].GainLF;
1194 /* Distance-based air absorption and initial send decay. */
1195 if(ClampedDist > props->RefDistance && props->RolloffFactor > 0.0f)
1197 ALfloat meters_base{(ClampedDist-props->RefDistance) * props->RolloffFactor *
1198 Listener.Params.MetersPerUnit};
1199 if(props->AirAbsorptionFactor > 0.0f)
1201 ALfloat hfattn{std::pow(AIRABSORBGAINHF, meters_base * props->AirAbsorptionFactor)};
1202 DryGainHF *= hfattn;
1203 std::transform(std::begin(WetGainHF), std::begin(WetGainHF)+NumSends,
1204 std::begin(WetGainHF),
1205 [hfattn](ALfloat gain) noexcept -> ALfloat { return gain * hfattn; }
1209 if(props->WetGainAuto)
1211 /* Apply a decay-time transformation to the wet path, based on the
1212 * source distance in meters. The initial decay of the reverb
1213 * effect is calculated and applied to the wet path.
1215 for(ALuint i{0};i < NumSends;i++)
1217 if(!(DecayDistance[i] > 0.0f))
1218 continue;
1220 const ALfloat gain{std::pow(REVERB_DECAY_GAIN, meters_base/DecayDistance[i])};
1221 WetGain[i] *= gain;
1222 /* Yes, the wet path's air absorption is applied with
1223 * WetGainAuto on, rather than WetGainHFAuto.
1225 if(gain > 0.0f)
1227 ALfloat gainhf{std::pow(REVERB_DECAY_GAIN, meters_base/DecayHFDistance[i])};
1228 WetGainHF[i] *= minf(gainhf / gain, 1.0f);
1229 ALfloat gainlf{std::pow(REVERB_DECAY_GAIN, meters_base/DecayLFDistance[i])};
1230 WetGainLF[i] *= minf(gainlf / gain, 1.0f);
1237 /* Initial source pitch */
1238 ALfloat Pitch{props->Pitch};
1240 /* Calculate velocity-based doppler effect */
1241 ALfloat DopplerFactor{props->DopplerFactor * Listener.Params.DopplerFactor};
1242 if(DopplerFactor > 0.0f)
1244 const alu::Vector &lvelocity = Listener.Params.Velocity;
1245 ALfloat vss{aluDotproduct(Velocity, ToSource) * -DopplerFactor};
1246 ALfloat vls{aluDotproduct(lvelocity, ToSource) * -DopplerFactor};
1248 const ALfloat SpeedOfSound{Listener.Params.SpeedOfSound};
1249 if(!(vls < SpeedOfSound))
1251 /* Listener moving away from the source at the speed of sound.
1252 * Sound waves can't catch it.
1254 Pitch = 0.0f;
1256 else if(!(vss < SpeedOfSound))
1258 /* Source moving toward the listener at the speed of sound. Sound
1259 * waves bunch up to extreme frequencies.
1261 Pitch = std::numeric_limits<float>::infinity();
1263 else
1265 /* Source and listener movement is nominal. Calculate the proper
1266 * doppler shift.
1268 Pitch *= (SpeedOfSound-vls) / (SpeedOfSound-vss);
1272 /* Adjust pitch based on the buffer and output frequencies, and calculate
1273 * fixed-point stepping value.
1275 Pitch *= static_cast<ALfloat>(voice->mFrequency)/static_cast<ALfloat>(Device->Frequency);
1276 if(Pitch > static_cast<ALfloat>(MAX_PITCH))
1277 voice->mStep = MAX_PITCH<<FRACTIONBITS;
1278 else
1279 voice->mStep = maxu(fastf2u(Pitch * FRACTIONONE), 1);
1280 if(props->mResampler == Resampler::BSinc24)
1281 BsincPrepare(voice->mStep, &voice->mResampleState.bsinc, &bsinc24);
1282 else if(props->mResampler == Resampler::BSinc12)
1283 BsincPrepare(voice->mStep, &voice->mResampleState.bsinc, &bsinc12);
1284 voice->mResampler = SelectResampler(props->mResampler);
1286 ALfloat spread{0.0f};
1287 if(props->Radius > Distance)
1288 spread = al::MathDefs<float>::Tau() - Distance/props->Radius*al::MathDefs<float>::Pi();
1289 else if(Distance > 0.0f)
1290 spread = std::asin(props->Radius/Distance) * 2.0f;
1292 CalcPanningAndFilters(voice, ToSource[0], ToSource[1], ToSource[2]*ZScale,
1293 Distance*Listener.Params.MetersPerUnit, spread, DryGain, DryGainHF, DryGainLF, WetGain,
1294 WetGainLF, WetGainHF, SendSlots, props, Listener, Device);
1297 void CalcSourceParams(ALvoice *voice, ALCcontext *context, bool force)
1299 ALvoiceProps *props{voice->mUpdate.exchange(nullptr, std::memory_order_acq_rel)};
1300 if(!props && !force) return;
1302 if(props)
1304 voice->mProps = *props;
1306 AtomicReplaceHead(context->mFreeVoiceProps, props);
1309 if((voice->mProps.mSpatializeMode == SpatializeAuto && voice->mFmtChannels == FmtMono) ||
1310 voice->mProps.mSpatializeMode == SpatializeOn)
1311 CalcAttnSourceParams(voice, &voice->mProps, context);
1312 else
1313 CalcNonAttnSourceParams(voice, &voice->mProps, context);
1317 void ProcessParamUpdates(ALCcontext *ctx, const ALeffectslotArray &slots,
1318 const al::span<ALvoice> voices)
1320 IncrementRef(ctx->mUpdateCount);
1321 if LIKELY(!ctx->mHoldUpdates.load(std::memory_order_acquire))
1323 bool force{CalcContextParams(ctx)};
1324 force |= CalcListenerParams(ctx);
1325 force = std::accumulate(slots.begin(), slots.end(), force,
1326 [ctx](const bool f, ALeffectslot *slot) -> bool
1327 { return CalcEffectSlotParams(slot, ctx) | f; }
1330 auto calc_params = [ctx,force](ALvoice &voice) -> void
1332 if(voice.mSourceID.load(std::memory_order_acquire) != 0)
1333 CalcSourceParams(&voice, ctx, force);
1335 std::for_each(voices.begin(), voices.end(), calc_params);
1337 IncrementRef(ctx->mUpdateCount);
1340 void ProcessContext(ALCcontext *ctx, const ALuint SamplesToDo)
1342 ASSUME(SamplesToDo > 0);
1344 const ALeffectslotArray &auxslots = *ctx->mActiveAuxSlots.load(std::memory_order_acquire);
1345 const al::span<ALvoice> voices{ctx->mVoices.data(), ctx->mVoices.size()};
1347 /* Process pending propery updates for objects on the context. */
1348 ProcessParamUpdates(ctx, auxslots, voices);
1350 /* Clear auxiliary effect slot mixing buffers. */
1351 std::for_each(auxslots.begin(), auxslots.end(),
1352 [SamplesToDo](ALeffectslot *slot) -> void
1354 for(auto &buffer : slot->MixBuffer)
1355 std::fill_n(buffer.begin(), SamplesToDo, 0.0f);
1359 /* Process voices that have a playing source. */
1360 std::for_each(voices.begin(), voices.end(),
1361 [SamplesToDo,ctx](ALvoice &voice) -> void
1363 const ALvoice::State vstate{voice.mPlayState.load(std::memory_order_acquire)};
1364 if(vstate != ALvoice::Stopped) voice.mix(vstate, ctx, SamplesToDo);
1368 /* Process effects. */
1369 if(auxslots.empty()) return;
1370 auto slots = auxslots.data();
1371 auto slots_end = slots + auxslots.size();
1373 /* First sort the slots into scratch storage, so that effects come before
1374 * their effect target (or their targets' target).
1376 auto sorted_slots = const_cast<ALeffectslot**>(slots_end);
1377 auto sorted_slots_end = sorted_slots;
1378 auto in_chain = [](const ALeffectslot *slot1, const ALeffectslot *slot2) noexcept -> bool
1380 while((slot1=slot1->Params.Target) != nullptr) {
1381 if(slot1 == slot2) return true;
1383 return false;
1386 *sorted_slots_end = *slots;
1387 ++sorted_slots_end;
1388 while(++slots != slots_end)
1390 /* If this effect slot targets an effect slot already in the list (i.e.
1391 * slots outputs to something in sorted_slots), directly or indirectly,
1392 * insert it prior to that element.
1394 auto checker = sorted_slots;
1395 do {
1396 if(in_chain(*slots, *checker)) break;
1397 } while(++checker != sorted_slots_end);
1399 checker = std::move_backward(checker, sorted_slots_end, sorted_slots_end+1);
1400 *--checker = *slots;
1401 ++sorted_slots_end;
1404 std::for_each(sorted_slots, sorted_slots_end,
1405 [SamplesToDo](const ALeffectslot *slot) -> void
1407 EffectState *state{slot->Params.mEffectState};
1408 state->process(SamplesToDo, slot->Wet.Buffer, state->mOutTarget);
1414 void ApplyStablizer(FrontStablizer *Stablizer, const al::span<FloatBufferLine> Buffer,
1415 const ALuint lidx, const ALuint ridx, const ALuint cidx, const ALuint SamplesToDo)
1417 ASSUME(SamplesToDo > 0);
1419 /* Apply a delay to all channels, except the front-left and front-right, so
1420 * they maintain correct timing.
1422 const size_t NumChannels{Buffer.size()};
1423 for(size_t i{0u};i < NumChannels;i++)
1425 if(i == lidx || i == ridx)
1426 continue;
1428 auto &DelayBuf = Stablizer->DelayBuf[i];
1429 auto buffer_end = Buffer[i].begin() + SamplesToDo;
1430 if LIKELY(SamplesToDo >= ALuint{FrontStablizer::DelayLength})
1432 auto delay_end = std::rotate(Buffer[i].begin(),
1433 buffer_end - FrontStablizer::DelayLength, buffer_end);
1434 std::swap_ranges(Buffer[i].begin(), delay_end, std::begin(DelayBuf));
1436 else
1438 auto delay_start = std::swap_ranges(Buffer[i].begin(), buffer_end,
1439 std::begin(DelayBuf));
1440 std::rotate(std::begin(DelayBuf), delay_start, std::end(DelayBuf));
1444 ALfloat (&lsplit)[2][BUFFERSIZE] = Stablizer->LSplit;
1445 ALfloat (&rsplit)[2][BUFFERSIZE] = Stablizer->RSplit;
1446 auto &tmpbuf = Stablizer->TempBuf;
1448 /* This applies the band-splitter, preserving phase at the cost of some
1449 * delay. The shorter the delay, the more error seeps into the result.
1451 auto apply_splitter = [&tmpbuf,SamplesToDo](const FloatBufferLine &InBuf,
1452 ALfloat (&DelayBuf)[FrontStablizer::DelayLength], BandSplitter &Filter,
1453 ALfloat (&splitbuf)[2][BUFFERSIZE]) -> void
1455 /* Combine the delayed samples and the input samples into the temp
1456 * buffer, in reverse. Then copy the final samples back into the delay
1457 * buffer for next time. Note that the delay buffer's samples are
1458 * stored backwards here.
1460 auto tmpbuf_end = std::begin(tmpbuf) + SamplesToDo;
1461 std::copy_n(std::begin(DelayBuf), FrontStablizer::DelayLength, tmpbuf_end);
1462 std::reverse_copy(InBuf.begin(), InBuf.begin()+SamplesToDo, std::begin(tmpbuf));
1463 std::copy_n(std::begin(tmpbuf), FrontStablizer::DelayLength, std::begin(DelayBuf));
1465 /* Apply an all-pass on the reversed signal, then reverse the samples
1466 * to get the forward signal with a reversed phase shift.
1468 Filter.applyAllpass(tmpbuf, SamplesToDo+FrontStablizer::DelayLength);
1469 std::reverse(std::begin(tmpbuf), tmpbuf_end+FrontStablizer::DelayLength);
1471 /* Now apply the band-splitter, combining its phase shift with the
1472 * reversed phase shift, restoring the original phase on the split
1473 * signal.
1475 Filter.process(splitbuf[1], splitbuf[0], tmpbuf, SamplesToDo);
1477 apply_splitter(Buffer[lidx], Stablizer->DelayBuf[lidx], Stablizer->LFilter, lsplit);
1478 apply_splitter(Buffer[ridx], Stablizer->DelayBuf[ridx], Stablizer->RFilter, rsplit);
1480 for(ALuint i{0};i < SamplesToDo;i++)
1482 ALfloat lfsum{lsplit[0][i] + rsplit[0][i]};
1483 ALfloat hfsum{lsplit[1][i] + rsplit[1][i]};
1484 ALfloat s{lsplit[0][i] + lsplit[1][i] - rsplit[0][i] - rsplit[1][i]};
1486 /* This pans the separate low- and high-frequency sums between being on
1487 * the center channel and the left/right channels. The low-frequency
1488 * sum is 1/3rd toward center (2/3rds on left/right) and the high-
1489 * frequency sum is 1/4th toward center (3/4ths on left/right). These
1490 * values can be tweaked.
1492 ALfloat m{lfsum*std::cos(1.0f/3.0f * (al::MathDefs<float>::Pi()*0.5f)) +
1493 hfsum*std::cos(1.0f/4.0f * (al::MathDefs<float>::Pi()*0.5f))};
1494 ALfloat c{lfsum*std::sin(1.0f/3.0f * (al::MathDefs<float>::Pi()*0.5f)) +
1495 hfsum*std::sin(1.0f/4.0f * (al::MathDefs<float>::Pi()*0.5f))};
1497 /* The generated center channel signal adds to the existing signal,
1498 * while the modified left and right channels replace.
1500 Buffer[lidx][i] = (m + s) * 0.5f;
1501 Buffer[ridx][i] = (m - s) * 0.5f;
1502 Buffer[cidx][i] += c * 0.5f;
1506 void ApplyDistanceComp(const al::span<FloatBufferLine> Samples, const ALuint SamplesToDo,
1507 const DistanceComp::DistData *distcomp)
1509 ASSUME(SamplesToDo > 0);
1511 for(auto &chanbuffer : Samples)
1513 const ALfloat gain{distcomp->Gain};
1514 const ALuint base{distcomp->Length};
1515 ALfloat *distbuf{al::assume_aligned<16>(distcomp->Buffer)};
1516 ++distcomp;
1518 if(base < 1)
1519 continue;
1521 ALfloat *inout{al::assume_aligned<16>(chanbuffer.data())};
1522 auto inout_end = inout + SamplesToDo;
1523 if LIKELY(SamplesToDo >= base)
1525 auto delay_end = std::rotate(inout, inout_end - base, inout_end);
1526 std::swap_ranges(inout, delay_end, distbuf);
1528 else
1530 auto delay_start = std::swap_ranges(inout, inout_end, distbuf);
1531 std::rotate(distbuf, delay_start, distbuf + base);
1533 std::transform(inout, inout_end, inout, std::bind(std::multiplies<float>{}, _1, gain));
1537 void ApplyDither(const al::span<FloatBufferLine> Samples, ALuint *dither_seed,
1538 const ALfloat quant_scale, const ALuint SamplesToDo)
1540 /* Dithering. Generate whitenoise (uniform distribution of random values
1541 * between -1 and +1) and add it to the sample values, after scaling up to
1542 * the desired quantization depth amd before rounding.
1544 const ALfloat invscale{1.0f / quant_scale};
1545 ALuint seed{*dither_seed};
1546 auto dither_channel = [&seed,invscale,quant_scale,SamplesToDo](FloatBufferLine &input) -> void
1548 ASSUME(SamplesToDo > 0);
1549 auto dither_sample = [&seed,invscale,quant_scale](const ALfloat sample) noexcept -> ALfloat
1551 ALfloat val{sample * quant_scale};
1552 ALuint rng0{dither_rng(&seed)};
1553 ALuint rng1{dither_rng(&seed)};
1554 val += static_cast<ALfloat>(rng0*(1.0/UINT_MAX) - rng1*(1.0/UINT_MAX));
1555 return fast_roundf(val) * invscale;
1557 std::transform(input.begin(), input.begin()+SamplesToDo, input.begin(), dither_sample);
1559 std::for_each(Samples.begin(), Samples.end(), dither_channel);
1560 *dither_seed = seed;
1564 /* Base template left undefined. Should be marked =delete, but Clang 3.8.1
1565 * chokes on that given the inline specializations.
1567 template<typename T>
1568 inline T SampleConv(ALfloat) noexcept;
1570 template<> inline ALfloat SampleConv(ALfloat val) noexcept
1571 { return val; }
1572 template<> inline ALint SampleConv(ALfloat val) noexcept
1574 /* Floats have a 23-bit mantissa, plus an implied 1 bit and a sign bit.
1575 * This means a normalized float has at most 25 bits of signed precision.
1576 * When scaling and clamping for a signed 32-bit integer, these following
1577 * values are the best a float can give.
1579 return fastf2i(clampf(val*2147483648.0f, -2147483648.0f, 2147483520.0f));
1581 template<> inline ALshort SampleConv(ALfloat val) noexcept
1582 { return static_cast<ALshort>(fastf2i(clampf(val*32768.0f, -32768.0f, 32767.0f))); }
1583 template<> inline ALbyte SampleConv(ALfloat val) noexcept
1584 { return static_cast<ALbyte>(fastf2i(clampf(val*128.0f, -128.0f, 127.0f))); }
1586 /* Define unsigned output variations. */
1587 template<> inline ALuint SampleConv(ALfloat val) noexcept
1588 { return static_cast<ALuint>(SampleConv<ALint>(val)) + 2147483648u; }
1589 template<> inline ALushort SampleConv(ALfloat val) noexcept
1590 { return static_cast<ALushort>(SampleConv<ALshort>(val) + 32768); }
1591 template<> inline ALubyte SampleConv(ALfloat val) noexcept
1592 { return static_cast<ALubyte>(SampleConv<ALbyte>(val) + 128); }
1594 template<DevFmtType T>
1595 void Write(const al::span<const FloatBufferLine> InBuffer, ALvoid *OutBuffer, const size_t Offset,
1596 const ALuint SamplesToDo)
1598 using SampleType = typename DevFmtTypeTraits<T>::Type;
1600 const size_t numchans{InBuffer.size()};
1601 ASSUME(numchans > 0);
1603 SampleType *outbase = static_cast<SampleType*>(OutBuffer) + Offset*numchans;
1604 auto conv_channel = [&outbase,SamplesToDo,numchans](const FloatBufferLine &inbuf) -> void
1606 ASSUME(SamplesToDo > 0);
1607 SampleType *out{outbase++};
1608 auto conv_sample = [numchans,&out](const ALfloat s) noexcept -> void
1610 *out = SampleConv<SampleType>(s);
1611 out += numchans;
1613 std::for_each(inbuf.begin(), inbuf.begin()+SamplesToDo, conv_sample);
1615 std::for_each(InBuffer.cbegin(), InBuffer.cend(), conv_channel);
1618 } // namespace
1620 void aluMixData(ALCdevice *device, ALvoid *OutBuffer, const ALuint NumSamples)
1622 FPUCtl mixer_mode{};
1623 for(ALuint SamplesDone{0u};SamplesDone < NumSamples;)
1625 const ALuint SamplesToDo{minu(NumSamples-SamplesDone, BUFFERSIZE)};
1627 /* Clear main mixing buffers. */
1628 std::for_each(device->MixBuffer.begin(), device->MixBuffer.end(),
1629 [SamplesToDo](std::array<ALfloat,BUFFERSIZE> &buffer) -> void
1630 { std::fill_n(buffer.begin(), SamplesToDo, 0.0f); }
1633 /* Increment the mix count at the start (lsb should now be 1). */
1634 IncrementRef(device->MixCount);
1636 /* For each context on this device, process and mix its sources and
1637 * effects.
1639 for(ALCcontext *ctx : *device->mContexts.load(std::memory_order_acquire))
1640 ProcessContext(ctx, SamplesToDo);
1642 /* Increment the clock time. Every second's worth of samples is
1643 * converted and added to clock base so that large sample counts don't
1644 * overflow during conversion. This also guarantees a stable
1645 * conversion.
1647 device->SamplesDone += SamplesToDo;
1648 device->ClockBase += std::chrono::seconds{device->SamplesDone / device->Frequency};
1649 device->SamplesDone %= device->Frequency;
1651 /* Increment the mix count at the end (lsb should now be 0). */
1652 IncrementRef(device->MixCount);
1654 /* Apply any needed post-process for finalizing the Dry mix to the
1655 * RealOut (Ambisonic decode, UHJ encode, etc).
1657 device->postProcess(SamplesToDo);
1659 const al::span<FloatBufferLine> RealOut{device->RealOut.Buffer};
1661 /* Apply front image stablization for surround sound, if applicable. */
1662 if(device->Stablizer)
1664 const ALuint lidx{GetChannelIdxByName(device->RealOut, FrontLeft)};
1665 const ALuint ridx{GetChannelIdxByName(device->RealOut, FrontRight)};
1666 const ALuint cidx{GetChannelIdxByName(device->RealOut, FrontCenter)};
1668 ApplyStablizer(device->Stablizer.get(), RealOut, lidx, ridx, cidx, SamplesToDo);
1671 /* Apply compression, limiting sample amplitude if needed or desired. */
1672 if(Compressor *comp{device->Limiter.get()})
1673 comp->process(SamplesToDo, RealOut.data());
1675 /* Apply delays and attenuation for mismatched speaker distances. */
1676 ApplyDistanceComp(RealOut, SamplesToDo, device->ChannelDelay.as_span().cbegin());
1678 /* Apply dithering. The compressor should have left enough headroom for
1679 * the dither noise to not saturate.
1681 if(device->DitherDepth > 0.0f)
1682 ApplyDither(RealOut, &device->DitherSeed, device->DitherDepth, SamplesToDo);
1684 if LIKELY(OutBuffer)
1686 /* Finally, interleave and convert samples, writing to the device's
1687 * output buffer.
1689 switch(device->FmtType)
1691 #define HANDLE_WRITE(T) case T: \
1692 Write<T>(RealOut, OutBuffer, SamplesDone, SamplesToDo); break;
1693 HANDLE_WRITE(DevFmtByte)
1694 HANDLE_WRITE(DevFmtUByte)
1695 HANDLE_WRITE(DevFmtShort)
1696 HANDLE_WRITE(DevFmtUShort)
1697 HANDLE_WRITE(DevFmtInt)
1698 HANDLE_WRITE(DevFmtUInt)
1699 HANDLE_WRITE(DevFmtFloat)
1700 #undef HANDLE_WRITE
1704 SamplesDone += SamplesToDo;
1709 void aluHandleDisconnect(ALCdevice *device, const char *msg, ...)
1711 if(!device->Connected.exchange(false, std::memory_order_acq_rel))
1712 return;
1714 AsyncEvent evt{EventType_Disconnected};
1715 evt.u.user.type = AL_EVENT_TYPE_DISCONNECTED_SOFT;
1716 evt.u.user.id = 0;
1717 evt.u.user.param = 0;
1719 va_list args;
1720 va_start(args, msg);
1721 int msglen{vsnprintf(evt.u.user.msg, sizeof(evt.u.user.msg), msg, args)};
1722 va_end(args);
1724 if(msglen < 0 || static_cast<size_t>(msglen) >= sizeof(evt.u.user.msg))
1725 evt.u.user.msg[sizeof(evt.u.user.msg)-1] = 0;
1727 IncrementRef(device->MixCount);
1728 for(ALCcontext *ctx : *device->mContexts.load())
1730 const ALbitfieldSOFT enabledevt{ctx->mEnabledEvts.load(std::memory_order_acquire)};
1731 if((enabledevt&EventType_Disconnected))
1733 RingBuffer *ring{ctx->mAsyncEvents.get()};
1734 auto evt_data = ring->getWriteVector().first;
1735 if(evt_data.len > 0)
1737 ::new (evt_data.buf) AsyncEvent{evt};
1738 ring->writeAdvance(1);
1739 ctx->mEventSem.post();
1743 auto stop_voice = [](ALvoice &voice) -> void
1745 voice.mCurrentBuffer.store(nullptr, std::memory_order_relaxed);
1746 voice.mLoopBuffer.store(nullptr, std::memory_order_relaxed);
1747 voice.mSourceID.store(0u, std::memory_order_relaxed);
1748 voice.mPlayState.store(ALvoice::Stopped, std::memory_order_release);
1750 std::for_each(ctx->mVoices.begin(), ctx->mVoices.end(), stop_voice);
1752 IncrementRef(device->MixCount);