Rename the ALEffect_ macros to ALeffectState_ to reflect what they work on
[openal-soft/android.git] / Alc / ALu.c
blob2b5a6e75f3357b13cce1c42f77a02c545b63ece0
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 "AL/al.h"
31 #include "AL/alc.h"
32 #include "alSource.h"
33 #include "alBuffer.h"
34 #include "alListener.h"
35 #include "alAuxEffectSlot.h"
36 #include "alu.h"
37 #include "bs2b.h"
40 static __inline ALvoid aluCrossproduct(const ALfloat *inVector1, const ALfloat *inVector2, ALfloat *outVector)
42 outVector[0] = inVector1[1]*inVector2[2] - inVector1[2]*inVector2[1];
43 outVector[1] = inVector1[2]*inVector2[0] - inVector1[0]*inVector2[2];
44 outVector[2] = inVector1[0]*inVector2[1] - inVector1[1]*inVector2[0];
47 static __inline ALfloat aluDotproduct(const ALfloat *inVector1, const ALfloat *inVector2)
49 return inVector1[0]*inVector2[0] + inVector1[1]*inVector2[1] +
50 inVector1[2]*inVector2[2];
53 static __inline ALvoid aluNormalize(ALfloat *inVector)
55 ALfloat length, inverse_length;
57 length = aluSqrt(aluDotproduct(inVector, inVector));
58 if(length != 0.0f)
60 inverse_length = 1.0f/length;
61 inVector[0] *= inverse_length;
62 inVector[1] *= inverse_length;
63 inVector[2] *= inverse_length;
67 static __inline ALvoid aluMatrixVector(ALfloat *vector,ALfloat w,ALfloat matrix[4][4])
69 ALfloat temp[4] = {
70 vector[0], vector[1], vector[2], w
73 vector[0] = temp[0]*matrix[0][0] + temp[1]*matrix[1][0] + temp[2]*matrix[2][0] + temp[3]*matrix[3][0];
74 vector[1] = temp[0]*matrix[0][1] + temp[1]*matrix[1][1] + temp[2]*matrix[2][1] + temp[3]*matrix[3][1];
75 vector[2] = temp[0]*matrix[0][2] + temp[1]*matrix[1][2] + temp[2]*matrix[2][2] + temp[3]*matrix[3][2];
79 ALvoid CalcNonAttnSourceParams(ALsource *ALSource, const ALCcontext *ALContext)
81 static const ALfloat angles_Mono[1] = { 0.0f };
82 static const ALfloat angles_Stereo[2] = { -30.0f, 30.0f };
83 static const ALfloat angles_Rear[2] = { -150.0f, 150.0f };
84 static const ALfloat angles_Quad[4] = { -45.0f, 45.0f, -135.0f, 135.0f };
85 static const ALfloat angles_X51[6] = { -30.0f, 30.0f, 0.0f, 0.0f,
86 -110.0f, 110.0f };
87 static const ALfloat angles_X61[7] = { -30.0f, 30.0f, 0.0f, 0.0f,
88 180.0f, -90.0f, 90.0f };
89 static const ALfloat angles_X71[8] = { -30.0f, 30.0f, 0.0f, 0.0f,
90 -110.0f, 110.0f, -90.0f, 90.0f };
92 static const enum Channel chans_Mono[1] = { FRONT_CENTER };
93 static const enum Channel chans_Stereo[2] = { FRONT_LEFT, FRONT_RIGHT };
94 static const enum Channel chans_Rear[2] = { BACK_LEFT, BACK_RIGHT };
95 static const enum Channel chans_Quad[4] = { FRONT_LEFT, FRONT_RIGHT,
96 BACK_LEFT, BACK_RIGHT };
97 static const enum Channel chans_X51[6] = { FRONT_LEFT, FRONT_RIGHT,
98 FRONT_CENTER, LFE,
99 BACK_LEFT, BACK_RIGHT };
100 static const enum Channel chans_X61[7] = { FRONT_LEFT, FRONT_RIGHT,
101 FRONT_CENTER, LFE, BACK_CENTER,
102 SIDE_LEFT, SIDE_RIGHT };
103 static const enum Channel chans_X71[8] = { FRONT_LEFT, FRONT_RIGHT,
104 FRONT_CENTER, LFE,
105 BACK_LEFT, BACK_RIGHT,
106 SIDE_LEFT, SIDE_RIGHT };
108 ALCdevice *Device = ALContext->Device;
109 ALfloat SourceVolume,ListenerGain,MinVolume,MaxVolume;
110 ALbufferlistitem *BufferListItem;
111 enum DevFmtChannels DevChans;
112 enum FmtChannels Channels;
113 ALfloat (*SrcMatrix)[MAXCHANNELS];
114 ALfloat DryGain, DryGainHF;
115 ALfloat WetGain[MAX_SENDS];
116 ALfloat WetGainHF[MAX_SENDS];
117 ALint NumSends, Frequency;
118 const ALfloat *SpeakerGain;
119 const ALfloat *angles = NULL;
120 const enum Channel *chans = NULL;
121 enum Resampler Resampler;
122 ALint num_channels = 0;
123 ALboolean VirtualChannels;
124 ALfloat Pitch;
125 ALfloat cw;
126 ALuint pos;
127 ALint i, c;
129 /* Get device properties */
130 DevChans = ALContext->Device->FmtChans;
131 NumSends = ALContext->Device->NumAuxSends;
132 Frequency = ALContext->Device->Frequency;
134 /* Get listener properties */
135 ListenerGain = ALContext->Listener.Gain;
137 /* Get source properties */
138 SourceVolume = ALSource->flGain;
139 MinVolume = ALSource->flMinGain;
140 MaxVolume = ALSource->flMaxGain;
141 Pitch = ALSource->flPitch;
142 Resampler = ALSource->Resampler;
143 VirtualChannels = ALSource->VirtualChannels;
145 /* Calculate the stepping value */
146 Channels = FmtMono;
147 BufferListItem = ALSource->queue;
148 while(BufferListItem != NULL)
150 ALbuffer *ALBuffer;
151 if((ALBuffer=BufferListItem->buffer) != NULL)
153 ALint maxstep = STACK_DATA_SIZE / ALSource->NumChannels /
154 ALSource->SampleSize;
155 maxstep -= ResamplerPadding[Resampler] +
156 ResamplerPrePadding[Resampler] + 1;
157 maxstep = mini(maxstep, INT_MAX>>FRACTIONBITS);
159 Pitch = Pitch * ALBuffer->Frequency / Frequency;
160 if(Pitch > (ALfloat)maxstep)
161 ALSource->Params.Step = maxstep<<FRACTIONBITS;
162 else
164 ALSource->Params.Step = Pitch*FRACTIONONE;
165 if(ALSource->Params.Step == 0)
166 ALSource->Params.Step = 1;
169 Channels = ALBuffer->FmtChannels;
171 if(ALSource->VirtualChannels && (Device->Flags&DEVICE_USE_HRTF))
172 ALSource->Params.DoMix = SelectHrtfMixer(ALBuffer,
173 (ALSource->Params.Step==FRACTIONONE) ? POINT_RESAMPLER :
174 Resampler);
175 else
176 ALSource->Params.DoMix = SelectMixer(ALBuffer,
177 (ALSource->Params.Step==FRACTIONONE) ? POINT_RESAMPLER :
178 Resampler);
179 break;
181 BufferListItem = BufferListItem->next;
184 /* Calculate gains */
185 DryGain = clampf(SourceVolume, MinVolume, MaxVolume);
186 DryGain *= ALSource->DirectGain;
187 DryGainHF = ALSource->DirectGainHF;
188 for(i = 0;i < NumSends;i++)
190 WetGain[i] = clampf(SourceVolume, MinVolume, MaxVolume);
191 WetGain[i] *= ALSource->Send[i].WetGain;
192 WetGainHF[i] = ALSource->Send[i].WetGainHF;
195 SrcMatrix = ALSource->Params.DryGains;
196 for(i = 0;i < MAXCHANNELS;i++)
198 for(c = 0;c < MAXCHANNELS;c++)
199 SrcMatrix[i][c] = 0.0f;
201 switch(Channels)
203 case FmtMono:
204 angles = angles_Mono;
205 chans = chans_Mono;
206 num_channels = 1;
207 break;
208 case FmtStereo:
209 if(VirtualChannels && (ALContext->Device->Flags&DEVICE_DUPLICATE_STEREO))
211 DryGain *= aluSqrt(2.0f/4.0f);
212 for(c = 0;c < 2;c++)
214 pos = aluCart2LUTpos(cos(angles_Rear[c] * (M_PI/180.0)),
215 sin(angles_Rear[c] * (M_PI/180.0)));
216 SpeakerGain = Device->PanningLUT[pos];
218 for(i = 0;i < (ALint)Device->NumChan;i++)
220 enum Channel chan = Device->Speaker2Chan[i];
221 SrcMatrix[c][chan] += DryGain * ListenerGain *
222 SpeakerGain[chan];
226 angles = angles_Stereo;
227 chans = chans_Stereo;
228 num_channels = 2;
229 break;
231 case FmtRear:
232 angles = angles_Rear;
233 chans = chans_Rear;
234 num_channels = 2;
235 break;
237 case FmtQuad:
238 angles = angles_Quad;
239 chans = chans_Quad;
240 num_channels = 4;
241 break;
243 case FmtX51:
244 angles = angles_X51;
245 chans = chans_X51;
246 num_channels = 6;
247 break;
249 case FmtX61:
250 angles = angles_X61;
251 chans = chans_X61;
252 num_channels = 7;
253 break;
255 case FmtX71:
256 angles = angles_X71;
257 chans = chans_X71;
258 num_channels = 8;
259 break;
262 if(VirtualChannels == AL_FALSE)
264 for(c = 0;c < num_channels;c++)
265 SrcMatrix[c][chans[c]] += DryGain * ListenerGain;
267 else if((Device->Flags&DEVICE_USE_HRTF))
269 for(c = 0;c < num_channels;c++)
271 if(chans[c] == LFE)
273 /* Skip LFE */
274 ALSource->Params.HrtfDelay[c][0] = 0;
275 ALSource->Params.HrtfDelay[c][1] = 0;
276 for(i = 0;i < HRIR_LENGTH;i++)
278 ALSource->Params.HrtfCoeffs[c][i][0] = 0.0f;
279 ALSource->Params.HrtfCoeffs[c][i][1] = 0.0f;
282 else
284 /* Get the static HRIR coefficients and delays for this
285 * channel. */
286 GetLerpedHrtfCoeffs(0.0, angles[c] * (M_PI/180.0),
287 DryGain*ListenerGain,
288 ALSource->Params.HrtfCoeffs[c],
289 ALSource->Params.HrtfDelay[c]);
291 ALSource->HrtfCounter = 0;
294 else
296 for(c = 0;c < num_channels;c++)
298 if(chans[c] == LFE) /* Special-case LFE */
300 SrcMatrix[c][LFE] += DryGain * ListenerGain;
301 continue;
303 pos = aluCart2LUTpos(cos(angles[c] * (M_PI/180.0)),
304 sin(angles[c] * (M_PI/180.0)));
305 SpeakerGain = Device->PanningLUT[pos];
307 for(i = 0;i < (ALint)Device->NumChan;i++)
309 enum Channel chan = Device->Speaker2Chan[i];
310 SrcMatrix[c][chan] += DryGain * ListenerGain *
311 SpeakerGain[chan];
315 for(i = 0;i < NumSends;i++)
317 ALSource->Params.Send[i].Slot = ALSource->Send[i].Slot;
318 ALSource->Params.Send[i].WetGain = WetGain[i] * ListenerGain;
321 /* Update filter coefficients. Calculations based on the I3DL2
322 * spec. */
323 cw = cos(2.0*M_PI * LOWPASSFREQCUTOFF / Frequency);
325 /* We use two chained one-pole filters, so we need to take the
326 * square root of the squared gain, which is the same as the base
327 * gain. */
328 ALSource->Params.iirFilter.coeff = lpCoeffCalc(DryGainHF, cw);
329 for(i = 0;i < NumSends;i++)
331 /* We use a one-pole filter, so we need to take the squared gain */
332 ALfloat a = lpCoeffCalc(WetGainHF[i]*WetGainHF[i], cw);
333 ALSource->Params.Send[i].iirFilter.coeff = a;
337 ALvoid CalcSourceParams(ALsource *ALSource, const ALCcontext *ALContext)
339 const ALCdevice *Device = ALContext->Device;
340 ALfloat InnerAngle,OuterAngle,Angle,Distance,ClampedDist;
341 ALfloat Direction[3],Position[3],SourceToListener[3];
342 ALfloat Velocity[3],ListenerVel[3];
343 ALfloat MinVolume,MaxVolume,MinDist,MaxDist,Rolloff;
344 ALfloat ConeVolume,ConeHF,SourceVolume,ListenerGain;
345 ALfloat DopplerFactor, DopplerVelocity, SpeedOfSound;
346 ALfloat AirAbsorptionFactor;
347 ALfloat RoomAirAbsorption[MAX_SENDS];
348 ALbufferlistitem *BufferListItem;
349 ALfloat Attenuation, EffectiveDist;
350 ALfloat RoomAttenuation[MAX_SENDS];
351 ALfloat MetersPerUnit;
352 ALfloat RoomRolloffBase;
353 ALfloat RoomRolloff[MAX_SENDS];
354 ALfloat DecayDistance[MAX_SENDS];
355 ALfloat DryGain;
356 ALfloat DryGainHF;
357 ALboolean DryGainHFAuto;
358 ALfloat WetGain[MAX_SENDS];
359 ALfloat WetGainHF[MAX_SENDS];
360 ALboolean WetGainAuto;
361 ALboolean WetGainHFAuto;
362 enum Resampler Resampler;
363 ALfloat Pitch;
364 ALuint Frequency;
365 ALint NumSends;
366 ALfloat cw;
367 ALint i;
369 DryGainHF = 1.0f;
370 for(i = 0;i < MAX_SENDS;i++)
371 WetGainHF[i] = 1.0f;
373 //Get context properties
374 DopplerFactor = ALContext->DopplerFactor * ALSource->DopplerFactor;
375 DopplerVelocity = ALContext->DopplerVelocity;
376 SpeedOfSound = ALContext->flSpeedOfSound;
377 NumSends = Device->NumAuxSends;
378 Frequency = Device->Frequency;
380 //Get listener properties
381 ListenerGain = ALContext->Listener.Gain;
382 MetersPerUnit = ALContext->Listener.MetersPerUnit;
383 ListenerVel[0] = ALContext->Listener.Velocity[0];
384 ListenerVel[1] = ALContext->Listener.Velocity[1];
385 ListenerVel[2] = ALContext->Listener.Velocity[2];
387 //Get source properties
388 SourceVolume = ALSource->flGain;
389 MinVolume = ALSource->flMinGain;
390 MaxVolume = ALSource->flMaxGain;
391 Pitch = ALSource->flPitch;
392 Resampler = ALSource->Resampler;
393 Position[0] = ALSource->vPosition[0];
394 Position[1] = ALSource->vPosition[1];
395 Position[2] = ALSource->vPosition[2];
396 Direction[0] = ALSource->vOrientation[0];
397 Direction[1] = ALSource->vOrientation[1];
398 Direction[2] = ALSource->vOrientation[2];
399 Velocity[0] = ALSource->vVelocity[0];
400 Velocity[1] = ALSource->vVelocity[1];
401 Velocity[2] = ALSource->vVelocity[2];
402 MinDist = ALSource->flRefDistance;
403 MaxDist = ALSource->flMaxDistance;
404 Rolloff = ALSource->flRollOffFactor;
405 InnerAngle = ALSource->flInnerAngle * ConeScale;
406 OuterAngle = ALSource->flOuterAngle * ConeScale;
407 AirAbsorptionFactor = ALSource->AirAbsorptionFactor;
408 DryGainHFAuto = ALSource->DryGainHFAuto;
409 WetGainAuto = ALSource->WetGainAuto;
410 WetGainHFAuto = ALSource->WetGainHFAuto;
411 RoomRolloffBase = ALSource->RoomRolloffFactor;
412 for(i = 0;i < NumSends;i++)
414 ALeffectslot *Slot = ALSource->Send[i].Slot;
416 if(!Slot || Slot->effect.type == AL_EFFECT_NULL)
418 RoomRolloff[i] = 0.0f;
419 DecayDistance[i] = 0.0f;
420 RoomAirAbsorption[i] = 1.0f;
422 else if(Slot->AuxSendAuto)
424 RoomRolloff[i] = RoomRolloffBase;
425 if(IsReverbEffect(Slot->effect.type))
427 RoomRolloff[i] += Slot->effect.Reverb.RoomRolloffFactor;
428 DecayDistance[i] = Slot->effect.Reverb.DecayTime *
429 SPEEDOFSOUNDMETRESPERSEC;
430 RoomAirAbsorption[i] = Slot->effect.Reverb.AirAbsorptionGainHF;
432 else
434 DecayDistance[i] = 0.0f;
435 RoomAirAbsorption[i] = 1.0f;
438 else
440 /* If the slot's auxiliary send auto is off, the data sent to the
441 * effect slot is the same as the dry path, sans filter effects */
442 RoomRolloff[i] = Rolloff;
443 DecayDistance[i] = 0.0f;
444 RoomAirAbsorption[i] = AIRABSORBGAINHF;
447 ALSource->Params.Send[i].Slot = Slot;
450 //1. Translate Listener to origin (convert to head relative)
451 if(ALSource->bHeadRelative == AL_FALSE)
453 ALfloat U[3],V[3],N[3];
454 ALfloat Matrix[4][4];
456 // Build transform matrix
457 N[0] = ALContext->Listener.Forward[0]; // At-vector
458 N[1] = ALContext->Listener.Forward[1];
459 N[2] = ALContext->Listener.Forward[2];
460 aluNormalize(N); // Normalized At-vector
461 V[0] = ALContext->Listener.Up[0]; // Up-vector
462 V[1] = ALContext->Listener.Up[1];
463 V[2] = ALContext->Listener.Up[2];
464 aluNormalize(V); // Normalized Up-vector
465 aluCrossproduct(N, V, U); // Right-vector
466 aluNormalize(U); // Normalized Right-vector
467 Matrix[0][0] = U[0]; Matrix[0][1] = V[0]; Matrix[0][2] = -N[0]; Matrix[0][3] = 0.0f;
468 Matrix[1][0] = U[1]; Matrix[1][1] = V[1]; Matrix[1][2] = -N[1]; Matrix[1][3] = 0.0f;
469 Matrix[2][0] = U[2]; Matrix[2][1] = V[2]; Matrix[2][2] = -N[2]; Matrix[2][3] = 0.0f;
470 Matrix[3][0] = 0.0f; Matrix[3][1] = 0.0f; Matrix[3][2] = 0.0f; Matrix[3][3] = 1.0f;
472 // Translate position
473 Position[0] -= ALContext->Listener.Position[0];
474 Position[1] -= ALContext->Listener.Position[1];
475 Position[2] -= ALContext->Listener.Position[2];
477 // Transform source position and direction into listener space
478 aluMatrixVector(Position, 1.0f, Matrix);
479 aluMatrixVector(Direction, 0.0f, Matrix);
480 // Transform source and listener velocity into listener space
481 aluMatrixVector(Velocity, 0.0f, Matrix);
482 aluMatrixVector(ListenerVel, 0.0f, Matrix);
484 else
485 ListenerVel[0] = ListenerVel[1] = ListenerVel[2] = 0.0f;
487 SourceToListener[0] = -Position[0];
488 SourceToListener[1] = -Position[1];
489 SourceToListener[2] = -Position[2];
490 aluNormalize(SourceToListener);
491 aluNormalize(Direction);
493 //2. Calculate distance attenuation
494 Distance = aluSqrt(aluDotproduct(Position, Position));
495 ClampedDist = Distance;
497 Attenuation = 1.0f;
498 for(i = 0;i < NumSends;i++)
499 RoomAttenuation[i] = 1.0f;
500 switch(ALContext->SourceDistanceModel ? ALSource->DistanceModel :
501 ALContext->DistanceModel)
503 case InverseDistanceClamped:
504 ClampedDist = clampf(ClampedDist, MinDist, MaxDist);
505 if(MaxDist < MinDist)
506 break;
507 //fall-through
508 case InverseDistance:
509 if(MinDist > 0.0f)
511 if((MinDist + (Rolloff * (ClampedDist - MinDist))) > 0.0f)
512 Attenuation = MinDist / (MinDist + (Rolloff * (ClampedDist - MinDist)));
513 for(i = 0;i < NumSends;i++)
515 if((MinDist + (RoomRolloff[i] * (ClampedDist - MinDist))) > 0.0f)
516 RoomAttenuation[i] = MinDist / (MinDist + (RoomRolloff[i] * (ClampedDist - MinDist)));
519 break;
521 case LinearDistanceClamped:
522 ClampedDist = clampf(ClampedDist, MinDist, MaxDist);
523 if(MaxDist < MinDist)
524 break;
525 //fall-through
526 case LinearDistance:
527 if(MaxDist != MinDist)
529 Attenuation = 1.0f - (Rolloff*(ClampedDist-MinDist)/(MaxDist - MinDist));
530 Attenuation = maxf(Attenuation, 0.0f);
531 for(i = 0;i < NumSends;i++)
533 RoomAttenuation[i] = 1.0f - (RoomRolloff[i]*(ClampedDist-MinDist)/(MaxDist - MinDist));
534 RoomAttenuation[i] = maxf(RoomAttenuation[i], 0.0f);
537 break;
539 case ExponentDistanceClamped:
540 ClampedDist = clampf(ClampedDist, MinDist, MaxDist);
541 if(MaxDist < MinDist)
542 break;
543 //fall-through
544 case ExponentDistance:
545 if(ClampedDist > 0.0f && MinDist > 0.0f)
547 Attenuation = aluPow(ClampedDist/MinDist, -Rolloff);
548 for(i = 0;i < NumSends;i++)
549 RoomAttenuation[i] = aluPow(ClampedDist/MinDist, -RoomRolloff[i]);
551 break;
553 case DisableDistance:
554 break;
557 // Source Gain + Attenuation
558 DryGain = SourceVolume * Attenuation;
559 for(i = 0;i < NumSends;i++)
560 WetGain[i] = SourceVolume * RoomAttenuation[i];
562 // Distance-based air absorption
563 EffectiveDist = 0.0f;
564 if(MinDist > 0.0f && Attenuation < 1.0f)
565 EffectiveDist = (MinDist/Attenuation - MinDist)*MetersPerUnit;
566 if(AirAbsorptionFactor > 0.0f && EffectiveDist > 0.0f)
568 DryGainHF *= aluPow(AIRABSORBGAINHF, AirAbsorptionFactor*EffectiveDist);
569 for(i = 0;i < NumSends;i++)
570 WetGainHF[i] *= aluPow(RoomAirAbsorption[i],
571 AirAbsorptionFactor*EffectiveDist);
574 //3. Apply directional soundcones
575 Angle = aluAcos(aluDotproduct(Direction,SourceToListener)) * (180.0/M_PI);
576 if(Angle >= InnerAngle && Angle <= OuterAngle)
578 ALfloat scale = (Angle-InnerAngle) / (OuterAngle-InnerAngle);
579 ConeVolume = lerp(1.0, ALSource->flOuterGain, scale);
580 ConeHF = lerp(1.0, ALSource->OuterGainHF, scale);
582 else if(Angle > OuterAngle)
584 ConeVolume = ALSource->flOuterGain;
585 ConeHF = ALSource->OuterGainHF;
587 else
589 ConeVolume = 1.0f;
590 ConeHF = 1.0f;
593 DryGain *= ConeVolume;
594 if(WetGainAuto)
596 for(i = 0;i < NumSends;i++)
597 WetGain[i] *= ConeVolume;
599 if(DryGainHFAuto)
600 DryGainHF *= ConeHF;
601 if(WetGainHFAuto)
603 for(i = 0;i < NumSends;i++)
604 WetGainHF[i] *= ConeHF;
607 // Clamp to Min/Max Gain
608 DryGain = clampf(DryGain, MinVolume, MaxVolume);
609 for(i = 0;i < NumSends;i++)
610 WetGain[i] = clampf(WetGain[i], MinVolume, MaxVolume);
612 // Apply filter gains and filters
613 DryGain *= ALSource->DirectGain * ListenerGain;
614 DryGainHF *= ALSource->DirectGainHF;
615 for(i = 0;i < NumSends;i++)
617 WetGain[i] *= ALSource->Send[i].WetGain * ListenerGain;
618 WetGainHF[i] *= ALSource->Send[i].WetGainHF;
621 if(WetGainAuto)
623 /* Apply a decay-time transformation to the wet path, based on the
624 * attenuation of the dry path.
626 * Using the approximate (effective) source to listener distance, the
627 * initial decay of the reverb effect is calculated and applied to the
628 * wet path.
630 for(i = 0;i < NumSends;i++)
632 if(DecayDistance[i] > 0.0f)
633 WetGain[i] *= aluPow(0.001f /* -60dB */,
634 EffectiveDist / DecayDistance[i]);
638 // Calculate Velocity
639 if(DopplerFactor != 0.0f)
641 ALfloat VSS, VLS;
642 ALfloat MaxVelocity = (SpeedOfSound*DopplerVelocity) /
643 DopplerFactor;
645 VSS = aluDotproduct(Velocity, SourceToListener);
646 if(VSS >= MaxVelocity)
647 VSS = (MaxVelocity - 1.0f);
648 else if(VSS <= -MaxVelocity)
649 VSS = -MaxVelocity + 1.0f;
651 VLS = aluDotproduct(ListenerVel, SourceToListener);
652 if(VLS >= MaxVelocity)
653 VLS = (MaxVelocity - 1.0f);
654 else if(VLS <= -MaxVelocity)
655 VLS = -MaxVelocity + 1.0f;
657 Pitch *= ((SpeedOfSound*DopplerVelocity) - (DopplerFactor*VLS)) /
658 ((SpeedOfSound*DopplerVelocity) - (DopplerFactor*VSS));
661 BufferListItem = ALSource->queue;
662 while(BufferListItem != NULL)
664 ALbuffer *ALBuffer;
665 if((ALBuffer=BufferListItem->buffer) != NULL)
667 ALint maxstep = STACK_DATA_SIZE / ALSource->NumChannels /
668 ALSource->SampleSize;
669 maxstep -= ResamplerPadding[Resampler] +
670 ResamplerPrePadding[Resampler] + 1;
671 maxstep = mini(maxstep, INT_MAX>>FRACTIONBITS);
673 Pitch = Pitch * ALBuffer->Frequency / Frequency;
674 if(Pitch > (ALfloat)maxstep)
675 ALSource->Params.Step = maxstep<<FRACTIONBITS;
676 else
678 ALSource->Params.Step = Pitch*FRACTIONONE;
679 if(ALSource->Params.Step == 0)
680 ALSource->Params.Step = 1;
683 if((Device->Flags&DEVICE_USE_HRTF))
684 ALSource->Params.DoMix = SelectHrtfMixer(ALBuffer,
685 (ALSource->Params.Step==FRACTIONONE) ? POINT_RESAMPLER :
686 Resampler);
687 else
688 ALSource->Params.DoMix = SelectMixer(ALBuffer,
689 (ALSource->Params.Step==FRACTIONONE) ? POINT_RESAMPLER :
690 Resampler);
691 break;
693 BufferListItem = BufferListItem->next;
696 if((Device->Flags&DEVICE_USE_HRTF))
698 // Use a binaural HRTF algorithm for stereo headphone playback
699 ALfloat delta, ev = 0.0f, az = 0.0f;
701 if(Distance > 0.0f)
703 ALfloat invlen = 1.0f/Distance;
704 Position[0] *= invlen;
705 Position[1] *= invlen;
706 Position[2] *= invlen;
708 // Calculate elevation and azimuth only when the source is not at
709 // the listener. This prevents +0 and -0 Z from producing
710 // inconsistent panning.
711 ev = asin(Position[1]);
712 az = atan2(Position[0], -Position[2]*ZScale);
715 // Check to see if the HRIR is already moving.
716 if(ALSource->HrtfMoving)
718 // Calculate the normalized HRTF transition factor (delta).
719 delta = CalcHrtfDelta(ALSource->Params.HrtfGain, DryGain,
720 ALSource->Params.HrtfDir, Position);
721 // If the delta is large enough, get the moving HRIR target
722 // coefficients, target delays, steppping values, and counter.
723 if(delta > 0.001f)
725 ALSource->HrtfCounter = GetMovingHrtfCoeffs(ev, az, DryGain,
726 delta, ALSource->HrtfCounter,
727 ALSource->Params.HrtfCoeffs[0],
728 ALSource->Params.HrtfDelay[0],
729 ALSource->Params.HrtfCoeffStep,
730 ALSource->Params.HrtfDelayStep);
731 ALSource->Params.HrtfGain = DryGain;
732 ALSource->Params.HrtfDir[0] = Position[0];
733 ALSource->Params.HrtfDir[1] = Position[1];
734 ALSource->Params.HrtfDir[2] = Position[2];
737 else
739 // Get the initial (static) HRIR coefficients and delays.
740 GetLerpedHrtfCoeffs(ev, az, DryGain,
741 ALSource->Params.HrtfCoeffs[0],
742 ALSource->Params.HrtfDelay[0]);
743 ALSource->HrtfCounter = 0;
744 ALSource->Params.HrtfGain = DryGain;
745 ALSource->Params.HrtfDir[0] = Position[0];
746 ALSource->Params.HrtfDir[1] = Position[1];
747 ALSource->Params.HrtfDir[2] = Position[2];
750 else
752 // Use energy-preserving panning algorithm for multi-speaker playback
753 ALfloat DirGain, AmbientGain;
754 const ALfloat *SpeakerGain;
755 ALfloat length;
756 ALint pos;
758 length = maxf(Distance, MinDist);
759 if(length > 0.0f)
761 ALfloat invlen = 1.0f/length;
762 Position[0] *= invlen;
763 Position[1] *= invlen;
764 Position[2] *= invlen;
767 pos = aluCart2LUTpos(-Position[2]*ZScale, Position[0]);
768 SpeakerGain = Device->PanningLUT[pos];
770 DirGain = aluSqrt(Position[0]*Position[0] + Position[2]*Position[2]);
771 // elevation adjustment for directional gain. this sucks, but
772 // has low complexity
773 AmbientGain = aluSqrt(1.0/Device->NumChan);
774 for(i = 0;i < MAXCHANNELS;i++)
776 ALuint i2;
777 for(i2 = 0;i2 < MAXCHANNELS;i2++)
778 ALSource->Params.DryGains[i][i2] = 0.0f;
780 for(i = 0;i < (ALint)Device->NumChan;i++)
782 enum Channel chan = Device->Speaker2Chan[i];
783 ALfloat gain = lerp(AmbientGain, SpeakerGain[chan], DirGain);
784 ALSource->Params.DryGains[0][chan] = DryGain * gain;
787 for(i = 0;i < NumSends;i++)
788 ALSource->Params.Send[i].WetGain = WetGain[i];
790 /* Update filter coefficients. */
791 cw = cos(2.0*M_PI * LOWPASSFREQCUTOFF / Frequency);
793 ALSource->Params.iirFilter.coeff = lpCoeffCalc(DryGainHF, cw);
794 for(i = 0;i < NumSends;i++)
796 ALfloat a = lpCoeffCalc(WetGainHF[i]*WetGainHF[i], cw);
797 ALSource->Params.Send[i].iirFilter.coeff = a;
802 static __inline ALfloat aluF2F(ALfloat val)
803 { return val; }
804 static __inline ALshort aluF2S(ALfloat val)
806 if(val > 1.0f) return 32767;
807 if(val < -1.0f) return -32768;
808 return (ALint)(val*32767.0f);
810 static __inline ALushort aluF2US(ALfloat val)
811 { return aluF2S(val)+32768; }
812 static __inline ALbyte aluF2B(ALfloat val)
813 { return aluF2S(val)>>8; }
814 static __inline ALubyte aluF2UB(ALfloat val)
815 { return aluF2US(val)>>8; }
817 #define DECL_TEMPLATE(T, N, func) \
818 static void Write_##T##_##N(ALCdevice *device, T *RESTRICT buffer, \
819 ALuint SamplesToDo) \
821 ALfloat (*RESTRICT DryBuffer)[MAXCHANNELS] = device->DryBuffer; \
822 const enum Channel *ChanMap = device->DevChannels; \
823 ALuint i, j; \
825 for(i = 0;i < SamplesToDo;i++) \
827 for(j = 0;j < N;j++) \
828 *(buffer++) = func(DryBuffer[i][ChanMap[j]]); \
832 DECL_TEMPLATE(ALfloat, 1, aluF2F)
833 DECL_TEMPLATE(ALfloat, 4, aluF2F)
834 DECL_TEMPLATE(ALfloat, 6, aluF2F)
835 DECL_TEMPLATE(ALfloat, 7, aluF2F)
836 DECL_TEMPLATE(ALfloat, 8, aluF2F)
838 DECL_TEMPLATE(ALushort, 1, aluF2US)
839 DECL_TEMPLATE(ALushort, 4, aluF2US)
840 DECL_TEMPLATE(ALushort, 6, aluF2US)
841 DECL_TEMPLATE(ALushort, 7, aluF2US)
842 DECL_TEMPLATE(ALushort, 8, aluF2US)
844 DECL_TEMPLATE(ALshort, 1, aluF2S)
845 DECL_TEMPLATE(ALshort, 4, aluF2S)
846 DECL_TEMPLATE(ALshort, 6, aluF2S)
847 DECL_TEMPLATE(ALshort, 7, aluF2S)
848 DECL_TEMPLATE(ALshort, 8, aluF2S)
850 DECL_TEMPLATE(ALubyte, 1, aluF2UB)
851 DECL_TEMPLATE(ALubyte, 4, aluF2UB)
852 DECL_TEMPLATE(ALubyte, 6, aluF2UB)
853 DECL_TEMPLATE(ALubyte, 7, aluF2UB)
854 DECL_TEMPLATE(ALubyte, 8, aluF2UB)
856 DECL_TEMPLATE(ALbyte, 1, aluF2B)
857 DECL_TEMPLATE(ALbyte, 4, aluF2B)
858 DECL_TEMPLATE(ALbyte, 6, aluF2B)
859 DECL_TEMPLATE(ALbyte, 7, aluF2B)
860 DECL_TEMPLATE(ALbyte, 8, aluF2B)
862 #undef DECL_TEMPLATE
864 #define DECL_TEMPLATE(T, N, func) \
865 static void Write_##T##_##N(ALCdevice *device, T *RESTRICT buffer, \
866 ALuint SamplesToDo) \
868 ALfloat (*RESTRICT DryBuffer)[MAXCHANNELS] = device->DryBuffer; \
869 const enum Channel *ChanMap = device->DevChannels; \
870 ALuint i, j; \
872 if(device->Bs2b) \
874 for(i = 0;i < SamplesToDo;i++) \
876 float samples[2]; \
877 samples[0] = DryBuffer[i][ChanMap[0]]; \
878 samples[1] = DryBuffer[i][ChanMap[1]]; \
879 bs2b_cross_feed(device->Bs2b, samples); \
880 *(buffer++) = func(samples[0]); \
881 *(buffer++) = func(samples[1]); \
884 else \
886 for(i = 0;i < SamplesToDo;i++) \
888 for(j = 0;j < N;j++) \
889 *(buffer++) = func(DryBuffer[i][ChanMap[j]]); \
894 DECL_TEMPLATE(ALfloat, 2, aluF2F)
895 DECL_TEMPLATE(ALushort, 2, aluF2US)
896 DECL_TEMPLATE(ALshort, 2, aluF2S)
897 DECL_TEMPLATE(ALubyte, 2, aluF2UB)
898 DECL_TEMPLATE(ALbyte, 2, aluF2B)
900 #undef DECL_TEMPLATE
902 #define DECL_TEMPLATE(T) \
903 static void Write_##T(ALCdevice *device, T *buffer, ALuint SamplesToDo) \
905 switch(device->FmtChans) \
907 case DevFmtMono: \
908 Write_##T##_1(device, buffer, SamplesToDo); \
909 break; \
910 case DevFmtStereo: \
911 Write_##T##_2(device, buffer, SamplesToDo); \
912 break; \
913 case DevFmtQuad: \
914 Write_##T##_4(device, buffer, SamplesToDo); \
915 break; \
916 case DevFmtX51: \
917 case DevFmtX51Side: \
918 Write_##T##_6(device, buffer, SamplesToDo); \
919 break; \
920 case DevFmtX61: \
921 Write_##T##_7(device, buffer, SamplesToDo); \
922 break; \
923 case DevFmtX71: \
924 Write_##T##_8(device, buffer, SamplesToDo); \
925 break; \
929 DECL_TEMPLATE(ALfloat)
930 DECL_TEMPLATE(ALushort)
931 DECL_TEMPLATE(ALshort)
932 DECL_TEMPLATE(ALubyte)
933 DECL_TEMPLATE(ALbyte)
935 #undef DECL_TEMPLATE
937 ALvoid aluMixData(ALCdevice *device, ALvoid *buffer, ALsizei size)
939 ALuint SamplesToDo;
940 ALeffectslot **slot, **slot_end;
941 ALsource **src, **src_end;
942 ALCcontext *ctx;
943 int fpuState;
944 ALuint i, c;
946 #if defined(HAVE_FESETROUND)
947 fpuState = fegetround();
948 fesetround(FE_TOWARDZERO);
949 #elif defined(HAVE__CONTROLFP)
950 fpuState = _controlfp(0, 0);
951 (void)_controlfp(_RC_CHOP, _MCW_RC);
952 #else
953 (void)fpuState;
954 #endif
956 while(size > 0)
958 /* Setup variables */
959 SamplesToDo = minu(size, BUFFERSIZE);
961 /* Clear mixing buffer */
962 memset(device->DryBuffer, 0, SamplesToDo*MAXCHANNELS*sizeof(ALfloat));
964 LockDevice(device);
965 ctx = device->ContextList;
966 while(ctx)
968 ALenum DeferUpdates = ctx->DeferUpdates;
969 ALenum UpdateSources = AL_FALSE;
971 if(!DeferUpdates)
972 UpdateSources = ExchangeInt(&ctx->UpdateSources, AL_FALSE);
974 src = ctx->ActiveSources;
975 src_end = src + ctx->ActiveSourceCount;
976 while(src != src_end)
978 if((*src)->state != AL_PLAYING)
980 --(ctx->ActiveSourceCount);
981 *src = *(--src_end);
982 continue;
985 if(!DeferUpdates && (ExchangeInt(&(*src)->NeedsUpdate, AL_FALSE) ||
986 UpdateSources))
987 ALsource_Update(*src, ctx);
989 MixSource(*src, device, SamplesToDo);
990 src++;
993 /* effect slot processing */
994 slot = ctx->ActiveEffectSlots;
995 slot_end = slot + ctx->ActiveEffectSlotCount;
996 while(slot != slot_end)
998 for(c = 0;c < SamplesToDo;c++)
1000 (*slot)->WetBuffer[c] += (*slot)->ClickRemoval[0];
1001 (*slot)->ClickRemoval[0] -= (*slot)->ClickRemoval[0] / 256.0f;
1003 (*slot)->ClickRemoval[0] += (*slot)->PendingClicks[0];
1004 (*slot)->PendingClicks[0] = 0.0f;
1006 if(!DeferUpdates && ExchangeInt(&(*slot)->NeedsUpdate, AL_FALSE))
1007 ALeffectState_Update((*slot)->EffectState, ctx, *slot);
1009 ALeffectState_Process((*slot)->EffectState, SamplesToDo,
1010 (*slot)->WetBuffer, device->DryBuffer);
1012 for(i = 0;i < SamplesToDo;i++)
1013 (*slot)->WetBuffer[i] = 0.0f;
1015 slot++;
1018 ctx = ctx->next;
1020 UnlockDevice(device);
1022 //Post processing loop
1023 if(device->FmtChans == DevFmtMono)
1025 for(i = 0;i < SamplesToDo;i++)
1027 device->DryBuffer[i][FRONT_CENTER] += device->ClickRemoval[FRONT_CENTER];
1028 device->ClickRemoval[FRONT_CENTER] -= device->ClickRemoval[FRONT_CENTER] / 256.0f;
1030 device->ClickRemoval[FRONT_CENTER] += device->PendingClicks[FRONT_CENTER];
1031 device->PendingClicks[FRONT_CENTER] = 0.0f;
1033 else if(device->FmtChans == DevFmtStereo)
1035 /* Assumes the first two channels are FRONT_LEFT and FRONT_RIGHT */
1036 for(i = 0;i < SamplesToDo;i++)
1038 for(c = 0;c < 2;c++)
1040 device->DryBuffer[i][c] += device->ClickRemoval[c];
1041 device->ClickRemoval[c] -= device->ClickRemoval[c] / 256.0f;
1044 for(c = 0;c < 2;c++)
1046 device->ClickRemoval[c] += device->PendingClicks[c];
1047 device->PendingClicks[c] = 0.0f;
1050 else
1052 for(i = 0;i < SamplesToDo;i++)
1054 for(c = 0;c < MAXCHANNELS;c++)
1056 device->DryBuffer[i][c] += device->ClickRemoval[c];
1057 device->ClickRemoval[c] -= device->ClickRemoval[c] / 256.0f;
1060 for(c = 0;c < MAXCHANNELS;c++)
1062 device->ClickRemoval[c] += device->PendingClicks[c];
1063 device->PendingClicks[c] = 0.0f;
1067 if(buffer)
1069 switch(device->FmtType)
1071 case DevFmtByte:
1072 Write_ALbyte(device, buffer, SamplesToDo);
1073 break;
1074 case DevFmtUByte:
1075 Write_ALubyte(device, buffer, SamplesToDo);
1076 break;
1077 case DevFmtShort:
1078 Write_ALshort(device, buffer, SamplesToDo);
1079 break;
1080 case DevFmtUShort:
1081 Write_ALushort(device, buffer, SamplesToDo);
1082 break;
1083 case DevFmtFloat:
1084 Write_ALfloat(device, buffer, SamplesToDo);
1085 break;
1089 size -= SamplesToDo;
1092 #if defined(HAVE_FESETROUND)
1093 fesetround(fpuState);
1094 #elif defined(HAVE__CONTROLFP)
1095 _controlfp(fpuState, _MCW_RC);
1096 #endif
1100 ALvoid aluHandleDisconnect(ALCdevice *device)
1102 ALCcontext *Context;
1104 LockDevice(device);
1105 device->Connected = ALC_FALSE;
1107 Context = device->ContextList;
1108 while(Context)
1110 ALsource **src, **src_end;
1112 src = Context->ActiveSources;
1113 src_end = src + Context->ActiveSourceCount;
1114 while(src != src_end)
1116 if((*src)->state == AL_PLAYING)
1118 (*src)->state = AL_STOPPED;
1119 (*src)->BuffersPlayed = (*src)->BuffersInQueue;
1120 (*src)->position = 0;
1121 (*src)->position_fraction = 0;
1123 src++;
1125 Context->ActiveSourceCount = 0;
1127 Context = Context->next;
1129 UnlockDevice(device);