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
48 #include "al/auxeffectslot.h"
49 #include "al/buffer.h"
50 #include "al/effect.h"
52 #include "al/listener.h"
54 #include "alcontext.h"
56 #include "alnumeric.h"
61 #include "bformatdec.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"
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"
79 #include "uhjfilter.h"
82 #include "bsinc_inc.h"
87 using namespace std::placeholders
;
89 ALfloat
InitConeScale()
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)
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)
116 const ALfloat ConeScale
{InitConeScale()};
118 /* Localized Z scalar for mono sources */
119 const ALfloat ZScale
{InitZScale()};
124 void ClearArray(ALfloat (&f
)[MAX_OUTPUT_CHANNELS
])
126 std::fill(std::begin(f
), std::end(f
), 0.0f
);
135 HrtfDirectMixerFunc MixDirectHrtf
= MixDirectHrtf_
<CTag
>;
136 inline HrtfDirectMixerFunc
SelectHrtfMixer(void)
139 if((CPUCapFlags
&CPU_CAP_NEON
))
140 return MixDirectHrtf_
<NEONTag
>;
143 if((CPUCapFlags
&CPU_CAP_SSE
))
144 return MixDirectHrtf_
<SSETag
>;
147 return MixDirectHrtf_
<CTag
>;
151 inline void BsincPrepare(const ALuint increment
, BsincState
*state
, const BSincTable
*table
)
153 size_t si
{BSINC_SCALE_COUNT
- 1};
156 if(increment
> FRACTIONONE
)
158 sf
= FRACTIONONE
/ static_cast<float>(increment
);
159 sf
= maxf(0.0f
, (BSINC_SCALE_COUNT
-1) * (sf
-table
->scaleBase
) * table
->scaleRange
);
161 /* The interpolation factor is fit to this diagonally-symmetric curve
162 * to reduce the transition ripple caused by interpolating different
163 * scales of the sinc function.
165 sf
= 1.0f
- std::cos(std::asin(sf
- static_cast<float>(si
)));
169 state
->m
= table
->m
[si
];
170 state
->l
= (state
->m
/2) - 1;
171 state
->filter
= table
->Tab
+ table
->filterOffset
[si
];
174 inline ResamplerFunc
SelectResampler(Resampler resampler
, ALuint increment
)
178 case Resampler::Point
:
179 return Resample_
<PointTag
,CTag
>;
180 case Resampler::Linear
:
182 if((CPUCapFlags
&CPU_CAP_NEON
))
183 return Resample_
<LerpTag
,NEONTag
>;
186 if((CPUCapFlags
&CPU_CAP_SSE4_1
))
187 return Resample_
<LerpTag
,SSE4Tag
>;
190 if((CPUCapFlags
&CPU_CAP_SSE2
))
191 return Resample_
<LerpTag
,SSE2Tag
>;
193 return Resample_
<LerpTag
,CTag
>;
194 case Resampler::Cubic
:
195 return Resample_
<CubicTag
,CTag
>;
196 case Resampler::BSinc12
:
197 case Resampler::BSinc24
:
198 if(increment
<= FRACTIONONE
)
201 case Resampler::FastBSinc12
:
202 case Resampler::FastBSinc24
:
204 if((CPUCapFlags
&CPU_CAP_NEON
))
205 return Resample_
<FastBSincTag
,NEONTag
>;
208 if((CPUCapFlags
&CPU_CAP_SSE
))
209 return Resample_
<FastBSincTag
,SSETag
>;
211 return Resample_
<FastBSincTag
,CTag
>;
214 if((CPUCapFlags
&CPU_CAP_NEON
))
215 return Resample_
<BSincTag
,NEONTag
>;
218 if((CPUCapFlags
&CPU_CAP_SSE
))
219 return Resample_
<BSincTag
,SSETag
>;
221 return Resample_
<BSincTag
,CTag
>;
224 return Resample_
<PointTag
,CTag
>;
231 MixDirectHrtf
= SelectHrtfMixer();
235 ResamplerFunc
PrepareResampler(Resampler resampler
, ALuint increment
, InterpState
*state
)
239 case Resampler::Point
:
240 case Resampler::Linear
:
241 case Resampler::Cubic
:
243 case Resampler::FastBSinc12
:
244 case Resampler::BSinc12
:
245 BsincPrepare(increment
, &state
->bsinc
, &bsinc12
);
247 case Resampler::FastBSinc24
:
248 case Resampler::BSinc24
:
249 BsincPrepare(increment
, &state
->bsinc
, &bsinc24
);
252 return SelectResampler(resampler
, increment
);
256 void ALCdevice::ProcessHrtf(const size_t SamplesToDo
)
258 /* HRTF is stereo output only. */
259 const ALuint lidx
{RealOut
.ChannelIndex
[FrontLeft
]};
260 const ALuint ridx
{RealOut
.ChannelIndex
[FrontRight
]};
262 MixDirectHrtf(RealOut
.Buffer
[lidx
], RealOut
.Buffer
[ridx
], Dry
.Buffer
, HrtfAccumData
,
263 mHrtfState
.get(), SamplesToDo
);
266 void ALCdevice::ProcessAmbiDec(const size_t SamplesToDo
)
268 AmbiDecoder
->process(RealOut
.Buffer
, Dry
.Buffer
.data(), SamplesToDo
);
271 void ALCdevice::ProcessUhj(const size_t SamplesToDo
)
273 /* UHJ is stereo output only. */
274 const ALuint lidx
{RealOut
.ChannelIndex
[FrontLeft
]};
275 const ALuint ridx
{RealOut
.ChannelIndex
[FrontRight
]};
277 /* Encode to stereo-compatible 2-channel UHJ output. */
278 Uhj_Encoder
->encode(RealOut
.Buffer
[lidx
], RealOut
.Buffer
[ridx
], Dry
.Buffer
.data(),
282 void ALCdevice::ProcessBs2b(const size_t SamplesToDo
)
284 /* First, decode the ambisonic mix to the "real" output. */
285 AmbiDecoder
->process(RealOut
.Buffer
, Dry
.Buffer
.data(), SamplesToDo
);
287 /* BS2B is stereo output only. */
288 const ALuint lidx
{RealOut
.ChannelIndex
[FrontLeft
]};
289 const ALuint ridx
{RealOut
.ChannelIndex
[FrontRight
]};
291 /* Now apply the BS2B binaural/crossfeed filter. */
292 bs2b_cross_feed(Bs2b
.get(), RealOut
.Buffer
[lidx
].data(), RealOut
.Buffer
[ridx
].data(),
299 /* This RNG method was created based on the math found in opusdec. It's quick,
300 * and starting with a seed value of 22222, is suitable for generating
303 inline ALuint
dither_rng(ALuint
*seed
) noexcept
305 *seed
= (*seed
* 96314165) + 907633515;
310 inline alu::Vector
aluCrossproduct(const alu::Vector
&in1
, const alu::Vector
&in2
)
313 in1
[1]*in2
[2] - in1
[2]*in2
[1],
314 in1
[2]*in2
[0] - in1
[0]*in2
[2],
315 in1
[0]*in2
[1] - in1
[1]*in2
[0],
320 inline ALfloat
aluDotproduct(const alu::Vector
&vec1
, const alu::Vector
&vec2
)
322 return vec1
[0]*vec2
[0] + vec1
[1]*vec2
[1] + vec1
[2]*vec2
[2];
326 alu::Vector
operator*(const alu::Matrix
&mtx
, const alu::Vector
&vec
) noexcept
329 vec
[0]*mtx
[0][0] + vec
[1]*mtx
[1][0] + vec
[2]*mtx
[2][0] + vec
[3]*mtx
[3][0],
330 vec
[0]*mtx
[0][1] + vec
[1]*mtx
[1][1] + vec
[2]*mtx
[2][1] + vec
[3]*mtx
[3][1],
331 vec
[0]*mtx
[0][2] + vec
[1]*mtx
[1][2] + vec
[2]*mtx
[2][2] + vec
[3]*mtx
[3][2],
332 vec
[0]*mtx
[0][3] + vec
[1]*mtx
[1][3] + vec
[2]*mtx
[2][3] + vec
[3]*mtx
[3][3]
337 bool CalcContextParams(ALCcontext
*Context
)
339 ALcontextProps
*props
{Context
->mUpdate
.exchange(nullptr, std::memory_order_acq_rel
)};
340 if(!props
) return false;
342 ALlistener
&Listener
= Context
->mListener
;
343 Listener
.Params
.DopplerFactor
= props
->DopplerFactor
;
344 Listener
.Params
.SpeedOfSound
= props
->SpeedOfSound
* props
->DopplerVelocity
;
346 Listener
.Params
.SourceDistanceModel
= props
->SourceDistanceModel
;
347 Listener
.Params
.mDistanceModel
= props
->mDistanceModel
;
349 AtomicReplaceHead(Context
->mFreeContextProps
, props
);
353 bool CalcListenerParams(ALCcontext
*Context
)
355 ALlistener
&Listener
= Context
->mListener
;
357 ALlistenerProps
*props
{Listener
.Params
.Update
.exchange(nullptr, std::memory_order_acq_rel
)};
358 if(!props
) return false;
361 alu::Vector N
{props
->OrientAt
[0], props
->OrientAt
[1], props
->OrientAt
[2], 0.0f
};
363 alu::Vector V
{props
->OrientUp
[0], props
->OrientUp
[1], props
->OrientUp
[2], 0.0f
};
365 /* Build and normalize right-vector */
366 alu::Vector U
{aluCrossproduct(N
, V
)};
369 Listener
.Params
.Matrix
= alu::Matrix
{
370 U
[0], V
[0], -N
[0], 0.0f
,
371 U
[1], V
[1], -N
[1], 0.0f
,
372 U
[2], V
[2], -N
[2], 0.0f
,
373 0.0f
, 0.0f
, 0.0f
, 1.0f
376 const alu::Vector P
{Listener
.Params
.Matrix
*
377 alu::Vector
{props
->Position
[0], props
->Position
[1], props
->Position
[2], 1.0f
}};
378 Listener
.Params
.Matrix
.setRow(3, -P
[0], -P
[1], -P
[2], 1.0f
);
380 const alu::Vector vel
{props
->Velocity
[0], props
->Velocity
[1], props
->Velocity
[2], 0.0f
};
381 Listener
.Params
.Velocity
= Listener
.Params
.Matrix
* vel
;
383 Listener
.Params
.Gain
= props
->Gain
* Context
->mGainBoost
;
384 Listener
.Params
.MetersPerUnit
= props
->MetersPerUnit
;
386 AtomicReplaceHead(Context
->mFreeListenerProps
, props
);
390 bool CalcEffectSlotParams(ALeffectslot
*slot
, ALCcontext
*context
)
392 ALeffectslotProps
*props
{slot
->Params
.Update
.exchange(nullptr, std::memory_order_acq_rel
)};
393 if(!props
) return false;
395 slot
->Params
.Gain
= props
->Gain
;
396 slot
->Params
.AuxSendAuto
= props
->AuxSendAuto
;
397 slot
->Params
.Target
= props
->Target
;
398 slot
->Params
.EffectType
= props
->Type
;
399 slot
->Params
.mEffectProps
= props
->Props
;
400 if(IsReverbEffect(props
->Type
))
402 slot
->Params
.RoomRolloff
= props
->Props
.Reverb
.RoomRolloffFactor
;
403 slot
->Params
.DecayTime
= props
->Props
.Reverb
.DecayTime
;
404 slot
->Params
.DecayLFRatio
= props
->Props
.Reverb
.DecayLFRatio
;
405 slot
->Params
.DecayHFRatio
= props
->Props
.Reverb
.DecayHFRatio
;
406 slot
->Params
.DecayHFLimit
= props
->Props
.Reverb
.DecayHFLimit
;
407 slot
->Params
.AirAbsorptionGainHF
= props
->Props
.Reverb
.AirAbsorptionGainHF
;
411 slot
->Params
.RoomRolloff
= 0.0f
;
412 slot
->Params
.DecayTime
= 0.0f
;
413 slot
->Params
.DecayLFRatio
= 0.0f
;
414 slot
->Params
.DecayHFRatio
= 0.0f
;
415 slot
->Params
.DecayHFLimit
= AL_FALSE
;
416 slot
->Params
.AirAbsorptionGainHF
= 1.0f
;
419 EffectState
*state
{props
->State
};
420 props
->State
= nullptr;
421 EffectState
*oldstate
{slot
->Params
.mEffectState
};
422 slot
->Params
.mEffectState
= state
;
424 /* Only release the old state if it won't get deleted, since we can't be
425 * deleting/freeing anything in the mixer.
427 if(!oldstate
->releaseIfNoDelete())
429 /* Otherwise, if it would be deleted send it off with a release event. */
430 RingBuffer
*ring
{context
->mAsyncEvents
.get()};
431 auto evt_vec
= ring
->getWriteVector();
432 if LIKELY(evt_vec
.first
.len
> 0)
434 AsyncEvent
*evt
{new (evt_vec
.first
.buf
) AsyncEvent
{EventType_ReleaseEffectState
}};
435 evt
->u
.mEffectState
= oldstate
;
436 ring
->writeAdvance(1);
437 context
->mEventSem
.post();
441 /* If writing the event failed, the queue was probably full. Store
442 * the old state in the property object where it can eventually be
443 * cleaned up sometime later (not ideal, but better than blocking
446 props
->State
= oldstate
;
450 AtomicReplaceHead(context
->mFreeEffectslotProps
, props
);
453 if(ALeffectslot
*target
{slot
->Params
.Target
})
454 output
= EffectTarget
{&target
->Wet
, nullptr};
457 ALCdevice
*device
{context
->mDevice
.get()};
458 output
= EffectTarget
{&device
->Dry
, &device
->RealOut
};
460 state
->update(context
, slot
, &slot
->Params
.mEffectProps
, output
);
465 /* Scales the given azimuth toward the side (+/- pi/2 radians) for positions in
468 inline float ScaleAzimuthFront(float azimuth
, float scale
)
470 const ALfloat abs_azi
{std::fabs(azimuth
)};
471 if(!(abs_azi
>= al::MathDefs
<float>::Pi()*0.5f
))
472 return std::copysign(minf(abs_azi
*scale
, al::MathDefs
<float>::Pi()*0.5f
), azimuth
);
476 void CalcPanningAndFilters(ALvoice
*voice
, const ALfloat xpos
, const ALfloat ypos
,
477 const ALfloat zpos
, const ALfloat Distance
, const ALfloat Spread
, const ALfloat DryGain
,
478 const ALfloat DryGainHF
, const ALfloat DryGainLF
, const ALfloat (&WetGain
)[MAX_SENDS
],
479 const ALfloat (&WetGainLF
)[MAX_SENDS
], const ALfloat (&WetGainHF
)[MAX_SENDS
],
480 ALeffectslot
*(&SendSlots
)[MAX_SENDS
], const ALvoicePropsBase
*props
,
481 const ALlistener
&Listener
, const ALCdevice
*Device
)
483 static constexpr ChanMap MonoMap
[1]{
484 { FrontCenter
, 0.0f
, 0.0f
}
486 { BackLeft
, Deg2Rad(-150.0f
), Deg2Rad(0.0f
) },
487 { BackRight
, Deg2Rad( 150.0f
), Deg2Rad(0.0f
) }
489 { FrontLeft
, Deg2Rad( -45.0f
), Deg2Rad(0.0f
) },
490 { FrontRight
, Deg2Rad( 45.0f
), Deg2Rad(0.0f
) },
491 { BackLeft
, Deg2Rad(-135.0f
), Deg2Rad(0.0f
) },
492 { BackRight
, Deg2Rad( 135.0f
), Deg2Rad(0.0f
) }
494 { FrontLeft
, Deg2Rad( -30.0f
), Deg2Rad(0.0f
) },
495 { FrontRight
, Deg2Rad( 30.0f
), Deg2Rad(0.0f
) },
496 { FrontCenter
, Deg2Rad( 0.0f
), Deg2Rad(0.0f
) },
498 { SideLeft
, Deg2Rad(-110.0f
), Deg2Rad(0.0f
) },
499 { SideRight
, Deg2Rad( 110.0f
), Deg2Rad(0.0f
) }
501 { FrontLeft
, Deg2Rad(-30.0f
), Deg2Rad(0.0f
) },
502 { FrontRight
, Deg2Rad( 30.0f
), Deg2Rad(0.0f
) },
503 { FrontCenter
, Deg2Rad( 0.0f
), Deg2Rad(0.0f
) },
505 { BackCenter
, Deg2Rad(180.0f
), Deg2Rad(0.0f
) },
506 { SideLeft
, Deg2Rad(-90.0f
), Deg2Rad(0.0f
) },
507 { SideRight
, Deg2Rad( 90.0f
), Deg2Rad(0.0f
) }
509 { FrontLeft
, Deg2Rad( -30.0f
), Deg2Rad(0.0f
) },
510 { FrontRight
, Deg2Rad( 30.0f
), Deg2Rad(0.0f
) },
511 { FrontCenter
, Deg2Rad( 0.0f
), Deg2Rad(0.0f
) },
513 { BackLeft
, Deg2Rad(-150.0f
), Deg2Rad(0.0f
) },
514 { BackRight
, Deg2Rad( 150.0f
), Deg2Rad(0.0f
) },
515 { SideLeft
, Deg2Rad( -90.0f
), Deg2Rad(0.0f
) },
516 { SideRight
, Deg2Rad( 90.0f
), Deg2Rad(0.0f
) }
519 ChanMap StereoMap
[2]{
520 { FrontLeft
, Deg2Rad(-30.0f
), Deg2Rad(0.0f
) },
521 { FrontRight
, Deg2Rad( 30.0f
), Deg2Rad(0.0f
) }
524 const auto Frequency
= static_cast<ALfloat
>(Device
->Frequency
);
525 const ALuint NumSends
{Device
->NumAuxSends
};
527 bool DirectChannels
{props
->DirectChannels
!= AL_FALSE
};
528 const ChanMap
*chans
{nullptr};
529 ALuint num_channels
{0};
530 bool isbformat
{false};
531 ALfloat downmix_gain
{1.0f
};
532 switch(voice
->mFmtChannels
)
537 /* Mono buffers are never played direct. */
538 DirectChannels
= false;
542 /* Convert counter-clockwise to clockwise. */
543 StereoMap
[0].angle
= -props
->StereoPan
[0];
544 StereoMap
[1].angle
= -props
->StereoPan
[1];
548 downmix_gain
= 1.0f
/ 2.0f
;
554 downmix_gain
= 1.0f
/ 2.0f
;
560 downmix_gain
= 1.0f
/ 4.0f
;
566 /* NOTE: Excludes LFE. */
567 downmix_gain
= 1.0f
/ 5.0f
;
573 /* NOTE: Excludes LFE. */
574 downmix_gain
= 1.0f
/ 6.0f
;
580 /* NOTE: Excludes LFE. */
581 downmix_gain
= 1.0f
/ 7.0f
;
587 DirectChannels
= false;
593 DirectChannels
= false;
596 ASSUME(num_channels
> 0);
598 std::for_each(voice
->mChans
.begin(), voice
->mChans
.begin()+num_channels
,
599 [NumSends
](ALvoice::ChannelData
&chandata
) -> void
601 chandata
.mDryParams
.Hrtf
.Target
= HrtfFilter
{};
602 ClearArray(chandata
.mDryParams
.Gains
.Target
);
603 std::for_each(chandata
.mWetParams
.begin(), chandata
.mWetParams
.begin()+NumSends
,
604 [](SendParams
¶ms
) -> void { ClearArray(params
.Gains
.Target
); });
607 voice
->mFlags
&= ~(VOICE_HAS_HRTF
| VOICE_HAS_NFC
);
610 /* Special handling for B-Format sources. */
612 if(Distance
> std::numeric_limits
<float>::epsilon())
614 /* Panning a B-Format sound toward some direction is easy. Just pan
615 * the first (W) channel as a normal mono sound and silence the
619 if(Device
->AvgSpeakerDist
> 0.0f
)
621 /* Clamp the distance for really close sources, to prevent
624 const ALfloat mdist
{maxf(Distance
, Device
->AvgSpeakerDist
/4.0f
)};
625 const ALfloat w0
{SPEEDOFSOUNDMETRESPERSEC
/ (mdist
* Frequency
)};
627 /* Only need to adjust the first channel of a B-Format source. */
628 voice
->mChans
[0].mDryParams
.NFCtrlFilter
.adjust(w0
);
630 voice
->mFlags
|= VOICE_HAS_NFC
;
633 ALfloat coeffs
[MAX_AMBI_CHANNELS
];
634 if(Device
->mRenderMode
!= StereoPair
)
635 CalcDirectionCoeffs({xpos
, ypos
, zpos
}, Spread
, coeffs
);
638 /* Clamp Y, in case rounding errors caused it to end up outside
641 const ALfloat ev
{std::asin(clampf(ypos
, -1.0f
, 1.0f
))};
642 /* Negate Z for right-handed coords with -Z in front. */
643 const ALfloat az
{std::atan2(xpos
, -zpos
)};
645 /* A scalar of 1.5 for plain stereo results in +/-60 degrees
646 * being moved to +/-90 degrees for direct right and left
649 CalcAngleCoeffs(ScaleAzimuthFront(az
, 1.5f
), ev
, Spread
, coeffs
);
652 /* NOTE: W needs to be scaled due to FuMa normalization. */
653 const ALfloat
&scale0
= AmbiScale::FromFuMa
[0];
654 ComputePanGains(&Device
->Dry
, coeffs
, DryGain
*scale0
,
655 voice
->mChans
[0].mDryParams
.Gains
.Target
);
656 for(ALuint i
{0};i
< NumSends
;i
++)
658 if(const ALeffectslot
*Slot
{SendSlots
[i
]})
659 ComputePanGains(&Slot
->Wet
, coeffs
, WetGain
[i
]*scale0
,
660 voice
->mChans
[0].mWetParams
[i
].Gains
.Target
);
665 if(Device
->AvgSpeakerDist
> 0.0f
)
667 /* NOTE: The NFCtrlFilters were created with a w0 of 0, which
668 * is what we want for FOA input. The first channel may have
669 * been previously re-adjusted if panned, so reset it.
671 voice
->mChans
[0].mDryParams
.NFCtrlFilter
.adjust(0.0f
);
673 voice
->mFlags
|= VOICE_HAS_NFC
;
676 /* Local B-Format sources have their XYZ channels rotated according
677 * to the orientation.
680 alu::Vector N
{props
->OrientAt
[0], props
->OrientAt
[1], props
->OrientAt
[2], 0.0f
};
682 alu::Vector V
{props
->OrientUp
[0], props
->OrientUp
[1], props
->OrientUp
[2], 0.0f
};
684 if(!props
->HeadRelative
)
686 N
= Listener
.Params
.Matrix
* N
;
687 V
= Listener
.Params
.Matrix
* V
;
689 /* Build and normalize right-vector */
690 alu::Vector U
{aluCrossproduct(N
, V
)};
693 /* Build a rotate + conversion matrix (FuMa -> ACN+N3D). NOTE: This
694 * matrix is transposed, for the inputs to align on the rows and
695 * outputs on the columns.
697 const ALfloat
&wscale
= AmbiScale::FromFuMa
[0];
698 const ALfloat
&yscale
= AmbiScale::FromFuMa
[1];
699 const ALfloat
&zscale
= AmbiScale::FromFuMa
[2];
700 const ALfloat
&xscale
= AmbiScale::FromFuMa
[3];
701 const ALfloat matrix
[4][MAX_AMBI_CHANNELS
]{
702 // ACN0 ACN1 ACN2 ACN3
703 { wscale
, 0.0f
, 0.0f
, 0.0f
}, // FuMa W
704 { 0.0f
, -N
[0]*xscale
, N
[1]*xscale
, -N
[2]*xscale
}, // FuMa X
705 { 0.0f
, U
[0]*yscale
, -U
[1]*yscale
, U
[2]*yscale
}, // FuMa Y
706 { 0.0f
, -V
[0]*zscale
, V
[1]*zscale
, -V
[2]*zscale
} // FuMa Z
709 for(ALuint c
{0};c
< num_channels
;c
++)
711 ComputePanGains(&Device
->Dry
, matrix
[c
], DryGain
,
712 voice
->mChans
[c
].mDryParams
.Gains
.Target
);
714 for(ALuint i
{0};i
< NumSends
;i
++)
716 if(const ALeffectslot
*Slot
{SendSlots
[i
]})
717 ComputePanGains(&Slot
->Wet
, matrix
[c
], WetGain
[i
],
718 voice
->mChans
[c
].mWetParams
[i
].Gains
.Target
);
723 else if(DirectChannels
)
725 /* Direct source channels always play local. Skip the virtual channels
726 * and write inputs to the matching real outputs.
728 voice
->mDirect
.Buffer
= Device
->RealOut
.Buffer
;
730 for(ALuint c
{0};c
< num_channels
;c
++)
732 const ALuint idx
{GetChannelIdxByName(Device
->RealOut
, chans
[c
].channel
)};
733 if(idx
!= INVALID_CHANNEL_INDEX
)
734 voice
->mChans
[c
].mDryParams
.Gains
.Target
[idx
] = DryGain
;
737 /* Auxiliary sends still use normal channel panning since they mix to
738 * B-Format, which can't channel-match.
740 for(ALuint c
{0};c
< num_channels
;c
++)
742 ALfloat coeffs
[MAX_AMBI_CHANNELS
];
743 CalcAngleCoeffs(chans
[c
].angle
, chans
[c
].elevation
, 0.0f
, coeffs
);
745 for(ALuint i
{0};i
< NumSends
;i
++)
747 if(const ALeffectslot
*Slot
{SendSlots
[i
]})
748 ComputePanGains(&Slot
->Wet
, coeffs
, WetGain
[i
],
749 voice
->mChans
[c
].mWetParams
[i
].Gains
.Target
);
753 else if(Device
->mRenderMode
== HrtfRender
)
755 /* Full HRTF rendering. Skip the virtual channels and render to the
758 voice
->mDirect
.Buffer
= Device
->RealOut
.Buffer
;
760 if(Distance
> std::numeric_limits
<float>::epsilon())
762 const ALfloat ev
{std::asin(clampf(ypos
, -1.0f
, 1.0f
))};
763 const ALfloat az
{std::atan2(xpos
, -zpos
)};
765 /* Get the HRIR coefficients and delays just once, for the given
768 GetHrtfCoeffs(Device
->mHrtf
, ev
, az
, Distance
, Spread
,
769 voice
->mChans
[0].mDryParams
.Hrtf
.Target
.Coeffs
,
770 voice
->mChans
[0].mDryParams
.Hrtf
.Target
.Delay
);
771 voice
->mChans
[0].mDryParams
.Hrtf
.Target
.Gain
= DryGain
* downmix_gain
;
773 /* Remaining channels use the same results as the first. */
774 for(ALuint c
{1};c
< num_channels
;c
++)
777 if(chans
[c
].channel
== LFE
) continue;
778 voice
->mChans
[c
].mDryParams
.Hrtf
.Target
= voice
->mChans
[0].mDryParams
.Hrtf
.Target
;
781 /* Calculate the directional coefficients once, which apply to all
782 * input channels of the source sends.
784 ALfloat coeffs
[MAX_AMBI_CHANNELS
];
785 CalcDirectionCoeffs({xpos
, ypos
, zpos
}, Spread
, coeffs
);
787 for(ALuint c
{0};c
< num_channels
;c
++)
790 if(chans
[c
].channel
== LFE
)
792 for(ALuint i
{0};i
< NumSends
;i
++)
794 if(const ALeffectslot
*Slot
{SendSlots
[i
]})
795 ComputePanGains(&Slot
->Wet
, coeffs
, WetGain
[i
] * downmix_gain
,
796 voice
->mChans
[c
].mWetParams
[i
].Gains
.Target
);
802 /* Local sources on HRTF play with each channel panned to its
803 * relative location around the listener, providing "virtual
804 * speaker" responses.
806 for(ALuint c
{0};c
< num_channels
;c
++)
809 if(chans
[c
].channel
== LFE
)
812 /* Get the HRIR coefficients and delays for this channel
815 GetHrtfCoeffs(Device
->mHrtf
, chans
[c
].elevation
, chans
[c
].angle
,
816 std::numeric_limits
<float>::infinity(), Spread
,
817 voice
->mChans
[c
].mDryParams
.Hrtf
.Target
.Coeffs
,
818 voice
->mChans
[c
].mDryParams
.Hrtf
.Target
.Delay
);
819 voice
->mChans
[c
].mDryParams
.Hrtf
.Target
.Gain
= DryGain
;
821 /* Normal panning for auxiliary sends. */
822 ALfloat coeffs
[MAX_AMBI_CHANNELS
];
823 CalcAngleCoeffs(chans
[c
].angle
, chans
[c
].elevation
, Spread
, coeffs
);
825 for(ALuint i
{0};i
< NumSends
;i
++)
827 if(const ALeffectslot
*Slot
{SendSlots
[i
]})
828 ComputePanGains(&Slot
->Wet
, coeffs
, WetGain
[i
],
829 voice
->mChans
[c
].mWetParams
[i
].Gains
.Target
);
834 voice
->mFlags
|= VOICE_HAS_HRTF
;
838 /* Non-HRTF rendering. Use normal panning to the output. */
840 if(Distance
> std::numeric_limits
<float>::epsilon())
842 /* Calculate NFC filter coefficient if needed. */
843 if(Device
->AvgSpeakerDist
> 0.0f
)
845 /* Clamp the distance for really close sources, to prevent
848 const ALfloat mdist
{maxf(Distance
, Device
->AvgSpeakerDist
/4.0f
)};
849 const ALfloat w0
{SPEEDOFSOUNDMETRESPERSEC
/ (mdist
* Frequency
)};
851 /* Adjust NFC filters. */
852 for(ALuint c
{0};c
< num_channels
;c
++)
853 voice
->mChans
[c
].mDryParams
.NFCtrlFilter
.adjust(w0
);
855 voice
->mFlags
|= VOICE_HAS_NFC
;
858 /* Calculate the directional coefficients once, which apply to all
861 ALfloat coeffs
[MAX_AMBI_CHANNELS
];
862 if(Device
->mRenderMode
!= StereoPair
)
863 CalcDirectionCoeffs({xpos
, ypos
, zpos
}, Spread
, coeffs
);
866 const ALfloat ev
{std::asin(clampf(ypos
, -1.0f
, 1.0f
))};
867 const ALfloat az
{std::atan2(xpos
, -zpos
)};
868 CalcAngleCoeffs(ScaleAzimuthFront(az
, 1.5f
), ev
, Spread
, coeffs
);
871 for(ALuint c
{0};c
< num_channels
;c
++)
873 /* Special-case LFE */
874 if(chans
[c
].channel
== LFE
)
876 if(Device
->Dry
.Buffer
.data() == Device
->RealOut
.Buffer
.data())
878 const ALuint idx
{GetChannelIdxByName(Device
->RealOut
, chans
[c
].channel
)};
879 if(idx
!= INVALID_CHANNEL_INDEX
)
880 voice
->mChans
[c
].mDryParams
.Gains
.Target
[idx
] = DryGain
;
885 ComputePanGains(&Device
->Dry
, coeffs
, DryGain
* downmix_gain
,
886 voice
->mChans
[c
].mDryParams
.Gains
.Target
);
887 for(ALuint i
{0};i
< NumSends
;i
++)
889 if(const ALeffectslot
*Slot
{SendSlots
[i
]})
890 ComputePanGains(&Slot
->Wet
, coeffs
, WetGain
[i
] * downmix_gain
,
891 voice
->mChans
[c
].mWetParams
[i
].Gains
.Target
);
897 if(Device
->AvgSpeakerDist
> 0.0f
)
899 /* If the source distance is 0, set w0 to w1 to act as a pass-
900 * through. We still want to pass the signal through the
901 * filters so they keep an appropriate history, in case the
902 * source moves away from the listener.
904 const ALfloat w0
{SPEEDOFSOUNDMETRESPERSEC
/ (Device
->AvgSpeakerDist
* Frequency
)};
906 for(ALuint c
{0};c
< num_channels
;c
++)
907 voice
->mChans
[c
].mDryParams
.NFCtrlFilter
.adjust(w0
);
909 voice
->mFlags
|= VOICE_HAS_NFC
;
912 for(ALuint c
{0};c
< num_channels
;c
++)
914 /* Special-case LFE */
915 if(chans
[c
].channel
== LFE
)
917 if(Device
->Dry
.Buffer
.data() == Device
->RealOut
.Buffer
.data())
919 const ALuint idx
{GetChannelIdxByName(Device
->RealOut
, chans
[c
].channel
)};
920 if(idx
!= INVALID_CHANNEL_INDEX
)
921 voice
->mChans
[c
].mDryParams
.Gains
.Target
[idx
] = DryGain
;
926 ALfloat coeffs
[MAX_AMBI_CHANNELS
];
928 (Device
->mRenderMode
==StereoPair
) ? ScaleAzimuthFront(chans
[c
].angle
, 3.0f
)
930 chans
[c
].elevation
, Spread
, coeffs
933 ComputePanGains(&Device
->Dry
, coeffs
, DryGain
,
934 voice
->mChans
[c
].mDryParams
.Gains
.Target
);
935 for(ALuint i
{0};i
< NumSends
;i
++)
937 if(const ALeffectslot
*Slot
{SendSlots
[i
]})
938 ComputePanGains(&Slot
->Wet
, coeffs
, WetGain
[i
],
939 voice
->mChans
[c
].mWetParams
[i
].Gains
.Target
);
946 const ALfloat hfScale
{props
->Direct
.HFReference
/ Frequency
};
947 const ALfloat lfScale
{props
->Direct
.LFReference
/ Frequency
};
948 const ALfloat gainHF
{maxf(DryGainHF
, 0.001f
)}; /* Limit -60dB */
949 const ALfloat gainLF
{maxf(DryGainLF
, 0.001f
)};
951 voice
->mDirect
.FilterType
= AF_None
;
952 if(gainHF
!= 1.0f
) voice
->mDirect
.FilterType
|= AF_LowPass
;
953 if(gainLF
!= 1.0f
) voice
->mDirect
.FilterType
|= AF_HighPass
;
954 auto &lowpass
= voice
->mChans
[0].mDryParams
.LowPass
;
955 auto &highpass
= voice
->mChans
[0].mDryParams
.HighPass
;
956 lowpass
.setParams(BiquadType::HighShelf
, gainHF
, hfScale
,
957 lowpass
.rcpQFromSlope(gainHF
, 1.0f
));
958 highpass
.setParams(BiquadType::LowShelf
, gainLF
, lfScale
,
959 highpass
.rcpQFromSlope(gainLF
, 1.0f
));
960 for(ALuint c
{1};c
< num_channels
;c
++)
962 voice
->mChans
[c
].mDryParams
.LowPass
.copyParamsFrom(lowpass
);
963 voice
->mChans
[c
].mDryParams
.HighPass
.copyParamsFrom(highpass
);
966 for(ALuint i
{0};i
< NumSends
;i
++)
968 const ALfloat hfScale
{props
->Send
[i
].HFReference
/ Frequency
};
969 const ALfloat lfScale
{props
->Send
[i
].LFReference
/ Frequency
};
970 const ALfloat gainHF
{maxf(WetGainHF
[i
], 0.001f
)};
971 const ALfloat gainLF
{maxf(WetGainLF
[i
], 0.001f
)};
973 voice
->mSend
[i
].FilterType
= AF_None
;
974 if(gainHF
!= 1.0f
) voice
->mSend
[i
].FilterType
|= AF_LowPass
;
975 if(gainLF
!= 1.0f
) voice
->mSend
[i
].FilterType
|= AF_HighPass
;
977 auto &lowpass
= voice
->mChans
[0].mWetParams
[i
].LowPass
;
978 auto &highpass
= voice
->mChans
[0].mWetParams
[i
].HighPass
;
979 lowpass
.setParams(BiquadType::HighShelf
, gainHF
, hfScale
,
980 lowpass
.rcpQFromSlope(gainHF
, 1.0f
));
981 highpass
.setParams(BiquadType::LowShelf
, gainLF
, lfScale
,
982 highpass
.rcpQFromSlope(gainLF
, 1.0f
));
983 for(ALuint c
{1};c
< num_channels
;c
++)
985 voice
->mChans
[c
].mWetParams
[i
].LowPass
.copyParamsFrom(lowpass
);
986 voice
->mChans
[c
].mWetParams
[i
].HighPass
.copyParamsFrom(highpass
);
991 void CalcNonAttnSourceParams(ALvoice
*voice
, const ALvoicePropsBase
*props
, const ALCcontext
*ALContext
)
993 const ALCdevice
*Device
{ALContext
->mDevice
.get()};
994 ALeffectslot
*SendSlots
[MAX_SENDS
];
996 voice
->mDirect
.Buffer
= Device
->Dry
.Buffer
;
997 for(ALuint i
{0};i
< Device
->NumAuxSends
;i
++)
999 SendSlots
[i
] = props
->Send
[i
].Slot
;
1000 if(!SendSlots
[i
] && i
== 0)
1001 SendSlots
[i
] = ALContext
->mDefaultSlot
.get();
1002 if(!SendSlots
[i
] || SendSlots
[i
]->Params
.EffectType
== AL_EFFECT_NULL
)
1004 SendSlots
[i
] = nullptr;
1005 voice
->mSend
[i
].Buffer
= {};
1008 voice
->mSend
[i
].Buffer
= SendSlots
[i
]->Wet
.Buffer
;
1011 /* Calculate the stepping value */
1012 const auto Pitch
= static_cast<ALfloat
>(voice
->mFrequency
) /
1013 static_cast<ALfloat
>(Device
->Frequency
) * props
->Pitch
;
1014 if(Pitch
> float{MAX_PITCH
})
1015 voice
->mStep
= MAX_PITCH
<<FRACTIONBITS
;
1017 voice
->mStep
= maxu(fastf2u(Pitch
* FRACTIONONE
), 1);
1018 voice
->mResampler
= PrepareResampler(props
->mResampler
, voice
->mStep
, &voice
->mResampleState
);
1020 /* Calculate gains */
1021 const ALlistener
&Listener
= ALContext
->mListener
;
1022 ALfloat DryGain
{clampf(props
->Gain
, props
->MinGain
, props
->MaxGain
)};
1023 DryGain
*= props
->Direct
.Gain
* Listener
.Params
.Gain
;
1024 DryGain
= minf(DryGain
, GAIN_MIX_MAX
);
1025 ALfloat DryGainHF
{props
->Direct
.GainHF
};
1026 ALfloat DryGainLF
{props
->Direct
.GainLF
};
1027 ALfloat WetGain
[MAX_SENDS
], WetGainHF
[MAX_SENDS
], WetGainLF
[MAX_SENDS
];
1028 for(ALuint i
{0};i
< Device
->NumAuxSends
;i
++)
1030 WetGain
[i
] = clampf(props
->Gain
, props
->MinGain
, props
->MaxGain
);
1031 WetGain
[i
] *= props
->Send
[i
].Gain
* Listener
.Params
.Gain
;
1032 WetGain
[i
] = minf(WetGain
[i
], GAIN_MIX_MAX
);
1033 WetGainHF
[i
] = props
->Send
[i
].GainHF
;
1034 WetGainLF
[i
] = props
->Send
[i
].GainLF
;
1037 CalcPanningAndFilters(voice
, 0.0f
, 0.0f
, -1.0f
, 0.0f
, 0.0f
, DryGain
, DryGainHF
, DryGainLF
,
1038 WetGain
, WetGainLF
, WetGainHF
, SendSlots
, props
, Listener
, Device
);
1041 void CalcAttnSourceParams(ALvoice
*voice
, const ALvoicePropsBase
*props
, const ALCcontext
*ALContext
)
1043 const ALCdevice
*Device
{ALContext
->mDevice
.get()};
1044 const ALuint NumSends
{Device
->NumAuxSends
};
1045 const ALlistener
&Listener
= ALContext
->mListener
;
1047 /* Set mixing buffers and get send parameters. */
1048 voice
->mDirect
.Buffer
= Device
->Dry
.Buffer
;
1049 ALeffectslot
*SendSlots
[MAX_SENDS
];
1050 ALfloat RoomRolloff
[MAX_SENDS
];
1051 ALfloat DecayDistance
[MAX_SENDS
];
1052 ALfloat DecayLFDistance
[MAX_SENDS
];
1053 ALfloat DecayHFDistance
[MAX_SENDS
];
1054 for(ALuint i
{0};i
< NumSends
;i
++)
1056 SendSlots
[i
] = props
->Send
[i
].Slot
;
1057 if(!SendSlots
[i
] && i
== 0)
1058 SendSlots
[i
] = ALContext
->mDefaultSlot
.get();
1059 if(!SendSlots
[i
] || SendSlots
[i
]->Params
.EffectType
== AL_EFFECT_NULL
)
1061 SendSlots
[i
] = nullptr;
1062 RoomRolloff
[i
] = 0.0f
;
1063 DecayDistance
[i
] = 0.0f
;
1064 DecayLFDistance
[i
] = 0.0f
;
1065 DecayHFDistance
[i
] = 0.0f
;
1067 else if(SendSlots
[i
]->Params
.AuxSendAuto
)
1069 RoomRolloff
[i
] = SendSlots
[i
]->Params
.RoomRolloff
+ props
->RoomRolloffFactor
;
1070 /* Calculate the distances to where this effect's decay reaches
1073 DecayDistance
[i
] = SendSlots
[i
]->Params
.DecayTime
* SPEEDOFSOUNDMETRESPERSEC
;
1074 DecayLFDistance
[i
] = DecayDistance
[i
] * SendSlots
[i
]->Params
.DecayLFRatio
;
1075 DecayHFDistance
[i
] = DecayDistance
[i
] * SendSlots
[i
]->Params
.DecayHFRatio
;
1076 if(SendSlots
[i
]->Params
.DecayHFLimit
)
1078 ALfloat airAbsorption
{SendSlots
[i
]->Params
.AirAbsorptionGainHF
};
1079 if(airAbsorption
< 1.0f
)
1081 /* Calculate the distance to where this effect's air
1082 * absorption reaches -60dB, and limit the effect's HF
1083 * decay distance (so it doesn't take any longer to decay
1084 * than the air would allow).
1086 ALfloat absorb_dist
{std::log10(REVERB_DECAY_GAIN
) / std::log10(airAbsorption
)};
1087 DecayHFDistance
[i
] = minf(absorb_dist
, DecayHFDistance
[i
]);
1093 /* If the slot's auxiliary send auto is off, the data sent to the
1094 * effect slot is the same as the dry path, sans filter effects */
1095 RoomRolloff
[i
] = props
->RolloffFactor
;
1096 DecayDistance
[i
] = 0.0f
;
1097 DecayLFDistance
[i
] = 0.0f
;
1098 DecayHFDistance
[i
] = 0.0f
;
1102 voice
->mSend
[i
].Buffer
= {};
1104 voice
->mSend
[i
].Buffer
= SendSlots
[i
]->Wet
.Buffer
;
1107 /* Transform source to listener space (convert to head relative) */
1108 alu::Vector Position
{props
->Position
[0], props
->Position
[1], props
->Position
[2], 1.0f
};
1109 alu::Vector Velocity
{props
->Velocity
[0], props
->Velocity
[1], props
->Velocity
[2], 0.0f
};
1110 alu::Vector Direction
{props
->Direction
[0], props
->Direction
[1], props
->Direction
[2], 0.0f
};
1111 if(props
->HeadRelative
== AL_FALSE
)
1113 /* Transform source vectors */
1114 Position
= Listener
.Params
.Matrix
* Position
;
1115 Velocity
= Listener
.Params
.Matrix
* Velocity
;
1116 Direction
= Listener
.Params
.Matrix
* Direction
;
1120 /* Offset the source velocity to be relative of the listener velocity */
1121 Velocity
+= Listener
.Params
.Velocity
;
1124 const bool directional
{Direction
.normalize() > 0.0f
};
1125 alu::Vector ToSource
{Position
[0], Position
[1], Position
[2], 0.0f
};
1126 const ALfloat Distance
{ToSource
.normalize()};
1128 /* Initial source gain */
1129 ALfloat DryGain
{props
->Gain
};
1130 ALfloat DryGainHF
{1.0f
};
1131 ALfloat DryGainLF
{1.0f
};
1132 ALfloat WetGain
[MAX_SENDS
], WetGainHF
[MAX_SENDS
], WetGainLF
[MAX_SENDS
];
1133 for(ALuint i
{0};i
< NumSends
;i
++)
1135 WetGain
[i
] = props
->Gain
;
1136 WetGainHF
[i
] = 1.0f
;
1137 WetGainLF
[i
] = 1.0f
;
1140 /* Calculate distance attenuation */
1141 ALfloat ClampedDist
{Distance
};
1143 switch(Listener
.Params
.SourceDistanceModel
?
1144 props
->mDistanceModel
: Listener
.Params
.mDistanceModel
)
1146 case DistanceModel::InverseClamped
:
1147 ClampedDist
= clampf(ClampedDist
, props
->RefDistance
, props
->MaxDistance
);
1148 if(props
->MaxDistance
< props
->RefDistance
) break;
1150 case DistanceModel::Inverse
:
1151 if(!(props
->RefDistance
> 0.0f
))
1152 ClampedDist
= props
->RefDistance
;
1155 ALfloat dist
= lerp(props
->RefDistance
, ClampedDist
, props
->RolloffFactor
);
1156 if(dist
> 0.0f
) DryGain
*= props
->RefDistance
/ dist
;
1157 for(ALuint i
{0};i
< NumSends
;i
++)
1159 dist
= lerp(props
->RefDistance
, ClampedDist
, RoomRolloff
[i
]);
1160 if(dist
> 0.0f
) WetGain
[i
] *= props
->RefDistance
/ dist
;
1165 case DistanceModel::LinearClamped
:
1166 ClampedDist
= clampf(ClampedDist
, props
->RefDistance
, props
->MaxDistance
);
1167 if(props
->MaxDistance
< props
->RefDistance
) break;
1169 case DistanceModel::Linear
:
1170 if(!(props
->MaxDistance
!= props
->RefDistance
))
1171 ClampedDist
= props
->RefDistance
;
1174 ALfloat attn
= props
->RolloffFactor
* (ClampedDist
-props
->RefDistance
) /
1175 (props
->MaxDistance
-props
->RefDistance
);
1176 DryGain
*= maxf(1.0f
- attn
, 0.0f
);
1177 for(ALuint i
{0};i
< NumSends
;i
++)
1179 attn
= RoomRolloff
[i
] * (ClampedDist
-props
->RefDistance
) /
1180 (props
->MaxDistance
-props
->RefDistance
);
1181 WetGain
[i
] *= maxf(1.0f
- attn
, 0.0f
);
1186 case DistanceModel::ExponentClamped
:
1187 ClampedDist
= clampf(ClampedDist
, props
->RefDistance
, props
->MaxDistance
);
1188 if(props
->MaxDistance
< props
->RefDistance
) break;
1190 case DistanceModel::Exponent
:
1191 if(!(ClampedDist
> 0.0f
&& props
->RefDistance
> 0.0f
))
1192 ClampedDist
= props
->RefDistance
;
1195 DryGain
*= std::pow(ClampedDist
/props
->RefDistance
, -props
->RolloffFactor
);
1196 for(ALuint i
{0};i
< NumSends
;i
++)
1197 WetGain
[i
] *= std::pow(ClampedDist
/props
->RefDistance
, -RoomRolloff
[i
]);
1201 case DistanceModel::Disable
:
1202 ClampedDist
= props
->RefDistance
;
1206 /* Calculate directional soundcones */
1207 if(directional
&& props
->InnerAngle
< 360.0f
)
1209 const ALfloat Angle
{Rad2Deg(std::acos(-aluDotproduct(Direction
, ToSource
)) *
1212 ALfloat ConeVolume
, ConeHF
;
1213 if(!(Angle
> props
->InnerAngle
))
1218 else if(Angle
< props
->OuterAngle
)
1220 ALfloat scale
= ( Angle
-props
->InnerAngle
) /
1221 (props
->OuterAngle
-props
->InnerAngle
);
1222 ConeVolume
= lerp(1.0f
, props
->OuterGain
, scale
);
1223 ConeHF
= lerp(1.0f
, props
->OuterGainHF
, scale
);
1227 ConeVolume
= props
->OuterGain
;
1228 ConeHF
= props
->OuterGainHF
;
1231 DryGain
*= ConeVolume
;
1232 if(props
->DryGainHFAuto
)
1233 DryGainHF
*= ConeHF
;
1234 if(props
->WetGainAuto
)
1235 std::transform(std::begin(WetGain
), std::begin(WetGain
)+NumSends
, std::begin(WetGain
),
1236 [ConeVolume
](ALfloat gain
) noexcept
-> ALfloat
{ return gain
* ConeVolume
; }
1238 if(props
->WetGainHFAuto
)
1239 std::transform(std::begin(WetGainHF
), std::begin(WetGainHF
)+NumSends
,
1240 std::begin(WetGainHF
),
1241 [ConeHF
](ALfloat gain
) noexcept
-> ALfloat
{ return gain
* ConeHF
; }
1245 /* Apply gain and frequency filters */
1246 DryGain
= clampf(DryGain
, props
->MinGain
, props
->MaxGain
);
1247 DryGain
= minf(DryGain
*props
->Direct
.Gain
*Listener
.Params
.Gain
, GAIN_MIX_MAX
);
1248 DryGainHF
*= props
->Direct
.GainHF
;
1249 DryGainLF
*= props
->Direct
.GainLF
;
1250 for(ALuint i
{0};i
< NumSends
;i
++)
1252 WetGain
[i
] = clampf(WetGain
[i
], props
->MinGain
, props
->MaxGain
);
1253 WetGain
[i
] = minf(WetGain
[i
]*props
->Send
[i
].Gain
*Listener
.Params
.Gain
, GAIN_MIX_MAX
);
1254 WetGainHF
[i
] *= props
->Send
[i
].GainHF
;
1255 WetGainLF
[i
] *= props
->Send
[i
].GainLF
;
1258 /* Distance-based air absorption and initial send decay. */
1259 if(ClampedDist
> props
->RefDistance
&& props
->RolloffFactor
> 0.0f
)
1261 ALfloat meters_base
{(ClampedDist
-props
->RefDistance
) * props
->RolloffFactor
*
1262 Listener
.Params
.MetersPerUnit
};
1263 if(props
->AirAbsorptionFactor
> 0.0f
)
1265 ALfloat hfattn
{std::pow(AIRABSORBGAINHF
, meters_base
* props
->AirAbsorptionFactor
)};
1266 DryGainHF
*= hfattn
;
1267 std::transform(std::begin(WetGainHF
), std::begin(WetGainHF
)+NumSends
,
1268 std::begin(WetGainHF
),
1269 [hfattn
](ALfloat gain
) noexcept
-> ALfloat
{ return gain
* hfattn
; }
1273 if(props
->WetGainAuto
)
1275 /* Apply a decay-time transformation to the wet path, based on the
1276 * source distance in meters. The initial decay of the reverb
1277 * effect is calculated and applied to the wet path.
1279 for(ALuint i
{0};i
< NumSends
;i
++)
1281 if(!(DecayDistance
[i
] > 0.0f
))
1284 const ALfloat gain
{std::pow(REVERB_DECAY_GAIN
, meters_base
/DecayDistance
[i
])};
1286 /* Yes, the wet path's air absorption is applied with
1287 * WetGainAuto on, rather than WetGainHFAuto.
1291 ALfloat gainhf
{std::pow(REVERB_DECAY_GAIN
, meters_base
/DecayHFDistance
[i
])};
1292 WetGainHF
[i
] *= minf(gainhf
/ gain
, 1.0f
);
1293 ALfloat gainlf
{std::pow(REVERB_DECAY_GAIN
, meters_base
/DecayLFDistance
[i
])};
1294 WetGainLF
[i
] *= minf(gainlf
/ gain
, 1.0f
);
1301 /* Initial source pitch */
1302 ALfloat Pitch
{props
->Pitch
};
1304 /* Calculate velocity-based doppler effect */
1305 ALfloat DopplerFactor
{props
->DopplerFactor
* Listener
.Params
.DopplerFactor
};
1306 if(DopplerFactor
> 0.0f
)
1308 const alu::Vector
&lvelocity
= Listener
.Params
.Velocity
;
1309 ALfloat vss
{aluDotproduct(Velocity
, ToSource
) * -DopplerFactor
};
1310 ALfloat vls
{aluDotproduct(lvelocity
, ToSource
) * -DopplerFactor
};
1312 const ALfloat SpeedOfSound
{Listener
.Params
.SpeedOfSound
};
1313 if(!(vls
< SpeedOfSound
))
1315 /* Listener moving away from the source at the speed of sound.
1316 * Sound waves can't catch it.
1320 else if(!(vss
< SpeedOfSound
))
1322 /* Source moving toward the listener at the speed of sound. Sound
1323 * waves bunch up to extreme frequencies.
1325 Pitch
= std::numeric_limits
<float>::infinity();
1329 /* Source and listener movement is nominal. Calculate the proper
1332 Pitch
*= (SpeedOfSound
-vls
) / (SpeedOfSound
-vss
);
1336 /* Adjust pitch based on the buffer and output frequencies, and calculate
1337 * fixed-point stepping value.
1339 Pitch
*= static_cast<ALfloat
>(voice
->mFrequency
)/static_cast<ALfloat
>(Device
->Frequency
);
1340 if(Pitch
> float{MAX_PITCH
})
1341 voice
->mStep
= MAX_PITCH
<<FRACTIONBITS
;
1343 voice
->mStep
= maxu(fastf2u(Pitch
* FRACTIONONE
), 1);
1344 voice
->mResampler
= PrepareResampler(props
->mResampler
, voice
->mStep
, &voice
->mResampleState
);
1346 ALfloat spread
{0.0f
};
1347 if(props
->Radius
> Distance
)
1348 spread
= al::MathDefs
<float>::Tau() - Distance
/props
->Radius
*al::MathDefs
<float>::Pi();
1349 else if(Distance
> 0.0f
)
1350 spread
= std::asin(props
->Radius
/Distance
) * 2.0f
;
1352 CalcPanningAndFilters(voice
, ToSource
[0], ToSource
[1], ToSource
[2]*ZScale
,
1353 Distance
*Listener
.Params
.MetersPerUnit
, spread
, DryGain
, DryGainHF
, DryGainLF
, WetGain
,
1354 WetGainLF
, WetGainHF
, SendSlots
, props
, Listener
, Device
);
1357 void CalcSourceParams(ALvoice
*voice
, ALCcontext
*context
, bool force
)
1359 ALvoiceProps
*props
{voice
->mUpdate
.exchange(nullptr, std::memory_order_acq_rel
)};
1360 if(!props
&& !force
) return;
1364 voice
->mProps
= *props
;
1366 AtomicReplaceHead(context
->mFreeVoiceProps
, props
);
1369 if((voice
->mProps
.mSpatializeMode
== SpatializeAuto
&& voice
->mFmtChannels
== FmtMono
) ||
1370 voice
->mProps
.mSpatializeMode
== SpatializeOn
)
1371 CalcAttnSourceParams(voice
, &voice
->mProps
, context
);
1373 CalcNonAttnSourceParams(voice
, &voice
->mProps
, context
);
1377 void ProcessParamUpdates(ALCcontext
*ctx
, const ALeffectslotArray
&slots
,
1378 const al::span
<ALvoice
> voices
)
1380 IncrementRef(ctx
->mUpdateCount
);
1381 if LIKELY(!ctx
->mHoldUpdates
.load(std::memory_order_acquire
))
1383 bool force
{CalcContextParams(ctx
)};
1384 force
|= CalcListenerParams(ctx
);
1385 force
= std::accumulate(slots
.begin(), slots
.end(), force
,
1386 [ctx
](const bool f
, ALeffectslot
*slot
) -> bool
1387 { return CalcEffectSlotParams(slot
, ctx
) | f
; }
1390 auto calc_params
= [ctx
,force
](ALvoice
&voice
) -> void
1392 if(voice
.mSourceID
.load(std::memory_order_acquire
) != 0)
1393 CalcSourceParams(&voice
, ctx
, force
);
1395 std::for_each(voices
.begin(), voices
.end(), calc_params
);
1397 IncrementRef(ctx
->mUpdateCount
);
1400 void ProcessContext(ALCcontext
*ctx
, const ALuint SamplesToDo
)
1402 ASSUME(SamplesToDo
> 0);
1404 const ALeffectslotArray
&auxslots
= *ctx
->mActiveAuxSlots
.load(std::memory_order_acquire
);
1405 const al::span
<ALvoice
> voices
{ctx
->mVoices
.data(), ctx
->mVoices
.size()};
1407 /* Process pending propery updates for objects on the context. */
1408 ProcessParamUpdates(ctx
, auxslots
, voices
);
1410 /* Clear auxiliary effect slot mixing buffers. */
1411 std::for_each(auxslots
.begin(), auxslots
.end(),
1412 [SamplesToDo
](ALeffectslot
*slot
) -> void
1414 for(auto &buffer
: slot
->MixBuffer
)
1415 std::fill_n(buffer
.begin(), SamplesToDo
, 0.0f
);
1419 /* Process voices that have a playing source. */
1420 std::for_each(voices
.begin(), voices
.end(),
1421 [SamplesToDo
,ctx
](ALvoice
&voice
) -> void
1423 const ALvoice::State vstate
{voice
.mPlayState
.load(std::memory_order_acquire
)};
1424 if(vstate
!= ALvoice::Stopped
) voice
.mix(vstate
, ctx
, SamplesToDo
);
1428 /* Process effects. */
1429 if(auxslots
.empty()) return;
1430 auto slots
= auxslots
.data();
1431 auto slots_end
= slots
+ auxslots
.size();
1433 /* First sort the slots into scratch storage, so that effects come before
1434 * their effect target (or their targets' target).
1436 auto sorted_slots
= const_cast<ALeffectslot
**>(slots_end
);
1437 auto sorted_slots_end
= sorted_slots
;
1438 auto in_chain
= [](const ALeffectslot
*slot1
, const ALeffectslot
*slot2
) noexcept
-> bool
1440 while((slot1
=slot1
->Params
.Target
) != nullptr) {
1441 if(slot1
== slot2
) return true;
1446 *sorted_slots_end
= *slots
;
1448 while(++slots
!= slots_end
)
1450 /* If this effect slot targets an effect slot already in the list (i.e.
1451 * slots outputs to something in sorted_slots), directly or indirectly,
1452 * insert it prior to that element.
1454 auto checker
= sorted_slots
;
1456 if(in_chain(*slots
, *checker
)) break;
1457 } while(++checker
!= sorted_slots_end
);
1459 checker
= std::move_backward(checker
, sorted_slots_end
, sorted_slots_end
+1);
1460 *--checker
= *slots
;
1464 std::for_each(sorted_slots
, sorted_slots_end
,
1465 [SamplesToDo
](const ALeffectslot
*slot
) -> void
1467 EffectState
*state
{slot
->Params
.mEffectState
};
1468 state
->process(SamplesToDo
, slot
->Wet
.Buffer
, state
->mOutTarget
);
1474 void ApplyStablizer(FrontStablizer
*Stablizer
, const al::span
<FloatBufferLine
> Buffer
,
1475 const ALuint lidx
, const ALuint ridx
, const ALuint cidx
, const ALuint SamplesToDo
)
1477 ASSUME(SamplesToDo
> 0);
1479 /* Apply a delay to all channels, except the front-left and front-right, so
1480 * they maintain correct timing.
1482 const size_t NumChannels
{Buffer
.size()};
1483 for(size_t i
{0u};i
< NumChannels
;i
++)
1485 if(i
== lidx
|| i
== ridx
)
1488 auto &DelayBuf
= Stablizer
->DelayBuf
[i
];
1489 auto buffer_end
= Buffer
[i
].begin() + SamplesToDo
;
1490 if LIKELY(SamplesToDo
>= ALuint
{FrontStablizer::DelayLength
})
1492 auto delay_end
= std::rotate(Buffer
[i
].begin(),
1493 buffer_end
- FrontStablizer::DelayLength
, buffer_end
);
1494 std::swap_ranges(Buffer
[i
].begin(), delay_end
, std::begin(DelayBuf
));
1498 auto delay_start
= std::swap_ranges(Buffer
[i
].begin(), buffer_end
,
1499 std::begin(DelayBuf
));
1500 std::rotate(std::begin(DelayBuf
), delay_start
, std::end(DelayBuf
));
1504 ALfloat (&lsplit
)[2][BUFFERSIZE
] = Stablizer
->LSplit
;
1505 ALfloat (&rsplit
)[2][BUFFERSIZE
] = Stablizer
->RSplit
;
1506 auto &tmpbuf
= Stablizer
->TempBuf
;
1508 /* This applies the band-splitter, preserving phase at the cost of some
1509 * delay. The shorter the delay, the more error seeps into the result.
1511 auto apply_splitter
= [&tmpbuf
,SamplesToDo
](const FloatBufferLine
&InBuf
,
1512 ALfloat (&DelayBuf
)[FrontStablizer::DelayLength
], BandSplitter
&Filter
,
1513 ALfloat (&splitbuf
)[2][BUFFERSIZE
]) -> void
1515 /* Combine the delayed samples and the input samples into the temp
1516 * buffer, in reverse. Then copy the final samples back into the delay
1517 * buffer for next time. Note that the delay buffer's samples are
1518 * stored backwards here.
1520 auto tmpbuf_end
= std::begin(tmpbuf
) + SamplesToDo
;
1521 std::copy_n(std::begin(DelayBuf
), FrontStablizer::DelayLength
, tmpbuf_end
);
1522 std::reverse_copy(InBuf
.begin(), InBuf
.begin()+SamplesToDo
, std::begin(tmpbuf
));
1523 std::copy_n(std::begin(tmpbuf
), FrontStablizer::DelayLength
, std::begin(DelayBuf
));
1525 /* Apply an all-pass on the reversed signal, then reverse the samples
1526 * to get the forward signal with a reversed phase shift.
1528 Filter
.applyAllpass(tmpbuf
, SamplesToDo
+FrontStablizer::DelayLength
);
1529 std::reverse(std::begin(tmpbuf
), tmpbuf_end
+FrontStablizer::DelayLength
);
1531 /* Now apply the band-splitter, combining its phase shift with the
1532 * reversed phase shift, restoring the original phase on the split
1535 Filter
.process(splitbuf
[1], splitbuf
[0], tmpbuf
, SamplesToDo
);
1537 apply_splitter(Buffer
[lidx
], Stablizer
->DelayBuf
[lidx
], Stablizer
->LFilter
, lsplit
);
1538 apply_splitter(Buffer
[ridx
], Stablizer
->DelayBuf
[ridx
], Stablizer
->RFilter
, rsplit
);
1540 for(ALuint i
{0};i
< SamplesToDo
;i
++)
1542 ALfloat lfsum
{lsplit
[0][i
] + rsplit
[0][i
]};
1543 ALfloat hfsum
{lsplit
[1][i
] + rsplit
[1][i
]};
1544 ALfloat s
{lsplit
[0][i
] + lsplit
[1][i
] - rsplit
[0][i
] - rsplit
[1][i
]};
1546 /* This pans the separate low- and high-frequency sums between being on
1547 * the center channel and the left/right channels. The low-frequency
1548 * sum is 1/3rd toward center (2/3rds on left/right) and the high-
1549 * frequency sum is 1/4th toward center (3/4ths on left/right). These
1550 * values can be tweaked.
1552 ALfloat m
{lfsum
*std::cos(1.0f
/3.0f
* (al::MathDefs
<float>::Pi()*0.5f
)) +
1553 hfsum
*std::cos(1.0f
/4.0f
* (al::MathDefs
<float>::Pi()*0.5f
))};
1554 ALfloat c
{lfsum
*std::sin(1.0f
/3.0f
* (al::MathDefs
<float>::Pi()*0.5f
)) +
1555 hfsum
*std::sin(1.0f
/4.0f
* (al::MathDefs
<float>::Pi()*0.5f
))};
1557 /* The generated center channel signal adds to the existing signal,
1558 * while the modified left and right channels replace.
1560 Buffer
[lidx
][i
] = (m
+ s
) * 0.5f
;
1561 Buffer
[ridx
][i
] = (m
- s
) * 0.5f
;
1562 Buffer
[cidx
][i
] += c
* 0.5f
;
1566 void ApplyDistanceComp(const al::span
<FloatBufferLine
> Samples
, const ALuint SamplesToDo
,
1567 const DistanceComp::DistData
*distcomp
)
1569 ASSUME(SamplesToDo
> 0);
1571 for(auto &chanbuffer
: Samples
)
1573 const ALfloat gain
{distcomp
->Gain
};
1574 const ALuint base
{distcomp
->Length
};
1575 ALfloat
*distbuf
{al::assume_aligned
<16>(distcomp
->Buffer
)};
1581 ALfloat
*inout
{al::assume_aligned
<16>(chanbuffer
.data())};
1582 auto inout_end
= inout
+ SamplesToDo
;
1583 if LIKELY(SamplesToDo
>= base
)
1585 auto delay_end
= std::rotate(inout
, inout_end
- base
, inout_end
);
1586 std::swap_ranges(inout
, delay_end
, distbuf
);
1590 auto delay_start
= std::swap_ranges(inout
, inout_end
, distbuf
);
1591 std::rotate(distbuf
, delay_start
, distbuf
+ base
);
1593 std::transform(inout
, inout_end
, inout
, std::bind(std::multiplies
<float>{}, _1
, gain
));
1597 void ApplyDither(const al::span
<FloatBufferLine
> Samples
, ALuint
*dither_seed
,
1598 const ALfloat quant_scale
, const ALuint SamplesToDo
)
1600 /* Dithering. Generate whitenoise (uniform distribution of random values
1601 * between -1 and +1) and add it to the sample values, after scaling up to
1602 * the desired quantization depth amd before rounding.
1604 const ALfloat invscale
{1.0f
/ quant_scale
};
1605 ALuint seed
{*dither_seed
};
1606 auto dither_channel
= [&seed
,invscale
,quant_scale
,SamplesToDo
](FloatBufferLine
&input
) -> void
1608 ASSUME(SamplesToDo
> 0);
1609 auto dither_sample
= [&seed
,invscale
,quant_scale
](const ALfloat sample
) noexcept
-> ALfloat
1611 ALfloat val
{sample
* quant_scale
};
1612 ALuint rng0
{dither_rng(&seed
)};
1613 ALuint rng1
{dither_rng(&seed
)};
1614 val
+= static_cast<ALfloat
>(rng0
*(1.0/UINT_MAX
) - rng1
*(1.0/UINT_MAX
));
1615 return fast_roundf(val
) * invscale
;
1617 std::transform(input
.begin(), input
.begin()+SamplesToDo
, input
.begin(), dither_sample
);
1619 std::for_each(Samples
.begin(), Samples
.end(), dither_channel
);
1620 *dither_seed
= seed
;
1624 /* Base template left undefined. Should be marked =delete, but Clang 3.8.1
1625 * chokes on that given the inline specializations.
1627 template<typename T
>
1628 inline T
SampleConv(ALfloat
) noexcept
;
1630 template<> inline ALfloat
SampleConv(ALfloat val
) noexcept
1632 template<> inline ALint
SampleConv(ALfloat val
) noexcept
1634 /* Floats have a 23-bit mantissa, plus an implied 1 bit and a sign bit.
1635 * This means a normalized float has at most 25 bits of signed precision.
1636 * When scaling and clamping for a signed 32-bit integer, these following
1637 * values are the best a float can give.
1639 return fastf2i(clampf(val
*2147483648.0f
, -2147483648.0f
, 2147483520.0f
));
1641 template<> inline ALshort
SampleConv(ALfloat val
) noexcept
1642 { return static_cast<ALshort
>(fastf2i(clampf(val
*32768.0f
, -32768.0f
, 32767.0f
))); }
1643 template<> inline ALbyte
SampleConv(ALfloat val
) noexcept
1644 { return static_cast<ALbyte
>(fastf2i(clampf(val
*128.0f
, -128.0f
, 127.0f
))); }
1646 /* Define unsigned output variations. */
1647 template<> inline ALuint
SampleConv(ALfloat val
) noexcept
1648 { return static_cast<ALuint
>(SampleConv
<ALint
>(val
)) + 2147483648u; }
1649 template<> inline ALushort
SampleConv(ALfloat val
) noexcept
1650 { return static_cast<ALushort
>(SampleConv
<ALshort
>(val
) + 32768); }
1651 template<> inline ALubyte
SampleConv(ALfloat val
) noexcept
1652 { return static_cast<ALubyte
>(SampleConv
<ALbyte
>(val
) + 128); }
1654 template<DevFmtType T
>
1655 void Write(const al::span
<const FloatBufferLine
> InBuffer
, ALvoid
*OutBuffer
, const size_t Offset
,
1656 const ALuint SamplesToDo
)
1658 using SampleType
= typename DevFmtTypeTraits
<T
>::Type
;
1660 const size_t numchans
{InBuffer
.size()};
1661 ASSUME(numchans
> 0);
1663 SampleType
*outbase
= static_cast<SampleType
*>(OutBuffer
) + Offset
*numchans
;
1664 auto conv_channel
= [&outbase
,SamplesToDo
,numchans
](const FloatBufferLine
&inbuf
) -> void
1666 ASSUME(SamplesToDo
> 0);
1667 SampleType
*out
{outbase
++};
1668 auto conv_sample
= [numchans
,&out
](const ALfloat s
) noexcept
-> void
1670 *out
= SampleConv
<SampleType
>(s
);
1673 std::for_each(inbuf
.begin(), inbuf
.begin()+SamplesToDo
, conv_sample
);
1675 std::for_each(InBuffer
.cbegin(), InBuffer
.cend(), conv_channel
);
1680 void aluMixData(ALCdevice
*device
, ALvoid
*OutBuffer
, const ALuint NumSamples
)
1682 FPUCtl mixer_mode
{};
1683 for(ALuint SamplesDone
{0u};SamplesDone
< NumSamples
;)
1685 const ALuint SamplesToDo
{minu(NumSamples
-SamplesDone
, BUFFERSIZE
)};
1687 /* Clear main mixing buffers. */
1688 std::for_each(device
->MixBuffer
.begin(), device
->MixBuffer
.end(),
1689 [SamplesToDo
](std::array
<ALfloat
,BUFFERSIZE
> &buffer
) -> void
1690 { std::fill_n(buffer
.begin(), SamplesToDo
, 0.0f
); }
1693 /* Increment the mix count at the start (lsb should now be 1). */
1694 IncrementRef(device
->MixCount
);
1696 /* For each context on this device, process and mix its sources and
1699 for(ALCcontext
*ctx
: *device
->mContexts
.load(std::memory_order_acquire
))
1700 ProcessContext(ctx
, SamplesToDo
);
1702 /* Increment the clock time. Every second's worth of samples is
1703 * converted and added to clock base so that large sample counts don't
1704 * overflow during conversion. This also guarantees a stable
1707 device
->SamplesDone
+= SamplesToDo
;
1708 device
->ClockBase
+= std::chrono::seconds
{device
->SamplesDone
/ device
->Frequency
};
1709 device
->SamplesDone
%= device
->Frequency
;
1711 /* Increment the mix count at the end (lsb should now be 0). */
1712 IncrementRef(device
->MixCount
);
1714 /* Apply any needed post-process for finalizing the Dry mix to the
1715 * RealOut (Ambisonic decode, UHJ encode, etc).
1717 device
->postProcess(SamplesToDo
);
1719 const al::span
<FloatBufferLine
> RealOut
{device
->RealOut
.Buffer
};
1721 /* Apply front image stablization for surround sound, if applicable. */
1722 if(device
->Stablizer
)
1724 const ALuint lidx
{GetChannelIdxByName(device
->RealOut
, FrontLeft
)};
1725 const ALuint ridx
{GetChannelIdxByName(device
->RealOut
, FrontRight
)};
1726 const ALuint cidx
{GetChannelIdxByName(device
->RealOut
, FrontCenter
)};
1728 ApplyStablizer(device
->Stablizer
.get(), RealOut
, lidx
, ridx
, cidx
, SamplesToDo
);
1731 /* Apply compression, limiting sample amplitude if needed or desired. */
1732 if(Compressor
*comp
{device
->Limiter
.get()})
1733 comp
->process(SamplesToDo
, RealOut
.data());
1735 /* Apply delays and attenuation for mismatched speaker distances. */
1736 ApplyDistanceComp(RealOut
, SamplesToDo
, device
->ChannelDelay
.as_span().cbegin());
1738 /* Apply dithering. The compressor should have left enough headroom for
1739 * the dither noise to not saturate.
1741 if(device
->DitherDepth
> 0.0f
)
1742 ApplyDither(RealOut
, &device
->DitherSeed
, device
->DitherDepth
, SamplesToDo
);
1744 if LIKELY(OutBuffer
)
1746 /* Finally, interleave and convert samples, writing to the device's
1749 switch(device
->FmtType
)
1751 #define HANDLE_WRITE(T) case T: \
1752 Write<T>(RealOut, OutBuffer, SamplesDone, SamplesToDo); break;
1753 HANDLE_WRITE(DevFmtByte
)
1754 HANDLE_WRITE(DevFmtUByte
)
1755 HANDLE_WRITE(DevFmtShort
)
1756 HANDLE_WRITE(DevFmtUShort
)
1757 HANDLE_WRITE(DevFmtInt
)
1758 HANDLE_WRITE(DevFmtUInt
)
1759 HANDLE_WRITE(DevFmtFloat
)
1764 SamplesDone
+= SamplesToDo
;
1769 void aluHandleDisconnect(ALCdevice
*device
, const char *msg
, ...)
1771 if(!device
->Connected
.exchange(false, std::memory_order_acq_rel
))
1774 AsyncEvent evt
{EventType_Disconnected
};
1775 evt
.u
.user
.type
= AL_EVENT_TYPE_DISCONNECTED_SOFT
;
1777 evt
.u
.user
.param
= 0;
1780 va_start(args
, msg
);
1781 int msglen
{vsnprintf(evt
.u
.user
.msg
, sizeof(evt
.u
.user
.msg
), msg
, args
)};
1784 if(msglen
< 0 || static_cast<size_t>(msglen
) >= sizeof(evt
.u
.user
.msg
))
1785 evt
.u
.user
.msg
[sizeof(evt
.u
.user
.msg
)-1] = 0;
1787 IncrementRef(device
->MixCount
);
1788 for(ALCcontext
*ctx
: *device
->mContexts
.load())
1790 const ALbitfieldSOFT enabledevt
{ctx
->mEnabledEvts
.load(std::memory_order_acquire
)};
1791 if((enabledevt
&EventType_Disconnected
))
1793 RingBuffer
*ring
{ctx
->mAsyncEvents
.get()};
1794 auto evt_data
= ring
->getWriteVector().first
;
1795 if(evt_data
.len
> 0)
1797 ::new (evt_data
.buf
) AsyncEvent
{evt
};
1798 ring
->writeAdvance(1);
1799 ctx
->mEventSem
.post();
1803 auto stop_voice
= [](ALvoice
&voice
) -> void
1805 voice
.mCurrentBuffer
.store(nullptr, std::memory_order_relaxed
);
1806 voice
.mLoopBuffer
.store(nullptr, std::memory_order_relaxed
);
1807 voice
.mSourceID
.store(0u, std::memory_order_relaxed
);
1808 voice
.mPlayState
.store(ALvoice::Stopped
, std::memory_order_release
);
1810 std::for_each(ctx
->mVoices
.begin(), ctx
->mVoices
.end(), stop_voice
);
1812 IncrementRef(device
->MixCount
);