Use a union to combine HRTF and non-HRTF mixer params
[openal-soft.git] / Alc / ALu.c
blobca38e737f7cb59d6cf53a25ea88613be8c7f1657
1 /**
2 * OpenAL cross platform audio library
3 * Copyright (C) 1999-2007 by authors.
4 * This library is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Library General Public
6 * License as published by the Free Software Foundation; either
7 * version 2 of the License, or (at your option) any later version.
9 * This library is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Library General Public License for more details.
14 * You should have received a copy of the GNU Library General Public
15 * License along with this library; if not, write to the
16 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17 * Boston, MA 02111-1307, USA.
18 * Or go to http://www.gnu.org/copyleft/lgpl.html
21 #include "config.h"
23 #include <math.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <ctype.h>
27 #include <assert.h>
29 #include "alMain.h"
30 #include "alSource.h"
31 #include "alBuffer.h"
32 #include "alListener.h"
33 #include "alAuxEffectSlot.h"
34 #include "alu.h"
35 #include "bs2b.h"
36 #include "hrtf.h"
38 #include "mixer_defs.h"
40 #include "midi/base.h"
43 struct ChanMap {
44 enum Channel channel;
45 ALfloat angle;
48 /* Cone scalar */
49 ALfloat ConeScale = 1.0f;
51 /* Localized Z scalar for mono sources */
52 ALfloat ZScale = 1.0f;
54 extern inline ALfloat minf(ALfloat a, ALfloat b);
55 extern inline ALfloat maxf(ALfloat a, ALfloat b);
56 extern inline ALfloat clampf(ALfloat val, ALfloat min, ALfloat max);
58 extern inline ALdouble mind(ALdouble a, ALdouble b);
59 extern inline ALdouble maxd(ALdouble a, ALdouble b);
60 extern inline ALdouble clampd(ALdouble val, ALdouble min, ALdouble max);
62 extern inline ALuint minu(ALuint a, ALuint b);
63 extern inline ALuint maxu(ALuint a, ALuint b);
64 extern inline ALuint clampu(ALuint val, ALuint min, ALuint max);
66 extern inline ALint mini(ALint a, ALint b);
67 extern inline ALint maxi(ALint a, ALint b);
68 extern inline ALint clampi(ALint val, ALint min, ALint max);
70 extern inline ALint64 mini64(ALint64 a, ALint64 b);
71 extern inline ALint64 maxi64(ALint64 a, ALint64 b);
72 extern inline ALint64 clampi64(ALint64 val, ALint64 min, ALint64 max);
74 extern inline ALuint64 minu64(ALuint64 a, ALuint64 b);
75 extern inline ALuint64 maxu64(ALuint64 a, ALuint64 b);
76 extern inline ALuint64 clampu64(ALuint64 val, ALuint64 min, ALuint64 max);
78 extern inline ALfloat lerp(ALfloat val1, ALfloat val2, ALfloat mu);
79 extern inline ALfloat cubic(ALfloat val0, ALfloat val1, ALfloat val2, ALfloat val3, ALfloat mu);
81 static ResamplerFunc SelectResampler(enum Resampler Resampler, ALuint increment)
83 if(increment == FRACTIONONE)
84 return Resample_copy32_C;
85 switch(Resampler)
87 case PointResampler:
88 return Resample_point32_C;
89 case LinearResampler:
90 return Resample_lerp32_C;
91 case CubicResampler:
92 return Resample_cubic32_C;
93 case ResamplerMax:
94 /* Shouldn't happen */
95 break;
98 return Resample_point32_C;
102 static DryMixerFunc SelectHrtfMixer(void)
104 #ifdef HAVE_SSE
105 if((CPUCapFlags&CPU_CAP_SSE))
106 return MixDirect_Hrtf_SSE;
107 #endif
108 #ifdef HAVE_NEON
109 if((CPUCapFlags&CPU_CAP_NEON))
110 return MixDirect_Hrtf_Neon;
111 #endif
113 return MixDirect_Hrtf_C;
116 static DryMixerFunc SelectDirectMixer(void)
118 #ifdef HAVE_SSE
119 if((CPUCapFlags&CPU_CAP_SSE))
120 return MixDirect_SSE;
121 #endif
122 #ifdef HAVE_NEON
123 if((CPUCapFlags&CPU_CAP_NEON))
124 return MixDirect_Neon;
125 #endif
127 return MixDirect_C;
130 static WetMixerFunc SelectSendMixer(void)
132 #ifdef HAVE_SSE
133 if((CPUCapFlags&CPU_CAP_SSE))
134 return MixSend_SSE;
135 #endif
136 #ifdef HAVE_NEON
137 if((CPUCapFlags&CPU_CAP_NEON))
138 return MixSend_Neon;
139 #endif
141 return MixSend_C;
145 static inline void aluCrossproduct(const ALfloat *inVector1, const ALfloat *inVector2, ALfloat *outVector)
147 outVector[0] = inVector1[1]*inVector2[2] - inVector1[2]*inVector2[1];
148 outVector[1] = inVector1[2]*inVector2[0] - inVector1[0]*inVector2[2];
149 outVector[2] = inVector1[0]*inVector2[1] - inVector1[1]*inVector2[0];
152 static inline ALfloat aluDotproduct(const ALfloat *inVector1, const ALfloat *inVector2)
154 return inVector1[0]*inVector2[0] + inVector1[1]*inVector2[1] +
155 inVector1[2]*inVector2[2];
158 static inline void aluNormalize(ALfloat *inVector)
160 ALfloat lengthsqr = aluDotproduct(inVector, inVector);
161 if(lengthsqr > 0.0f)
163 ALfloat inv_length = 1.0f/sqrtf(lengthsqr);
164 inVector[0] *= inv_length;
165 inVector[1] *= inv_length;
166 inVector[2] *= inv_length;
170 static inline ALvoid aluMatrixVector(ALfloat *vector, ALfloat w, ALfloat (*restrict matrix)[4])
172 ALfloat temp[4] = {
173 vector[0], vector[1], vector[2], w
176 vector[0] = temp[0]*matrix[0][0] + temp[1]*matrix[1][0] + temp[2]*matrix[2][0] + temp[3]*matrix[3][0];
177 vector[1] = temp[0]*matrix[0][1] + temp[1]*matrix[1][1] + temp[2]*matrix[2][1] + temp[3]*matrix[3][1];
178 vector[2] = temp[0]*matrix[0][2] + temp[1]*matrix[1][2] + temp[2]*matrix[2][2] + temp[3]*matrix[3][2];
182 static ALvoid CalcListenerParams(ALlistener *Listener)
184 ALfloat N[3], V[3], U[3], P[3];
186 /* AT then UP */
187 N[0] = Listener->Forward[0];
188 N[1] = Listener->Forward[1];
189 N[2] = Listener->Forward[2];
190 aluNormalize(N);
191 V[0] = Listener->Up[0];
192 V[1] = Listener->Up[1];
193 V[2] = Listener->Up[2];
194 aluNormalize(V);
195 /* Build and normalize right-vector */
196 aluCrossproduct(N, V, U);
197 aluNormalize(U);
199 Listener->Params.Matrix[0][0] = U[0];
200 Listener->Params.Matrix[0][1] = V[0];
201 Listener->Params.Matrix[0][2] = -N[0];
202 Listener->Params.Matrix[0][3] = 0.0f;
203 Listener->Params.Matrix[1][0] = U[1];
204 Listener->Params.Matrix[1][1] = V[1];
205 Listener->Params.Matrix[1][2] = -N[1];
206 Listener->Params.Matrix[1][3] = 0.0f;
207 Listener->Params.Matrix[2][0] = U[2];
208 Listener->Params.Matrix[2][1] = V[2];
209 Listener->Params.Matrix[2][2] = -N[2];
210 Listener->Params.Matrix[2][3] = 0.0f;
211 Listener->Params.Matrix[3][0] = 0.0f;
212 Listener->Params.Matrix[3][1] = 0.0f;
213 Listener->Params.Matrix[3][2] = 0.0f;
214 Listener->Params.Matrix[3][3] = 1.0f;
216 P[0] = Listener->Position[0];
217 P[1] = Listener->Position[1];
218 P[2] = Listener->Position[2];
219 aluMatrixVector(P, 1.0f, Listener->Params.Matrix);
220 Listener->Params.Matrix[3][0] = -P[0];
221 Listener->Params.Matrix[3][1] = -P[1];
222 Listener->Params.Matrix[3][2] = -P[2];
224 Listener->Params.Velocity[0] = Listener->Velocity[0];
225 Listener->Params.Velocity[1] = Listener->Velocity[1];
226 Listener->Params.Velocity[2] = Listener->Velocity[2];
227 aluMatrixVector(Listener->Params.Velocity, 0.0f, Listener->Params.Matrix);
230 ALvoid CalcNonAttnSourceParams(ALactivesource *src, const ALCcontext *ALContext)
232 static const struct ChanMap MonoMap[1] = { { FrontCenter, 0.0f } };
233 static const struct ChanMap StereoMap[2] = {
234 { FrontLeft, DEG2RAD(-30.0f) },
235 { FrontRight, DEG2RAD( 30.0f) }
237 static const struct ChanMap StereoWideMap[2] = {
238 { FrontLeft, DEG2RAD(-90.0f) },
239 { FrontRight, DEG2RAD( 90.0f) }
241 static const struct ChanMap RearMap[2] = {
242 { BackLeft, DEG2RAD(-150.0f) },
243 { BackRight, DEG2RAD( 150.0f) }
245 static const struct ChanMap QuadMap[4] = {
246 { FrontLeft, DEG2RAD( -45.0f) },
247 { FrontRight, DEG2RAD( 45.0f) },
248 { BackLeft, DEG2RAD(-135.0f) },
249 { BackRight, DEG2RAD( 135.0f) }
251 static const struct ChanMap X51Map[6] = {
252 { FrontLeft, DEG2RAD( -30.0f) },
253 { FrontRight, DEG2RAD( 30.0f) },
254 { FrontCenter, DEG2RAD( 0.0f) },
255 { LFE, 0.0f },
256 { BackLeft, DEG2RAD(-110.0f) },
257 { BackRight, DEG2RAD( 110.0f) }
259 static const struct ChanMap X61Map[7] = {
260 { FrontLeft, DEG2RAD(-30.0f) },
261 { FrontRight, DEG2RAD( 30.0f) },
262 { FrontCenter, DEG2RAD( 0.0f) },
263 { LFE, 0.0f },
264 { BackCenter, DEG2RAD(180.0f) },
265 { SideLeft, DEG2RAD(-90.0f) },
266 { SideRight, DEG2RAD( 90.0f) }
268 static const struct ChanMap X71Map[8] = {
269 { FrontLeft, DEG2RAD( -30.0f) },
270 { FrontRight, DEG2RAD( 30.0f) },
271 { FrontCenter, DEG2RAD( 0.0f) },
272 { LFE, 0.0f },
273 { BackLeft, DEG2RAD(-150.0f) },
274 { BackRight, DEG2RAD( 150.0f) },
275 { SideLeft, DEG2RAD( -90.0f) },
276 { SideRight, DEG2RAD( 90.0f) }
279 ALCdevice *Device = ALContext->Device;
280 ALsource *ALSource = src->Source;
281 ALfloat SourceVolume,ListenerGain,MinVolume,MaxVolume;
282 ALbufferlistitem *BufferListItem;
283 enum FmtChannels Channels;
284 ALfloat DryGain, DryGainHF;
285 ALfloat WetGain[MAX_SENDS];
286 ALfloat WetGainHF[MAX_SENDS];
287 ALint NumSends, Frequency;
288 const struct ChanMap *chans = NULL;
289 enum Resampler Resampler;
290 ALint num_channels = 0;
291 ALboolean DirectChannels;
292 ALfloat hwidth = 0.0f;
293 ALfloat Pitch;
294 ALint i, c;
296 /* Get device properties */
297 NumSends = Device->NumAuxSends;
298 Frequency = Device->Frequency;
300 /* Get listener properties */
301 ListenerGain = ALContext->Listener->Gain;
303 /* Get source properties */
304 SourceVolume = ALSource->Gain;
305 MinVolume = ALSource->MinGain;
306 MaxVolume = ALSource->MaxGain;
307 Pitch = ALSource->Pitch;
308 Resampler = ALSource->Resampler;
309 DirectChannels = ALSource->DirectChannels;
311 src->Direct.OutBuffer = Device->DryBuffer;
312 src->Direct.ClickRemoval = Device->ClickRemoval;
313 src->Direct.PendingClicks = Device->PendingClicks;
314 for(i = 0;i < NumSends;i++)
316 ALeffectslot *Slot = ALSource->Send[i].Slot;
317 if(!Slot && i == 0)
318 Slot = Device->DefaultSlot;
319 if(!Slot || Slot->EffectType == AL_EFFECT_NULL)
321 src->Send[i].OutBuffer = NULL;
322 src->Send[i].ClickRemoval = NULL;
323 src->Send[i].PendingClicks = NULL;
325 else
327 src->Send[i].OutBuffer = Slot->WetBuffer;
328 src->Send[i].ClickRemoval = Slot->ClickRemoval;
329 src->Send[i].PendingClicks = Slot->PendingClicks;
333 /* Calculate the stepping value */
334 Channels = FmtMono;
335 BufferListItem = ALSource->queue;
336 while(BufferListItem != NULL)
338 ALbuffer *ALBuffer;
339 if((ALBuffer=BufferListItem->buffer) != NULL)
341 Pitch = Pitch * ALBuffer->Frequency / Frequency;
342 if(Pitch > 10.0f)
343 src->Step = 10<<FRACTIONBITS;
344 else
346 src->Step = fastf2i(Pitch*FRACTIONONE);
347 if(src->Step == 0)
348 src->Step = 1;
350 src->Resample = SelectResampler(Resampler, src->Step);
352 Channels = ALBuffer->FmtChannels;
353 break;
355 BufferListItem = BufferListItem->next;
358 /* Calculate gains */
359 DryGain = clampf(SourceVolume, MinVolume, MaxVolume);
360 DryGain *= ALSource->DirectGain * ListenerGain;
361 DryGainHF = ALSource->DirectGainHF;
362 for(i = 0;i < NumSends;i++)
364 WetGain[i] = clampf(SourceVolume, MinVolume, MaxVolume);
365 WetGain[i] *= ALSource->Send[i].Gain * ListenerGain;
366 WetGainHF[i] = ALSource->Send[i].GainHF;
369 switch(Channels)
371 case FmtMono:
372 chans = MonoMap;
373 num_channels = 1;
374 break;
376 case FmtStereo:
377 if(!(Device->Flags&DEVICE_WIDE_STEREO))
379 /* HACK: Place the stereo channels at +/-90 degrees when using non-
380 * HRTF stereo output. This helps reduce the "monoization" caused
381 * by them panning towards the center. */
382 if(Device->FmtChans == DevFmtStereo && !Device->Hrtf)
383 chans = StereoWideMap;
384 else
385 chans = StereoMap;
387 else
389 chans = StereoWideMap;
390 hwidth = DEG2RAD(60.0f);
392 num_channels = 2;
393 break;
395 case FmtRear:
396 chans = RearMap;
397 num_channels = 2;
398 break;
400 case FmtQuad:
401 chans = QuadMap;
402 num_channels = 4;
403 break;
405 case FmtX51:
406 chans = X51Map;
407 num_channels = 6;
408 break;
410 case FmtX61:
411 chans = X61Map;
412 num_channels = 7;
413 break;
415 case FmtX71:
416 chans = X71Map;
417 num_channels = 8;
418 break;
421 if(DirectChannels != AL_FALSE)
423 ALfloat (*SrcMatrix)[MaxChannels] = src->Direct.Mix.Gains;
424 for(i = 0;i < MAX_INPUT_CHANNELS;i++)
426 for(c = 0;c < MaxChannels;c++)
427 SrcMatrix[i][c] = 0.0f;
429 for(c = 0;c < num_channels;c++)
431 for(i = 0;i < (ALint)Device->NumChan;i++)
433 enum Channel chan = Device->Speaker2Chan[i];
434 if(chan == chans[c].channel)
436 SrcMatrix[c][chan] = DryGain;
437 break;
441 src->DryMix = SelectDirectMixer();
443 else if(Device->Hrtf)
445 for(c = 0;c < num_channels;c++)
447 if(chans[c].channel == LFE)
449 /* Skip LFE */
450 src->Direct.Mix.Hrtf.Params.Delay[c][0] = 0;
451 src->Direct.Mix.Hrtf.Params.Delay[c][1] = 0;
452 for(i = 0;i < HRIR_LENGTH;i++)
454 src->Direct.Mix.Hrtf.Params.Coeffs[c][i][0] = 0.0f;
455 src->Direct.Mix.Hrtf.Params.Coeffs[c][i][1] = 0.0f;
458 else
460 /* Get the static HRIR coefficients and delays for this
461 * channel. */
462 GetLerpedHrtfCoeffs(Device->Hrtf,
463 0.0f, chans[c].angle, DryGain,
464 src->Direct.Mix.Hrtf.Params.Coeffs[c],
465 src->Direct.Mix.Hrtf.Params.Delay[c]);
468 ALSource->Hrtf.Counter = 0;
469 src->Direct.Mix.Hrtf.Params.IrSize = GetHrtfIrSize(Device->Hrtf);
471 src->Direct.Mix.Hrtf.State = &ALSource->Hrtf;
472 src->DryMix = SelectHrtfMixer();
474 else
476 ALfloat (*SrcMatrix)[MaxChannels] = src->Direct.Mix.Gains;
477 for(i = 0;i < MAX_INPUT_CHANNELS;i++)
479 for(c = 0;c < MaxChannels;c++)
480 SrcMatrix[i][c] = 0.0f;
483 DryGain *= lerp(1.0f, 1.0f/sqrtf((float)Device->NumChan), hwidth/F_PI);
484 for(c = 0;c < num_channels;c++)
486 /* Special-case LFE */
487 if(chans[c].channel == LFE)
489 SrcMatrix[c][chans[c].channel] = DryGain;
490 continue;
492 ComputeAngleGains(Device, chans[c].angle, hwidth, DryGain,
493 SrcMatrix[c]);
495 src->DryMix = SelectDirectMixer();
497 for(i = 0;i < NumSends;i++)
498 src->Send[i].Gain = WetGain[i];
499 src->WetMix = SelectSendMixer();
502 ALfloat gain = maxf(0.01f, DryGainHF);
503 for(c = 0;c < num_channels;c++)
504 ALfilterState_setParams(&src->Direct.LpFilter[c],
505 ALfilterType_HighShelf, gain,
506 (ALfloat)LOWPASSFREQREF/Frequency, 0.0f);
508 for(i = 0;i < NumSends;i++)
510 ALfloat gain = maxf(0.01f, WetGainHF[i]);
511 for(c = 0;c < num_channels;c++)
512 ALfilterState_setParams(&src->Send[i].LpFilter[c],
513 ALfilterType_HighShelf, gain,
514 (ALfloat)LOWPASSFREQREF/Frequency, 0.0f);
518 ALvoid CalcSourceParams(ALactivesource *src, const ALCcontext *ALContext)
520 ALCdevice *Device = ALContext->Device;
521 ALsource *ALSource = src->Source;
522 ALfloat Velocity[3],Direction[3],Position[3],SourceToListener[3];
523 ALfloat InnerAngle,OuterAngle,Angle,Distance,ClampedDist;
524 ALfloat MinVolume,MaxVolume,MinDist,MaxDist,Rolloff;
525 ALfloat ConeVolume,ConeHF,SourceVolume,ListenerGain;
526 ALfloat DopplerFactor, SpeedOfSound;
527 ALfloat AirAbsorptionFactor;
528 ALfloat RoomAirAbsorption[MAX_SENDS];
529 ALbufferlistitem *BufferListItem;
530 ALfloat Attenuation;
531 ALfloat RoomAttenuation[MAX_SENDS];
532 ALfloat MetersPerUnit;
533 ALfloat RoomRolloffBase;
534 ALfloat RoomRolloff[MAX_SENDS];
535 ALfloat DecayDistance[MAX_SENDS];
536 ALfloat DryGain;
537 ALfloat DryGainHF;
538 ALboolean DryGainHFAuto;
539 ALfloat WetGain[MAX_SENDS];
540 ALfloat WetGainHF[MAX_SENDS];
541 ALboolean WetGainAuto;
542 ALboolean WetGainHFAuto;
543 enum Resampler Resampler;
544 ALfloat Pitch;
545 ALuint Frequency;
546 ALint NumSends;
547 ALint i, j;
549 DryGainHF = 1.0f;
550 for(i = 0;i < MAX_SENDS;i++)
551 WetGainHF[i] = 1.0f;
553 /* Get context/device properties */
554 DopplerFactor = ALContext->DopplerFactor * ALSource->DopplerFactor;
555 SpeedOfSound = ALContext->SpeedOfSound * ALContext->DopplerVelocity;
556 NumSends = Device->NumAuxSends;
557 Frequency = Device->Frequency;
559 /* Get listener properties */
560 ListenerGain = ALContext->Listener->Gain;
561 MetersPerUnit = ALContext->Listener->MetersPerUnit;
563 /* Get source properties */
564 SourceVolume = ALSource->Gain;
565 MinVolume = ALSource->MinGain;
566 MaxVolume = ALSource->MaxGain;
567 Pitch = ALSource->Pitch;
568 Resampler = ALSource->Resampler;
569 Position[0] = ALSource->Position[0];
570 Position[1] = ALSource->Position[1];
571 Position[2] = ALSource->Position[2];
572 Direction[0] = ALSource->Orientation[0];
573 Direction[1] = ALSource->Orientation[1];
574 Direction[2] = ALSource->Orientation[2];
575 Velocity[0] = ALSource->Velocity[0];
576 Velocity[1] = ALSource->Velocity[1];
577 Velocity[2] = ALSource->Velocity[2];
578 MinDist = ALSource->RefDistance;
579 MaxDist = ALSource->MaxDistance;
580 Rolloff = ALSource->RollOffFactor;
581 InnerAngle = ALSource->InnerAngle;
582 OuterAngle = ALSource->OuterAngle;
583 AirAbsorptionFactor = ALSource->AirAbsorptionFactor;
584 DryGainHFAuto = ALSource->DryGainHFAuto;
585 WetGainAuto = ALSource->WetGainAuto;
586 WetGainHFAuto = ALSource->WetGainHFAuto;
587 RoomRolloffBase = ALSource->RoomRolloffFactor;
589 src->Direct.OutBuffer = Device->DryBuffer;
590 src->Direct.ClickRemoval = Device->ClickRemoval;
591 src->Direct.PendingClicks = Device->PendingClicks;
592 for(i = 0;i < NumSends;i++)
594 ALeffectslot *Slot = ALSource->Send[i].Slot;
596 if(!Slot && i == 0)
597 Slot = Device->DefaultSlot;
598 if(!Slot || Slot->EffectType == AL_EFFECT_NULL)
600 Slot = NULL;
601 RoomRolloff[i] = 0.0f;
602 DecayDistance[i] = 0.0f;
603 RoomAirAbsorption[i] = 1.0f;
605 else if(Slot->AuxSendAuto)
607 RoomRolloff[i] = RoomRolloffBase;
608 if(IsReverbEffect(Slot->EffectType))
610 RoomRolloff[i] += Slot->EffectProps.Reverb.RoomRolloffFactor;
611 DecayDistance[i] = Slot->EffectProps.Reverb.DecayTime *
612 SPEEDOFSOUNDMETRESPERSEC;
613 RoomAirAbsorption[i] = Slot->EffectProps.Reverb.AirAbsorptionGainHF;
615 else
617 DecayDistance[i] = 0.0f;
618 RoomAirAbsorption[i] = 1.0f;
621 else
623 /* If the slot's auxiliary send auto is off, the data sent to the
624 * effect slot is the same as the dry path, sans filter effects */
625 RoomRolloff[i] = Rolloff;
626 DecayDistance[i] = 0.0f;
627 RoomAirAbsorption[i] = AIRABSORBGAINHF;
630 if(!Slot || Slot->EffectType == AL_EFFECT_NULL)
632 src->Send[i].OutBuffer = NULL;
633 src->Send[i].ClickRemoval = NULL;
634 src->Send[i].PendingClicks = NULL;
636 else
638 src->Send[i].OutBuffer = Slot->WetBuffer;
639 src->Send[i].ClickRemoval = Slot->ClickRemoval;
640 src->Send[i].PendingClicks = Slot->PendingClicks;
644 /* Transform source to listener space (convert to head relative) */
645 if(ALSource->HeadRelative == AL_FALSE)
647 ALfloat (*restrict Matrix)[4] = ALContext->Listener->Params.Matrix;
648 /* Transform source vectors */
649 aluMatrixVector(Position, 1.0f, Matrix);
650 aluMatrixVector(Direction, 0.0f, Matrix);
651 aluMatrixVector(Velocity, 0.0f, Matrix);
653 else
655 const ALfloat *ListenerVel = ALContext->Listener->Params.Velocity;
656 /* Offset the source velocity to be relative of the listener velocity */
657 Velocity[0] += ListenerVel[0];
658 Velocity[1] += ListenerVel[1];
659 Velocity[2] += ListenerVel[2];
662 SourceToListener[0] = -Position[0];
663 SourceToListener[1] = -Position[1];
664 SourceToListener[2] = -Position[2];
665 aluNormalize(SourceToListener);
666 aluNormalize(Direction);
668 /* Calculate distance attenuation */
669 Distance = sqrtf(aluDotproduct(Position, Position));
670 ClampedDist = Distance;
672 Attenuation = 1.0f;
673 for(i = 0;i < NumSends;i++)
674 RoomAttenuation[i] = 1.0f;
675 switch(ALContext->SourceDistanceModel ? ALSource->DistanceModel :
676 ALContext->DistanceModel)
678 case InverseDistanceClamped:
679 ClampedDist = clampf(ClampedDist, MinDist, MaxDist);
680 if(MaxDist < MinDist)
681 break;
682 /*fall-through*/
683 case InverseDistance:
684 if(MinDist > 0.0f)
686 if((MinDist + (Rolloff * (ClampedDist - MinDist))) > 0.0f)
687 Attenuation = MinDist / (MinDist + (Rolloff * (ClampedDist - MinDist)));
688 for(i = 0;i < NumSends;i++)
690 if((MinDist + (RoomRolloff[i] * (ClampedDist - MinDist))) > 0.0f)
691 RoomAttenuation[i] = MinDist / (MinDist + (RoomRolloff[i] * (ClampedDist - MinDist)));
694 break;
696 case LinearDistanceClamped:
697 ClampedDist = clampf(ClampedDist, MinDist, MaxDist);
698 if(MaxDist < MinDist)
699 break;
700 /*fall-through*/
701 case LinearDistance:
702 if(MaxDist != MinDist)
704 Attenuation = 1.0f - (Rolloff*(ClampedDist-MinDist)/(MaxDist - MinDist));
705 Attenuation = maxf(Attenuation, 0.0f);
706 for(i = 0;i < NumSends;i++)
708 RoomAttenuation[i] = 1.0f - (RoomRolloff[i]*(ClampedDist-MinDist)/(MaxDist - MinDist));
709 RoomAttenuation[i] = maxf(RoomAttenuation[i], 0.0f);
712 break;
714 case ExponentDistanceClamped:
715 ClampedDist = clampf(ClampedDist, MinDist, MaxDist);
716 if(MaxDist < MinDist)
717 break;
718 /*fall-through*/
719 case ExponentDistance:
720 if(ClampedDist > 0.0f && MinDist > 0.0f)
722 Attenuation = powf(ClampedDist/MinDist, -Rolloff);
723 for(i = 0;i < NumSends;i++)
724 RoomAttenuation[i] = powf(ClampedDist/MinDist, -RoomRolloff[i]);
726 break;
728 case DisableDistance:
729 ClampedDist = MinDist;
730 break;
733 /* Source Gain + Attenuation */
734 DryGain = SourceVolume * Attenuation;
735 for(i = 0;i < NumSends;i++)
736 WetGain[i] = SourceVolume * RoomAttenuation[i];
738 /* Distance-based air absorption */
739 if(AirAbsorptionFactor > 0.0f && ClampedDist > MinDist)
741 ALfloat meters = maxf(ClampedDist-MinDist, 0.0f) * MetersPerUnit;
742 DryGainHF *= powf(AIRABSORBGAINHF, AirAbsorptionFactor*meters);
743 for(i = 0;i < NumSends;i++)
744 WetGainHF[i] *= powf(RoomAirAbsorption[i], AirAbsorptionFactor*meters);
747 if(WetGainAuto)
749 ALfloat ApparentDist = 1.0f/maxf(Attenuation, 0.00001f) - 1.0f;
751 /* Apply a decay-time transformation to the wet path, based on the
752 * attenuation of the dry path.
754 * Using the apparent distance, based on the distance attenuation, the
755 * initial decay of the reverb effect is calculated and applied to the
756 * wet path.
758 for(i = 0;i < NumSends;i++)
760 if(DecayDistance[i] > 0.0f)
761 WetGain[i] *= powf(0.001f/*-60dB*/, ApparentDist/DecayDistance[i]);
765 /* Calculate directional soundcones */
766 Angle = RAD2DEG(acosf(aluDotproduct(Direction,SourceToListener)) * ConeScale) * 2.0f;
767 if(Angle > InnerAngle && Angle <= OuterAngle)
769 ALfloat scale = (Angle-InnerAngle) / (OuterAngle-InnerAngle);
770 ConeVolume = lerp(1.0f, ALSource->OuterGain, scale);
771 ConeHF = lerp(1.0f, ALSource->OuterGainHF, scale);
773 else if(Angle > OuterAngle)
775 ConeVolume = ALSource->OuterGain;
776 ConeHF = ALSource->OuterGainHF;
778 else
780 ConeVolume = 1.0f;
781 ConeHF = 1.0f;
784 DryGain *= ConeVolume;
785 if(WetGainAuto)
787 for(i = 0;i < NumSends;i++)
788 WetGain[i] *= ConeVolume;
790 if(DryGainHFAuto)
791 DryGainHF *= ConeHF;
792 if(WetGainHFAuto)
794 for(i = 0;i < NumSends;i++)
795 WetGainHF[i] *= ConeHF;
798 /* Clamp to Min/Max Gain */
799 DryGain = clampf(DryGain, MinVolume, MaxVolume);
800 for(i = 0;i < NumSends;i++)
801 WetGain[i] = clampf(WetGain[i], MinVolume, MaxVolume);
803 /* Apply gain and frequency filters */
804 DryGain *= ALSource->DirectGain * ListenerGain;
805 DryGainHF *= ALSource->DirectGainHF;
806 for(i = 0;i < NumSends;i++)
808 WetGain[i] *= ALSource->Send[i].Gain * ListenerGain;
809 WetGainHF[i] *= ALSource->Send[i].GainHF;
812 /* Calculate velocity-based doppler effect */
813 if(DopplerFactor > 0.0f)
815 const ALfloat *ListenerVel = ALContext->Listener->Params.Velocity;
816 ALfloat VSS, VLS;
818 if(SpeedOfSound < 1.0f)
820 DopplerFactor *= 1.0f/SpeedOfSound;
821 SpeedOfSound = 1.0f;
824 VSS = aluDotproduct(Velocity, SourceToListener) * DopplerFactor;
825 VLS = aluDotproduct(ListenerVel, SourceToListener) * DopplerFactor;
827 Pitch *= clampf(SpeedOfSound-VLS, 1.0f, SpeedOfSound*2.0f - 1.0f) /
828 clampf(SpeedOfSound-VSS, 1.0f, SpeedOfSound*2.0f - 1.0f);
831 BufferListItem = ALSource->queue;
832 while(BufferListItem != NULL)
834 ALbuffer *ALBuffer;
835 if((ALBuffer=BufferListItem->buffer) != NULL)
837 /* Calculate fixed-point stepping value, based on the pitch, buffer
838 * frequency, and output frequency. */
839 Pitch = Pitch * ALBuffer->Frequency / Frequency;
840 if(Pitch > 10.0f)
841 src->Step = 10<<FRACTIONBITS;
842 else
844 src->Step = fastf2i(Pitch*FRACTIONONE);
845 if(src->Step == 0)
846 src->Step = 1;
848 src->Resample = SelectResampler(Resampler, src->Step);
850 break;
852 BufferListItem = BufferListItem->next;
855 if(Device->Hrtf)
857 /* Use a binaural HRTF algorithm for stereo headphone playback */
858 ALfloat delta, ev = 0.0f, az = 0.0f;
860 if(Distance > FLT_EPSILON)
862 ALfloat invlen = 1.0f/Distance;
863 Position[0] *= invlen;
864 Position[1] *= invlen;
865 Position[2] *= invlen;
867 /* Calculate elevation and azimuth only when the source is not at
868 * the listener. This prevents +0 and -0 Z from producing
869 * inconsistent panning. Also, clamp Y in case FP precision errors
870 * cause it to land outside of -1..+1. */
871 ev = asinf(clampf(Position[1], -1.0f, 1.0f));
872 az = atan2f(Position[0], -Position[2]*ZScale);
875 /* Check to see if the HRIR is already moving. */
876 if(ALSource->Hrtf.Moving)
878 /* Calculate the normalized HRTF transition factor (delta). */
879 delta = CalcHrtfDelta(src->Direct.Mix.Hrtf.Params.Gain, DryGain,
880 src->Direct.Mix.Hrtf.Params.Dir, Position);
881 /* If the delta is large enough, get the moving HRIR target
882 * coefficients, target delays, steppping values, and counter. */
883 if(delta > 0.001f)
885 ALSource->Hrtf.Counter = GetMovingHrtfCoeffs(Device->Hrtf,
886 ev, az, DryGain, delta,
887 ALSource->Hrtf.Counter,
888 src->Direct.Mix.Hrtf.Params.Coeffs[0],
889 src->Direct.Mix.Hrtf.Params.Delay[0],
890 src->Direct.Mix.Hrtf.Params.CoeffStep,
891 src->Direct.Mix.Hrtf.Params.DelayStep);
892 src->Direct.Mix.Hrtf.Params.Gain = DryGain;
893 src->Direct.Mix.Hrtf.Params.Dir[0] = Position[0];
894 src->Direct.Mix.Hrtf.Params.Dir[1] = Position[1];
895 src->Direct.Mix.Hrtf.Params.Dir[2] = Position[2];
898 else
900 /* Get the initial (static) HRIR coefficients and delays. */
901 GetLerpedHrtfCoeffs(Device->Hrtf, ev, az, DryGain,
902 src->Direct.Mix.Hrtf.Params.Coeffs[0],
903 src->Direct.Mix.Hrtf.Params.Delay[0]);
904 ALSource->Hrtf.Counter = 0;
905 ALSource->Hrtf.Moving = AL_TRUE;
906 src->Direct.Mix.Hrtf.Params.Gain = DryGain;
907 src->Direct.Mix.Hrtf.Params.Dir[0] = Position[0];
908 src->Direct.Mix.Hrtf.Params.Dir[1] = Position[1];
909 src->Direct.Mix.Hrtf.Params.Dir[2] = Position[2];
911 src->Direct.Mix.Hrtf.Params.IrSize = GetHrtfIrSize(Device->Hrtf);
913 src->Direct.Mix.Hrtf.State = &ALSource->Hrtf;
914 src->DryMix = SelectHrtfMixer();
916 else
918 ALfloat (*Matrix)[MaxChannels] = src->Direct.Mix.Gains;
919 ALfloat DirGain = 0.0f;
920 ALfloat AmbientGain;
922 for(i = 0;i < MAX_INPUT_CHANNELS;i++)
924 for(j = 0;j < MaxChannels;j++)
925 Matrix[i][j] = 0.0f;
928 /* Normalize the length, and compute panned gains. */
929 if(Distance > FLT_EPSILON)
931 ALfloat invlen = 1.0f/Distance;
932 Position[0] *= invlen;
933 Position[1] *= invlen;
934 Position[2] *= invlen;
936 DirGain = sqrtf(Position[0]*Position[0] + Position[2]*Position[2]);
937 ComputeAngleGains(Device, atan2f(Position[0], -Position[2]*ZScale), 0.0f,
938 DryGain*DirGain, Matrix[0]);
941 /* Adjustment for vertical offsets. Not the greatest, but simple
942 * enough. */
943 AmbientGain = DryGain * sqrtf(1.0f/Device->NumChan) * (1.0f-DirGain);
944 for(i = 0;i < (ALint)Device->NumChan;i++)
946 enum Channel chan = Device->Speaker2Chan[i];
947 Matrix[0][chan] = maxf(Matrix[0][chan], AmbientGain);
949 src->DryMix = SelectDirectMixer();
951 for(i = 0;i < NumSends;i++)
952 src->Send[i].Gain = WetGain[i];
953 src->WetMix = SelectSendMixer();
956 ALfloat gain = maxf(0.01f, DryGainHF);
957 ALfilterState_setParams(&src->Direct.LpFilter[0],
958 ALfilterType_HighShelf, gain,
959 (ALfloat)LOWPASSFREQREF/Frequency, 0.0f);
961 for(i = 0;i < NumSends;i++)
963 ALfloat gain = maxf(0.01f, WetGainHF[i]);
964 ALfilterState_setParams(&src->Send[i].LpFilter[0],
965 ALfilterType_HighShelf, gain,
966 (ALfloat)LOWPASSFREQREF/Frequency, 0.0f);
971 static inline ALint aluF2I25(ALfloat val)
973 /* Clamp the value between -1 and +1. This handles that with only a single branch. */
974 if(fabsf(val) > 1.0f)
975 val = (ALfloat)((0.0f < val) - (val < 0.0f));
976 /* Convert to a signed integer, between -16777215 and +16777215. */
977 return fastf2i(val*16777215.0f);
980 static inline ALfloat aluF2F(ALfloat val)
981 { return val; }
982 static inline ALint aluF2I(ALfloat val)
983 { return aluF2I25(val)<<7; }
984 static inline ALuint aluF2UI(ALfloat val)
985 { return aluF2I(val)+2147483648u; }
986 static inline ALshort aluF2S(ALfloat val)
987 { return aluF2I25(val)>>9; }
988 static inline ALushort aluF2US(ALfloat val)
989 { return aluF2S(val)+32768; }
990 static inline ALbyte aluF2B(ALfloat val)
991 { return aluF2I25(val)>>17; }
992 static inline ALubyte aluF2UB(ALfloat val)
993 { return aluF2B(val)+128; }
995 #define DECL_TEMPLATE(T, func) \
996 static int Write_##T(ALCdevice *device, T *restrict buffer, \
997 ALuint SamplesToDo) \
999 ALfloat (*restrict DryBuffer)[BUFFERSIZE] = device->DryBuffer; \
1000 ALuint numchans = ChannelsFromDevFmt(device->FmtChans); \
1001 const ALuint *offsets = device->ChannelOffsets; \
1002 ALuint i, j; \
1004 for(j = 0;j < MaxChannels;j++) \
1006 T *restrict out; \
1008 if(offsets[j] == INVALID_OFFSET) \
1009 continue; \
1011 out = buffer + offsets[j]; \
1012 for(i = 0;i < SamplesToDo;i++) \
1013 out[i*numchans] = func(DryBuffer[j][i]); \
1015 return SamplesToDo*numchans*sizeof(T); \
1018 DECL_TEMPLATE(ALfloat, aluF2F)
1019 DECL_TEMPLATE(ALuint, aluF2UI)
1020 DECL_TEMPLATE(ALint, aluF2I)
1021 DECL_TEMPLATE(ALushort, aluF2US)
1022 DECL_TEMPLATE(ALshort, aluF2S)
1023 DECL_TEMPLATE(ALubyte, aluF2UB)
1024 DECL_TEMPLATE(ALbyte, aluF2B)
1026 #undef DECL_TEMPLATE
1029 ALvoid aluMixData(ALCdevice *device, ALvoid *buffer, ALsizei size)
1031 ALuint SamplesToDo;
1032 ALeffectslot **slot, **slot_end;
1033 ALactivesource **src, **src_end;
1034 ALCcontext *ctx;
1035 FPUCtl oldMode;
1036 ALuint i, c;
1038 SetMixerFPUMode(&oldMode);
1040 while(size > 0)
1042 SamplesToDo = minu(size, BUFFERSIZE);
1043 for(c = 0;c < MaxChannels;c++)
1044 memset(device->DryBuffer[c], 0, SamplesToDo*sizeof(ALfloat));
1046 ALCdevice_Lock(device);
1047 V(device->Synth,process)(SamplesToDo, device->DryBuffer);
1049 ctx = device->ContextList;
1050 while(ctx)
1052 ALenum DeferUpdates = ctx->DeferUpdates;
1053 ALenum UpdateSources = AL_FALSE;
1055 if(!DeferUpdates)
1056 UpdateSources = ExchangeInt(&ctx->UpdateSources, AL_FALSE);
1058 if(UpdateSources)
1059 CalcListenerParams(ctx->Listener);
1061 /* source processing */
1062 src = ctx->ActiveSources;
1063 src_end = src + ctx->ActiveSourceCount;
1064 while(src != src_end)
1066 ALsource *source = (*src)->Source;
1068 if(source->state != AL_PLAYING && source->state != AL_PAUSED)
1070 ALactivesource *temp = *(--src_end);
1071 *src_end = *src;
1072 *src = temp;
1073 --(ctx->ActiveSourceCount);
1074 continue;
1077 if(!DeferUpdates && (ExchangeInt(&source->NeedsUpdate, AL_FALSE) ||
1078 UpdateSources))
1079 (*src)->Update(*src, ctx);
1081 if(source->state != AL_PAUSED)
1082 MixSource(*src, device, SamplesToDo);
1083 src++;
1086 /* effect slot processing */
1087 slot = ctx->ActiveEffectSlots;
1088 slot_end = slot + ctx->ActiveEffectSlotCount;
1089 while(slot != slot_end)
1091 ALfloat offset = (*slot)->ClickRemoval[0];
1092 if(offset < (1.0f/32768.0f))
1093 offset = 0.0f;
1094 else for(i = 0;i < SamplesToDo;i++)
1096 (*slot)->WetBuffer[0][i] += offset;
1097 offset -= offset * (1.0f/256.0f);
1099 (*slot)->ClickRemoval[0] = offset + (*slot)->PendingClicks[0];
1100 (*slot)->PendingClicks[0] = 0.0f;
1102 if(!DeferUpdates && ExchangeInt(&(*slot)->NeedsUpdate, AL_FALSE))
1103 V((*slot)->EffectState,update)(device, *slot);
1105 V((*slot)->EffectState,process)(SamplesToDo, (*slot)->WetBuffer[0],
1106 device->DryBuffer);
1108 for(i = 0;i < SamplesToDo;i++)
1109 (*slot)->WetBuffer[0][i] = 0.0f;
1111 slot++;
1114 ctx = ctx->next;
1117 slot = &device->DefaultSlot;
1118 if(*slot != NULL)
1120 ALfloat offset = (*slot)->ClickRemoval[0];
1121 if(offset < (1.0f/32768.0f))
1122 offset = 0.0f;
1123 else for(i = 0;i < SamplesToDo;i++)
1125 (*slot)->WetBuffer[0][i] += offset;
1126 offset -= offset * (1.0f/256.0f);
1128 (*slot)->ClickRemoval[0] = offset + (*slot)->PendingClicks[0];
1129 (*slot)->PendingClicks[0] = 0.0f;
1131 if(ExchangeInt(&(*slot)->NeedsUpdate, AL_FALSE))
1132 V((*slot)->EffectState,update)(device, *slot);
1134 V((*slot)->EffectState,process)(SamplesToDo, (*slot)->WetBuffer[0],
1135 device->DryBuffer);
1137 for(i = 0;i < SamplesToDo;i++)
1138 (*slot)->WetBuffer[0][i] = 0.0f;
1141 /* Increment the clock time. Every second's worth of samples is
1142 * converted and added to clock base so that large sample counts don't
1143 * overflow during conversion. This also guarantees an exact, stable
1144 * conversion. */
1145 device->SamplesDone += SamplesToDo;
1146 device->ClockBase += (device->SamplesDone/device->Frequency) * DEVICE_CLOCK_RES;
1147 device->SamplesDone %= device->Frequency;
1148 ALCdevice_Unlock(device);
1150 /* Click-removal. Could do better; this only really handles immediate
1151 * changes between updates where a predictive sample could be
1152 * generated. Delays caused by effects and HRTF aren't caught. */
1153 if(device->FmtChans == DevFmtStereo)
1155 /* Assumes the first two channels are FrontLeft and FrontRight */
1156 for(c = 0;c < 2;c++)
1158 ALfloat offset = device->ClickRemoval[c];
1159 if(offset < (1.0f/32768.0f))
1160 offset = 0.0f;
1161 else for(i = 0;i < SamplesToDo;i++)
1163 device->DryBuffer[c][i] += offset;
1164 offset -= offset * (1.0f/256.0f);
1166 device->ClickRemoval[c] = offset + device->PendingClicks[c];
1167 device->PendingClicks[c] = 0.0f;
1169 if(device->Bs2b)
1171 float samples[2];
1172 for(i = 0;i < SamplesToDo;i++)
1174 samples[0] = device->DryBuffer[FrontLeft][i];
1175 samples[1] = device->DryBuffer[FrontRight][i];
1176 bs2b_cross_feed(device->Bs2b, samples);
1177 device->DryBuffer[FrontLeft][i] = samples[0];
1178 device->DryBuffer[FrontRight][i] = samples[1];
1182 else
1184 for(c = 0;c < MaxChannels;c++)
1186 ALfloat offset = device->ClickRemoval[c];
1187 if(offset < (1.0f/32768.0f))
1188 offset = 0.0f;
1189 else for(i = 0;i < SamplesToDo;i++)
1191 device->DryBuffer[c][i] += offset;
1192 offset -= offset * (1.0f/256.0f);
1194 device->ClickRemoval[c] = offset + device->PendingClicks[c];
1195 device->PendingClicks[c] = 0.0f;
1199 if(buffer)
1201 int bytes = 0;
1202 switch(device->FmtType)
1204 case DevFmtByte:
1205 bytes = Write_ALbyte(device, buffer, SamplesToDo);
1206 break;
1207 case DevFmtUByte:
1208 bytes = Write_ALubyte(device, buffer, SamplesToDo);
1209 break;
1210 case DevFmtShort:
1211 bytes = Write_ALshort(device, buffer, SamplesToDo);
1212 break;
1213 case DevFmtUShort:
1214 bytes = Write_ALushort(device, buffer, SamplesToDo);
1215 break;
1216 case DevFmtInt:
1217 bytes = Write_ALint(device, buffer, SamplesToDo);
1218 break;
1219 case DevFmtUInt:
1220 bytes = Write_ALuint(device, buffer, SamplesToDo);
1221 break;
1222 case DevFmtFloat:
1223 bytes = Write_ALfloat(device, buffer, SamplesToDo);
1224 break;
1227 buffer = (ALubyte*)buffer + bytes;
1230 size -= SamplesToDo;
1233 RestoreFPUMode(&oldMode);
1237 ALvoid aluHandleDisconnect(ALCdevice *device)
1239 ALCcontext *Context;
1241 device->Connected = ALC_FALSE;
1243 Context = device->ContextList;
1244 while(Context)
1246 ALactivesource **src, **src_end;
1248 src = Context->ActiveSources;
1249 src_end = src + Context->ActiveSourceCount;
1250 while(src != src_end)
1252 ALsource *source = (*src)->Source;
1253 if(source->state == AL_PLAYING)
1255 source->state = AL_STOPPED;
1256 source->BuffersPlayed = source->BuffersInQueue;
1257 source->position = 0;
1258 source->position_fraction = 0;
1260 src++;
1262 Context->ActiveSourceCount = 0;
1264 Context = Context->next;