Properly make the source velocity relative to the listener velocity
[openal-soft.git] / Alc / ALu.c
blob5a53dbba5478c1d0c85354a19e392e6237ce6f02
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 struct ChanMap {
41 enum Channel channel;
42 ALfloat angle;
45 /* Cone scalar */
46 ALfloat ConeScale = 0.5f;
48 /* Localized Z scalar for mono sources */
49 ALfloat ZScale = 1.0f;
52 static __inline ALvoid aluMatrixVector(ALfloat *vector,ALfloat w,ALfloat matrix[4][4])
54 ALfloat temp[4] = {
55 vector[0], vector[1], vector[2], w
58 vector[0] = temp[0]*matrix[0][0] + temp[1]*matrix[1][0] + temp[2]*matrix[2][0] + temp[3]*matrix[3][0];
59 vector[1] = temp[0]*matrix[0][1] + temp[1]*matrix[1][1] + temp[2]*matrix[2][1] + temp[3]*matrix[3][1];
60 vector[2] = temp[0]*matrix[0][2] + temp[1]*matrix[1][2] + temp[2]*matrix[2][2] + temp[3]*matrix[3][2];
64 ALvoid CalcNonAttnSourceParams(ALsource *ALSource, const ALCcontext *ALContext)
66 static const struct ChanMap MonoMap[1] = { { FRONT_CENTER, 0.0f } };
67 static const struct ChanMap StereoMap[2] = {
68 { FRONT_LEFT, -30.0f * F_PI/180.0f },
69 { FRONT_RIGHT, 30.0f * F_PI/180.0f }
71 static const struct ChanMap RearMap[2] = {
72 { BACK_LEFT, -150.0f * F_PI/180.0f },
73 { BACK_RIGHT, 150.0f * F_PI/180.0f }
75 static const struct ChanMap QuadMap[4] = {
76 { FRONT_LEFT, -45.0f * F_PI/180.0f },
77 { FRONT_RIGHT, 45.0f * F_PI/180.0f },
78 { BACK_LEFT, -135.0f * F_PI/180.0f },
79 { BACK_RIGHT, 135.0f * F_PI/180.0f }
81 static const struct ChanMap X51Map[6] = {
82 { FRONT_LEFT, -30.0f * F_PI/180.0f },
83 { FRONT_RIGHT, 30.0f * F_PI/180.0f },
84 { FRONT_CENTER, 0.0f * F_PI/180.0f },
85 { LFE, 0.0f },
86 { BACK_LEFT, -110.0f * F_PI/180.0f },
87 { BACK_RIGHT, 110.0f * F_PI/180.0f }
89 static const struct ChanMap X61Map[7] = {
90 { FRONT_LEFT, -30.0f * F_PI/180.0f },
91 { FRONT_RIGHT, 30.0f * F_PI/180.0f },
92 { FRONT_CENTER, 0.0f * F_PI/180.0f },
93 { LFE, 0.0f },
94 { BACK_CENTER, 180.0f * F_PI/180.0f },
95 { SIDE_LEFT, -90.0f * F_PI/180.0f },
96 { SIDE_RIGHT, 90.0f * F_PI/180.0f }
98 static const struct ChanMap X71Map[8] = {
99 { FRONT_LEFT, -30.0f * F_PI/180.0f },
100 { FRONT_RIGHT, 30.0f * F_PI/180.0f },
101 { FRONT_CENTER, 0.0f * F_PI/180.0f },
102 { LFE, 0.0f },
103 { BACK_LEFT, -150.0f * F_PI/180.0f },
104 { BACK_RIGHT, 150.0f * F_PI/180.0f },
105 { SIDE_LEFT, -90.0f * F_PI/180.0f },
106 { SIDE_RIGHT, 90.0f * F_PI/180.0f }
109 ALCdevice *Device = ALContext->Device;
110 ALfloat SourceVolume,ListenerGain,MinVolume,MaxVolume;
111 ALbufferlistitem *BufferListItem;
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 *ChannelGain;
119 const struct ChanMap *chans = NULL;
120 enum Resampler Resampler;
121 ALint num_channels = 0;
122 ALboolean DirectChannels;
123 ALfloat Pitch;
124 ALfloat cw;
125 ALuint pos;
126 ALint i, c;
128 /* Get device properties */
129 NumSends = Device->NumAuxSends;
130 Frequency = Device->Frequency;
132 /* Get listener properties */
133 ListenerGain = ALContext->Listener.Gain;
135 /* Get source properties */
136 SourceVolume = ALSource->flGain;
137 MinVolume = ALSource->flMinGain;
138 MaxVolume = ALSource->flMaxGain;
139 Pitch = ALSource->flPitch;
140 Resampler = ALSource->Resampler;
141 DirectChannels = ALSource->DirectChannels;
143 /* Calculate the stepping value */
144 Channels = FmtMono;
145 BufferListItem = ALSource->queue;
146 while(BufferListItem != NULL)
148 ALbuffer *ALBuffer;
149 if((ALBuffer=BufferListItem->buffer) != NULL)
151 ALsizei maxstep = STACK_DATA_SIZE/sizeof(ALfloat) /
152 ALSource->NumChannels;
153 maxstep -= ResamplerPadding[Resampler] +
154 ResamplerPrePadding[Resampler] + 1;
155 maxstep = mini(maxstep, INT_MAX>>FRACTIONBITS);
157 Pitch = Pitch * ALBuffer->Frequency / Frequency;
158 if(Pitch > (ALfloat)maxstep)
159 ALSource->Params.Step = maxstep<<FRACTIONBITS;
160 else
162 ALSource->Params.Step = fastf2i(Pitch*FRACTIONONE);
163 if(ALSource->Params.Step == 0)
164 ALSource->Params.Step = 1;
166 if(ALSource->Params.Step == FRACTIONONE)
167 Resampler = PointResampler;
169 Channels = ALBuffer->FmtChannels;
170 break;
172 BufferListItem = BufferListItem->next;
174 if(!DirectChannels && Device->Hrtf)
175 ALSource->Params.DoMix = SelectHrtfMixer(Resampler);
176 else
177 ALSource->Params.DoMix = SelectMixer(Resampler);
179 /* Calculate gains */
180 DryGain = clampf(SourceVolume, MinVolume, MaxVolume);
181 DryGain *= ALSource->DirectGain;
182 DryGainHF = ALSource->DirectGainHF;
183 for(i = 0;i < NumSends;i++)
185 WetGain[i] = clampf(SourceVolume, MinVolume, MaxVolume);
186 WetGain[i] *= ALSource->Send[i].WetGain;
187 WetGainHF[i] = ALSource->Send[i].WetGainHF;
190 SrcMatrix = ALSource->Params.DryGains;
191 for(i = 0;i < MAXCHANNELS;i++)
193 for(c = 0;c < MAXCHANNELS;c++)
194 SrcMatrix[i][c] = 0.0f;
196 switch(Channels)
198 case FmtMono:
199 chans = MonoMap;
200 num_channels = 1;
201 break;
202 case FmtStereo:
203 if(!DirectChannels && (Device->Flags&DEVICE_DUPLICATE_STEREO))
205 DryGain *= aluSqrt(2.0f/4.0f);
206 for(c = 0;c < 2;c++)
208 pos = aluCart2LUTpos(aluCos(RearMap[c].angle),
209 aluSin(RearMap[c].angle));
210 ChannelGain = Device->PanningLUT[pos];
212 for(i = 0;i < (ALint)Device->NumChan;i++)
214 enum Channel chan = Device->Speaker2Chan[i];
215 SrcMatrix[c][chan] += DryGain * ListenerGain *
216 ChannelGain[chan];
220 chans = StereoMap;
221 num_channels = 2;
222 break;
224 case FmtRear:
225 chans = RearMap;
226 num_channels = 2;
227 break;
229 case FmtQuad:
230 chans = QuadMap;
231 num_channels = 4;
232 break;
234 case FmtX51:
235 chans = X51Map;
236 num_channels = 6;
237 break;
239 case FmtX61:
240 chans = X61Map;
241 num_channels = 7;
242 break;
244 case FmtX71:
245 chans = X71Map;
246 num_channels = 8;
247 break;
250 if(DirectChannels != AL_FALSE)
252 for(c = 0;c < num_channels;c++)
253 SrcMatrix[c][chans[c].channel] += DryGain * ListenerGain;
255 else if(Device->Hrtf)
257 for(c = 0;c < num_channels;c++)
259 if(chans[c].channel == LFE)
261 /* Skip LFE */
262 ALSource->Params.HrtfDelay[c][0] = 0;
263 ALSource->Params.HrtfDelay[c][1] = 0;
264 for(i = 0;i < HRIR_LENGTH;i++)
266 ALSource->Params.HrtfCoeffs[c][i][0] = 0.0f;
267 ALSource->Params.HrtfCoeffs[c][i][1] = 0.0f;
270 else
272 /* Get the static HRIR coefficients and delays for this
273 * channel. */
274 GetLerpedHrtfCoeffs(Device->Hrtf,
275 0.0f, F_PI/180.0f * chans[c].angle,
276 DryGain*ListenerGain,
277 ALSource->Params.HrtfCoeffs[c],
278 ALSource->Params.HrtfDelay[c]);
280 ALSource->HrtfCounter = 0;
283 else
285 for(c = 0;c < num_channels;c++)
287 if(chans[c].channel == LFE) /* Special-case LFE */
289 SrcMatrix[c][LFE] += DryGain * ListenerGain;
290 continue;
292 pos = aluCart2LUTpos(aluCos(chans[c].angle), aluSin(chans[c].angle));
293 ChannelGain = Device->PanningLUT[pos];
295 for(i = 0;i < (ALint)Device->NumChan;i++)
297 enum Channel chan = Device->Speaker2Chan[i];
298 SrcMatrix[c][chan] += DryGain * ListenerGain *
299 ChannelGain[chan];
303 for(i = 0;i < NumSends;i++)
305 ALeffectslot *Slot = ALSource->Send[i].Slot;
307 if(!Slot && i == 0)
308 Slot = Device->DefaultSlot;
309 if(Slot && Slot->effect.type == AL_EFFECT_NULL)
310 Slot = NULL;
311 ALSource->Params.Send[i].Slot = Slot;
312 ALSource->Params.Send[i].WetGain = WetGain[i] * ListenerGain;
315 /* Update filter coefficients. Calculations based on the I3DL2
316 * spec. */
317 cw = aluCos(F_PI*2.0f * LOWPASSFREQREF / Frequency);
319 /* We use two chained one-pole filters, so we need to take the
320 * square root of the squared gain, which is the same as the base
321 * gain. */
322 ALSource->Params.iirFilter.coeff = lpCoeffCalc(DryGainHF, cw);
323 for(i = 0;i < NumSends;i++)
325 /* We use a one-pole filter, so we need to take the squared gain */
326 ALfloat a = lpCoeffCalc(WetGainHF[i]*WetGainHF[i], cw);
327 ALSource->Params.Send[i].iirFilter.coeff = a;
331 ALvoid CalcSourceParams(ALsource *ALSource, const ALCcontext *ALContext)
333 const ALCdevice *Device = ALContext->Device;
334 ALfloat InnerAngle,OuterAngle,Angle,Distance,ClampedDist;
335 ALfloat Direction[3],Position[3],SourceToListener[3];
336 ALfloat Velocity[3],ListenerVel[3];
337 ALfloat MinVolume,MaxVolume,MinDist,MaxDist,Rolloff;
338 ALfloat ConeVolume,ConeHF,SourceVolume,ListenerGain;
339 ALfloat DopplerFactor, SpeedOfSound;
340 ALfloat AirAbsorptionFactor;
341 ALfloat RoomAirAbsorption[MAX_SENDS];
342 ALbufferlistitem *BufferListItem;
343 ALfloat Attenuation, EffectiveDist;
344 ALfloat RoomAttenuation[MAX_SENDS];
345 ALfloat MetersPerUnit;
346 ALfloat RoomRolloffBase;
347 ALfloat RoomRolloff[MAX_SENDS];
348 ALfloat DecayDistance[MAX_SENDS];
349 ALfloat DryGain;
350 ALfloat DryGainHF;
351 ALboolean DryGainHFAuto;
352 ALfloat WetGain[MAX_SENDS];
353 ALfloat WetGainHF[MAX_SENDS];
354 ALboolean WetGainAuto;
355 ALboolean WetGainHFAuto;
356 enum Resampler Resampler;
357 ALfloat Matrix[4][4];
358 ALfloat Pitch;
359 ALuint Frequency;
360 ALint NumSends;
361 ALfloat cw;
362 ALint i, j;
364 DryGainHF = 1.0f;
365 for(i = 0;i < MAX_SENDS;i++)
366 WetGainHF[i] = 1.0f;
368 //Get context properties
369 DopplerFactor = ALContext->DopplerFactor * ALSource->DopplerFactor;
370 SpeedOfSound = ALContext->flSpeedOfSound * ALContext->DopplerVelocity;
371 NumSends = Device->NumAuxSends;
372 Frequency = Device->Frequency;
374 //Get listener properties
375 ListenerGain = ALContext->Listener.Gain;
376 MetersPerUnit = ALContext->Listener.MetersPerUnit;
377 ListenerVel[0] = ALContext->Listener.Velocity[0];
378 ListenerVel[1] = ALContext->Listener.Velocity[1];
379 ListenerVel[2] = ALContext->Listener.Velocity[2];
381 //Get source properties
382 SourceVolume = ALSource->flGain;
383 MinVolume = ALSource->flMinGain;
384 MaxVolume = ALSource->flMaxGain;
385 Pitch = ALSource->flPitch;
386 Resampler = ALSource->Resampler;
387 Position[0] = ALSource->vPosition[0];
388 Position[1] = ALSource->vPosition[1];
389 Position[2] = ALSource->vPosition[2];
390 Direction[0] = ALSource->vOrientation[0];
391 Direction[1] = ALSource->vOrientation[1];
392 Direction[2] = ALSource->vOrientation[2];
393 Velocity[0] = ALSource->vVelocity[0];
394 Velocity[1] = ALSource->vVelocity[1];
395 Velocity[2] = ALSource->vVelocity[2];
396 MinDist = ALSource->flRefDistance;
397 MaxDist = ALSource->flMaxDistance;
398 Rolloff = ALSource->flRollOffFactor;
399 InnerAngle = ALSource->flInnerAngle * ConeScale;
400 OuterAngle = ALSource->flOuterAngle * ConeScale;
401 AirAbsorptionFactor = ALSource->AirAbsorptionFactor;
402 DryGainHFAuto = ALSource->DryGainHFAuto;
403 WetGainAuto = ALSource->WetGainAuto;
404 WetGainHFAuto = ALSource->WetGainHFAuto;
405 RoomRolloffBase = ALSource->RoomRolloffFactor;
406 for(i = 0;i < NumSends;i++)
408 ALeffectslot *Slot = ALSource->Send[i].Slot;
410 if(!Slot && i == 0)
411 Slot = Device->DefaultSlot;
412 if(!Slot || Slot->effect.type == AL_EFFECT_NULL)
414 Slot = NULL;
415 RoomRolloff[i] = 0.0f;
416 DecayDistance[i] = 0.0f;
417 RoomAirAbsorption[i] = 1.0f;
419 else if(Slot->AuxSendAuto)
421 RoomRolloff[i] = RoomRolloffBase;
422 if(IsReverbEffect(Slot->effect.type))
424 RoomRolloff[i] += Slot->effect.Reverb.RoomRolloffFactor;
425 DecayDistance[i] = Slot->effect.Reverb.DecayTime *
426 SPEEDOFSOUNDMETRESPERSEC;
427 RoomAirAbsorption[i] = Slot->effect.Reverb.AirAbsorptionGainHF;
429 else
431 DecayDistance[i] = 0.0f;
432 RoomAirAbsorption[i] = 1.0f;
435 else
437 /* If the slot's auxiliary send auto is off, the data sent to the
438 * effect slot is the same as the dry path, sans filter effects */
439 RoomRolloff[i] = Rolloff;
440 DecayDistance[i] = 0.0f;
441 RoomAirAbsorption[i] = AIRABSORBGAINHF;
444 ALSource->Params.Send[i].Slot = Slot;
447 for(i = 0;i < 4;i++)
449 for(j = 0;j < 4;j++)
450 Matrix[i][j] = ALContext->Listener.Matrix[i][j];
453 //1. Translate Listener to origin (convert to head relative)
454 if(ALSource->bHeadRelative == AL_FALSE)
456 /* Translate position */
457 Position[0] -= ALContext->Listener.Position[0];
458 Position[1] -= ALContext->Listener.Position[1];
459 Position[2] -= ALContext->Listener.Position[2];
461 /* Transform source vectors into listener space */
462 aluMatrixVector(Position, 1.0f, Matrix);
463 aluMatrixVector(Direction, 0.0f, Matrix);
464 aluMatrixVector(Velocity, 0.0f, Matrix);
465 /* Transform listener velocity into listener space */
466 aluMatrixVector(ListenerVel, 0.0f, Matrix);
468 else
470 /* Transform listener velocity into listener space */
471 aluMatrixVector(ListenerVel, 0.0f, Matrix);
472 /* Offset the source velocity to be relative of the listener velocity */
473 Velocity[0] += ListenerVel[0];
474 Velocity[1] += ListenerVel[1];
475 Velocity[2] += ListenerVel[2];
478 SourceToListener[0] = -Position[0];
479 SourceToListener[1] = -Position[1];
480 SourceToListener[2] = -Position[2];
481 aluNormalize(SourceToListener);
482 aluNormalize(Direction);
484 //2. Calculate distance attenuation
485 Distance = aluSqrt(aluDotproduct(Position, Position));
486 ClampedDist = Distance;
488 Attenuation = 1.0f;
489 for(i = 0;i < NumSends;i++)
490 RoomAttenuation[i] = 1.0f;
491 switch(ALContext->SourceDistanceModel ? ALSource->DistanceModel :
492 ALContext->DistanceModel)
494 case InverseDistanceClamped:
495 ClampedDist = clampf(ClampedDist, MinDist, MaxDist);
496 if(MaxDist < MinDist)
497 break;
498 //fall-through
499 case InverseDistance:
500 if(MinDist > 0.0f)
502 if((MinDist + (Rolloff * (ClampedDist - MinDist))) > 0.0f)
503 Attenuation = MinDist / (MinDist + (Rolloff * (ClampedDist - MinDist)));
504 for(i = 0;i < NumSends;i++)
506 if((MinDist + (RoomRolloff[i] * (ClampedDist - MinDist))) > 0.0f)
507 RoomAttenuation[i] = MinDist / (MinDist + (RoomRolloff[i] * (ClampedDist - MinDist)));
510 break;
512 case LinearDistanceClamped:
513 ClampedDist = clampf(ClampedDist, MinDist, MaxDist);
514 if(MaxDist < MinDist)
515 break;
516 //fall-through
517 case LinearDistance:
518 if(MaxDist != MinDist)
520 Attenuation = 1.0f - (Rolloff*(ClampedDist-MinDist)/(MaxDist - MinDist));
521 Attenuation = maxf(Attenuation, 0.0f);
522 for(i = 0;i < NumSends;i++)
524 RoomAttenuation[i] = 1.0f - (RoomRolloff[i]*(ClampedDist-MinDist)/(MaxDist - MinDist));
525 RoomAttenuation[i] = maxf(RoomAttenuation[i], 0.0f);
528 break;
530 case ExponentDistanceClamped:
531 ClampedDist = clampf(ClampedDist, MinDist, MaxDist);
532 if(MaxDist < MinDist)
533 break;
534 //fall-through
535 case ExponentDistance:
536 if(ClampedDist > 0.0f && MinDist > 0.0f)
538 Attenuation = aluPow(ClampedDist/MinDist, -Rolloff);
539 for(i = 0;i < NumSends;i++)
540 RoomAttenuation[i] = aluPow(ClampedDist/MinDist, -RoomRolloff[i]);
542 break;
544 case DisableDistance:
545 break;
548 // Source Gain + Attenuation
549 DryGain = SourceVolume * Attenuation;
550 for(i = 0;i < NumSends;i++)
551 WetGain[i] = SourceVolume * RoomAttenuation[i];
553 // Distance-based air absorption
554 EffectiveDist = 0.0f;
555 if(MinDist > 0.0f && Attenuation < 1.0f)
556 EffectiveDist = (MinDist/Attenuation - MinDist)*MetersPerUnit;
557 if(AirAbsorptionFactor > 0.0f && EffectiveDist > 0.0f)
559 DryGainHF *= aluPow(AIRABSORBGAINHF, AirAbsorptionFactor*EffectiveDist);
560 for(i = 0;i < NumSends;i++)
561 WetGainHF[i] *= aluPow(RoomAirAbsorption[i],
562 AirAbsorptionFactor*EffectiveDist);
565 if(WetGainAuto)
567 /* Apply a decay-time transformation to the wet path, based on the
568 * attenuation of the dry path.
570 * Using the approximate (effective) source to listener distance, the
571 * initial decay of the reverb effect is calculated and applied to the
572 * wet path.
574 for(i = 0;i < NumSends;i++)
576 if(DecayDistance[i] > 0.0f)
577 WetGain[i] *= aluPow(0.001f /* -60dB */,
578 EffectiveDist / DecayDistance[i]);
582 /* Calculate directional soundcones */
583 Angle = aluAcos(aluDotproduct(Direction,SourceToListener)) * (180.0f/F_PI);
584 if(Angle >= InnerAngle && Angle <= OuterAngle)
586 ALfloat scale = (Angle-InnerAngle) / (OuterAngle-InnerAngle);
587 ConeVolume = lerp(1.0f, ALSource->flOuterGain, scale);
588 ConeHF = lerp(1.0f, ALSource->OuterGainHF, scale);
590 else if(Angle > OuterAngle)
592 ConeVolume = ALSource->flOuterGain;
593 ConeHF = ALSource->OuterGainHF;
595 else
597 ConeVolume = 1.0f;
598 ConeHF = 1.0f;
601 DryGain *= ConeVolume;
602 if(WetGainAuto)
604 for(i = 0;i < NumSends;i++)
605 WetGain[i] *= ConeVolume;
607 if(DryGainHFAuto)
608 DryGainHF *= ConeHF;
609 if(WetGainHFAuto)
611 for(i = 0;i < NumSends;i++)
612 WetGainHF[i] *= ConeHF;
615 // Clamp to Min/Max Gain
616 DryGain = clampf(DryGain, MinVolume, MaxVolume);
617 for(i = 0;i < NumSends;i++)
618 WetGain[i] = clampf(WetGain[i], MinVolume, MaxVolume);
620 // Apply filter gains and filters
621 DryGain *= ALSource->DirectGain * ListenerGain;
622 DryGainHF *= ALSource->DirectGainHF;
623 for(i = 0;i < NumSends;i++)
625 WetGain[i] *= ALSource->Send[i].WetGain * ListenerGain;
626 WetGainHF[i] *= ALSource->Send[i].WetGainHF;
629 // Calculate Velocity
630 if(DopplerFactor > 0.0f && SpeedOfSound > 0.5f)
632 ALfloat VSS, VLS;
634 VSS = aluDotproduct(Velocity, SourceToListener) * DopplerFactor;
635 VLS = aluDotproduct(ListenerVel, SourceToListener) * DopplerFactor;
637 Pitch *= clampf(SpeedOfSound-VLS, 1.0f, SpeedOfSound*2.0f - 1.0f) /
638 clampf(SpeedOfSound-VSS, 1.0f, SpeedOfSound*2.0f - 1.0f);
641 BufferListItem = ALSource->queue;
642 while(BufferListItem != NULL)
644 ALbuffer *ALBuffer;
645 if((ALBuffer=BufferListItem->buffer) != NULL)
647 ALsizei maxstep = STACK_DATA_SIZE/sizeof(ALfloat) /
648 ALSource->NumChannels;
649 maxstep -= ResamplerPadding[Resampler] +
650 ResamplerPrePadding[Resampler] + 1;
651 maxstep = mini(maxstep, INT_MAX>>FRACTIONBITS);
653 Pitch = Pitch * ALBuffer->Frequency / Frequency;
654 if(Pitch > (ALfloat)maxstep)
655 ALSource->Params.Step = maxstep<<FRACTIONBITS;
656 else
658 ALSource->Params.Step = fastf2i(Pitch*FRACTIONONE);
659 if(ALSource->Params.Step == 0)
660 ALSource->Params.Step = 1;
662 if(ALSource->Params.Step == FRACTIONONE)
663 Resampler = PointResampler;
665 break;
667 BufferListItem = BufferListItem->next;
669 if(Device->Hrtf)
670 ALSource->Params.DoMix = SelectHrtfMixer(Resampler);
671 else
672 ALSource->Params.DoMix = SelectMixer(Resampler);
674 if(Device->Hrtf)
676 // Use a binaural HRTF algorithm for stereo headphone playback
677 ALfloat delta, ev = 0.0f, az = 0.0f;
679 if(Distance > 0.0f)
681 ALfloat invlen = 1.0f/Distance;
682 Position[0] *= invlen;
683 Position[1] *= invlen;
684 Position[2] *= invlen;
686 // Calculate elevation and azimuth only when the source is not at
687 // the listener. This prevents +0 and -0 Z from producing
688 // inconsistent panning.
689 ev = aluAsin(Position[1]);
690 az = aluAtan2(Position[0], -Position[2]*ZScale);
693 // Check to see if the HRIR is already moving.
694 if(ALSource->HrtfMoving)
696 // Calculate the normalized HRTF transition factor (delta).
697 delta = CalcHrtfDelta(ALSource->Params.HrtfGain, DryGain,
698 ALSource->Params.HrtfDir, Position);
699 // If the delta is large enough, get the moving HRIR target
700 // coefficients, target delays, steppping values, and counter.
701 if(delta > 0.001f)
703 ALSource->HrtfCounter = GetMovingHrtfCoeffs(Device->Hrtf,
704 ev, az, DryGain, delta,
705 ALSource->HrtfCounter,
706 ALSource->Params.HrtfCoeffs[0],
707 ALSource->Params.HrtfDelay[0],
708 ALSource->Params.HrtfCoeffStep,
709 ALSource->Params.HrtfDelayStep);
710 ALSource->Params.HrtfGain = DryGain;
711 ALSource->Params.HrtfDir[0] = Position[0];
712 ALSource->Params.HrtfDir[1] = Position[1];
713 ALSource->Params.HrtfDir[2] = Position[2];
716 else
718 // Get the initial (static) HRIR coefficients and delays.
719 GetLerpedHrtfCoeffs(Device->Hrtf, ev, az, DryGain,
720 ALSource->Params.HrtfCoeffs[0],
721 ALSource->Params.HrtfDelay[0]);
722 ALSource->HrtfCounter = 0;
723 ALSource->Params.HrtfGain = DryGain;
724 ALSource->Params.HrtfDir[0] = Position[0];
725 ALSource->Params.HrtfDir[1] = Position[1];
726 ALSource->Params.HrtfDir[2] = Position[2];
729 else
731 // Use energy-preserving panning algorithm for multi-speaker playback
732 ALfloat DirGain, AmbientGain;
733 const ALfloat *ChannelGain;
734 ALfloat length;
735 ALint pos;
737 length = maxf(Distance, MinDist);
738 if(length > 0.0f)
740 ALfloat invlen = 1.0f/length;
741 Position[0] *= invlen;
742 Position[1] *= invlen;
743 Position[2] *= invlen;
746 pos = aluCart2LUTpos(-Position[2]*ZScale, Position[0]);
747 ChannelGain = Device->PanningLUT[pos];
749 DirGain = aluSqrt(Position[0]*Position[0] + Position[2]*Position[2]);
750 // elevation adjustment for directional gain. this sucks, but
751 // has low complexity
752 AmbientGain = aluSqrt(1.0f/Device->NumChan);
753 for(i = 0;i < MAXCHANNELS;i++)
755 ALuint i2;
756 for(i2 = 0;i2 < MAXCHANNELS;i2++)
757 ALSource->Params.DryGains[i][i2] = 0.0f;
759 for(i = 0;i < (ALint)Device->NumChan;i++)
761 enum Channel chan = Device->Speaker2Chan[i];
762 ALfloat gain = lerp(AmbientGain, ChannelGain[chan], DirGain);
763 ALSource->Params.DryGains[0][chan] = DryGain * gain;
766 for(i = 0;i < NumSends;i++)
767 ALSource->Params.Send[i].WetGain = WetGain[i];
769 /* Update filter coefficients. */
770 cw = aluCos(F_PI*2.0f * LOWPASSFREQREF / Frequency);
772 ALSource->Params.iirFilter.coeff = lpCoeffCalc(DryGainHF, cw);
773 for(i = 0;i < NumSends;i++)
775 ALfloat a = lpCoeffCalc(WetGainHF[i]*WetGainHF[i], cw);
776 ALSource->Params.Send[i].iirFilter.coeff = a;
781 static __inline ALfloat aluF2F(ALfloat val)
782 { return val; }
783 static __inline ALint aluF2I(ALfloat val)
785 if(val > 1.0f) return 2147483647;
786 if(val < -1.0f) return -2147483647-1;
787 return fastf2i((ALfloat)(val*2147483647.0));
789 static __inline ALuint aluF2UI(ALfloat val)
790 { return aluF2I(val)+2147483648u; }
791 static __inline ALshort aluF2S(ALfloat val)
792 { return aluF2I(val)>>16; }
793 static __inline ALushort aluF2US(ALfloat val)
794 { return aluF2S(val)+32768; }
795 static __inline ALbyte aluF2B(ALfloat val)
796 { return aluF2I(val)>>24; }
797 static __inline ALubyte aluF2UB(ALfloat val)
798 { return aluF2B(val)+128; }
800 #define DECL_TEMPLATE(T, N, func) \
801 static void Write_##T##_##N(ALCdevice *device, T *RESTRICT buffer, \
802 ALuint SamplesToDo) \
804 ALfloat (*RESTRICT DryBuffer)[MAXCHANNELS] = device->DryBuffer; \
805 const enum Channel *ChanMap = device->DevChannels; \
806 ALuint i, j; \
808 for(j = 0;j < N;j++) \
810 T *RESTRICT out = buffer + j; \
811 enum Channel chan = ChanMap[j]; \
813 for(i = 0;i < SamplesToDo;i++) \
814 out[i*N] = func(DryBuffer[i][chan]); \
818 DECL_TEMPLATE(ALfloat, 1, aluF2F)
819 DECL_TEMPLATE(ALfloat, 2, aluF2F)
820 DECL_TEMPLATE(ALfloat, 4, aluF2F)
821 DECL_TEMPLATE(ALfloat, 6, aluF2F)
822 DECL_TEMPLATE(ALfloat, 7, aluF2F)
823 DECL_TEMPLATE(ALfloat, 8, aluF2F)
825 DECL_TEMPLATE(ALuint, 1, aluF2UI)
826 DECL_TEMPLATE(ALuint, 2, aluF2UI)
827 DECL_TEMPLATE(ALuint, 4, aluF2UI)
828 DECL_TEMPLATE(ALuint, 6, aluF2UI)
829 DECL_TEMPLATE(ALuint, 7, aluF2UI)
830 DECL_TEMPLATE(ALuint, 8, aluF2UI)
832 DECL_TEMPLATE(ALint, 1, aluF2I)
833 DECL_TEMPLATE(ALint, 2, aluF2I)
834 DECL_TEMPLATE(ALint, 4, aluF2I)
835 DECL_TEMPLATE(ALint, 6, aluF2I)
836 DECL_TEMPLATE(ALint, 7, aluF2I)
837 DECL_TEMPLATE(ALint, 8, aluF2I)
839 DECL_TEMPLATE(ALushort, 1, aluF2US)
840 DECL_TEMPLATE(ALushort, 2, aluF2US)
841 DECL_TEMPLATE(ALushort, 4, aluF2US)
842 DECL_TEMPLATE(ALushort, 6, aluF2US)
843 DECL_TEMPLATE(ALushort, 7, aluF2US)
844 DECL_TEMPLATE(ALushort, 8, aluF2US)
846 DECL_TEMPLATE(ALshort, 1, aluF2S)
847 DECL_TEMPLATE(ALshort, 2, aluF2S)
848 DECL_TEMPLATE(ALshort, 4, aluF2S)
849 DECL_TEMPLATE(ALshort, 6, aluF2S)
850 DECL_TEMPLATE(ALshort, 7, aluF2S)
851 DECL_TEMPLATE(ALshort, 8, aluF2S)
853 DECL_TEMPLATE(ALubyte, 1, aluF2UB)
854 DECL_TEMPLATE(ALubyte, 2, aluF2UB)
855 DECL_TEMPLATE(ALubyte, 4, aluF2UB)
856 DECL_TEMPLATE(ALubyte, 6, aluF2UB)
857 DECL_TEMPLATE(ALubyte, 7, aluF2UB)
858 DECL_TEMPLATE(ALubyte, 8, aluF2UB)
860 DECL_TEMPLATE(ALbyte, 1, aluF2B)
861 DECL_TEMPLATE(ALbyte, 2, aluF2B)
862 DECL_TEMPLATE(ALbyte, 4, aluF2B)
863 DECL_TEMPLATE(ALbyte, 6, aluF2B)
864 DECL_TEMPLATE(ALbyte, 7, aluF2B)
865 DECL_TEMPLATE(ALbyte, 8, aluF2B)
867 #undef DECL_TEMPLATE
869 #define DECL_TEMPLATE(T) \
870 static void Write_##T(ALCdevice *device, T *buffer, ALuint SamplesToDo) \
872 switch(device->FmtChans) \
874 case DevFmtMono: \
875 Write_##T##_1(device, buffer, SamplesToDo); \
876 break; \
877 case DevFmtStereo: \
878 Write_##T##_2(device, buffer, SamplesToDo); \
879 break; \
880 case DevFmtQuad: \
881 Write_##T##_4(device, buffer, SamplesToDo); \
882 break; \
883 case DevFmtX51: \
884 case DevFmtX51Side: \
885 Write_##T##_6(device, buffer, SamplesToDo); \
886 break; \
887 case DevFmtX61: \
888 Write_##T##_7(device, buffer, SamplesToDo); \
889 break; \
890 case DevFmtX71: \
891 Write_##T##_8(device, buffer, SamplesToDo); \
892 break; \
896 DECL_TEMPLATE(ALfloat)
897 DECL_TEMPLATE(ALuint)
898 DECL_TEMPLATE(ALint)
899 DECL_TEMPLATE(ALushort)
900 DECL_TEMPLATE(ALshort)
901 DECL_TEMPLATE(ALubyte)
902 DECL_TEMPLATE(ALbyte)
904 #undef DECL_TEMPLATE
906 ALvoid aluMixData(ALCdevice *device, ALvoid *buffer, ALsizei size)
908 ALuint SamplesToDo;
909 ALeffectslot **slot, **slot_end;
910 ALsource **src, **src_end;
911 ALCcontext *ctx;
912 int fpuState;
913 ALuint i, c;
915 fpuState = SetMixerFPUMode();
917 while(size > 0)
919 /* Setup variables */
920 SamplesToDo = minu(size, BUFFERSIZE);
922 /* Clear mixing buffer */
923 memset(device->DryBuffer, 0, SamplesToDo*MAXCHANNELS*sizeof(ALfloat));
925 LockDevice(device);
926 ctx = device->ContextList;
927 while(ctx)
929 ALenum DeferUpdates = ctx->DeferUpdates;
930 ALenum UpdateSources = AL_FALSE;
932 if(!DeferUpdates)
933 UpdateSources = ExchangeInt(&ctx->UpdateSources, AL_FALSE);
935 src = ctx->ActiveSources;
936 src_end = src + ctx->ActiveSourceCount;
937 while(src != src_end)
939 if((*src)->state != AL_PLAYING)
941 --(ctx->ActiveSourceCount);
942 *src = *(--src_end);
943 continue;
946 if(!DeferUpdates && (ExchangeInt(&(*src)->NeedsUpdate, AL_FALSE) ||
947 UpdateSources))
948 ALsource_Update(*src, ctx);
950 MixSource(*src, device, SamplesToDo);
951 src++;
954 /* effect slot processing */
955 slot = ctx->ActiveEffectSlots;
956 slot_end = slot + ctx->ActiveEffectSlotCount;
957 while(slot != slot_end)
959 for(c = 0;c < SamplesToDo;c++)
961 (*slot)->WetBuffer[c] += (*slot)->ClickRemoval[0];
962 (*slot)->ClickRemoval[0] -= (*slot)->ClickRemoval[0] * (1.0f/256.0f);
964 (*slot)->ClickRemoval[0] += (*slot)->PendingClicks[0];
965 (*slot)->PendingClicks[0] = 0.0f;
967 if(!DeferUpdates && ExchangeInt(&(*slot)->NeedsUpdate, AL_FALSE))
968 ALeffectState_Update((*slot)->EffectState, ctx, *slot);
970 ALeffectState_Process((*slot)->EffectState, SamplesToDo,
971 (*slot)->WetBuffer, device->DryBuffer);
973 for(i = 0;i < SamplesToDo;i++)
974 (*slot)->WetBuffer[i] = 0.0f;
976 slot++;
979 ctx = ctx->next;
982 slot = &device->DefaultSlot;
983 if(*slot != NULL)
985 for(c = 0;c < SamplesToDo;c++)
987 (*slot)->WetBuffer[c] += (*slot)->ClickRemoval[0];
988 (*slot)->ClickRemoval[0] -= (*slot)->ClickRemoval[0] * (1.0f/256.0f);
990 (*slot)->ClickRemoval[0] += (*slot)->PendingClicks[0];
991 (*slot)->PendingClicks[0] = 0.0f;
993 if(ExchangeInt(&(*slot)->NeedsUpdate, AL_FALSE))
994 ALeffectState_Update((*slot)->EffectState, ctx, *slot);
996 ALeffectState_Process((*slot)->EffectState, SamplesToDo,
997 (*slot)->WetBuffer, device->DryBuffer);
999 for(i = 0;i < SamplesToDo;i++)
1000 (*slot)->WetBuffer[i] = 0.0f;
1002 UnlockDevice(device);
1004 //Post processing loop
1005 if(device->FmtChans == DevFmtMono)
1007 for(i = 0;i < SamplesToDo;i++)
1009 device->DryBuffer[i][FRONT_CENTER] += device->ClickRemoval[FRONT_CENTER];
1010 device->ClickRemoval[FRONT_CENTER] -= device->ClickRemoval[FRONT_CENTER] * (1.0f/256.0f);
1012 device->ClickRemoval[FRONT_CENTER] += device->PendingClicks[FRONT_CENTER];
1013 device->PendingClicks[FRONT_CENTER] = 0.0f;
1015 else if(device->FmtChans == DevFmtStereo)
1017 /* Assumes the first two channels are FRONT_LEFT and FRONT_RIGHT */
1018 for(i = 0;i < SamplesToDo;i++)
1020 for(c = 0;c < 2;c++)
1022 device->DryBuffer[i][c] += device->ClickRemoval[c];
1023 device->ClickRemoval[c] -= device->ClickRemoval[c] * (1.0f/256.0f);
1026 for(c = 0;c < 2;c++)
1028 device->ClickRemoval[c] += device->PendingClicks[c];
1029 device->PendingClicks[c] = 0.0f;
1031 if(device->Bs2b)
1033 for(i = 0;i < SamplesToDo;i++)
1034 bs2b_cross_feed(device->Bs2b, &device->DryBuffer[i][0]);
1037 else
1039 for(i = 0;i < SamplesToDo;i++)
1041 for(c = 0;c < MAXCHANNELS;c++)
1043 device->DryBuffer[i][c] += device->ClickRemoval[c];
1044 device->ClickRemoval[c] -= device->ClickRemoval[c] * (1.0f/256.0f);
1047 for(c = 0;c < MAXCHANNELS;c++)
1049 device->ClickRemoval[c] += device->PendingClicks[c];
1050 device->PendingClicks[c] = 0.0f;
1054 if(buffer)
1056 switch(device->FmtType)
1058 case DevFmtByte:
1059 Write_ALbyte(device, buffer, SamplesToDo);
1060 break;
1061 case DevFmtUByte:
1062 Write_ALubyte(device, buffer, SamplesToDo);
1063 break;
1064 case DevFmtShort:
1065 Write_ALshort(device, buffer, SamplesToDo);
1066 break;
1067 case DevFmtUShort:
1068 Write_ALushort(device, buffer, SamplesToDo);
1069 break;
1070 case DevFmtInt:
1071 Write_ALint(device, buffer, SamplesToDo);
1072 break;
1073 case DevFmtUInt:
1074 Write_ALuint(device, buffer, SamplesToDo);
1075 break;
1076 case DevFmtFloat:
1077 Write_ALfloat(device, buffer, SamplesToDo);
1078 break;
1082 size -= SamplesToDo;
1085 RestoreFPUMode(fpuState);
1089 ALvoid aluHandleDisconnect(ALCdevice *device)
1091 ALCcontext *Context;
1093 LockDevice(device);
1094 device->Connected = ALC_FALSE;
1096 Context = device->ContextList;
1097 while(Context)
1099 ALsource **src, **src_end;
1101 src = Context->ActiveSources;
1102 src_end = src + Context->ActiveSourceCount;
1103 while(src != src_end)
1105 if((*src)->state == AL_PLAYING)
1107 (*src)->state = AL_STOPPED;
1108 (*src)->BuffersPlayed = (*src)->BuffersInQueue;
1109 (*src)->position = 0;
1110 (*src)->position_fraction = 0;
1112 src++;
1114 Context->ActiveSourceCount = 0;
1116 Context = Context->next;
1118 UnlockDevice(device);