Fixup some comments in ALu.c
[openal-soft.git] / Alc / ALu.c
blobec0042941bea0b2e3eeb1c46885c346407822968
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->Gain;
137 MinVolume = ALSource->MinGain;
138 MaxVolume = ALSource->MaxGain;
139 Pitch = ALSource->Pitch;
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++)
254 for(i = 0;i < (ALint)Device->NumChan;i++)
256 enum Channel chan = Device->Speaker2Chan[i];
257 if(chan == chans[c].channel)
259 SrcMatrix[c][chan] += DryGain * ListenerGain;
260 break;
265 else if(Device->Hrtf)
267 for(c = 0;c < num_channels;c++)
269 if(chans[c].channel == LFE)
271 /* Skip LFE */
272 ALSource->Params.HrtfDelay[c][0] = 0;
273 ALSource->Params.HrtfDelay[c][1] = 0;
274 for(i = 0;i < HRIR_LENGTH;i++)
276 ALSource->Params.HrtfCoeffs[c][i][0] = 0.0f;
277 ALSource->Params.HrtfCoeffs[c][i][1] = 0.0f;
280 else
282 /* Get the static HRIR coefficients and delays for this
283 * channel. */
284 GetLerpedHrtfCoeffs(Device->Hrtf,
285 0.0f, chans[c].angle,
286 DryGain*ListenerGain,
287 ALSource->Params.HrtfCoeffs[c],
288 ALSource->Params.HrtfDelay[c]);
290 ALSource->HrtfCounter = 0;
293 else
295 for(c = 0;c < num_channels;c++)
297 /* Special-case LFE */
298 if(chans[c].channel == LFE)
300 SrcMatrix[c][LFE] += DryGain * ListenerGain;
301 continue;
303 pos = aluCart2LUTpos(aluCos(chans[c].angle), aluSin(chans[c].angle));
304 ChannelGain = Device->PanningLUT[pos];
306 for(i = 0;i < (ALint)Device->NumChan;i++)
308 enum Channel chan = Device->Speaker2Chan[i];
309 SrcMatrix[c][chan] += DryGain * ListenerGain *
310 ChannelGain[chan];
314 for(i = 0;i < NumSends;i++)
316 ALeffectslot *Slot = ALSource->Send[i].Slot;
318 if(!Slot && i == 0)
319 Slot = Device->DefaultSlot;
320 if(Slot && Slot->effect.type == AL_EFFECT_NULL)
321 Slot = NULL;
322 ALSource->Params.Send[i].Slot = Slot;
323 ALSource->Params.Send[i].WetGain = WetGain[i] * ListenerGain;
326 /* Update filter coefficients. Calculations based on the I3DL2
327 * spec. */
328 cw = aluCos(F_PI*2.0f * LOWPASSFREQREF / Frequency);
330 /* We use two chained one-pole filters, so we need to take the
331 * square root of the squared gain, which is the same as the base
332 * gain. */
333 ALSource->Params.iirFilter.coeff = lpCoeffCalc(DryGainHF, cw);
334 for(i = 0;i < NumSends;i++)
336 /* We use a one-pole filter, so we need to take the squared gain */
337 ALfloat a = lpCoeffCalc(WetGainHF[i]*WetGainHF[i], cw);
338 ALSource->Params.Send[i].iirFilter.coeff = a;
342 ALvoid CalcSourceParams(ALsource *ALSource, const ALCcontext *ALContext)
344 const ALCdevice *Device = ALContext->Device;
345 ALfloat InnerAngle,OuterAngle,Angle,Distance,ClampedDist;
346 ALfloat Direction[3],Position[3],SourceToListener[3];
347 ALfloat Velocity[3],ListenerVel[3];
348 ALfloat MinVolume,MaxVolume,MinDist,MaxDist,Rolloff;
349 ALfloat ConeVolume,ConeHF,SourceVolume,ListenerGain;
350 ALfloat DopplerFactor, SpeedOfSound;
351 ALfloat AirAbsorptionFactor;
352 ALfloat RoomAirAbsorption[MAX_SENDS];
353 ALbufferlistitem *BufferListItem;
354 ALfloat Attenuation;
355 ALfloat RoomAttenuation[MAX_SENDS];
356 ALfloat MetersPerUnit;
357 ALfloat RoomRolloffBase;
358 ALfloat RoomRolloff[MAX_SENDS];
359 ALfloat DecayDistance[MAX_SENDS];
360 ALfloat DryGain;
361 ALfloat DryGainHF;
362 ALboolean DryGainHFAuto;
363 ALfloat WetGain[MAX_SENDS];
364 ALfloat WetGainHF[MAX_SENDS];
365 ALboolean WetGainAuto;
366 ALboolean WetGainHFAuto;
367 enum Resampler Resampler;
368 ALfloat Matrix[4][4];
369 ALfloat Pitch;
370 ALuint Frequency;
371 ALint NumSends;
372 ALfloat cw;
373 ALint i, j;
375 DryGainHF = 1.0f;
376 for(i = 0;i < MAX_SENDS;i++)
377 WetGainHF[i] = 1.0f;
379 /* Get context/device properties */
380 DopplerFactor = ALContext->DopplerFactor * ALSource->DopplerFactor;
381 SpeedOfSound = ALContext->SpeedOfSound * ALContext->DopplerVelocity;
382 NumSends = Device->NumAuxSends;
383 Frequency = Device->Frequency;
385 /* Get listener properties */
386 ListenerGain = ALContext->Listener.Gain;
387 MetersPerUnit = ALContext->Listener.MetersPerUnit;
388 ListenerVel[0] = ALContext->Listener.Velocity[0];
389 ListenerVel[1] = ALContext->Listener.Velocity[1];
390 ListenerVel[2] = ALContext->Listener.Velocity[2];
391 for(i = 0;i < 4;i++)
393 for(j = 0;j < 4;j++)
394 Matrix[i][j] = ALContext->Listener.Matrix[i][j];
397 /* Get source properties */
398 SourceVolume = ALSource->Gain;
399 MinVolume = ALSource->MinGain;
400 MaxVolume = ALSource->MaxGain;
401 Pitch = ALSource->Pitch;
402 Resampler = ALSource->Resampler;
403 Position[0] = ALSource->Position[0];
404 Position[1] = ALSource->Position[1];
405 Position[2] = ALSource->Position[2];
406 Direction[0] = ALSource->Orientation[0];
407 Direction[1] = ALSource->Orientation[1];
408 Direction[2] = ALSource->Orientation[2];
409 Velocity[0] = ALSource->Velocity[0];
410 Velocity[1] = ALSource->Velocity[1];
411 Velocity[2] = ALSource->Velocity[2];
412 MinDist = ALSource->RefDistance;
413 MaxDist = ALSource->MaxDistance;
414 Rolloff = ALSource->RollOffFactor;
415 InnerAngle = ALSource->InnerAngle * ConeScale;
416 OuterAngle = ALSource->OuterAngle * ConeScale;
417 AirAbsorptionFactor = ALSource->AirAbsorptionFactor;
418 DryGainHFAuto = ALSource->DryGainHFAuto;
419 WetGainAuto = ALSource->WetGainAuto;
420 WetGainHFAuto = ALSource->WetGainHFAuto;
421 RoomRolloffBase = ALSource->RoomRolloffFactor;
422 for(i = 0;i < NumSends;i++)
424 ALeffectslot *Slot = ALSource->Send[i].Slot;
426 if(!Slot && i == 0)
427 Slot = Device->DefaultSlot;
428 if(!Slot || Slot->effect.type == AL_EFFECT_NULL)
430 Slot = NULL;
431 RoomRolloff[i] = 0.0f;
432 DecayDistance[i] = 0.0f;
433 RoomAirAbsorption[i] = 1.0f;
435 else if(Slot->AuxSendAuto)
437 RoomRolloff[i] = RoomRolloffBase;
438 if(IsReverbEffect(Slot->effect.type))
440 RoomRolloff[i] += Slot->effect.Reverb.RoomRolloffFactor;
441 DecayDistance[i] = Slot->effect.Reverb.DecayTime *
442 SPEEDOFSOUNDMETRESPERSEC;
443 RoomAirAbsorption[i] = Slot->effect.Reverb.AirAbsorptionGainHF;
445 else
447 DecayDistance[i] = 0.0f;
448 RoomAirAbsorption[i] = 1.0f;
451 else
453 /* If the slot's auxiliary send auto is off, the data sent to the
454 * effect slot is the same as the dry path, sans filter effects */
455 RoomRolloff[i] = Rolloff;
456 DecayDistance[i] = 0.0f;
457 RoomAirAbsorption[i] = AIRABSORBGAINHF;
460 ALSource->Params.Send[i].Slot = Slot;
463 /* Transform source to listener space (convert to head relative) */
464 if(ALSource->HeadRelative == AL_FALSE)
466 /* Translate position */
467 Position[0] -= ALContext->Listener.Position[0];
468 Position[1] -= ALContext->Listener.Position[1];
469 Position[2] -= ALContext->Listener.Position[2];
471 /* Transform source vectors */
472 aluMatrixVector(Position, 1.0f, Matrix);
473 aluMatrixVector(Direction, 0.0f, Matrix);
474 aluMatrixVector(Velocity, 0.0f, Matrix);
475 /* Transform listener velocity */
476 aluMatrixVector(ListenerVel, 0.0f, Matrix);
478 else
480 /* Transform listener velocity from world space to listener space */
481 aluMatrixVector(ListenerVel, 0.0f, Matrix);
482 /* Offset the source velocity to be relative of the listener velocity */
483 Velocity[0] += ListenerVel[0];
484 Velocity[1] += ListenerVel[1];
485 Velocity[2] += ListenerVel[2];
488 SourceToListener[0] = -Position[0];
489 SourceToListener[1] = -Position[1];
490 SourceToListener[2] = -Position[2];
491 aluNormalize(SourceToListener);
492 aluNormalize(Direction);
494 /* Calculate distance attenuation */
495 Distance = aluSqrt(aluDotproduct(Position, Position));
496 ClampedDist = Distance;
498 Attenuation = 1.0f;
499 for(i = 0;i < NumSends;i++)
500 RoomAttenuation[i] = 1.0f;
501 switch(ALContext->SourceDistanceModel ? ALSource->DistanceModel :
502 ALContext->DistanceModel)
504 case InverseDistanceClamped:
505 ClampedDist = clampf(ClampedDist, MinDist, MaxDist);
506 if(MaxDist < MinDist)
507 break;
508 /*fall-through*/
509 case InverseDistance:
510 if(MinDist > 0.0f)
512 if((MinDist + (Rolloff * (ClampedDist - MinDist))) > 0.0f)
513 Attenuation = MinDist / (MinDist + (Rolloff * (ClampedDist - MinDist)));
514 for(i = 0;i < NumSends;i++)
516 if((MinDist + (RoomRolloff[i] * (ClampedDist - MinDist))) > 0.0f)
517 RoomAttenuation[i] = MinDist / (MinDist + (RoomRolloff[i] * (ClampedDist - MinDist)));
520 break;
522 case LinearDistanceClamped:
523 ClampedDist = clampf(ClampedDist, MinDist, MaxDist);
524 if(MaxDist < MinDist)
525 break;
526 /*fall-through*/
527 case LinearDistance:
528 if(MaxDist != MinDist)
530 Attenuation = 1.0f - (Rolloff*(ClampedDist-MinDist)/(MaxDist - MinDist));
531 Attenuation = maxf(Attenuation, 0.0f);
532 for(i = 0;i < NumSends;i++)
534 RoomAttenuation[i] = 1.0f - (RoomRolloff[i]*(ClampedDist-MinDist)/(MaxDist - MinDist));
535 RoomAttenuation[i] = maxf(RoomAttenuation[i], 0.0f);
538 break;
540 case ExponentDistanceClamped:
541 ClampedDist = clampf(ClampedDist, MinDist, MaxDist);
542 if(MaxDist < MinDist)
543 break;
544 /*fall-through*/
545 case ExponentDistance:
546 if(ClampedDist > 0.0f && MinDist > 0.0f)
548 Attenuation = aluPow(ClampedDist/MinDist, -Rolloff);
549 for(i = 0;i < NumSends;i++)
550 RoomAttenuation[i] = aluPow(ClampedDist/MinDist, -RoomRolloff[i]);
552 break;
554 case DisableDistance:
555 ClampedDist = MinDist;
556 break;
559 /* Source Gain + Attenuation */
560 DryGain = SourceVolume * Attenuation;
561 for(i = 0;i < NumSends;i++)
562 WetGain[i] = SourceVolume * RoomAttenuation[i];
564 /* Distance-based air absorption */
565 if(AirAbsorptionFactor > 0.0f && ClampedDist > MinDist)
567 ALfloat meters = maxf(ClampedDist-MinDist, 0.0f) * MetersPerUnit;
568 DryGainHF *= aluPow(AIRABSORBGAINHF, AirAbsorptionFactor*meters);
569 for(i = 0;i < NumSends;i++)
570 WetGainHF[i] *= aluPow(RoomAirAbsorption[i], AirAbsorptionFactor*meters);
573 if(WetGainAuto)
575 ALfloat ApparentDist = 1.0f/maxf(Attenuation, 0.00001f) - 1.0f;
577 /* Apply a decay-time transformation to the wet path, based on the
578 * attenuation of the dry path.
580 * Using the apparent distance, based on the distance attenuation, the
581 * initial decay of the reverb effect is calculated and applied to the
582 * wet path.
584 for(i = 0;i < NumSends;i++)
586 if(DecayDistance[i] > 0.0f)
587 WetGain[i] *= aluPow(0.001f/*-60dB*/, ApparentDist/DecayDistance[i]);
591 /* Calculate directional soundcones */
592 Angle = aluAcos(aluDotproduct(Direction,SourceToListener)) * (180.0f/F_PI);
593 if(Angle > InnerAngle && Angle <= OuterAngle)
595 ALfloat scale = (Angle-InnerAngle) / (OuterAngle-InnerAngle);
596 ConeVolume = lerp(1.0f, ALSource->OuterGain, scale);
597 ConeHF = lerp(1.0f, ALSource->OuterGainHF, scale);
599 else if(Angle > OuterAngle)
601 ConeVolume = ALSource->OuterGain;
602 ConeHF = ALSource->OuterGainHF;
604 else
606 ConeVolume = 1.0f;
607 ConeHF = 1.0f;
610 DryGain *= ConeVolume;
611 if(WetGainAuto)
613 for(i = 0;i < NumSends;i++)
614 WetGain[i] *= ConeVolume;
616 if(DryGainHFAuto)
617 DryGainHF *= ConeHF;
618 if(WetGainHFAuto)
620 for(i = 0;i < NumSends;i++)
621 WetGainHF[i] *= ConeHF;
624 /* Clamp to Min/Max Gain */
625 DryGain = clampf(DryGain, MinVolume, MaxVolume);
626 for(i = 0;i < NumSends;i++)
627 WetGain[i] = clampf(WetGain[i], MinVolume, MaxVolume);
629 /* Apply gain and frequency filters */
630 DryGain *= ALSource->DirectGain * ListenerGain;
631 DryGainHF *= ALSource->DirectGainHF;
632 for(i = 0;i < NumSends;i++)
634 WetGain[i] *= ALSource->Send[i].WetGain * ListenerGain;
635 WetGainHF[i] *= ALSource->Send[i].WetGainHF;
638 /* Calculate velocity-based doppler effect */
639 if(DopplerFactor > 0.0f)
641 ALfloat VSS, VLS;
643 if(SpeedOfSound < 1.0f)
645 DopplerFactor *= 1.0f/SpeedOfSound;
646 SpeedOfSound = 1.0f;
649 VSS = aluDotproduct(Velocity, SourceToListener) * DopplerFactor;
650 VLS = aluDotproduct(ListenerVel, SourceToListener) * DopplerFactor;
652 Pitch *= clampf(SpeedOfSound-VLS, 1.0f, SpeedOfSound*2.0f - 1.0f) /
653 clampf(SpeedOfSound-VSS, 1.0f, SpeedOfSound*2.0f - 1.0f);
656 BufferListItem = ALSource->queue;
657 while(BufferListItem != NULL)
659 ALbuffer *ALBuffer;
660 if((ALBuffer=BufferListItem->buffer) != NULL)
662 /* Calculate fixed-point stepping value, based on the pitch, buffer
663 * frequency, and output frequency. */
664 ALsizei maxstep = STACK_DATA_SIZE/sizeof(ALfloat) /
665 ALSource->NumChannels;
666 maxstep -= ResamplerPadding[Resampler] +
667 ResamplerPrePadding[Resampler] + 1;
668 maxstep = mini(maxstep, INT_MAX>>FRACTIONBITS);
670 Pitch = Pitch * ALBuffer->Frequency / Frequency;
671 if(Pitch > (ALfloat)maxstep)
672 ALSource->Params.Step = maxstep<<FRACTIONBITS;
673 else
675 ALSource->Params.Step = fastf2i(Pitch*FRACTIONONE);
676 if(ALSource->Params.Step == 0)
677 ALSource->Params.Step = 1;
679 if(ALSource->Params.Step == FRACTIONONE)
680 Resampler = PointResampler;
682 break;
684 BufferListItem = BufferListItem->next;
686 if(Device->Hrtf)
687 ALSource->Params.DoMix = SelectHrtfMixer(Resampler);
688 else
689 ALSource->Params.DoMix = SelectMixer(Resampler);
691 if(Device->Hrtf)
693 /* Use a binaural HRTF algorithm for stereo headphone playback */
694 ALfloat delta, ev = 0.0f, az = 0.0f;
696 if(Distance > 0.0f)
698 ALfloat invlen = 1.0f/Distance;
699 Position[0] *= invlen;
700 Position[1] *= invlen;
701 Position[2] *= invlen;
703 /* Calculate elevation and azimuth only when the source is not at
704 * the listener. This prevents +0 and -0 Z from producing
705 * inconsistent panning. */
706 ev = aluAsin(Position[1]);
707 az = aluAtan2(Position[0], -Position[2]*ZScale);
710 /* Check to see if the HRIR is already moving. */
711 if(ALSource->HrtfMoving)
713 /* Calculate the normalized HRTF transition factor (delta). */
714 delta = CalcHrtfDelta(ALSource->Params.HrtfGain, DryGain,
715 ALSource->Params.HrtfDir, Position);
716 /* If the delta is large enough, get the moving HRIR target
717 * coefficients, target delays, steppping values, and counter. */
718 if(delta > 0.001f)
720 ALSource->HrtfCounter = GetMovingHrtfCoeffs(Device->Hrtf,
721 ev, az, DryGain, delta,
722 ALSource->HrtfCounter,
723 ALSource->Params.HrtfCoeffs[0],
724 ALSource->Params.HrtfDelay[0],
725 ALSource->Params.HrtfCoeffStep,
726 ALSource->Params.HrtfDelayStep);
727 ALSource->Params.HrtfGain = DryGain;
728 ALSource->Params.HrtfDir[0] = Position[0];
729 ALSource->Params.HrtfDir[1] = Position[1];
730 ALSource->Params.HrtfDir[2] = Position[2];
733 else
735 /* Get the initial (static) HRIR coefficients and delays. */
736 GetLerpedHrtfCoeffs(Device->Hrtf, ev, az, DryGain,
737 ALSource->Params.HrtfCoeffs[0],
738 ALSource->Params.HrtfDelay[0]);
739 ALSource->HrtfCounter = 0;
740 ALSource->Params.HrtfGain = DryGain;
741 ALSource->Params.HrtfDir[0] = Position[0];
742 ALSource->Params.HrtfDir[1] = Position[1];
743 ALSource->Params.HrtfDir[2] = Position[2];
746 else
748 /* Use a lookup table for panning multi-speaker playback. */
749 ALfloat DirGain, AmbientGain;
750 const ALfloat *ChannelGain;
751 ALfloat length;
752 ALint pos;
754 /* Normalize the length based on the source's min distance. Sources
755 * closer than this will not pan as much. */
756 length = maxf(Distance, MinDist);
757 if(length > 0.0f)
759 ALfloat invlen = 1.0f/length;
760 Position[0] *= invlen;
761 Position[1] *= invlen;
762 Position[2] *= invlen;
765 pos = aluCart2LUTpos(-Position[2]*ZScale, Position[0]);
766 ChannelGain = Device->PanningLUT[pos];
768 /* Adjustment for partial panning. Not the greatest, but simple
769 * enough. */
770 DirGain = aluSqrt(Position[0]*Position[0] + Position[2]*Position[2]);
771 AmbientGain = aluSqrt(1.0f/Device->NumChan);
772 for(i = 0;i < MAXCHANNELS;i++)
774 for(j = 0;j < MAXCHANNELS;j++)
775 ALSource->Params.DryGains[i][j] = 0.0f;
777 for(i = 0;i < (ALint)Device->NumChan;i++)
779 enum Channel chan = Device->Speaker2Chan[i];
780 ALfloat gain = lerp(AmbientGain, ChannelGain[chan], DirGain);
781 ALSource->Params.DryGains[0][chan] = DryGain * gain;
784 for(i = 0;i < NumSends;i++)
785 ALSource->Params.Send[i].WetGain = WetGain[i];
787 /* Update filter coefficients. */
788 cw = aluCos(F_PI*2.0f * LOWPASSFREQREF / Frequency);
790 ALSource->Params.iirFilter.coeff = lpCoeffCalc(DryGainHF, cw);
791 for(i = 0;i < NumSends;i++)
793 ALfloat a = lpCoeffCalc(WetGainHF[i]*WetGainHF[i], cw);
794 ALSource->Params.Send[i].iirFilter.coeff = a;
799 static __inline ALfloat aluF2F(ALfloat val)
800 { return val; }
801 static __inline ALint aluF2I(ALfloat val)
803 if(val > 1.0f) return 2147483647;
804 if(val < -1.0f) return -2147483647-1;
805 return fastf2i((ALfloat)(val*2147483647.0));
807 static __inline ALuint aluF2UI(ALfloat val)
808 { return aluF2I(val)+2147483648u; }
809 static __inline ALshort aluF2S(ALfloat val)
810 { return aluF2I(val)>>16; }
811 static __inline ALushort aluF2US(ALfloat val)
812 { return aluF2S(val)+32768; }
813 static __inline ALbyte aluF2B(ALfloat val)
814 { return aluF2I(val)>>24; }
815 static __inline ALubyte aluF2UB(ALfloat val)
816 { return aluF2B(val)+128; }
818 #define DECL_TEMPLATE(T, N, func) \
819 static void Write_##T##_##N(ALCdevice *device, T *RESTRICT buffer, \
820 ALuint SamplesToDo) \
822 ALfloat (*RESTRICT DryBuffer)[MAXCHANNELS] = device->DryBuffer; \
823 const enum Channel *ChanMap = device->DevChannels; \
824 ALuint i, j; \
826 for(j = 0;j < N;j++) \
828 T *RESTRICT out = buffer + j; \
829 enum Channel chan = ChanMap[j]; \
831 for(i = 0;i < SamplesToDo;i++) \
832 out[i*N] = func(DryBuffer[i][chan]); \
836 DECL_TEMPLATE(ALfloat, 1, aluF2F)
837 DECL_TEMPLATE(ALfloat, 2, aluF2F)
838 DECL_TEMPLATE(ALfloat, 4, aluF2F)
839 DECL_TEMPLATE(ALfloat, 6, aluF2F)
840 DECL_TEMPLATE(ALfloat, 7, aluF2F)
841 DECL_TEMPLATE(ALfloat, 8, aluF2F)
843 DECL_TEMPLATE(ALuint, 1, aluF2UI)
844 DECL_TEMPLATE(ALuint, 2, aluF2UI)
845 DECL_TEMPLATE(ALuint, 4, aluF2UI)
846 DECL_TEMPLATE(ALuint, 6, aluF2UI)
847 DECL_TEMPLATE(ALuint, 7, aluF2UI)
848 DECL_TEMPLATE(ALuint, 8, aluF2UI)
850 DECL_TEMPLATE(ALint, 1, aluF2I)
851 DECL_TEMPLATE(ALint, 2, aluF2I)
852 DECL_TEMPLATE(ALint, 4, aluF2I)
853 DECL_TEMPLATE(ALint, 6, aluF2I)
854 DECL_TEMPLATE(ALint, 7, aluF2I)
855 DECL_TEMPLATE(ALint, 8, aluF2I)
857 DECL_TEMPLATE(ALushort, 1, aluF2US)
858 DECL_TEMPLATE(ALushort, 2, aluF2US)
859 DECL_TEMPLATE(ALushort, 4, aluF2US)
860 DECL_TEMPLATE(ALushort, 6, aluF2US)
861 DECL_TEMPLATE(ALushort, 7, aluF2US)
862 DECL_TEMPLATE(ALushort, 8, aluF2US)
864 DECL_TEMPLATE(ALshort, 1, aluF2S)
865 DECL_TEMPLATE(ALshort, 2, aluF2S)
866 DECL_TEMPLATE(ALshort, 4, aluF2S)
867 DECL_TEMPLATE(ALshort, 6, aluF2S)
868 DECL_TEMPLATE(ALshort, 7, aluF2S)
869 DECL_TEMPLATE(ALshort, 8, aluF2S)
871 DECL_TEMPLATE(ALubyte, 1, aluF2UB)
872 DECL_TEMPLATE(ALubyte, 2, aluF2UB)
873 DECL_TEMPLATE(ALubyte, 4, aluF2UB)
874 DECL_TEMPLATE(ALubyte, 6, aluF2UB)
875 DECL_TEMPLATE(ALubyte, 7, aluF2UB)
876 DECL_TEMPLATE(ALubyte, 8, aluF2UB)
878 DECL_TEMPLATE(ALbyte, 1, aluF2B)
879 DECL_TEMPLATE(ALbyte, 2, aluF2B)
880 DECL_TEMPLATE(ALbyte, 4, aluF2B)
881 DECL_TEMPLATE(ALbyte, 6, aluF2B)
882 DECL_TEMPLATE(ALbyte, 7, aluF2B)
883 DECL_TEMPLATE(ALbyte, 8, aluF2B)
885 #undef DECL_TEMPLATE
887 #define DECL_TEMPLATE(T) \
888 static void Write_##T(ALCdevice *device, T *buffer, ALuint SamplesToDo) \
890 switch(device->FmtChans) \
892 case DevFmtMono: \
893 Write_##T##_1(device, buffer, SamplesToDo); \
894 break; \
895 case DevFmtStereo: \
896 Write_##T##_2(device, buffer, SamplesToDo); \
897 break; \
898 case DevFmtQuad: \
899 Write_##T##_4(device, buffer, SamplesToDo); \
900 break; \
901 case DevFmtX51: \
902 case DevFmtX51Side: \
903 Write_##T##_6(device, buffer, SamplesToDo); \
904 break; \
905 case DevFmtX61: \
906 Write_##T##_7(device, buffer, SamplesToDo); \
907 break; \
908 case DevFmtX71: \
909 Write_##T##_8(device, buffer, SamplesToDo); \
910 break; \
914 DECL_TEMPLATE(ALfloat)
915 DECL_TEMPLATE(ALuint)
916 DECL_TEMPLATE(ALint)
917 DECL_TEMPLATE(ALushort)
918 DECL_TEMPLATE(ALshort)
919 DECL_TEMPLATE(ALubyte)
920 DECL_TEMPLATE(ALbyte)
922 #undef DECL_TEMPLATE
924 ALvoid aluMixData(ALCdevice *device, ALvoid *buffer, ALsizei size)
926 ALuint SamplesToDo;
927 ALeffectslot **slot, **slot_end;
928 ALsource **src, **src_end;
929 ALCcontext *ctx;
930 int fpuState;
931 ALuint i, c;
933 fpuState = SetMixerFPUMode();
935 while(size > 0)
937 SamplesToDo = minu(size, BUFFERSIZE);
938 memset(device->DryBuffer, 0, SamplesToDo*MAXCHANNELS*sizeof(ALfloat));
940 LockDevice(device);
941 ctx = device->ContextList;
942 while(ctx)
944 ALenum DeferUpdates = ctx->DeferUpdates;
945 ALenum UpdateSources = AL_FALSE;
947 if(!DeferUpdates)
948 UpdateSources = ExchangeInt(&ctx->UpdateSources, AL_FALSE);
950 /* source processing */
951 src = ctx->ActiveSources;
952 src_end = src + ctx->ActiveSourceCount;
953 while(src != src_end)
955 if((*src)->state != AL_PLAYING)
957 --(ctx->ActiveSourceCount);
958 *src = *(--src_end);
959 continue;
962 if(!DeferUpdates && (ExchangeInt(&(*src)->NeedsUpdate, AL_FALSE) ||
963 UpdateSources))
964 ALsource_Update(*src, ctx);
966 MixSource(*src, device, SamplesToDo);
967 src++;
970 /* effect slot processing */
971 slot = ctx->ActiveEffectSlots;
972 slot_end = slot + ctx->ActiveEffectSlotCount;
973 while(slot != slot_end)
975 for(c = 0;c < SamplesToDo;c++)
977 (*slot)->WetBuffer[c] += (*slot)->ClickRemoval[0];
978 (*slot)->ClickRemoval[0] -= (*slot)->ClickRemoval[0] * (1.0f/256.0f);
980 (*slot)->ClickRemoval[0] += (*slot)->PendingClicks[0];
981 (*slot)->PendingClicks[0] = 0.0f;
983 if(!DeferUpdates && ExchangeInt(&(*slot)->NeedsUpdate, AL_FALSE))
984 ALeffectState_Update((*slot)->EffectState, device, *slot);
986 ALeffectState_Process((*slot)->EffectState, SamplesToDo,
987 (*slot)->WetBuffer, device->DryBuffer);
989 for(i = 0;i < SamplesToDo;i++)
990 (*slot)->WetBuffer[i] = 0.0f;
992 slot++;
995 ctx = ctx->next;
998 slot = &device->DefaultSlot;
999 if(*slot != NULL)
1001 for(c = 0;c < SamplesToDo;c++)
1003 (*slot)->WetBuffer[c] += (*slot)->ClickRemoval[0];
1004 (*slot)->ClickRemoval[0] -= (*slot)->ClickRemoval[0] * (1.0f/256.0f);
1006 (*slot)->ClickRemoval[0] += (*slot)->PendingClicks[0];
1007 (*slot)->PendingClicks[0] = 0.0f;
1009 if(ExchangeInt(&(*slot)->NeedsUpdate, AL_FALSE))
1010 ALeffectState_Update((*slot)->EffectState, device, *slot);
1012 ALeffectState_Process((*slot)->EffectState, SamplesToDo,
1013 (*slot)->WetBuffer, device->DryBuffer);
1015 for(i = 0;i < SamplesToDo;i++)
1016 (*slot)->WetBuffer[i] = 0.0f;
1018 UnlockDevice(device);
1020 /* Click-removal. Could do better; this only really handles immediate
1021 * changes between updates where a predictive sample could be
1022 * generated. Delays caused by effects and HRTF aren't caught. */
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] * (1.0f/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] * (1.0f/256.0f);
1044 for(c = 0;c < 2;c++)
1046 device->ClickRemoval[c] += device->PendingClicks[c];
1047 device->PendingClicks[c] = 0.0f;
1049 if(device->Bs2b)
1051 for(i = 0;i < SamplesToDo;i++)
1052 bs2b_cross_feed(device->Bs2b, &device->DryBuffer[i][0]);
1055 else
1057 for(i = 0;i < SamplesToDo;i++)
1059 for(c = 0;c < MAXCHANNELS;c++)
1061 device->DryBuffer[i][c] += device->ClickRemoval[c];
1062 device->ClickRemoval[c] -= device->ClickRemoval[c] * (1.0f/256.0f);
1065 for(c = 0;c < MAXCHANNELS;c++)
1067 device->ClickRemoval[c] += device->PendingClicks[c];
1068 device->PendingClicks[c] = 0.0f;
1072 if(buffer)
1074 switch(device->FmtType)
1076 case DevFmtByte:
1077 Write_ALbyte(device, buffer, SamplesToDo);
1078 break;
1079 case DevFmtUByte:
1080 Write_ALubyte(device, buffer, SamplesToDo);
1081 break;
1082 case DevFmtShort:
1083 Write_ALshort(device, buffer, SamplesToDo);
1084 break;
1085 case DevFmtUShort:
1086 Write_ALushort(device, buffer, SamplesToDo);
1087 break;
1088 case DevFmtInt:
1089 Write_ALint(device, buffer, SamplesToDo);
1090 break;
1091 case DevFmtUInt:
1092 Write_ALuint(device, buffer, SamplesToDo);
1093 break;
1094 case DevFmtFloat:
1095 Write_ALfloat(device, buffer, SamplesToDo);
1096 break;
1100 size -= SamplesToDo;
1103 RestoreFPUMode(fpuState);
1107 ALvoid aluHandleDisconnect(ALCdevice *device)
1109 ALCcontext *Context;
1111 LockDevice(device);
1112 device->Connected = ALC_FALSE;
1114 Context = device->ContextList;
1115 while(Context)
1117 ALsource **src, **src_end;
1119 src = Context->ActiveSources;
1120 src_end = src + Context->ActiveSourceCount;
1121 while(src != src_end)
1123 if((*src)->state == AL_PLAYING)
1125 (*src)->state = AL_STOPPED;
1126 (*src)->BuffersPlayed = (*src)->BuffersInQueue;
1127 (*src)->position = 0;
1128 (*src)->position_fraction = 0;
1130 src++;
1132 Context->ActiveSourceCount = 0;
1134 Context = Context->next;
1136 UnlockDevice(device);