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
46 #include "al/auxeffectslot.h"
47 #include "al/buffer.h"
48 #include "al/effect.h"
50 #include "al/listener.h"
52 #include "alcontext.h"
54 #include "alnumeric.h"
59 #include "bformatdec.h"
62 #include "devformat.h"
63 #include "effects/base.h"
64 #include "filters/biquad.h"
65 #include "filters/nfc.h"
66 #include "filters/splitter.h"
67 #include "fpu_modes.h"
69 #include "inprogext.h"
70 #include "mastering.h"
71 #include "math_defs.h"
72 #include "mixer/defs.h"
73 #include "opthelpers.h"
74 #include "ringbuffer.h"
77 #include "uhjfilter.h"
81 #include "bsinc_inc.h"
84 static_assert(!(MAX_RESAMPLER_PADDING
&1) && MAX_RESAMPLER_PADDING
>= bsinc24
.m
[0],
85 "MAX_RESAMPLER_PADDING is not a multiple of two, or is too small");
90 using namespace std::placeholders
;
92 ALfloat
InitConeScale()
95 if(auto optval
= al::getenv("__ALSOFT_HALF_ANGLE_CONES"))
97 if(al::strcasecmp(optval
->c_str(), "true") == 0
98 || strtol(optval
->c_str(), nullptr, 0) == 1)
107 if(auto optval
= al::getenv("__ALSOFT_REVERSE_Z"))
109 if(al::strcasecmp(optval
->c_str(), "true") == 0
110 || strtol(optval
->c_str(), nullptr, 0) == 1)
119 const ALfloat ConeScale
{InitConeScale()};
121 /* Localized Z scalar for mono sources */
122 const ALfloat ZScale
{InitZScale()};
124 MixerFunc MixSamples
{Mix_
<CTag
>};
125 RowMixerFunc MixRowSamples
{MixRow_
<CTag
>};
135 HrtfDirectMixerFunc MixDirectHrtf
= MixDirectHrtf_
<CTag
>;
137 inline MixerFunc
SelectMixer()
140 if((CPUCapFlags
&CPU_CAP_NEON
))
141 return Mix_
<NEONTag
>;
144 if((CPUCapFlags
&CPU_CAP_SSE
))
150 inline RowMixerFunc
SelectRowMixer()
153 if((CPUCapFlags
&CPU_CAP_NEON
))
154 return MixRow_
<NEONTag
>;
157 if((CPUCapFlags
&CPU_CAP_SSE
))
158 return MixRow_
<SSETag
>;
160 return MixRow_
<CTag
>;
163 inline HrtfDirectMixerFunc
SelectHrtfMixer(void)
166 if((CPUCapFlags
&CPU_CAP_NEON
))
167 return MixDirectHrtf_
<NEONTag
>;
170 if((CPUCapFlags
&CPU_CAP_SSE
))
171 return MixDirectHrtf_
<SSETag
>;
174 return MixDirectHrtf_
<CTag
>;
178 inline void BsincPrepare(const ALuint increment
, BsincState
*state
, const BSincTable
*table
)
180 size_t si
{BSINC_SCALE_COUNT
- 1};
183 if(increment
> FRACTIONONE
)
185 sf
= FRACTIONONE
/ static_cast<float>(increment
);
186 sf
= maxf(0.0f
, (BSINC_SCALE_COUNT
-1) * (sf
-table
->scaleBase
) * table
->scaleRange
);
188 /* The interpolation factor is fit to this diagonally-symmetric curve
189 * to reduce the transition ripple caused by interpolating different
190 * scales of the sinc function.
192 sf
= 1.0f
- std::cos(std::asin(sf
- static_cast<float>(si
)));
196 state
->m
= table
->m
[si
];
197 state
->l
= (state
->m
/2) - 1;
198 state
->filter
= table
->Tab
+ table
->filterOffset
[si
];
201 inline ResamplerFunc
SelectResampler(Resampler resampler
, ALuint increment
)
205 case Resampler::Point
:
206 return Resample_
<PointTag
,CTag
>;
207 case Resampler::Linear
:
209 if((CPUCapFlags
&CPU_CAP_NEON
))
210 return Resample_
<LerpTag
,NEONTag
>;
213 if((CPUCapFlags
&CPU_CAP_SSE4_1
))
214 return Resample_
<LerpTag
,SSE4Tag
>;
217 if((CPUCapFlags
&CPU_CAP_SSE2
))
218 return Resample_
<LerpTag
,SSE2Tag
>;
220 return Resample_
<LerpTag
,CTag
>;
221 case Resampler::Cubic
:
222 return Resample_
<CubicTag
,CTag
>;
223 case Resampler::BSinc12
:
224 case Resampler::BSinc24
:
225 if(increment
<= FRACTIONONE
)
228 case Resampler::FastBSinc12
:
229 case Resampler::FastBSinc24
:
231 if((CPUCapFlags
&CPU_CAP_NEON
))
232 return Resample_
<FastBSincTag
,NEONTag
>;
235 if((CPUCapFlags
&CPU_CAP_SSE
))
236 return Resample_
<FastBSincTag
,SSETag
>;
238 return Resample_
<FastBSincTag
,CTag
>;
241 if((CPUCapFlags
&CPU_CAP_NEON
))
242 return Resample_
<BSincTag
,NEONTag
>;
245 if((CPUCapFlags
&CPU_CAP_SSE
))
246 return Resample_
<BSincTag
,SSETag
>;
248 return Resample_
<BSincTag
,CTag
>;
251 return Resample_
<PointTag
,CTag
>;
258 MixSamples
= SelectMixer();
259 MixRowSamples
= SelectRowMixer();
260 MixDirectHrtf
= SelectHrtfMixer();
264 ResamplerFunc
PrepareResampler(Resampler resampler
, ALuint increment
, InterpState
*state
)
268 case Resampler::Point
:
269 case Resampler::Linear
:
270 case Resampler::Cubic
:
272 case Resampler::FastBSinc12
:
273 case Resampler::BSinc12
:
274 BsincPrepare(increment
, &state
->bsinc
, &bsinc12
);
276 case Resampler::FastBSinc24
:
277 case Resampler::BSinc24
:
278 BsincPrepare(increment
, &state
->bsinc
, &bsinc24
);
281 return SelectResampler(resampler
, increment
);
285 void ALCdevice::ProcessHrtf(const size_t SamplesToDo
)
287 /* HRTF is stereo output only. */
288 const ALuint lidx
{RealOut
.ChannelIndex
[FrontLeft
]};
289 const ALuint ridx
{RealOut
.ChannelIndex
[FrontRight
]};
291 MixDirectHrtf(RealOut
.Buffer
[lidx
], RealOut
.Buffer
[ridx
], Dry
.Buffer
, HrtfAccumData
,
292 mHrtfState
.get(), SamplesToDo
);
295 void ALCdevice::ProcessAmbiDec(const size_t SamplesToDo
)
297 AmbiDecoder
->process(RealOut
.Buffer
, Dry
.Buffer
.data(), SamplesToDo
);
300 void ALCdevice::ProcessUhj(const size_t SamplesToDo
)
302 /* UHJ is stereo output only. */
303 const ALuint lidx
{RealOut
.ChannelIndex
[FrontLeft
]};
304 const ALuint ridx
{RealOut
.ChannelIndex
[FrontRight
]};
306 /* Encode to stereo-compatible 2-channel UHJ output. */
307 Uhj_Encoder
->encode(RealOut
.Buffer
[lidx
], RealOut
.Buffer
[ridx
], Dry
.Buffer
.data(),
311 void ALCdevice::ProcessBs2b(const size_t SamplesToDo
)
313 /* First, decode the ambisonic mix to the "real" output. */
314 AmbiDecoder
->process(RealOut
.Buffer
, Dry
.Buffer
.data(), SamplesToDo
);
316 /* BS2B is stereo output only. */
317 const ALuint lidx
{RealOut
.ChannelIndex
[FrontLeft
]};
318 const ALuint ridx
{RealOut
.ChannelIndex
[FrontRight
]};
320 /* Now apply the BS2B binaural/crossfeed filter. */
321 bs2b_cross_feed(Bs2b
.get(), RealOut
.Buffer
[lidx
].data(), RealOut
.Buffer
[ridx
].data(),
328 /* This RNG method was created based on the math found in opusdec. It's quick,
329 * and starting with a seed value of 22222, is suitable for generating
332 inline ALuint
dither_rng(ALuint
*seed
) noexcept
334 *seed
= (*seed
* 96314165) + 907633515;
339 inline alu::Vector
aluCrossproduct(const alu::Vector
&in1
, const alu::Vector
&in2
)
342 in1
[1]*in2
[2] - in1
[2]*in2
[1],
343 in1
[2]*in2
[0] - in1
[0]*in2
[2],
344 in1
[0]*in2
[1] - in1
[1]*in2
[0],
349 inline ALfloat
aluDotproduct(const alu::Vector
&vec1
, const alu::Vector
&vec2
)
351 return vec1
[0]*vec2
[0] + vec1
[1]*vec2
[1] + vec1
[2]*vec2
[2];
355 alu::Vector
operator*(const alu::Matrix
&mtx
, const alu::Vector
&vec
) noexcept
358 vec
[0]*mtx
[0][0] + vec
[1]*mtx
[1][0] + vec
[2]*mtx
[2][0] + vec
[3]*mtx
[3][0],
359 vec
[0]*mtx
[0][1] + vec
[1]*mtx
[1][1] + vec
[2]*mtx
[2][1] + vec
[3]*mtx
[3][1],
360 vec
[0]*mtx
[0][2] + vec
[1]*mtx
[1][2] + vec
[2]*mtx
[2][2] + vec
[3]*mtx
[3][2],
361 vec
[0]*mtx
[0][3] + vec
[1]*mtx
[1][3] + vec
[2]*mtx
[2][3] + vec
[3]*mtx
[3][3]
366 bool CalcContextParams(ALCcontext
*Context
)
368 ALcontextProps
*props
{Context
->mUpdate
.exchange(nullptr, std::memory_order_acq_rel
)};
369 if(!props
) return false;
371 ALlistener
&Listener
= Context
->mListener
;
372 Listener
.Params
.DopplerFactor
= props
->DopplerFactor
;
373 Listener
.Params
.SpeedOfSound
= props
->SpeedOfSound
* props
->DopplerVelocity
;
375 Listener
.Params
.SourceDistanceModel
= props
->SourceDistanceModel
;
376 Listener
.Params
.mDistanceModel
= props
->mDistanceModel
;
378 AtomicReplaceHead(Context
->mFreeContextProps
, props
);
382 bool CalcListenerParams(ALCcontext
*Context
)
384 ALlistener
&Listener
= Context
->mListener
;
386 ALlistenerProps
*props
{Listener
.Params
.Update
.exchange(nullptr, std::memory_order_acq_rel
)};
387 if(!props
) return false;
390 alu::Vector N
{props
->OrientAt
[0], props
->OrientAt
[1], props
->OrientAt
[2], 0.0f
};
392 alu::Vector V
{props
->OrientUp
[0], props
->OrientUp
[1], props
->OrientUp
[2], 0.0f
};
394 /* Build and normalize right-vector */
395 alu::Vector U
{aluCrossproduct(N
, V
)};
398 Listener
.Params
.Matrix
= alu::Matrix
{
399 U
[0], V
[0], -N
[0], 0.0f
,
400 U
[1], V
[1], -N
[1], 0.0f
,
401 U
[2], V
[2], -N
[2], 0.0f
,
402 0.0f
, 0.0f
, 0.0f
, 1.0f
405 const alu::Vector P
{Listener
.Params
.Matrix
*
406 alu::Vector
{props
->Position
[0], props
->Position
[1], props
->Position
[2], 1.0f
}};
407 Listener
.Params
.Matrix
.setRow(3, -P
[0], -P
[1], -P
[2], 1.0f
);
409 const alu::Vector vel
{props
->Velocity
[0], props
->Velocity
[1], props
->Velocity
[2], 0.0f
};
410 Listener
.Params
.Velocity
= Listener
.Params
.Matrix
* vel
;
412 Listener
.Params
.Gain
= props
->Gain
* Context
->mGainBoost
;
413 Listener
.Params
.MetersPerUnit
= props
->MetersPerUnit
;
415 AtomicReplaceHead(Context
->mFreeListenerProps
, props
);
419 bool CalcEffectSlotParams(ALeffectslot
*slot
, ALCcontext
*context
)
421 ALeffectslotProps
*props
{slot
->Params
.Update
.exchange(nullptr, std::memory_order_acq_rel
)};
422 if(!props
) return false;
424 slot
->Params
.Gain
= props
->Gain
;
425 slot
->Params
.AuxSendAuto
= props
->AuxSendAuto
;
426 slot
->Params
.Target
= props
->Target
;
427 slot
->Params
.EffectType
= props
->Type
;
428 slot
->Params
.mEffectProps
= props
->Props
;
429 if(IsReverbEffect(props
->Type
))
431 slot
->Params
.RoomRolloff
= props
->Props
.Reverb
.RoomRolloffFactor
;
432 slot
->Params
.DecayTime
= props
->Props
.Reverb
.DecayTime
;
433 slot
->Params
.DecayLFRatio
= props
->Props
.Reverb
.DecayLFRatio
;
434 slot
->Params
.DecayHFRatio
= props
->Props
.Reverb
.DecayHFRatio
;
435 slot
->Params
.DecayHFLimit
= props
->Props
.Reverb
.DecayHFLimit
;
436 slot
->Params
.AirAbsorptionGainHF
= props
->Props
.Reverb
.AirAbsorptionGainHF
;
440 slot
->Params
.RoomRolloff
= 0.0f
;
441 slot
->Params
.DecayTime
= 0.0f
;
442 slot
->Params
.DecayLFRatio
= 0.0f
;
443 slot
->Params
.DecayHFRatio
= 0.0f
;
444 slot
->Params
.DecayHFLimit
= AL_FALSE
;
445 slot
->Params
.AirAbsorptionGainHF
= 1.0f
;
448 EffectState
*state
{props
->State
};
449 props
->State
= nullptr;
450 EffectState
*oldstate
{slot
->Params
.mEffectState
};
451 slot
->Params
.mEffectState
= state
;
453 /* Only release the old state if it won't get deleted, since we can't be
454 * deleting/freeing anything in the mixer.
456 if(!oldstate
->releaseIfNoDelete())
458 /* Otherwise, if it would be deleted send it off with a release event. */
459 RingBuffer
*ring
{context
->mAsyncEvents
.get()};
460 auto evt_vec
= ring
->getWriteVector();
461 if LIKELY(evt_vec
.first
.len
> 0)
463 AsyncEvent
*evt
{new (evt_vec
.first
.buf
) AsyncEvent
{EventType_ReleaseEffectState
}};
464 evt
->u
.mEffectState
= oldstate
;
465 ring
->writeAdvance(1);
466 context
->mEventSem
.post();
470 /* If writing the event failed, the queue was probably full. Store
471 * the old state in the property object where it can eventually be
472 * cleaned up sometime later (not ideal, but better than blocking
475 props
->State
= oldstate
;
479 AtomicReplaceHead(context
->mFreeEffectslotProps
, props
);
482 if(ALeffectslot
*target
{slot
->Params
.Target
})
483 output
= EffectTarget
{&target
->Wet
, nullptr};
486 ALCdevice
*device
{context
->mDevice
.get()};
487 output
= EffectTarget
{&device
->Dry
, &device
->RealOut
};
489 state
->update(context
, slot
, &slot
->Params
.mEffectProps
, output
);
494 /* Scales the given azimuth toward the side (+/- pi/2 radians) for positions in
497 inline float ScaleAzimuthFront(float azimuth
, float scale
)
499 const ALfloat abs_azi
{std::fabs(azimuth
)};
500 if(!(abs_azi
>= al::MathDefs
<float>::Pi()*0.5f
))
501 return std::copysign(minf(abs_azi
*scale
, al::MathDefs
<float>::Pi()*0.5f
), azimuth
);
505 void CalcPanningAndFilters(ALvoice
*voice
, const ALfloat xpos
, const ALfloat ypos
,
506 const ALfloat zpos
, const ALfloat Distance
, const ALfloat Spread
, const ALfloat DryGain
,
507 const ALfloat DryGainHF
, const ALfloat DryGainLF
, const ALfloat (&WetGain
)[MAX_SENDS
],
508 const ALfloat (&WetGainLF
)[MAX_SENDS
], const ALfloat (&WetGainHF
)[MAX_SENDS
],
509 ALeffectslot
*(&SendSlots
)[MAX_SENDS
], const ALvoicePropsBase
*props
,
510 const ALlistener
&Listener
, const ALCdevice
*Device
)
512 static constexpr ChanMap MonoMap
[1]{
513 { FrontCenter
, 0.0f
, 0.0f
}
515 { BackLeft
, Deg2Rad(-150.0f
), Deg2Rad(0.0f
) },
516 { BackRight
, Deg2Rad( 150.0f
), Deg2Rad(0.0f
) }
518 { FrontLeft
, Deg2Rad( -45.0f
), Deg2Rad(0.0f
) },
519 { FrontRight
, Deg2Rad( 45.0f
), Deg2Rad(0.0f
) },
520 { BackLeft
, Deg2Rad(-135.0f
), Deg2Rad(0.0f
) },
521 { BackRight
, Deg2Rad( 135.0f
), Deg2Rad(0.0f
) }
523 { FrontLeft
, Deg2Rad( -30.0f
), Deg2Rad(0.0f
) },
524 { FrontRight
, Deg2Rad( 30.0f
), Deg2Rad(0.0f
) },
525 { FrontCenter
, Deg2Rad( 0.0f
), Deg2Rad(0.0f
) },
527 { SideLeft
, Deg2Rad(-110.0f
), Deg2Rad(0.0f
) },
528 { SideRight
, Deg2Rad( 110.0f
), Deg2Rad(0.0f
) }
530 { FrontLeft
, Deg2Rad(-30.0f
), Deg2Rad(0.0f
) },
531 { FrontRight
, Deg2Rad( 30.0f
), Deg2Rad(0.0f
) },
532 { FrontCenter
, Deg2Rad( 0.0f
), Deg2Rad(0.0f
) },
534 { BackCenter
, Deg2Rad(180.0f
), Deg2Rad(0.0f
) },
535 { SideLeft
, Deg2Rad(-90.0f
), Deg2Rad(0.0f
) },
536 { SideRight
, Deg2Rad( 90.0f
), Deg2Rad(0.0f
) }
538 { FrontLeft
, Deg2Rad( -30.0f
), Deg2Rad(0.0f
) },
539 { FrontRight
, Deg2Rad( 30.0f
), Deg2Rad(0.0f
) },
540 { FrontCenter
, Deg2Rad( 0.0f
), Deg2Rad(0.0f
) },
542 { BackLeft
, Deg2Rad(-150.0f
), Deg2Rad(0.0f
) },
543 { BackRight
, Deg2Rad( 150.0f
), Deg2Rad(0.0f
) },
544 { SideLeft
, Deg2Rad( -90.0f
), Deg2Rad(0.0f
) },
545 { SideRight
, Deg2Rad( 90.0f
), Deg2Rad(0.0f
) }
548 ChanMap StereoMap
[2]{
549 { FrontLeft
, Deg2Rad(-30.0f
), Deg2Rad(0.0f
) },
550 { FrontRight
, Deg2Rad( 30.0f
), Deg2Rad(0.0f
) }
553 const auto Frequency
= static_cast<ALfloat
>(Device
->Frequency
);
554 const ALuint NumSends
{Device
->NumAuxSends
};
556 bool DirectChannels
{props
->DirectChannels
!= AL_FALSE
};
557 const ChanMap
*chans
{nullptr};
558 ALuint num_channels
{0};
559 bool isbformat
{false};
560 ALfloat downmix_gain
{1.0f
};
561 switch(voice
->mFmtChannels
)
566 /* Mono buffers are never played direct. */
567 DirectChannels
= false;
571 /* Convert counter-clockwise to clockwise. */
572 StereoMap
[0].angle
= -props
->StereoPan
[0];
573 StereoMap
[1].angle
= -props
->StereoPan
[1];
577 downmix_gain
= 1.0f
/ 2.0f
;
583 downmix_gain
= 1.0f
/ 2.0f
;
589 downmix_gain
= 1.0f
/ 4.0f
;
595 /* NOTE: Excludes LFE. */
596 downmix_gain
= 1.0f
/ 5.0f
;
602 /* NOTE: Excludes LFE. */
603 downmix_gain
= 1.0f
/ 6.0f
;
609 /* NOTE: Excludes LFE. */
610 downmix_gain
= 1.0f
/ 7.0f
;
616 DirectChannels
= false;
622 DirectChannels
= false;
625 ASSUME(num_channels
> 0);
627 std::for_each(voice
->mChans
.begin(), voice
->mChans
.begin()+num_channels
,
628 [NumSends
](ALvoice::ChannelData
&chandata
) -> void
630 chandata
.mDryParams
.Hrtf
.Target
= HrtfFilter
{};
631 chandata
.mDryParams
.Gains
.Target
.fill(0.0f
);
632 std::for_each(chandata
.mWetParams
.begin(), chandata
.mWetParams
.begin()+NumSends
,
633 [](SendParams
¶ms
) -> void { params
.Gains
.Target
.fill(0.0f
); });
636 voice
->mFlags
&= ~(VOICE_HAS_HRTF
| VOICE_HAS_NFC
);
639 /* Special handling for B-Format sources. */
641 if(Distance
> std::numeric_limits
<float>::epsilon())
643 /* Panning a B-Format sound toward some direction is easy. Just pan
644 * the first (W) channel as a normal mono sound and silence the
648 if(Device
->AvgSpeakerDist
> 0.0f
)
650 /* Clamp the distance for really close sources, to prevent
653 const ALfloat mdist
{maxf(Distance
, Device
->AvgSpeakerDist
/4.0f
)};
654 const ALfloat w0
{SPEEDOFSOUNDMETRESPERSEC
/ (mdist
* Frequency
)};
656 /* Only need to adjust the first channel of a B-Format source. */
657 voice
->mChans
[0].mDryParams
.NFCtrlFilter
.adjust(w0
);
659 voice
->mFlags
|= VOICE_HAS_NFC
;
662 ALfloat coeffs
[MAX_AMBI_CHANNELS
];
663 if(Device
->mRenderMode
!= StereoPair
)
664 CalcDirectionCoeffs({xpos
, ypos
, zpos
}, Spread
, coeffs
);
667 /* Clamp Y, in case rounding errors caused it to end up outside
670 const ALfloat ev
{std::asin(clampf(ypos
, -1.0f
, 1.0f
))};
671 /* Negate Z for right-handed coords with -Z in front. */
672 const ALfloat az
{std::atan2(xpos
, -zpos
)};
674 /* A scalar of 1.5 for plain stereo results in +/-60 degrees
675 * being moved to +/-90 degrees for direct right and left
678 CalcAngleCoeffs(ScaleAzimuthFront(az
, 1.5f
), ev
, Spread
, coeffs
);
681 /* NOTE: W needs to be scaled due to FuMa normalization. */
682 const ALfloat
&scale0
= AmbiScale::FromFuMa
[0];
683 ComputePanGains(&Device
->Dry
, coeffs
, DryGain
*scale0
,
684 voice
->mChans
[0].mDryParams
.Gains
.Target
);
685 for(ALuint i
{0};i
< NumSends
;i
++)
687 if(const ALeffectslot
*Slot
{SendSlots
[i
]})
688 ComputePanGains(&Slot
->Wet
, coeffs
, WetGain
[i
]*scale0
,
689 voice
->mChans
[0].mWetParams
[i
].Gains
.Target
);
694 if(Device
->AvgSpeakerDist
> 0.0f
)
696 /* NOTE: The NFCtrlFilters were created with a w0 of 0, which
697 * is what we want for FOA input. The first channel may have
698 * been previously re-adjusted if panned, so reset it.
700 voice
->mChans
[0].mDryParams
.NFCtrlFilter
.adjust(0.0f
);
702 voice
->mFlags
|= VOICE_HAS_NFC
;
705 /* Local B-Format sources have their XYZ channels rotated according
706 * to the orientation.
709 alu::Vector N
{props
->OrientAt
[0], props
->OrientAt
[1], props
->OrientAt
[2], 0.0f
};
711 alu::Vector V
{props
->OrientUp
[0], props
->OrientUp
[1], props
->OrientUp
[2], 0.0f
};
713 if(!props
->HeadRelative
)
715 N
= Listener
.Params
.Matrix
* N
;
716 V
= Listener
.Params
.Matrix
* V
;
718 /* Build and normalize right-vector */
719 alu::Vector U
{aluCrossproduct(N
, V
)};
722 /* Build a rotate + conversion matrix (FuMa -> ACN+N3D). NOTE: This
723 * matrix is transposed, for the inputs to align on the rows and
724 * outputs on the columns.
726 const ALfloat
&wscale
= AmbiScale::FromFuMa
[0];
727 const ALfloat
&yscale
= AmbiScale::FromFuMa
[1];
728 const ALfloat
&zscale
= AmbiScale::FromFuMa
[2];
729 const ALfloat
&xscale
= AmbiScale::FromFuMa
[3];
730 const ALfloat matrix
[4][MAX_AMBI_CHANNELS
]{
731 // ACN0 ACN1 ACN2 ACN3
732 { wscale
, 0.0f
, 0.0f
, 0.0f
}, // FuMa W
733 { 0.0f
, -N
[0]*xscale
, N
[1]*xscale
, -N
[2]*xscale
}, // FuMa X
734 { 0.0f
, U
[0]*yscale
, -U
[1]*yscale
, U
[2]*yscale
}, // FuMa Y
735 { 0.0f
, -V
[0]*zscale
, V
[1]*zscale
, -V
[2]*zscale
} // FuMa Z
738 for(ALuint c
{0};c
< num_channels
;c
++)
740 ComputePanGains(&Device
->Dry
, matrix
[c
], DryGain
,
741 voice
->mChans
[c
].mDryParams
.Gains
.Target
);
743 for(ALuint i
{0};i
< NumSends
;i
++)
745 if(const ALeffectslot
*Slot
{SendSlots
[i
]})
746 ComputePanGains(&Slot
->Wet
, matrix
[c
], WetGain
[i
],
747 voice
->mChans
[c
].mWetParams
[i
].Gains
.Target
);
752 else if(DirectChannels
)
754 /* Direct source channels always play local. Skip the virtual channels
755 * and write inputs to the matching real outputs.
757 voice
->mDirect
.Buffer
= Device
->RealOut
.Buffer
;
759 for(ALuint c
{0};c
< num_channels
;c
++)
761 const ALuint idx
{GetChannelIdxByName(Device
->RealOut
, chans
[c
].channel
)};
762 if(idx
!= INVALID_CHANNEL_INDEX
)
763 voice
->mChans
[c
].mDryParams
.Gains
.Target
[idx
] = DryGain
;
766 /* Auxiliary sends still use normal channel panning since they mix to
767 * B-Format, which can't channel-match.
769 for(ALuint c
{0};c
< num_channels
;c
++)
771 ALfloat coeffs
[MAX_AMBI_CHANNELS
];
772 CalcAngleCoeffs(chans
[c
].angle
, chans
[c
].elevation
, 0.0f
, coeffs
);
774 for(ALuint i
{0};i
< NumSends
;i
++)
776 if(const ALeffectslot
*Slot
{SendSlots
[i
]})
777 ComputePanGains(&Slot
->Wet
, coeffs
, WetGain
[i
],
778 voice
->mChans
[c
].mWetParams
[i
].Gains
.Target
);
782 else if(Device
->mRenderMode
== HrtfRender
)
784 /* Full HRTF rendering. Skip the virtual channels and render to the
787 voice
->mDirect
.Buffer
= Device
->RealOut
.Buffer
;
789 if(Distance
> std::numeric_limits
<float>::epsilon())
791 const ALfloat ev
{std::asin(clampf(ypos
, -1.0f
, 1.0f
))};
792 const ALfloat az
{std::atan2(xpos
, -zpos
)};
794 /* Get the HRIR coefficients and delays just once, for the given
797 GetHrtfCoeffs(Device
->mHrtf
, ev
, az
, Distance
, Spread
,
798 voice
->mChans
[0].mDryParams
.Hrtf
.Target
.Coeffs
,
799 voice
->mChans
[0].mDryParams
.Hrtf
.Target
.Delay
);
800 voice
->mChans
[0].mDryParams
.Hrtf
.Target
.Gain
= DryGain
* downmix_gain
;
802 /* Remaining channels use the same results as the first. */
803 for(ALuint c
{1};c
< num_channels
;c
++)
806 if(chans
[c
].channel
== LFE
) continue;
807 voice
->mChans
[c
].mDryParams
.Hrtf
.Target
= voice
->mChans
[0].mDryParams
.Hrtf
.Target
;
810 /* Calculate the directional coefficients once, which apply to all
811 * input channels of the source sends.
813 ALfloat coeffs
[MAX_AMBI_CHANNELS
];
814 CalcDirectionCoeffs({xpos
, ypos
, zpos
}, Spread
, coeffs
);
816 for(ALuint c
{0};c
< num_channels
;c
++)
819 if(chans
[c
].channel
== LFE
)
821 for(ALuint i
{0};i
< NumSends
;i
++)
823 if(const ALeffectslot
*Slot
{SendSlots
[i
]})
824 ComputePanGains(&Slot
->Wet
, coeffs
, WetGain
[i
] * downmix_gain
,
825 voice
->mChans
[c
].mWetParams
[i
].Gains
.Target
);
831 /* Local sources on HRTF play with each channel panned to its
832 * relative location around the listener, providing "virtual
833 * speaker" responses.
835 for(ALuint c
{0};c
< num_channels
;c
++)
838 if(chans
[c
].channel
== LFE
)
841 /* Get the HRIR coefficients and delays for this channel
844 GetHrtfCoeffs(Device
->mHrtf
, chans
[c
].elevation
, chans
[c
].angle
,
845 std::numeric_limits
<float>::infinity(), Spread
,
846 voice
->mChans
[c
].mDryParams
.Hrtf
.Target
.Coeffs
,
847 voice
->mChans
[c
].mDryParams
.Hrtf
.Target
.Delay
);
848 voice
->mChans
[c
].mDryParams
.Hrtf
.Target
.Gain
= DryGain
;
850 /* Normal panning for auxiliary sends. */
851 ALfloat coeffs
[MAX_AMBI_CHANNELS
];
852 CalcAngleCoeffs(chans
[c
].angle
, chans
[c
].elevation
, Spread
, coeffs
);
854 for(ALuint i
{0};i
< NumSends
;i
++)
856 if(const ALeffectslot
*Slot
{SendSlots
[i
]})
857 ComputePanGains(&Slot
->Wet
, coeffs
, WetGain
[i
],
858 voice
->mChans
[c
].mWetParams
[i
].Gains
.Target
);
863 voice
->mFlags
|= VOICE_HAS_HRTF
;
867 /* Non-HRTF rendering. Use normal panning to the output. */
869 if(Distance
> std::numeric_limits
<float>::epsilon())
871 /* Calculate NFC filter coefficient if needed. */
872 if(Device
->AvgSpeakerDist
> 0.0f
)
874 /* Clamp the distance for really close sources, to prevent
877 const ALfloat mdist
{maxf(Distance
, Device
->AvgSpeakerDist
/4.0f
)};
878 const ALfloat w0
{SPEEDOFSOUNDMETRESPERSEC
/ (mdist
* Frequency
)};
880 /* Adjust NFC filters. */
881 for(ALuint c
{0};c
< num_channels
;c
++)
882 voice
->mChans
[c
].mDryParams
.NFCtrlFilter
.adjust(w0
);
884 voice
->mFlags
|= VOICE_HAS_NFC
;
887 /* Calculate the directional coefficients once, which apply to all
890 ALfloat coeffs
[MAX_AMBI_CHANNELS
];
891 if(Device
->mRenderMode
!= StereoPair
)
892 CalcDirectionCoeffs({xpos
, ypos
, zpos
}, Spread
, coeffs
);
895 const ALfloat ev
{std::asin(clampf(ypos
, -1.0f
, 1.0f
))};
896 const ALfloat az
{std::atan2(xpos
, -zpos
)};
897 CalcAngleCoeffs(ScaleAzimuthFront(az
, 1.5f
), ev
, Spread
, coeffs
);
900 for(ALuint c
{0};c
< num_channels
;c
++)
902 /* Special-case LFE */
903 if(chans
[c
].channel
== LFE
)
905 if(Device
->Dry
.Buffer
.data() == Device
->RealOut
.Buffer
.data())
907 const ALuint idx
{GetChannelIdxByName(Device
->RealOut
, chans
[c
].channel
)};
908 if(idx
!= INVALID_CHANNEL_INDEX
)
909 voice
->mChans
[c
].mDryParams
.Gains
.Target
[idx
] = DryGain
;
914 ComputePanGains(&Device
->Dry
, coeffs
, DryGain
* downmix_gain
,
915 voice
->mChans
[c
].mDryParams
.Gains
.Target
);
916 for(ALuint i
{0};i
< NumSends
;i
++)
918 if(const ALeffectslot
*Slot
{SendSlots
[i
]})
919 ComputePanGains(&Slot
->Wet
, coeffs
, WetGain
[i
] * downmix_gain
,
920 voice
->mChans
[c
].mWetParams
[i
].Gains
.Target
);
926 if(Device
->AvgSpeakerDist
> 0.0f
)
928 /* If the source distance is 0, set w0 to w1 to act as a pass-
929 * through. We still want to pass the signal through the
930 * filters so they keep an appropriate history, in case the
931 * source moves away from the listener.
933 const ALfloat w0
{SPEEDOFSOUNDMETRESPERSEC
/ (Device
->AvgSpeakerDist
* Frequency
)};
935 for(ALuint c
{0};c
< num_channels
;c
++)
936 voice
->mChans
[c
].mDryParams
.NFCtrlFilter
.adjust(w0
);
938 voice
->mFlags
|= VOICE_HAS_NFC
;
941 for(ALuint c
{0};c
< num_channels
;c
++)
943 /* Special-case LFE */
944 if(chans
[c
].channel
== LFE
)
946 if(Device
->Dry
.Buffer
.data() == Device
->RealOut
.Buffer
.data())
948 const ALuint idx
{GetChannelIdxByName(Device
->RealOut
, chans
[c
].channel
)};
949 if(idx
!= INVALID_CHANNEL_INDEX
)
950 voice
->mChans
[c
].mDryParams
.Gains
.Target
[idx
] = DryGain
;
955 ALfloat coeffs
[MAX_AMBI_CHANNELS
];
957 (Device
->mRenderMode
==StereoPair
) ? ScaleAzimuthFront(chans
[c
].angle
, 3.0f
)
959 chans
[c
].elevation
, Spread
, coeffs
962 ComputePanGains(&Device
->Dry
, coeffs
, DryGain
,
963 voice
->mChans
[c
].mDryParams
.Gains
.Target
);
964 for(ALuint i
{0};i
< NumSends
;i
++)
966 if(const ALeffectslot
*Slot
{SendSlots
[i
]})
967 ComputePanGains(&Slot
->Wet
, coeffs
, WetGain
[i
],
968 voice
->mChans
[c
].mWetParams
[i
].Gains
.Target
);
975 const ALfloat hfScale
{props
->Direct
.HFReference
/ Frequency
};
976 const ALfloat lfScale
{props
->Direct
.LFReference
/ Frequency
};
977 const ALfloat gainHF
{maxf(DryGainHF
, 0.001f
)}; /* Limit -60dB */
978 const ALfloat gainLF
{maxf(DryGainLF
, 0.001f
)};
980 voice
->mDirect
.FilterType
= AF_None
;
981 if(gainHF
!= 1.0f
) voice
->mDirect
.FilterType
|= AF_LowPass
;
982 if(gainLF
!= 1.0f
) voice
->mDirect
.FilterType
|= AF_HighPass
;
983 auto &lowpass
= voice
->mChans
[0].mDryParams
.LowPass
;
984 auto &highpass
= voice
->mChans
[0].mDryParams
.HighPass
;
985 lowpass
.setParams(BiquadType::HighShelf
, gainHF
, hfScale
,
986 lowpass
.rcpQFromSlope(gainHF
, 1.0f
));
987 highpass
.setParams(BiquadType::LowShelf
, gainLF
, lfScale
,
988 highpass
.rcpQFromSlope(gainLF
, 1.0f
));
989 for(ALuint c
{1};c
< num_channels
;c
++)
991 voice
->mChans
[c
].mDryParams
.LowPass
.copyParamsFrom(lowpass
);
992 voice
->mChans
[c
].mDryParams
.HighPass
.copyParamsFrom(highpass
);
995 for(ALuint i
{0};i
< NumSends
;i
++)
997 const ALfloat hfScale
{props
->Send
[i
].HFReference
/ Frequency
};
998 const ALfloat lfScale
{props
->Send
[i
].LFReference
/ Frequency
};
999 const ALfloat gainHF
{maxf(WetGainHF
[i
], 0.001f
)};
1000 const ALfloat gainLF
{maxf(WetGainLF
[i
], 0.001f
)};
1002 voice
->mSend
[i
].FilterType
= AF_None
;
1003 if(gainHF
!= 1.0f
) voice
->mSend
[i
].FilterType
|= AF_LowPass
;
1004 if(gainLF
!= 1.0f
) voice
->mSend
[i
].FilterType
|= AF_HighPass
;
1006 auto &lowpass
= voice
->mChans
[0].mWetParams
[i
].LowPass
;
1007 auto &highpass
= voice
->mChans
[0].mWetParams
[i
].HighPass
;
1008 lowpass
.setParams(BiquadType::HighShelf
, gainHF
, hfScale
,
1009 lowpass
.rcpQFromSlope(gainHF
, 1.0f
));
1010 highpass
.setParams(BiquadType::LowShelf
, gainLF
, lfScale
,
1011 highpass
.rcpQFromSlope(gainLF
, 1.0f
));
1012 for(ALuint c
{1};c
< num_channels
;c
++)
1014 voice
->mChans
[c
].mWetParams
[i
].LowPass
.copyParamsFrom(lowpass
);
1015 voice
->mChans
[c
].mWetParams
[i
].HighPass
.copyParamsFrom(highpass
);
1020 void CalcNonAttnSourceParams(ALvoice
*voice
, const ALvoicePropsBase
*props
, const ALCcontext
*ALContext
)
1022 const ALCdevice
*Device
{ALContext
->mDevice
.get()};
1023 ALeffectslot
*SendSlots
[MAX_SENDS
];
1025 voice
->mDirect
.Buffer
= Device
->Dry
.Buffer
;
1026 for(ALuint i
{0};i
< Device
->NumAuxSends
;i
++)
1028 SendSlots
[i
] = props
->Send
[i
].Slot
;
1029 if(!SendSlots
[i
] && i
== 0)
1030 SendSlots
[i
] = ALContext
->mDefaultSlot
.get();
1031 if(!SendSlots
[i
] || SendSlots
[i
]->Params
.EffectType
== AL_EFFECT_NULL
)
1033 SendSlots
[i
] = nullptr;
1034 voice
->mSend
[i
].Buffer
= {};
1037 voice
->mSend
[i
].Buffer
= SendSlots
[i
]->Wet
.Buffer
;
1040 /* Calculate the stepping value */
1041 const auto Pitch
= static_cast<ALfloat
>(voice
->mFrequency
) /
1042 static_cast<ALfloat
>(Device
->Frequency
) * props
->Pitch
;
1043 if(Pitch
> float{MAX_PITCH
})
1044 voice
->mStep
= MAX_PITCH
<<FRACTIONBITS
;
1046 voice
->mStep
= maxu(fastf2u(Pitch
* FRACTIONONE
), 1);
1047 voice
->mResampler
= PrepareResampler(props
->mResampler
, voice
->mStep
, &voice
->mResampleState
);
1049 /* Calculate gains */
1050 const ALlistener
&Listener
= ALContext
->mListener
;
1051 ALfloat DryGain
{clampf(props
->Gain
, props
->MinGain
, props
->MaxGain
)};
1052 DryGain
*= props
->Direct
.Gain
* Listener
.Params
.Gain
;
1053 DryGain
= minf(DryGain
, GAIN_MIX_MAX
);
1054 ALfloat DryGainHF
{props
->Direct
.GainHF
};
1055 ALfloat DryGainLF
{props
->Direct
.GainLF
};
1056 ALfloat WetGain
[MAX_SENDS
], WetGainHF
[MAX_SENDS
], WetGainLF
[MAX_SENDS
];
1057 for(ALuint i
{0};i
< Device
->NumAuxSends
;i
++)
1059 WetGain
[i
] = clampf(props
->Gain
, props
->MinGain
, props
->MaxGain
);
1060 WetGain
[i
] *= props
->Send
[i
].Gain
* Listener
.Params
.Gain
;
1061 WetGain
[i
] = minf(WetGain
[i
], GAIN_MIX_MAX
);
1062 WetGainHF
[i
] = props
->Send
[i
].GainHF
;
1063 WetGainLF
[i
] = props
->Send
[i
].GainLF
;
1066 CalcPanningAndFilters(voice
, 0.0f
, 0.0f
, -1.0f
, 0.0f
, 0.0f
, DryGain
, DryGainHF
, DryGainLF
,
1067 WetGain
, WetGainLF
, WetGainHF
, SendSlots
, props
, Listener
, Device
);
1070 void CalcAttnSourceParams(ALvoice
*voice
, const ALvoicePropsBase
*props
, const ALCcontext
*ALContext
)
1072 const ALCdevice
*Device
{ALContext
->mDevice
.get()};
1073 const ALuint NumSends
{Device
->NumAuxSends
};
1074 const ALlistener
&Listener
= ALContext
->mListener
;
1076 /* Set mixing buffers and get send parameters. */
1077 voice
->mDirect
.Buffer
= Device
->Dry
.Buffer
;
1078 ALeffectslot
*SendSlots
[MAX_SENDS
];
1079 ALfloat RoomRolloff
[MAX_SENDS
];
1080 ALfloat DecayDistance
[MAX_SENDS
];
1081 ALfloat DecayLFDistance
[MAX_SENDS
];
1082 ALfloat DecayHFDistance
[MAX_SENDS
];
1083 for(ALuint i
{0};i
< NumSends
;i
++)
1085 SendSlots
[i
] = props
->Send
[i
].Slot
;
1086 if(!SendSlots
[i
] && i
== 0)
1087 SendSlots
[i
] = ALContext
->mDefaultSlot
.get();
1088 if(!SendSlots
[i
] || SendSlots
[i
]->Params
.EffectType
== AL_EFFECT_NULL
)
1090 SendSlots
[i
] = nullptr;
1091 RoomRolloff
[i
] = 0.0f
;
1092 DecayDistance
[i
] = 0.0f
;
1093 DecayLFDistance
[i
] = 0.0f
;
1094 DecayHFDistance
[i
] = 0.0f
;
1096 else if(SendSlots
[i
]->Params
.AuxSendAuto
)
1098 RoomRolloff
[i
] = SendSlots
[i
]->Params
.RoomRolloff
+ props
->RoomRolloffFactor
;
1099 /* Calculate the distances to where this effect's decay reaches
1102 DecayDistance
[i
] = SendSlots
[i
]->Params
.DecayTime
* SPEEDOFSOUNDMETRESPERSEC
;
1103 DecayLFDistance
[i
] = DecayDistance
[i
] * SendSlots
[i
]->Params
.DecayLFRatio
;
1104 DecayHFDistance
[i
] = DecayDistance
[i
] * SendSlots
[i
]->Params
.DecayHFRatio
;
1105 if(SendSlots
[i
]->Params
.DecayHFLimit
)
1107 ALfloat airAbsorption
{SendSlots
[i
]->Params
.AirAbsorptionGainHF
};
1108 if(airAbsorption
< 1.0f
)
1110 /* Calculate the distance to where this effect's air
1111 * absorption reaches -60dB, and limit the effect's HF
1112 * decay distance (so it doesn't take any longer to decay
1113 * than the air would allow).
1115 ALfloat absorb_dist
{std::log10(REVERB_DECAY_GAIN
) / std::log10(airAbsorption
)};
1116 DecayHFDistance
[i
] = minf(absorb_dist
, DecayHFDistance
[i
]);
1122 /* If the slot's auxiliary send auto is off, the data sent to the
1123 * effect slot is the same as the dry path, sans filter effects */
1124 RoomRolloff
[i
] = props
->RolloffFactor
;
1125 DecayDistance
[i
] = 0.0f
;
1126 DecayLFDistance
[i
] = 0.0f
;
1127 DecayHFDistance
[i
] = 0.0f
;
1131 voice
->mSend
[i
].Buffer
= {};
1133 voice
->mSend
[i
].Buffer
= SendSlots
[i
]->Wet
.Buffer
;
1136 /* Transform source to listener space (convert to head relative) */
1137 alu::Vector Position
{props
->Position
[0], props
->Position
[1], props
->Position
[2], 1.0f
};
1138 alu::Vector Velocity
{props
->Velocity
[0], props
->Velocity
[1], props
->Velocity
[2], 0.0f
};
1139 alu::Vector Direction
{props
->Direction
[0], props
->Direction
[1], props
->Direction
[2], 0.0f
};
1140 if(props
->HeadRelative
== AL_FALSE
)
1142 /* Transform source vectors */
1143 Position
= Listener
.Params
.Matrix
* Position
;
1144 Velocity
= Listener
.Params
.Matrix
* Velocity
;
1145 Direction
= Listener
.Params
.Matrix
* Direction
;
1149 /* Offset the source velocity to be relative of the listener velocity */
1150 Velocity
+= Listener
.Params
.Velocity
;
1153 const bool directional
{Direction
.normalize() > 0.0f
};
1154 alu::Vector ToSource
{Position
[0], Position
[1], Position
[2], 0.0f
};
1155 const ALfloat Distance
{ToSource
.normalize()};
1157 /* Initial source gain */
1158 ALfloat DryGain
{props
->Gain
};
1159 ALfloat DryGainHF
{1.0f
};
1160 ALfloat DryGainLF
{1.0f
};
1161 ALfloat WetGain
[MAX_SENDS
], WetGainHF
[MAX_SENDS
], WetGainLF
[MAX_SENDS
];
1162 for(ALuint i
{0};i
< NumSends
;i
++)
1164 WetGain
[i
] = props
->Gain
;
1165 WetGainHF
[i
] = 1.0f
;
1166 WetGainLF
[i
] = 1.0f
;
1169 /* Calculate distance attenuation */
1170 ALfloat ClampedDist
{Distance
};
1172 switch(Listener
.Params
.SourceDistanceModel
?
1173 props
->mDistanceModel
: Listener
.Params
.mDistanceModel
)
1175 case DistanceModel::InverseClamped
:
1176 ClampedDist
= clampf(ClampedDist
, props
->RefDistance
, props
->MaxDistance
);
1177 if(props
->MaxDistance
< props
->RefDistance
) break;
1179 case DistanceModel::Inverse
:
1180 if(!(props
->RefDistance
> 0.0f
))
1181 ClampedDist
= props
->RefDistance
;
1184 ALfloat dist
= lerp(props
->RefDistance
, ClampedDist
, props
->RolloffFactor
);
1185 if(dist
> 0.0f
) DryGain
*= props
->RefDistance
/ dist
;
1186 for(ALuint i
{0};i
< NumSends
;i
++)
1188 dist
= lerp(props
->RefDistance
, ClampedDist
, RoomRolloff
[i
]);
1189 if(dist
> 0.0f
) WetGain
[i
] *= props
->RefDistance
/ dist
;
1194 case DistanceModel::LinearClamped
:
1195 ClampedDist
= clampf(ClampedDist
, props
->RefDistance
, props
->MaxDistance
);
1196 if(props
->MaxDistance
< props
->RefDistance
) break;
1198 case DistanceModel::Linear
:
1199 if(!(props
->MaxDistance
!= props
->RefDistance
))
1200 ClampedDist
= props
->RefDistance
;
1203 ALfloat attn
= props
->RolloffFactor
* (ClampedDist
-props
->RefDistance
) /
1204 (props
->MaxDistance
-props
->RefDistance
);
1205 DryGain
*= maxf(1.0f
- attn
, 0.0f
);
1206 for(ALuint i
{0};i
< NumSends
;i
++)
1208 attn
= RoomRolloff
[i
] * (ClampedDist
-props
->RefDistance
) /
1209 (props
->MaxDistance
-props
->RefDistance
);
1210 WetGain
[i
] *= maxf(1.0f
- attn
, 0.0f
);
1215 case DistanceModel::ExponentClamped
:
1216 ClampedDist
= clampf(ClampedDist
, props
->RefDistance
, props
->MaxDistance
);
1217 if(props
->MaxDistance
< props
->RefDistance
) break;
1219 case DistanceModel::Exponent
:
1220 if(!(ClampedDist
> 0.0f
&& props
->RefDistance
> 0.0f
))
1221 ClampedDist
= props
->RefDistance
;
1224 DryGain
*= std::pow(ClampedDist
/props
->RefDistance
, -props
->RolloffFactor
);
1225 for(ALuint i
{0};i
< NumSends
;i
++)
1226 WetGain
[i
] *= std::pow(ClampedDist
/props
->RefDistance
, -RoomRolloff
[i
]);
1230 case DistanceModel::Disable
:
1231 ClampedDist
= props
->RefDistance
;
1235 /* Calculate directional soundcones */
1236 if(directional
&& props
->InnerAngle
< 360.0f
)
1238 const ALfloat Angle
{Rad2Deg(std::acos(-aluDotproduct(Direction
, ToSource
)) *
1241 ALfloat ConeVolume
, ConeHF
;
1242 if(!(Angle
> props
->InnerAngle
))
1247 else if(Angle
< props
->OuterAngle
)
1249 ALfloat scale
= ( Angle
-props
->InnerAngle
) /
1250 (props
->OuterAngle
-props
->InnerAngle
);
1251 ConeVolume
= lerp(1.0f
, props
->OuterGain
, scale
);
1252 ConeHF
= lerp(1.0f
, props
->OuterGainHF
, scale
);
1256 ConeVolume
= props
->OuterGain
;
1257 ConeHF
= props
->OuterGainHF
;
1260 DryGain
*= ConeVolume
;
1261 if(props
->DryGainHFAuto
)
1262 DryGainHF
*= ConeHF
;
1263 if(props
->WetGainAuto
)
1264 std::transform(std::begin(WetGain
), std::begin(WetGain
)+NumSends
, std::begin(WetGain
),
1265 [ConeVolume
](ALfloat gain
) noexcept
-> ALfloat
{ return gain
* ConeVolume
; }
1267 if(props
->WetGainHFAuto
)
1268 std::transform(std::begin(WetGainHF
), std::begin(WetGainHF
)+NumSends
,
1269 std::begin(WetGainHF
),
1270 [ConeHF
](ALfloat gain
) noexcept
-> ALfloat
{ return gain
* ConeHF
; }
1274 /* Apply gain and frequency filters */
1275 DryGain
= clampf(DryGain
, props
->MinGain
, props
->MaxGain
);
1276 DryGain
= minf(DryGain
*props
->Direct
.Gain
*Listener
.Params
.Gain
, GAIN_MIX_MAX
);
1277 DryGainHF
*= props
->Direct
.GainHF
;
1278 DryGainLF
*= props
->Direct
.GainLF
;
1279 for(ALuint i
{0};i
< NumSends
;i
++)
1281 WetGain
[i
] = clampf(WetGain
[i
], props
->MinGain
, props
->MaxGain
);
1282 WetGain
[i
] = minf(WetGain
[i
]*props
->Send
[i
].Gain
*Listener
.Params
.Gain
, GAIN_MIX_MAX
);
1283 WetGainHF
[i
] *= props
->Send
[i
].GainHF
;
1284 WetGainLF
[i
] *= props
->Send
[i
].GainLF
;
1287 /* Distance-based air absorption and initial send decay. */
1288 if(ClampedDist
> props
->RefDistance
&& props
->RolloffFactor
> 0.0f
)
1290 ALfloat meters_base
{(ClampedDist
-props
->RefDistance
) * props
->RolloffFactor
*
1291 Listener
.Params
.MetersPerUnit
};
1292 if(props
->AirAbsorptionFactor
> 0.0f
)
1294 ALfloat hfattn
{std::pow(AIRABSORBGAINHF
, meters_base
* props
->AirAbsorptionFactor
)};
1295 DryGainHF
*= hfattn
;
1296 std::transform(std::begin(WetGainHF
), std::begin(WetGainHF
)+NumSends
,
1297 std::begin(WetGainHF
),
1298 [hfattn
](ALfloat gain
) noexcept
-> ALfloat
{ return gain
* hfattn
; }
1302 if(props
->WetGainAuto
)
1304 /* Apply a decay-time transformation to the wet path, based on the
1305 * source distance in meters. The initial decay of the reverb
1306 * effect is calculated and applied to the wet path.
1308 for(ALuint i
{0};i
< NumSends
;i
++)
1310 if(!(DecayDistance
[i
] > 0.0f
))
1313 const ALfloat gain
{std::pow(REVERB_DECAY_GAIN
, meters_base
/DecayDistance
[i
])};
1315 /* Yes, the wet path's air absorption is applied with
1316 * WetGainAuto on, rather than WetGainHFAuto.
1320 ALfloat gainhf
{std::pow(REVERB_DECAY_GAIN
, meters_base
/DecayHFDistance
[i
])};
1321 WetGainHF
[i
] *= minf(gainhf
/ gain
, 1.0f
);
1322 ALfloat gainlf
{std::pow(REVERB_DECAY_GAIN
, meters_base
/DecayLFDistance
[i
])};
1323 WetGainLF
[i
] *= minf(gainlf
/ gain
, 1.0f
);
1330 /* Initial source pitch */
1331 ALfloat Pitch
{props
->Pitch
};
1333 /* Calculate velocity-based doppler effect */
1334 ALfloat DopplerFactor
{props
->DopplerFactor
* Listener
.Params
.DopplerFactor
};
1335 if(DopplerFactor
> 0.0f
)
1337 const alu::Vector
&lvelocity
= Listener
.Params
.Velocity
;
1338 ALfloat vss
{aluDotproduct(Velocity
, ToSource
) * -DopplerFactor
};
1339 ALfloat vls
{aluDotproduct(lvelocity
, ToSource
) * -DopplerFactor
};
1341 const ALfloat SpeedOfSound
{Listener
.Params
.SpeedOfSound
};
1342 if(!(vls
< SpeedOfSound
))
1344 /* Listener moving away from the source at the speed of sound.
1345 * Sound waves can't catch it.
1349 else if(!(vss
< SpeedOfSound
))
1351 /* Source moving toward the listener at the speed of sound. Sound
1352 * waves bunch up to extreme frequencies.
1354 Pitch
= std::numeric_limits
<float>::infinity();
1358 /* Source and listener movement is nominal. Calculate the proper
1361 Pitch
*= (SpeedOfSound
-vls
) / (SpeedOfSound
-vss
);
1365 /* Adjust pitch based on the buffer and output frequencies, and calculate
1366 * fixed-point stepping value.
1368 Pitch
*= static_cast<ALfloat
>(voice
->mFrequency
)/static_cast<ALfloat
>(Device
->Frequency
);
1369 if(Pitch
> float{MAX_PITCH
})
1370 voice
->mStep
= MAX_PITCH
<<FRACTIONBITS
;
1372 voice
->mStep
= maxu(fastf2u(Pitch
* FRACTIONONE
), 1);
1373 voice
->mResampler
= PrepareResampler(props
->mResampler
, voice
->mStep
, &voice
->mResampleState
);
1375 ALfloat spread
{0.0f
};
1376 if(props
->Radius
> Distance
)
1377 spread
= al::MathDefs
<float>::Tau() - Distance
/props
->Radius
*al::MathDefs
<float>::Pi();
1378 else if(Distance
> 0.0f
)
1379 spread
= std::asin(props
->Radius
/Distance
) * 2.0f
;
1381 CalcPanningAndFilters(voice
, ToSource
[0], ToSource
[1], ToSource
[2]*ZScale
,
1382 Distance
*Listener
.Params
.MetersPerUnit
, spread
, DryGain
, DryGainHF
, DryGainLF
, WetGain
,
1383 WetGainLF
, WetGainHF
, SendSlots
, props
, Listener
, Device
);
1386 void CalcSourceParams(ALvoice
*voice
, ALCcontext
*context
, bool force
)
1388 ALvoiceProps
*props
{voice
->mUpdate
.exchange(nullptr, std::memory_order_acq_rel
)};
1389 if(!props
&& !force
) return;
1393 voice
->mProps
= *props
;
1395 AtomicReplaceHead(context
->mFreeVoiceProps
, props
);
1398 if((voice
->mProps
.mSpatializeMode
== SpatializeAuto
&& voice
->mFmtChannels
== FmtMono
) ||
1399 voice
->mProps
.mSpatializeMode
== SpatializeOn
)
1400 CalcAttnSourceParams(voice
, &voice
->mProps
, context
);
1402 CalcNonAttnSourceParams(voice
, &voice
->mProps
, context
);
1406 void ProcessParamUpdates(ALCcontext
*ctx
, const ALeffectslotArray
&slots
,
1407 const al::span
<ALvoice
> voices
)
1409 IncrementRef(ctx
->mUpdateCount
);
1410 if LIKELY(!ctx
->mHoldUpdates
.load(std::memory_order_acquire
))
1412 bool force
{CalcContextParams(ctx
)};
1413 force
|= CalcListenerParams(ctx
);
1414 force
= std::accumulate(slots
.begin(), slots
.end(), force
,
1415 [ctx
](const bool f
, ALeffectslot
*slot
) -> bool
1416 { return CalcEffectSlotParams(slot
, ctx
) | f
; }
1419 auto calc_params
= [ctx
,force
](ALvoice
&voice
) -> void
1421 if(voice
.mSourceID
.load(std::memory_order_acquire
) != 0)
1422 CalcSourceParams(&voice
, ctx
, force
);
1424 std::for_each(voices
.begin(), voices
.end(), calc_params
);
1426 IncrementRef(ctx
->mUpdateCount
);
1429 void ProcessContext(ALCcontext
*ctx
, const ALuint SamplesToDo
)
1431 ASSUME(SamplesToDo
> 0);
1433 const ALeffectslotArray
&auxslots
= *ctx
->mActiveAuxSlots
.load(std::memory_order_acquire
);
1434 const al::span
<ALvoice
> voices
{ctx
->mVoices
.data(), ctx
->mVoices
.size()};
1436 /* Process pending propery updates for objects on the context. */
1437 ProcessParamUpdates(ctx
, auxslots
, voices
);
1439 /* Clear auxiliary effect slot mixing buffers. */
1440 std::for_each(auxslots
.begin(), auxslots
.end(),
1441 [SamplesToDo
](ALeffectslot
*slot
) -> void
1443 for(auto &buffer
: slot
->MixBuffer
)
1444 std::fill_n(buffer
.begin(), SamplesToDo
, 0.0f
);
1448 /* Process voices that have a playing source. */
1449 std::for_each(voices
.begin(), voices
.end(),
1450 [SamplesToDo
,ctx
](ALvoice
&voice
) -> void
1452 const ALvoice::State vstate
{voice
.mPlayState
.load(std::memory_order_acquire
)};
1453 if(vstate
!= ALvoice::Stopped
) voice
.mix(vstate
, ctx
, SamplesToDo
);
1457 /* Process effects. */
1458 if(auxslots
.empty()) return;
1459 auto slots
= auxslots
.data();
1460 auto slots_end
= slots
+ auxslots
.size();
1462 /* First sort the slots into scratch storage, so that effects come before
1463 * their effect target (or their targets' target).
1465 auto sorted_slots
= const_cast<ALeffectslot
**>(slots_end
);
1466 auto sorted_slots_end
= sorted_slots
;
1467 auto in_chain
= [](const ALeffectslot
*slot1
, const ALeffectslot
*slot2
) noexcept
-> bool
1469 while((slot1
=slot1
->Params
.Target
) != nullptr) {
1470 if(slot1
== slot2
) return true;
1475 *sorted_slots_end
= *slots
;
1477 while(++slots
!= slots_end
)
1479 /* If this effect slot targets an effect slot already in the list (i.e.
1480 * slots outputs to something in sorted_slots), directly or indirectly,
1481 * insert it prior to that element.
1483 auto checker
= sorted_slots
;
1485 if(in_chain(*slots
, *checker
)) break;
1486 } while(++checker
!= sorted_slots_end
);
1488 checker
= std::move_backward(checker
, sorted_slots_end
, sorted_slots_end
+1);
1489 *--checker
= *slots
;
1493 std::for_each(sorted_slots
, sorted_slots_end
,
1494 [SamplesToDo
](const ALeffectslot
*slot
) -> void
1496 EffectState
*state
{slot
->Params
.mEffectState
};
1497 state
->process(SamplesToDo
, slot
->Wet
.Buffer
, state
->mOutTarget
);
1503 void ApplyStablizer(FrontStablizer
*Stablizer
, const al::span
<FloatBufferLine
> Buffer
,
1504 const ALuint lidx
, const ALuint ridx
, const ALuint cidx
, const ALuint SamplesToDo
)
1506 ASSUME(SamplesToDo
> 0);
1508 /* Apply a delay to all channels, except the front-left and front-right, so
1509 * they maintain correct timing.
1511 const size_t NumChannels
{Buffer
.size()};
1512 for(size_t i
{0u};i
< NumChannels
;i
++)
1514 if(i
== lidx
|| i
== ridx
)
1517 auto &DelayBuf
= Stablizer
->DelayBuf
[i
];
1518 auto buffer_end
= Buffer
[i
].begin() + SamplesToDo
;
1519 if LIKELY(SamplesToDo
>= ALuint
{FrontStablizer::DelayLength
})
1521 auto delay_end
= std::rotate(Buffer
[i
].begin(),
1522 buffer_end
- FrontStablizer::DelayLength
, buffer_end
);
1523 std::swap_ranges(Buffer
[i
].begin(), delay_end
, std::begin(DelayBuf
));
1527 auto delay_start
= std::swap_ranges(Buffer
[i
].begin(), buffer_end
,
1528 std::begin(DelayBuf
));
1529 std::rotate(std::begin(DelayBuf
), delay_start
, std::end(DelayBuf
));
1533 ALfloat (&lsplit
)[2][BUFFERSIZE
] = Stablizer
->LSplit
;
1534 ALfloat (&rsplit
)[2][BUFFERSIZE
] = Stablizer
->RSplit
;
1535 auto &tmpbuf
= Stablizer
->TempBuf
;
1537 /* This applies the band-splitter, preserving phase at the cost of some
1538 * delay. The shorter the delay, the more error seeps into the result.
1540 auto apply_splitter
= [&tmpbuf
,SamplesToDo
](const FloatBufferLine
&InBuf
,
1541 ALfloat (&DelayBuf
)[FrontStablizer::DelayLength
], BandSplitter
&Filter
,
1542 ALfloat (&splitbuf
)[2][BUFFERSIZE
]) -> void
1544 /* Combine the delayed samples and the input samples into the temp
1545 * buffer, in reverse. Then copy the final samples back into the delay
1546 * buffer for next time. Note that the delay buffer's samples are
1547 * stored backwards here.
1549 auto tmpbuf_end
= std::begin(tmpbuf
) + SamplesToDo
;
1550 std::copy_n(std::begin(DelayBuf
), FrontStablizer::DelayLength
, tmpbuf_end
);
1551 std::reverse_copy(InBuf
.begin(), InBuf
.begin()+SamplesToDo
, std::begin(tmpbuf
));
1552 std::copy_n(std::begin(tmpbuf
), FrontStablizer::DelayLength
, std::begin(DelayBuf
));
1554 /* Apply an all-pass on the reversed signal, then reverse the samples
1555 * to get the forward signal with a reversed phase shift.
1557 Filter
.applyAllpass(tmpbuf
, SamplesToDo
+FrontStablizer::DelayLength
);
1558 std::reverse(std::begin(tmpbuf
), tmpbuf_end
+FrontStablizer::DelayLength
);
1560 /* Now apply the band-splitter, combining its phase shift with the
1561 * reversed phase shift, restoring the original phase on the split
1564 Filter
.process(splitbuf
[1], splitbuf
[0], tmpbuf
, SamplesToDo
);
1566 apply_splitter(Buffer
[lidx
], Stablizer
->DelayBuf
[lidx
], Stablizer
->LFilter
, lsplit
);
1567 apply_splitter(Buffer
[ridx
], Stablizer
->DelayBuf
[ridx
], Stablizer
->RFilter
, rsplit
);
1569 for(ALuint i
{0};i
< SamplesToDo
;i
++)
1571 ALfloat lfsum
{lsplit
[0][i
] + rsplit
[0][i
]};
1572 ALfloat hfsum
{lsplit
[1][i
] + rsplit
[1][i
]};
1573 ALfloat s
{lsplit
[0][i
] + lsplit
[1][i
] - rsplit
[0][i
] - rsplit
[1][i
]};
1575 /* This pans the separate low- and high-frequency sums between being on
1576 * the center channel and the left/right channels. The low-frequency
1577 * sum is 1/3rd toward center (2/3rds on left/right) and the high-
1578 * frequency sum is 1/4th toward center (3/4ths on left/right). These
1579 * values can be tweaked.
1581 ALfloat m
{lfsum
*std::cos(1.0f
/3.0f
* (al::MathDefs
<float>::Pi()*0.5f
)) +
1582 hfsum
*std::cos(1.0f
/4.0f
* (al::MathDefs
<float>::Pi()*0.5f
))};
1583 ALfloat c
{lfsum
*std::sin(1.0f
/3.0f
* (al::MathDefs
<float>::Pi()*0.5f
)) +
1584 hfsum
*std::sin(1.0f
/4.0f
* (al::MathDefs
<float>::Pi()*0.5f
))};
1586 /* The generated center channel signal adds to the existing signal,
1587 * while the modified left and right channels replace.
1589 Buffer
[lidx
][i
] = (m
+ s
) * 0.5f
;
1590 Buffer
[ridx
][i
] = (m
- s
) * 0.5f
;
1591 Buffer
[cidx
][i
] += c
* 0.5f
;
1595 void ApplyDistanceComp(const al::span
<FloatBufferLine
> Samples
, const ALuint SamplesToDo
,
1596 const DistanceComp::DistData
*distcomp
)
1598 ASSUME(SamplesToDo
> 0);
1600 for(auto &chanbuffer
: Samples
)
1602 const ALfloat gain
{distcomp
->Gain
};
1603 const ALuint base
{distcomp
->Length
};
1604 ALfloat
*distbuf
{al::assume_aligned
<16>(distcomp
->Buffer
)};
1610 ALfloat
*inout
{al::assume_aligned
<16>(chanbuffer
.data())};
1611 auto inout_end
= inout
+ SamplesToDo
;
1612 if LIKELY(SamplesToDo
>= base
)
1614 auto delay_end
= std::rotate(inout
, inout_end
- base
, inout_end
);
1615 std::swap_ranges(inout
, delay_end
, distbuf
);
1619 auto delay_start
= std::swap_ranges(inout
, inout_end
, distbuf
);
1620 std::rotate(distbuf
, delay_start
, distbuf
+ base
);
1622 std::transform(inout
, inout_end
, inout
, std::bind(std::multiplies
<float>{}, _1
, gain
));
1626 void ApplyDither(const al::span
<FloatBufferLine
> Samples
, ALuint
*dither_seed
,
1627 const ALfloat quant_scale
, const ALuint SamplesToDo
)
1629 /* Dithering. Generate whitenoise (uniform distribution of random values
1630 * between -1 and +1) and add it to the sample values, after scaling up to
1631 * the desired quantization depth amd before rounding.
1633 const ALfloat invscale
{1.0f
/ quant_scale
};
1634 ALuint seed
{*dither_seed
};
1635 auto dither_channel
= [&seed
,invscale
,quant_scale
,SamplesToDo
](FloatBufferLine
&input
) -> void
1637 ASSUME(SamplesToDo
> 0);
1638 auto dither_sample
= [&seed
,invscale
,quant_scale
](const ALfloat sample
) noexcept
-> ALfloat
1640 ALfloat val
{sample
* quant_scale
};
1641 ALuint rng0
{dither_rng(&seed
)};
1642 ALuint rng1
{dither_rng(&seed
)};
1643 val
+= static_cast<ALfloat
>(rng0
*(1.0/UINT_MAX
) - rng1
*(1.0/UINT_MAX
));
1644 return fast_roundf(val
) * invscale
;
1646 std::transform(input
.begin(), input
.begin()+SamplesToDo
, input
.begin(), dither_sample
);
1648 std::for_each(Samples
.begin(), Samples
.end(), dither_channel
);
1649 *dither_seed
= seed
;
1653 /* Base template left undefined. Should be marked =delete, but Clang 3.8.1
1654 * chokes on that given the inline specializations.
1656 template<typename T
>
1657 inline T
SampleConv(float) noexcept
;
1659 template<> inline float SampleConv(float val
) noexcept
1661 template<> inline int32_t SampleConv(float val
) noexcept
1663 /* Floats have a 23-bit mantissa, plus an implied 1 bit and a sign bit.
1664 * This means a normalized float has at most 25 bits of signed precision.
1665 * When scaling and clamping for a signed 32-bit integer, these following
1666 * values are the best a float can give.
1668 return fastf2i(clampf(val
*2147483648.0f
, -2147483648.0f
, 2147483520.0f
));
1670 template<> inline int16_t SampleConv(float val
) noexcept
1671 { return static_cast<int16_t>(fastf2i(clampf(val
*32768.0f
, -32768.0f
, 32767.0f
))); }
1672 template<> inline int8_t SampleConv(float val
) noexcept
1673 { return static_cast<int8_t>(fastf2i(clampf(val
*128.0f
, -128.0f
, 127.0f
))); }
1675 /* Define unsigned output variations. */
1676 template<> inline uint32_t SampleConv(float val
) noexcept
1677 { return static_cast<uint32_t>(SampleConv
<int32_t>(val
)) + 2147483648u; }
1678 template<> inline uint16_t SampleConv(float val
) noexcept
1679 { return static_cast<uint16_t>(SampleConv
<int16_t>(val
) + 32768); }
1680 template<> inline uint8_t SampleConv(float val
) noexcept
1681 { return static_cast<uint8_t>(SampleConv
<int8_t>(val
) + 128); }
1683 template<DevFmtType T
>
1684 void Write(const al::span
<const FloatBufferLine
> InBuffer
, void *OutBuffer
, const size_t Offset
,
1685 const ALuint SamplesToDo
)
1687 using SampleType
= typename DevFmtTypeTraits
<T
>::Type
;
1689 const size_t numchans
{InBuffer
.size()};
1690 ASSUME(numchans
> 0);
1692 SampleType
*outbase
= static_cast<SampleType
*>(OutBuffer
) + Offset
*numchans
;
1693 auto conv_channel
= [&outbase
,SamplesToDo
,numchans
](const FloatBufferLine
&inbuf
) -> void
1695 ASSUME(SamplesToDo
> 0);
1696 SampleType
*out
{outbase
++};
1697 auto conv_sample
= [numchans
,&out
](const float s
) noexcept
-> void
1699 *out
= SampleConv
<SampleType
>(s
);
1702 std::for_each(inbuf
.begin(), inbuf
.begin()+SamplesToDo
, conv_sample
);
1704 std::for_each(InBuffer
.cbegin(), InBuffer
.cend(), conv_channel
);
1709 void aluMixData(ALCdevice
*device
, ALvoid
*OutBuffer
, const ALuint NumSamples
)
1711 FPUCtl mixer_mode
{};
1712 for(ALuint SamplesDone
{0u};SamplesDone
< NumSamples
;)
1714 const ALuint SamplesToDo
{minu(NumSamples
-SamplesDone
, BUFFERSIZE
)};
1716 /* Clear main mixing buffers. */
1717 std::for_each(device
->MixBuffer
.begin(), device
->MixBuffer
.end(),
1718 [SamplesToDo
](std::array
<ALfloat
,BUFFERSIZE
> &buffer
) -> void
1719 { std::fill_n(buffer
.begin(), SamplesToDo
, 0.0f
); }
1722 /* Increment the mix count at the start (lsb should now be 1). */
1723 IncrementRef(device
->MixCount
);
1725 /* For each context on this device, process and mix its sources and
1728 for(ALCcontext
*ctx
: *device
->mContexts
.load(std::memory_order_acquire
))
1729 ProcessContext(ctx
, SamplesToDo
);
1731 /* Increment the clock time. Every second's worth of samples is
1732 * converted and added to clock base so that large sample counts don't
1733 * overflow during conversion. This also guarantees a stable
1736 device
->SamplesDone
+= SamplesToDo
;
1737 device
->ClockBase
+= std::chrono::seconds
{device
->SamplesDone
/ device
->Frequency
};
1738 device
->SamplesDone
%= device
->Frequency
;
1740 /* Increment the mix count at the end (lsb should now be 0). */
1741 IncrementRef(device
->MixCount
);
1743 /* Apply any needed post-process for finalizing the Dry mix to the
1744 * RealOut (Ambisonic decode, UHJ encode, etc).
1746 device
->postProcess(SamplesToDo
);
1748 const al::span
<FloatBufferLine
> RealOut
{device
->RealOut
.Buffer
};
1750 /* Apply front image stablization for surround sound, if applicable. */
1751 if(device
->Stablizer
)
1753 const ALuint lidx
{GetChannelIdxByName(device
->RealOut
, FrontLeft
)};
1754 const ALuint ridx
{GetChannelIdxByName(device
->RealOut
, FrontRight
)};
1755 const ALuint cidx
{GetChannelIdxByName(device
->RealOut
, FrontCenter
)};
1757 ApplyStablizer(device
->Stablizer
.get(), RealOut
, lidx
, ridx
, cidx
, SamplesToDo
);
1760 /* Apply compression, limiting sample amplitude if needed or desired. */
1761 if(Compressor
*comp
{device
->Limiter
.get()})
1762 comp
->process(SamplesToDo
, RealOut
.data());
1764 /* Apply delays and attenuation for mismatched speaker distances. */
1765 ApplyDistanceComp(RealOut
, SamplesToDo
, device
->ChannelDelay
.as_span().cbegin());
1767 /* Apply dithering. The compressor should have left enough headroom for
1768 * the dither noise to not saturate.
1770 if(device
->DitherDepth
> 0.0f
)
1771 ApplyDither(RealOut
, &device
->DitherSeed
, device
->DitherDepth
, SamplesToDo
);
1773 if LIKELY(OutBuffer
)
1775 /* Finally, interleave and convert samples, writing to the device's
1778 switch(device
->FmtType
)
1780 #define HANDLE_WRITE(T) case T: \
1781 Write<T>(RealOut, OutBuffer, SamplesDone, SamplesToDo); break;
1782 HANDLE_WRITE(DevFmtByte
)
1783 HANDLE_WRITE(DevFmtUByte
)
1784 HANDLE_WRITE(DevFmtShort
)
1785 HANDLE_WRITE(DevFmtUShort
)
1786 HANDLE_WRITE(DevFmtInt
)
1787 HANDLE_WRITE(DevFmtUInt
)
1788 HANDLE_WRITE(DevFmtFloat
)
1793 SamplesDone
+= SamplesToDo
;
1798 void aluHandleDisconnect(ALCdevice
*device
, const char *msg
, ...)
1800 if(!device
->Connected
.exchange(false, std::memory_order_acq_rel
))
1803 AsyncEvent evt
{EventType_Disconnected
};
1804 evt
.u
.user
.type
= AL_EVENT_TYPE_DISCONNECTED_SOFT
;
1806 evt
.u
.user
.param
= 0;
1809 va_start(args
, msg
);
1810 int msglen
{vsnprintf(evt
.u
.user
.msg
, sizeof(evt
.u
.user
.msg
), msg
, args
)};
1813 if(msglen
< 0 || static_cast<size_t>(msglen
) >= sizeof(evt
.u
.user
.msg
))
1814 evt
.u
.user
.msg
[sizeof(evt
.u
.user
.msg
)-1] = 0;
1816 IncrementRef(device
->MixCount
);
1817 for(ALCcontext
*ctx
: *device
->mContexts
.load())
1819 const ALbitfieldSOFT enabledevt
{ctx
->mEnabledEvts
.load(std::memory_order_acquire
)};
1820 if((enabledevt
&EventType_Disconnected
))
1822 RingBuffer
*ring
{ctx
->mAsyncEvents
.get()};
1823 auto evt_data
= ring
->getWriteVector().first
;
1824 if(evt_data
.len
> 0)
1826 ::new (evt_data
.buf
) AsyncEvent
{evt
};
1827 ring
->writeAdvance(1);
1828 ctx
->mEventSem
.post();
1832 auto stop_voice
= [](ALvoice
&voice
) -> void
1834 voice
.mCurrentBuffer
.store(nullptr, std::memory_order_relaxed
);
1835 voice
.mLoopBuffer
.store(nullptr, std::memory_order_relaxed
);
1836 voice
.mSourceID
.store(0u, std::memory_order_relaxed
);
1837 voice
.mPlayState
.store(ALvoice::Stopped
, std::memory_order_release
);
1839 std::for_each(ctx
->mVoices
.begin(), ctx
->mVoices
.end(), stop_voice
);
1841 IncrementRef(device
->MixCount
);