Store some source mixing parameters in the active source struct
[openal-soft.git] / Alc / ALu.c
blob9ff9fc074ad4c2a0d442d21a0d6b30130dc02999
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 (*SrcMatrix)[MaxChannels];
285 ALfloat DryGain, DryGainHF;
286 ALfloat WetGain[MAX_SENDS];
287 ALfloat WetGainHF[MAX_SENDS];
288 ALint NumSends, Frequency;
289 const struct ChanMap *chans = NULL;
290 enum Resampler Resampler;
291 ALint num_channels = 0;
292 ALboolean DirectChannels;
293 ALfloat hwidth = 0.0f;
294 ALfloat Pitch;
295 ALint i, c;
297 /* Get device properties */
298 NumSends = Device->NumAuxSends;
299 Frequency = Device->Frequency;
301 /* Get listener properties */
302 ListenerGain = ALContext->Listener->Gain;
304 /* Get source properties */
305 SourceVolume = ALSource->Gain;
306 MinVolume = ALSource->MinGain;
307 MaxVolume = ALSource->MaxGain;
308 Pitch = ALSource->Pitch;
309 Resampler = ALSource->Resampler;
310 DirectChannels = ALSource->DirectChannels;
312 /* Calculate the stepping value */
313 Channels = FmtMono;
314 BufferListItem = ALSource->queue;
315 while(BufferListItem != NULL)
317 ALbuffer *ALBuffer;
318 if((ALBuffer=BufferListItem->buffer) != NULL)
320 Pitch = Pitch * ALBuffer->Frequency / Frequency;
321 if(Pitch > 10.0f)
322 src->Step = 10<<FRACTIONBITS;
323 else
325 src->Step = fastf2i(Pitch*FRACTIONONE);
326 if(src->Step == 0)
327 src->Step = 1;
329 src->Resample = SelectResampler(Resampler, src->Step);
331 Channels = ALBuffer->FmtChannels;
332 break;
334 BufferListItem = BufferListItem->next;
336 if(!DirectChannels && Device->Hrtf)
337 src->DryMix = SelectHrtfMixer();
338 else
339 src->DryMix = SelectDirectMixer();
340 src->WetMix = SelectSendMixer();
342 /* Calculate gains */
343 DryGain = clampf(SourceVolume, MinVolume, MaxVolume);
344 DryGain *= ALSource->DirectGain * ListenerGain;
345 DryGainHF = ALSource->DirectGainHF;
346 for(i = 0;i < NumSends;i++)
348 WetGain[i] = clampf(SourceVolume, MinVolume, MaxVolume);
349 WetGain[i] *= ALSource->Send[i].Gain * ListenerGain;
350 WetGainHF[i] = ALSource->Send[i].GainHF;
353 SrcMatrix = src->Direct.Gains;
354 for(i = 0;i < MAX_INPUT_CHANNELS;i++)
356 for(c = 0;c < MaxChannels;c++)
357 SrcMatrix[i][c] = 0.0f;
359 switch(Channels)
361 case FmtMono:
362 chans = MonoMap;
363 num_channels = 1;
364 break;
366 case FmtStereo:
367 if(!(Device->Flags&DEVICE_WIDE_STEREO))
369 /* HACK: Place the stereo channels at +/-90 degrees when using non-
370 * HRTF stereo output. This helps reduce the "monoization" caused
371 * by them panning towards the center. */
372 if(Device->FmtChans == DevFmtStereo && !Device->Hrtf)
373 chans = StereoWideMap;
374 else
375 chans = StereoMap;
377 else
379 chans = StereoWideMap;
380 hwidth = DEG2RAD(60.0f);
382 num_channels = 2;
383 break;
385 case FmtRear:
386 chans = RearMap;
387 num_channels = 2;
388 break;
390 case FmtQuad:
391 chans = QuadMap;
392 num_channels = 4;
393 break;
395 case FmtX51:
396 chans = X51Map;
397 num_channels = 6;
398 break;
400 case FmtX61:
401 chans = X61Map;
402 num_channels = 7;
403 break;
405 case FmtX71:
406 chans = X71Map;
407 num_channels = 8;
408 break;
411 if(DirectChannels != AL_FALSE)
413 for(c = 0;c < num_channels;c++)
415 for(i = 0;i < (ALint)Device->NumChan;i++)
417 enum Channel chan = Device->Speaker2Chan[i];
418 if(chan == chans[c].channel)
420 SrcMatrix[c][chan] = DryGain;
421 break;
426 else if(Device->Hrtf)
428 for(c = 0;c < num_channels;c++)
430 if(chans[c].channel == LFE)
432 /* Skip LFE */
433 src->Direct.Hrtf.Params.Delay[c][0] = 0;
434 src->Direct.Hrtf.Params.Delay[c][1] = 0;
435 for(i = 0;i < HRIR_LENGTH;i++)
437 src->Direct.Hrtf.Params.Coeffs[c][i][0] = 0.0f;
438 src->Direct.Hrtf.Params.Coeffs[c][i][1] = 0.0f;
441 else
443 /* Get the static HRIR coefficients and delays for this
444 * channel. */
445 GetLerpedHrtfCoeffs(Device->Hrtf,
446 0.0f, chans[c].angle, DryGain,
447 src->Direct.Hrtf.Params.Coeffs[c],
448 src->Direct.Hrtf.Params.Delay[c]);
451 ALSource->Hrtf.Counter = 0;
452 src->Direct.Hrtf.Params.IrSize = GetHrtfIrSize(Device->Hrtf);
454 src->Direct.Hrtf.State = &ALSource->Hrtf;
456 else
458 DryGain *= lerp(1.0f, 1.0f/sqrtf((float)Device->NumChan), hwidth/F_PI);
459 for(c = 0;c < num_channels;c++)
461 /* Special-case LFE */
462 if(chans[c].channel == LFE)
464 SrcMatrix[c][chans[c].channel] = DryGain;
465 continue;
467 ComputeAngleGains(Device, chans[c].angle, hwidth, DryGain,
468 SrcMatrix[c]);
472 src->Direct.OutBuffer = Device->DryBuffer;
473 src->Direct.ClickRemoval = Device->ClickRemoval;
474 src->Direct.PendingClicks = Device->PendingClicks;
475 for(i = 0;i < NumSends;i++)
477 ALeffectslot *Slot = ALSource->Send[i].Slot;
478 if(!Slot && i == 0)
479 Slot = Device->DefaultSlot;
480 if(!Slot || Slot->EffectType == AL_EFFECT_NULL)
482 src->Send[i].OutBuffer = NULL;
483 src->Send[i].ClickRemoval = NULL;
484 src->Send[i].PendingClicks = NULL;
486 else
488 src->Send[i].OutBuffer = Slot->WetBuffer;
489 src->Send[i].ClickRemoval = Slot->ClickRemoval;
490 src->Send[i].PendingClicks = Slot->PendingClicks;
492 src->Send[i].Gain = WetGain[i];
496 ALfloat gain = maxf(0.01f, DryGainHF);
497 for(c = 0;c < num_channels;c++)
498 ALfilterState_setParams(&src->Direct.LpFilter[c],
499 ALfilterType_HighShelf, gain,
500 (ALfloat)LOWPASSFREQREF/Frequency, 0.0f);
502 for(i = 0;i < NumSends;i++)
504 ALfloat gain = maxf(0.01f, WetGainHF[i]);
505 for(c = 0;c < num_channels;c++)
506 ALfilterState_setParams(&src->Send[i].LpFilter[c],
507 ALfilterType_HighShelf, gain,
508 (ALfloat)LOWPASSFREQREF/Frequency, 0.0f);
512 ALvoid CalcSourceParams(ALactivesource *src, const ALCcontext *ALContext)
514 ALCdevice *Device = ALContext->Device;
515 ALsource *ALSource = src->Source;
516 ALfloat Velocity[3],Direction[3],Position[3],SourceToListener[3];
517 ALfloat InnerAngle,OuterAngle,Angle,Distance,ClampedDist;
518 ALfloat MinVolume,MaxVolume,MinDist,MaxDist,Rolloff;
519 ALfloat ConeVolume,ConeHF,SourceVolume,ListenerGain;
520 ALfloat DopplerFactor, SpeedOfSound;
521 ALfloat AirAbsorptionFactor;
522 ALfloat RoomAirAbsorption[MAX_SENDS];
523 ALbufferlistitem *BufferListItem;
524 ALfloat Attenuation;
525 ALfloat RoomAttenuation[MAX_SENDS];
526 ALfloat MetersPerUnit;
527 ALfloat RoomRolloffBase;
528 ALfloat RoomRolloff[MAX_SENDS];
529 ALfloat DecayDistance[MAX_SENDS];
530 ALfloat DryGain;
531 ALfloat DryGainHF;
532 ALboolean DryGainHFAuto;
533 ALfloat WetGain[MAX_SENDS];
534 ALfloat WetGainHF[MAX_SENDS];
535 ALboolean WetGainAuto;
536 ALboolean WetGainHFAuto;
537 enum Resampler Resampler;
538 ALfloat Pitch;
539 ALuint Frequency;
540 ALint NumSends;
541 ALint i, j;
543 DryGainHF = 1.0f;
544 for(i = 0;i < MAX_SENDS;i++)
545 WetGainHF[i] = 1.0f;
547 /* Get context/device properties */
548 DopplerFactor = ALContext->DopplerFactor * ALSource->DopplerFactor;
549 SpeedOfSound = ALContext->SpeedOfSound * ALContext->DopplerVelocity;
550 NumSends = Device->NumAuxSends;
551 Frequency = Device->Frequency;
553 /* Get listener properties */
554 ListenerGain = ALContext->Listener->Gain;
555 MetersPerUnit = ALContext->Listener->MetersPerUnit;
557 /* Get source properties */
558 SourceVolume = ALSource->Gain;
559 MinVolume = ALSource->MinGain;
560 MaxVolume = ALSource->MaxGain;
561 Pitch = ALSource->Pitch;
562 Resampler = ALSource->Resampler;
563 Position[0] = ALSource->Position[0];
564 Position[1] = ALSource->Position[1];
565 Position[2] = ALSource->Position[2];
566 Direction[0] = ALSource->Orientation[0];
567 Direction[1] = ALSource->Orientation[1];
568 Direction[2] = ALSource->Orientation[2];
569 Velocity[0] = ALSource->Velocity[0];
570 Velocity[1] = ALSource->Velocity[1];
571 Velocity[2] = ALSource->Velocity[2];
572 MinDist = ALSource->RefDistance;
573 MaxDist = ALSource->MaxDistance;
574 Rolloff = ALSource->RollOffFactor;
575 InnerAngle = ALSource->InnerAngle;
576 OuterAngle = ALSource->OuterAngle;
577 AirAbsorptionFactor = ALSource->AirAbsorptionFactor;
578 DryGainHFAuto = ALSource->DryGainHFAuto;
579 WetGainAuto = ALSource->WetGainAuto;
580 WetGainHFAuto = ALSource->WetGainHFAuto;
581 RoomRolloffBase = ALSource->RoomRolloffFactor;
583 src->Direct.OutBuffer = Device->DryBuffer;
584 src->Direct.ClickRemoval = Device->ClickRemoval;
585 src->Direct.PendingClicks = Device->PendingClicks;
586 for(i = 0;i < NumSends;i++)
588 ALeffectslot *Slot = ALSource->Send[i].Slot;
590 if(!Slot && i == 0)
591 Slot = Device->DefaultSlot;
592 if(!Slot || Slot->EffectType == AL_EFFECT_NULL)
594 Slot = NULL;
595 RoomRolloff[i] = 0.0f;
596 DecayDistance[i] = 0.0f;
597 RoomAirAbsorption[i] = 1.0f;
599 else if(Slot->AuxSendAuto)
601 RoomRolloff[i] = RoomRolloffBase;
602 if(IsReverbEffect(Slot->EffectType))
604 RoomRolloff[i] += Slot->EffectProps.Reverb.RoomRolloffFactor;
605 DecayDistance[i] = Slot->EffectProps.Reverb.DecayTime *
606 SPEEDOFSOUNDMETRESPERSEC;
607 RoomAirAbsorption[i] = Slot->EffectProps.Reverb.AirAbsorptionGainHF;
609 else
611 DecayDistance[i] = 0.0f;
612 RoomAirAbsorption[i] = 1.0f;
615 else
617 /* If the slot's auxiliary send auto is off, the data sent to the
618 * effect slot is the same as the dry path, sans filter effects */
619 RoomRolloff[i] = Rolloff;
620 DecayDistance[i] = 0.0f;
621 RoomAirAbsorption[i] = AIRABSORBGAINHF;
624 if(!Slot || Slot->EffectType == AL_EFFECT_NULL)
626 src->Send[i].OutBuffer = NULL;
627 src->Send[i].ClickRemoval = NULL;
628 src->Send[i].PendingClicks = NULL;
630 else
632 src->Send[i].OutBuffer = Slot->WetBuffer;
633 src->Send[i].ClickRemoval = Slot->ClickRemoval;
634 src->Send[i].PendingClicks = Slot->PendingClicks;
638 /* Transform source to listener space (convert to head relative) */
639 if(ALSource->HeadRelative == AL_FALSE)
641 ALfloat (*restrict Matrix)[4] = ALContext->Listener->Params.Matrix;
642 /* Transform source vectors */
643 aluMatrixVector(Position, 1.0f, Matrix);
644 aluMatrixVector(Direction, 0.0f, Matrix);
645 aluMatrixVector(Velocity, 0.0f, Matrix);
647 else
649 const ALfloat *ListenerVel = ALContext->Listener->Params.Velocity;
650 /* Offset the source velocity to be relative of the listener velocity */
651 Velocity[0] += ListenerVel[0];
652 Velocity[1] += ListenerVel[1];
653 Velocity[2] += ListenerVel[2];
656 SourceToListener[0] = -Position[0];
657 SourceToListener[1] = -Position[1];
658 SourceToListener[2] = -Position[2];
659 aluNormalize(SourceToListener);
660 aluNormalize(Direction);
662 /* Calculate distance attenuation */
663 Distance = sqrtf(aluDotproduct(Position, Position));
664 ClampedDist = Distance;
666 Attenuation = 1.0f;
667 for(i = 0;i < NumSends;i++)
668 RoomAttenuation[i] = 1.0f;
669 switch(ALContext->SourceDistanceModel ? ALSource->DistanceModel :
670 ALContext->DistanceModel)
672 case InverseDistanceClamped:
673 ClampedDist = clampf(ClampedDist, MinDist, MaxDist);
674 if(MaxDist < MinDist)
675 break;
676 /*fall-through*/
677 case InverseDistance:
678 if(MinDist > 0.0f)
680 if((MinDist + (Rolloff * (ClampedDist - MinDist))) > 0.0f)
681 Attenuation = MinDist / (MinDist + (Rolloff * (ClampedDist - MinDist)));
682 for(i = 0;i < NumSends;i++)
684 if((MinDist + (RoomRolloff[i] * (ClampedDist - MinDist))) > 0.0f)
685 RoomAttenuation[i] = MinDist / (MinDist + (RoomRolloff[i] * (ClampedDist - MinDist)));
688 break;
690 case LinearDistanceClamped:
691 ClampedDist = clampf(ClampedDist, MinDist, MaxDist);
692 if(MaxDist < MinDist)
693 break;
694 /*fall-through*/
695 case LinearDistance:
696 if(MaxDist != MinDist)
698 Attenuation = 1.0f - (Rolloff*(ClampedDist-MinDist)/(MaxDist - MinDist));
699 Attenuation = maxf(Attenuation, 0.0f);
700 for(i = 0;i < NumSends;i++)
702 RoomAttenuation[i] = 1.0f - (RoomRolloff[i]*(ClampedDist-MinDist)/(MaxDist - MinDist));
703 RoomAttenuation[i] = maxf(RoomAttenuation[i], 0.0f);
706 break;
708 case ExponentDistanceClamped:
709 ClampedDist = clampf(ClampedDist, MinDist, MaxDist);
710 if(MaxDist < MinDist)
711 break;
712 /*fall-through*/
713 case ExponentDistance:
714 if(ClampedDist > 0.0f && MinDist > 0.0f)
716 Attenuation = powf(ClampedDist/MinDist, -Rolloff);
717 for(i = 0;i < NumSends;i++)
718 RoomAttenuation[i] = powf(ClampedDist/MinDist, -RoomRolloff[i]);
720 break;
722 case DisableDistance:
723 ClampedDist = MinDist;
724 break;
727 /* Source Gain + Attenuation */
728 DryGain = SourceVolume * Attenuation;
729 for(i = 0;i < NumSends;i++)
730 WetGain[i] = SourceVolume * RoomAttenuation[i];
732 /* Distance-based air absorption */
733 if(AirAbsorptionFactor > 0.0f && ClampedDist > MinDist)
735 ALfloat meters = maxf(ClampedDist-MinDist, 0.0f) * MetersPerUnit;
736 DryGainHF *= powf(AIRABSORBGAINHF, AirAbsorptionFactor*meters);
737 for(i = 0;i < NumSends;i++)
738 WetGainHF[i] *= powf(RoomAirAbsorption[i], AirAbsorptionFactor*meters);
741 if(WetGainAuto)
743 ALfloat ApparentDist = 1.0f/maxf(Attenuation, 0.00001f) - 1.0f;
745 /* Apply a decay-time transformation to the wet path, based on the
746 * attenuation of the dry path.
748 * Using the apparent distance, based on the distance attenuation, the
749 * initial decay of the reverb effect is calculated and applied to the
750 * wet path.
752 for(i = 0;i < NumSends;i++)
754 if(DecayDistance[i] > 0.0f)
755 WetGain[i] *= powf(0.001f/*-60dB*/, ApparentDist/DecayDistance[i]);
759 /* Calculate directional soundcones */
760 Angle = RAD2DEG(acosf(aluDotproduct(Direction,SourceToListener)) * ConeScale) * 2.0f;
761 if(Angle > InnerAngle && Angle <= OuterAngle)
763 ALfloat scale = (Angle-InnerAngle) / (OuterAngle-InnerAngle);
764 ConeVolume = lerp(1.0f, ALSource->OuterGain, scale);
765 ConeHF = lerp(1.0f, ALSource->OuterGainHF, scale);
767 else if(Angle > OuterAngle)
769 ConeVolume = ALSource->OuterGain;
770 ConeHF = ALSource->OuterGainHF;
772 else
774 ConeVolume = 1.0f;
775 ConeHF = 1.0f;
778 DryGain *= ConeVolume;
779 if(WetGainAuto)
781 for(i = 0;i < NumSends;i++)
782 WetGain[i] *= ConeVolume;
784 if(DryGainHFAuto)
785 DryGainHF *= ConeHF;
786 if(WetGainHFAuto)
788 for(i = 0;i < NumSends;i++)
789 WetGainHF[i] *= ConeHF;
792 /* Clamp to Min/Max Gain */
793 DryGain = clampf(DryGain, MinVolume, MaxVolume);
794 for(i = 0;i < NumSends;i++)
795 WetGain[i] = clampf(WetGain[i], MinVolume, MaxVolume);
797 /* Apply gain and frequency filters */
798 DryGain *= ALSource->DirectGain * ListenerGain;
799 DryGainHF *= ALSource->DirectGainHF;
800 for(i = 0;i < NumSends;i++)
802 WetGain[i] *= ALSource->Send[i].Gain * ListenerGain;
803 WetGainHF[i] *= ALSource->Send[i].GainHF;
806 /* Calculate velocity-based doppler effect */
807 if(DopplerFactor > 0.0f)
809 const ALfloat *ListenerVel = ALContext->Listener->Params.Velocity;
810 ALfloat VSS, VLS;
812 if(SpeedOfSound < 1.0f)
814 DopplerFactor *= 1.0f/SpeedOfSound;
815 SpeedOfSound = 1.0f;
818 VSS = aluDotproduct(Velocity, SourceToListener) * DopplerFactor;
819 VLS = aluDotproduct(ListenerVel, SourceToListener) * DopplerFactor;
821 Pitch *= clampf(SpeedOfSound-VLS, 1.0f, SpeedOfSound*2.0f - 1.0f) /
822 clampf(SpeedOfSound-VSS, 1.0f, SpeedOfSound*2.0f - 1.0f);
825 BufferListItem = ALSource->queue;
826 while(BufferListItem != NULL)
828 ALbuffer *ALBuffer;
829 if((ALBuffer=BufferListItem->buffer) != NULL)
831 /* Calculate fixed-point stepping value, based on the pitch, buffer
832 * frequency, and output frequency. */
833 Pitch = Pitch * ALBuffer->Frequency / Frequency;
834 if(Pitch > 10.0f)
835 src->Step = 10<<FRACTIONBITS;
836 else
838 src->Step = fastf2i(Pitch*FRACTIONONE);
839 if(src->Step == 0)
840 src->Step = 1;
842 src->Resample = SelectResampler(Resampler, src->Step);
844 break;
846 BufferListItem = BufferListItem->next;
848 if(Device->Hrtf)
849 src->DryMix = SelectHrtfMixer();
850 else
851 src->DryMix = SelectDirectMixer();
852 src->WetMix = SelectSendMixer();
854 if(Device->Hrtf)
856 /* Use a binaural HRTF algorithm for stereo headphone playback */
857 ALfloat delta, ev = 0.0f, az = 0.0f;
859 if(Distance > FLT_EPSILON)
861 ALfloat invlen = 1.0f/Distance;
862 Position[0] *= invlen;
863 Position[1] *= invlen;
864 Position[2] *= invlen;
866 /* Calculate elevation and azimuth only when the source is not at
867 * the listener. This prevents +0 and -0 Z from producing
868 * inconsistent panning. Also, clamp Y in case FP precision errors
869 * cause it to land outside of -1..+1. */
870 ev = asinf(clampf(Position[1], -1.0f, 1.0f));
871 az = atan2f(Position[0], -Position[2]*ZScale);
874 /* Check to see if the HRIR is already moving. */
875 if(ALSource->Hrtf.Moving)
877 /* Calculate the normalized HRTF transition factor (delta). */
878 delta = CalcHrtfDelta(src->Direct.Hrtf.Params.Gain, DryGain,
879 src->Direct.Hrtf.Params.Dir, Position);
880 /* If the delta is large enough, get the moving HRIR target
881 * coefficients, target delays, steppping values, and counter. */
882 if(delta > 0.001f)
884 ALSource->Hrtf.Counter = GetMovingHrtfCoeffs(Device->Hrtf,
885 ev, az, DryGain, delta,
886 ALSource->Hrtf.Counter,
887 src->Direct.Hrtf.Params.Coeffs[0],
888 src->Direct.Hrtf.Params.Delay[0],
889 src->Direct.Hrtf.Params.CoeffStep,
890 src->Direct.Hrtf.Params.DelayStep);
891 src->Direct.Hrtf.Params.Gain = DryGain;
892 src->Direct.Hrtf.Params.Dir[0] = Position[0];
893 src->Direct.Hrtf.Params.Dir[1] = Position[1];
894 src->Direct.Hrtf.Params.Dir[2] = Position[2];
897 else
899 /* Get the initial (static) HRIR coefficients and delays. */
900 GetLerpedHrtfCoeffs(Device->Hrtf, ev, az, DryGain,
901 src->Direct.Hrtf.Params.Coeffs[0],
902 src->Direct.Hrtf.Params.Delay[0]);
903 ALSource->Hrtf.Counter = 0;
904 ALSource->Hrtf.Moving = AL_TRUE;
905 src->Direct.Hrtf.Params.Gain = DryGain;
906 src->Direct.Hrtf.Params.Dir[0] = Position[0];
907 src->Direct.Hrtf.Params.Dir[1] = Position[1];
908 src->Direct.Hrtf.Params.Dir[2] = Position[2];
910 src->Direct.Hrtf.Params.IrSize = GetHrtfIrSize(Device->Hrtf);
912 src->Direct.Hrtf.State = &ALSource->Hrtf;
914 else
916 ALfloat (*Matrix)[MaxChannels] = src->Direct.Gains;
917 ALfloat DirGain = 0.0f;
918 ALfloat AmbientGain;
920 for(i = 0;i < MAX_INPUT_CHANNELS;i++)
922 for(j = 0;j < MaxChannels;j++)
923 Matrix[i][j] = 0.0f;
926 /* Normalize the length, and compute panned gains. */
927 if(Distance > FLT_EPSILON)
929 ALfloat invlen = 1.0f/Distance;
930 Position[0] *= invlen;
931 Position[1] *= invlen;
932 Position[2] *= invlen;
934 DirGain = sqrtf(Position[0]*Position[0] + Position[2]*Position[2]);
935 ComputeAngleGains(Device, atan2f(Position[0], -Position[2]*ZScale), 0.0f,
936 DryGain*DirGain, Matrix[0]);
939 /* Adjustment for vertical offsets. Not the greatest, but simple
940 * enough. */
941 AmbientGain = DryGain * sqrtf(1.0f/Device->NumChan) * (1.0f-DirGain);
942 for(i = 0;i < (ALint)Device->NumChan;i++)
944 enum Channel chan = Device->Speaker2Chan[i];
945 Matrix[0][chan] = maxf(Matrix[0][chan], AmbientGain);
948 for(i = 0;i < NumSends;i++)
949 src->Send[i].Gain = WetGain[i];
953 ALfloat gain = maxf(0.01f, DryGainHF);
954 ALfilterState_setParams(&src->Direct.LpFilter[0],
955 ALfilterType_HighShelf, gain,
956 (ALfloat)LOWPASSFREQREF/Frequency, 0.0f);
958 for(i = 0;i < NumSends;i++)
960 ALfloat gain = maxf(0.01f, WetGainHF[i]);
961 ALfilterState_setParams(&src->Send[i].LpFilter[0],
962 ALfilterType_HighShelf, gain,
963 (ALfloat)LOWPASSFREQREF/Frequency, 0.0f);
968 static inline ALint aluF2I25(ALfloat val)
970 /* Clamp the value between -1 and +1. This handles that with only a single branch. */
971 if(fabsf(val) > 1.0f)
972 val = (ALfloat)((0.0f < val) - (val < 0.0f));
973 /* Convert to a signed integer, between -16777215 and +16777215. */
974 return fastf2i(val*16777215.0f);
977 static inline ALfloat aluF2F(ALfloat val)
978 { return val; }
979 static inline ALint aluF2I(ALfloat val)
980 { return aluF2I25(val)<<7; }
981 static inline ALuint aluF2UI(ALfloat val)
982 { return aluF2I(val)+2147483648u; }
983 static inline ALshort aluF2S(ALfloat val)
984 { return aluF2I25(val)>>9; }
985 static inline ALushort aluF2US(ALfloat val)
986 { return aluF2S(val)+32768; }
987 static inline ALbyte aluF2B(ALfloat val)
988 { return aluF2I25(val)>>17; }
989 static inline ALubyte aluF2UB(ALfloat val)
990 { return aluF2B(val)+128; }
992 #define DECL_TEMPLATE(T, func) \
993 static int Write_##T(ALCdevice *device, T *restrict buffer, \
994 ALuint SamplesToDo) \
996 ALfloat (*restrict DryBuffer)[BUFFERSIZE] = device->DryBuffer; \
997 ALuint numchans = ChannelsFromDevFmt(device->FmtChans); \
998 const ALuint *offsets = device->ChannelOffsets; \
999 ALuint i, j; \
1001 for(j = 0;j < MaxChannels;j++) \
1003 T *restrict out; \
1005 if(offsets[j] == INVALID_OFFSET) \
1006 continue; \
1008 out = buffer + offsets[j]; \
1009 for(i = 0;i < SamplesToDo;i++) \
1010 out[i*numchans] = func(DryBuffer[j][i]); \
1012 return SamplesToDo*numchans*sizeof(T); \
1015 DECL_TEMPLATE(ALfloat, aluF2F)
1016 DECL_TEMPLATE(ALuint, aluF2UI)
1017 DECL_TEMPLATE(ALint, aluF2I)
1018 DECL_TEMPLATE(ALushort, aluF2US)
1019 DECL_TEMPLATE(ALshort, aluF2S)
1020 DECL_TEMPLATE(ALubyte, aluF2UB)
1021 DECL_TEMPLATE(ALbyte, aluF2B)
1023 #undef DECL_TEMPLATE
1026 ALvoid aluMixData(ALCdevice *device, ALvoid *buffer, ALsizei size)
1028 ALuint SamplesToDo;
1029 ALeffectslot **slot, **slot_end;
1030 ALactivesource **src, **src_end;
1031 ALCcontext *ctx;
1032 FPUCtl oldMode;
1033 ALuint i, c;
1035 SetMixerFPUMode(&oldMode);
1037 while(size > 0)
1039 SamplesToDo = minu(size, BUFFERSIZE);
1040 for(c = 0;c < MaxChannels;c++)
1041 memset(device->DryBuffer[c], 0, SamplesToDo*sizeof(ALfloat));
1043 ALCdevice_Lock(device);
1044 V(device->Synth,process)(SamplesToDo, device->DryBuffer);
1046 ctx = device->ContextList;
1047 while(ctx)
1049 ALenum DeferUpdates = ctx->DeferUpdates;
1050 ALenum UpdateSources = AL_FALSE;
1052 if(!DeferUpdates)
1053 UpdateSources = ExchangeInt(&ctx->UpdateSources, AL_FALSE);
1055 if(UpdateSources)
1056 CalcListenerParams(ctx->Listener);
1058 /* source processing */
1059 src = ctx->ActiveSources;
1060 src_end = src + ctx->ActiveSourceCount;
1061 while(src != src_end)
1063 ALsource *source = (*src)->Source;
1065 if(source->state != AL_PLAYING && source->state != AL_PAUSED)
1067 ALactivesource *temp = *(--src_end);
1068 *src_end = *src;
1069 *src = temp;
1070 --(ctx->ActiveSourceCount);
1071 continue;
1074 if(!DeferUpdates && (ExchangeInt(&source->NeedsUpdate, AL_FALSE) ||
1075 UpdateSources))
1076 (*src)->Update(*src, ctx);
1078 if(source->state != AL_PAUSED)
1079 MixSource(*src, device, SamplesToDo);
1080 src++;
1083 /* effect slot processing */
1084 slot = ctx->ActiveEffectSlots;
1085 slot_end = slot + ctx->ActiveEffectSlotCount;
1086 while(slot != slot_end)
1088 ALfloat offset = (*slot)->ClickRemoval[0];
1089 if(offset < (1.0f/32768.0f))
1090 offset = 0.0f;
1091 else for(i = 0;i < SamplesToDo;i++)
1093 (*slot)->WetBuffer[0][i] += offset;
1094 offset -= offset * (1.0f/256.0f);
1096 (*slot)->ClickRemoval[0] = offset + (*slot)->PendingClicks[0];
1097 (*slot)->PendingClicks[0] = 0.0f;
1099 if(!DeferUpdates && ExchangeInt(&(*slot)->NeedsUpdate, AL_FALSE))
1100 V((*slot)->EffectState,update)(device, *slot);
1102 V((*slot)->EffectState,process)(SamplesToDo, (*slot)->WetBuffer[0],
1103 device->DryBuffer);
1105 for(i = 0;i < SamplesToDo;i++)
1106 (*slot)->WetBuffer[0][i] = 0.0f;
1108 slot++;
1111 ctx = ctx->next;
1114 slot = &device->DefaultSlot;
1115 if(*slot != NULL)
1117 ALfloat offset = (*slot)->ClickRemoval[0];
1118 if(offset < (1.0f/32768.0f))
1119 offset = 0.0f;
1120 else for(i = 0;i < SamplesToDo;i++)
1122 (*slot)->WetBuffer[0][i] += offset;
1123 offset -= offset * (1.0f/256.0f);
1125 (*slot)->ClickRemoval[0] = offset + (*slot)->PendingClicks[0];
1126 (*slot)->PendingClicks[0] = 0.0f;
1128 if(ExchangeInt(&(*slot)->NeedsUpdate, AL_FALSE))
1129 V((*slot)->EffectState,update)(device, *slot);
1131 V((*slot)->EffectState,process)(SamplesToDo, (*slot)->WetBuffer[0],
1132 device->DryBuffer);
1134 for(i = 0;i < SamplesToDo;i++)
1135 (*slot)->WetBuffer[0][i] = 0.0f;
1138 /* Increment the clock time. Every second's worth of samples is
1139 * converted and added to clock base so that large sample counts don't
1140 * overflow during conversion. This also guarantees an exact, stable
1141 * conversion. */
1142 device->SamplesDone += SamplesToDo;
1143 device->ClockBase += (device->SamplesDone/device->Frequency) * DEVICE_CLOCK_RES;
1144 device->SamplesDone %= device->Frequency;
1145 ALCdevice_Unlock(device);
1147 /* Click-removal. Could do better; this only really handles immediate
1148 * changes between updates where a predictive sample could be
1149 * generated. Delays caused by effects and HRTF aren't caught. */
1150 if(device->FmtChans == DevFmtStereo)
1152 /* Assumes the first two channels are FrontLeft and FrontRight */
1153 for(c = 0;c < 2;c++)
1155 ALfloat offset = device->ClickRemoval[c];
1156 if(offset < (1.0f/32768.0f))
1157 offset = 0.0f;
1158 else for(i = 0;i < SamplesToDo;i++)
1160 device->DryBuffer[c][i] += offset;
1161 offset -= offset * (1.0f/256.0f);
1163 device->ClickRemoval[c] = offset + device->PendingClicks[c];
1164 device->PendingClicks[c] = 0.0f;
1166 if(device->Bs2b)
1168 float samples[2];
1169 for(i = 0;i < SamplesToDo;i++)
1171 samples[0] = device->DryBuffer[FrontLeft][i];
1172 samples[1] = device->DryBuffer[FrontRight][i];
1173 bs2b_cross_feed(device->Bs2b, samples);
1174 device->DryBuffer[FrontLeft][i] = samples[0];
1175 device->DryBuffer[FrontRight][i] = samples[1];
1179 else
1181 for(c = 0;c < MaxChannels;c++)
1183 ALfloat offset = device->ClickRemoval[c];
1184 if(offset < (1.0f/32768.0f))
1185 offset = 0.0f;
1186 else for(i = 0;i < SamplesToDo;i++)
1188 device->DryBuffer[c][i] += offset;
1189 offset -= offset * (1.0f/256.0f);
1191 device->ClickRemoval[c] = offset + device->PendingClicks[c];
1192 device->PendingClicks[c] = 0.0f;
1196 if(buffer)
1198 int bytes = 0;
1199 switch(device->FmtType)
1201 case DevFmtByte:
1202 bytes = Write_ALbyte(device, buffer, SamplesToDo);
1203 break;
1204 case DevFmtUByte:
1205 bytes = Write_ALubyte(device, buffer, SamplesToDo);
1206 break;
1207 case DevFmtShort:
1208 bytes = Write_ALshort(device, buffer, SamplesToDo);
1209 break;
1210 case DevFmtUShort:
1211 bytes = Write_ALushort(device, buffer, SamplesToDo);
1212 break;
1213 case DevFmtInt:
1214 bytes = Write_ALint(device, buffer, SamplesToDo);
1215 break;
1216 case DevFmtUInt:
1217 bytes = Write_ALuint(device, buffer, SamplesToDo);
1218 break;
1219 case DevFmtFloat:
1220 bytes = Write_ALfloat(device, buffer, SamplesToDo);
1221 break;
1224 buffer = (ALubyte*)buffer + bytes;
1227 size -= SamplesToDo;
1230 RestoreFPUMode(&oldMode);
1234 ALvoid aluHandleDisconnect(ALCdevice *device)
1236 ALCcontext *Context;
1238 device->Connected = ALC_FALSE;
1240 Context = device->ContextList;
1241 while(Context)
1243 ALactivesource **src, **src_end;
1245 src = Context->ActiveSources;
1246 src_end = src + Context->ActiveSourceCount;
1247 while(src != src_end)
1249 ALsource *source = (*src)->Source;
1250 if(source->state == AL_PLAYING)
1252 source->state = AL_STOPPED;
1253 source->BuffersPlayed = source->BuffersInQueue;
1254 source->position = 0;
1255 source->position_fraction = 0;
1257 src++;
1259 Context->ActiveSourceCount = 0;
1261 Context = Context->next;