Use sizeof(ALfloat) when finding the max stepping value
[openal-soft/android.git] / Alc / ALu.c
blob36229cfb378eca687a87ad6b341a3cfefa314e32
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] = { { FRONT_LEFT, -30.0f },
68 { FRONT_RIGHT, 30.0f } };
69 static const struct ChanMap RearMap[2] = { { BACK_LEFT, -150.0f },
70 { BACK_RIGHT, 150.0f } };
71 static const struct ChanMap QuadMap[4] = { { FRONT_LEFT, -45.0f },
72 { FRONT_RIGHT, 45.0f },
73 { BACK_LEFT, -135.0f },
74 { BACK_RIGHT, 135.0f } };
75 static const struct ChanMap X51Map[6] = { { FRONT_LEFT, -30.0f },
76 { FRONT_RIGHT, 30.0f },
77 { FRONT_CENTER, 0.0f },
78 { LFE, 0.0f },
79 { BACK_LEFT, -110.0f },
80 { BACK_RIGHT, 110.0f } };
81 static const struct ChanMap X61Map[7] = { { FRONT_LEFT, -30.0f },
82 { FRONT_RIGHT, 30.0f },
83 { FRONT_CENTER, 0.0f },
84 { LFE, 0.0f },
85 { BACK_CENTER, 180.0f },
86 { SIDE_LEFT, -90.0f },
87 { SIDE_RIGHT, 90.0f } };
88 static const struct ChanMap X71Map[8] = { { FRONT_LEFT, -30.0f },
89 { FRONT_RIGHT, 30.0f },
90 { FRONT_CENTER, 0.0f },
91 { LFE, 0.0f },
92 { BACK_LEFT, -110.0f },
93 { BACK_RIGHT, 110.0f },
94 { SIDE_LEFT, -90.0f },
95 { SIDE_RIGHT, 90.0f } };
97 ALCdevice *Device = ALContext->Device;
98 ALfloat SourceVolume,ListenerGain,MinVolume,MaxVolume;
99 ALbufferlistitem *BufferListItem;
100 enum DevFmtChannels DevChans;
101 enum FmtChannels Channels;
102 ALfloat (*SrcMatrix)[MAXCHANNELS];
103 ALfloat DryGain, DryGainHF;
104 ALfloat WetGain[MAX_SENDS];
105 ALfloat WetGainHF[MAX_SENDS];
106 ALint NumSends, Frequency;
107 const ALfloat *SpeakerGain;
108 const struct ChanMap *chans = NULL;
109 enum Resampler Resampler;
110 ALint num_channels = 0;
111 ALboolean VirtualChannels;
112 ALfloat Pitch;
113 ALfloat cw;
114 ALuint pos;
115 ALint i, c;
117 /* Get device properties */
118 DevChans = Device->FmtChans;
119 NumSends = Device->NumAuxSends;
120 Frequency = Device->Frequency;
122 /* Get listener properties */
123 ListenerGain = ALContext->Listener.Gain;
125 /* Get source properties */
126 SourceVolume = ALSource->flGain;
127 MinVolume = ALSource->flMinGain;
128 MaxVolume = ALSource->flMaxGain;
129 Pitch = ALSource->flPitch;
130 Resampler = ALSource->Resampler;
131 VirtualChannels = ALSource->VirtualChannels;
133 /* Calculate the stepping value */
134 Channels = FmtMono;
135 BufferListItem = ALSource->queue;
136 while(BufferListItem != NULL)
138 ALbuffer *ALBuffer;
139 if((ALBuffer=BufferListItem->buffer) != NULL)
141 ALsizei maxstep = STACK_DATA_SIZE/sizeof(ALfloat) /
142 ALSource->NumChannels;
143 maxstep -= ResamplerPadding[Resampler] +
144 ResamplerPrePadding[Resampler] + 1;
145 maxstep = mini(maxstep, INT_MAX>>FRACTIONBITS);
147 Pitch = Pitch * ALBuffer->Frequency / Frequency;
148 if(Pitch > (ALfloat)maxstep)
149 ALSource->Params.Step = maxstep<<FRACTIONBITS;
150 else
152 ALSource->Params.Step = fastf2i(Pitch*FRACTIONONE);
153 if(ALSource->Params.Step == 0)
154 ALSource->Params.Step = 1;
157 Channels = ALBuffer->FmtChannels;
158 break;
160 BufferListItem = BufferListItem->next;
162 if(VirtualChannels && Device->Hrtf)
163 ALSource->Params.DoMix = SelectHrtfMixer((ALSource->Params.Step==FRACTIONONE) ?
164 POINT_RESAMPLER : Resampler);
165 else
166 ALSource->Params.DoMix = SelectMixer((ALSource->Params.Step==FRACTIONONE) ?
167 POINT_RESAMPLER : Resampler);
169 /* Calculate gains */
170 DryGain = clampf(SourceVolume, MinVolume, MaxVolume);
171 DryGain *= ALSource->DirectGain;
172 DryGainHF = ALSource->DirectGainHF;
173 for(i = 0;i < NumSends;i++)
175 WetGain[i] = clampf(SourceVolume, MinVolume, MaxVolume);
176 WetGain[i] *= ALSource->Send[i].WetGain;
177 WetGainHF[i] = ALSource->Send[i].WetGainHF;
180 SrcMatrix = ALSource->Params.DryGains;
181 for(i = 0;i < MAXCHANNELS;i++)
183 for(c = 0;c < MAXCHANNELS;c++)
184 SrcMatrix[i][c] = 0.0f;
186 switch(Channels)
188 case FmtMono:
189 chans = MonoMap;
190 num_channels = 1;
191 break;
192 case FmtStereo:
193 if(VirtualChannels && (Device->Flags&DEVICE_DUPLICATE_STEREO))
195 DryGain *= aluSqrt(2.0f/4.0f);
196 for(c = 0;c < 2;c++)
198 pos = aluCart2LUTpos(aluCos(F_PI/180.0f * RearMap[c].angle),
199 aluSin(F_PI/180.0f * RearMap[c].angle));
200 SpeakerGain = Device->PanningLUT[pos];
202 for(i = 0;i < (ALint)Device->NumChan;i++)
204 enum Channel chan = Device->Speaker2Chan[i];
205 SrcMatrix[c][chan] += DryGain * ListenerGain *
206 SpeakerGain[chan];
210 chans = StereoMap;
211 num_channels = 2;
212 break;
214 case FmtRear:
215 chans = RearMap;
216 num_channels = 2;
217 break;
219 case FmtQuad:
220 chans = QuadMap;
221 num_channels = 4;
222 break;
224 case FmtX51:
225 chans = X51Map;
226 num_channels = 6;
227 break;
229 case FmtX61:
230 chans = X61Map;
231 num_channels = 7;
232 break;
234 case FmtX71:
235 chans = X71Map;
236 num_channels = 8;
237 break;
240 if(VirtualChannels == AL_FALSE)
242 for(c = 0;c < num_channels;c++)
243 SrcMatrix[c][chans[c].channel] += DryGain * ListenerGain;
245 else if(Device->Hrtf)
247 for(c = 0;c < num_channels;c++)
249 if(chans[c].channel == LFE)
251 /* Skip LFE */
252 ALSource->Params.HrtfDelay[c][0] = 0;
253 ALSource->Params.HrtfDelay[c][1] = 0;
254 for(i = 0;i < HRIR_LENGTH;i++)
256 ALSource->Params.HrtfCoeffs[c][i][0] = 0.0f;
257 ALSource->Params.HrtfCoeffs[c][i][1] = 0.0f;
260 else
262 /* Get the static HRIR coefficients and delays for this
263 * channel. */
264 GetLerpedHrtfCoeffs(Device->Hrtf,
265 0.0f, F_PI/180.0f * chans[c].angle,
266 DryGain*ListenerGain,
267 ALSource->Params.HrtfCoeffs[c],
268 ALSource->Params.HrtfDelay[c]);
270 ALSource->HrtfCounter = 0;
273 else
275 for(c = 0;c < num_channels;c++)
277 if(chans[c].channel == LFE) /* Special-case LFE */
279 SrcMatrix[c][LFE] += DryGain * ListenerGain;
280 continue;
282 pos = aluCart2LUTpos(aluCos(F_PI/180.0f * chans[c].angle),
283 aluSin(F_PI/180.0f * chans[c].angle));
284 SpeakerGain = Device->PanningLUT[pos];
286 for(i = 0;i < (ALint)Device->NumChan;i++)
288 enum Channel chan = Device->Speaker2Chan[i];
289 SrcMatrix[c][chan] += DryGain * ListenerGain *
290 SpeakerGain[chan];
294 for(i = 0;i < NumSends;i++)
296 ALeffectslot *Slot = ALSource->Send[i].Slot;
298 if(!Slot && i == 0)
299 Slot = Device->DefaultSlot;
300 if(Slot && Slot->effect.type == AL_EFFECT_NULL)
301 Slot = NULL;
302 ALSource->Params.Send[i].Slot = Slot;
303 ALSource->Params.Send[i].WetGain = WetGain[i] * ListenerGain;
306 /* Update filter coefficients. Calculations based on the I3DL2
307 * spec. */
308 cw = aluCos(F_PI*2.0f * LOWPASSFREQREF / Frequency);
310 /* We use two chained one-pole filters, so we need to take the
311 * square root of the squared gain, which is the same as the base
312 * gain. */
313 ALSource->Params.iirFilter.coeff = lpCoeffCalc(DryGainHF, cw);
314 for(i = 0;i < NumSends;i++)
316 /* We use a one-pole filter, so we need to take the squared gain */
317 ALfloat a = lpCoeffCalc(WetGainHF[i]*WetGainHF[i], cw);
318 ALSource->Params.Send[i].iirFilter.coeff = a;
322 ALvoid CalcSourceParams(ALsource *ALSource, const ALCcontext *ALContext)
324 const ALCdevice *Device = ALContext->Device;
325 ALfloat InnerAngle,OuterAngle,Angle,Distance,ClampedDist;
326 ALfloat Direction[3],Position[3],SourceToListener[3];
327 ALfloat Velocity[3],ListenerVel[3];
328 ALfloat MinVolume,MaxVolume,MinDist,MaxDist,Rolloff;
329 ALfloat ConeVolume,ConeHF,SourceVolume,ListenerGain;
330 ALfloat DopplerFactor, DopplerVelocity, SpeedOfSound;
331 ALfloat AirAbsorptionFactor;
332 ALfloat RoomAirAbsorption[MAX_SENDS];
333 ALbufferlistitem *BufferListItem;
334 ALfloat Attenuation, EffectiveDist;
335 ALfloat RoomAttenuation[MAX_SENDS];
336 ALfloat MetersPerUnit;
337 ALfloat RoomRolloffBase;
338 ALfloat RoomRolloff[MAX_SENDS];
339 ALfloat DecayDistance[MAX_SENDS];
340 ALfloat DryGain;
341 ALfloat DryGainHF;
342 ALboolean DryGainHFAuto;
343 ALfloat WetGain[MAX_SENDS];
344 ALfloat WetGainHF[MAX_SENDS];
345 ALboolean WetGainAuto;
346 ALboolean WetGainHFAuto;
347 enum Resampler Resampler;
348 ALfloat Pitch;
349 ALuint Frequency;
350 ALint NumSends;
351 ALfloat cw;
352 ALint i;
354 DryGainHF = 1.0f;
355 for(i = 0;i < MAX_SENDS;i++)
356 WetGainHF[i] = 1.0f;
358 //Get context properties
359 DopplerFactor = ALContext->DopplerFactor * ALSource->DopplerFactor;
360 DopplerVelocity = ALContext->DopplerVelocity;
361 SpeedOfSound = ALContext->flSpeedOfSound;
362 NumSends = Device->NumAuxSends;
363 Frequency = Device->Frequency;
365 //Get listener properties
366 ListenerGain = ALContext->Listener.Gain;
367 MetersPerUnit = ALContext->Listener.MetersPerUnit;
368 ListenerVel[0] = ALContext->Listener.Velocity[0];
369 ListenerVel[1] = ALContext->Listener.Velocity[1];
370 ListenerVel[2] = ALContext->Listener.Velocity[2];
372 //Get source properties
373 SourceVolume = ALSource->flGain;
374 MinVolume = ALSource->flMinGain;
375 MaxVolume = ALSource->flMaxGain;
376 Pitch = ALSource->flPitch;
377 Resampler = ALSource->Resampler;
378 Position[0] = ALSource->vPosition[0];
379 Position[1] = ALSource->vPosition[1];
380 Position[2] = ALSource->vPosition[2];
381 Direction[0] = ALSource->vOrientation[0];
382 Direction[1] = ALSource->vOrientation[1];
383 Direction[2] = ALSource->vOrientation[2];
384 Velocity[0] = ALSource->vVelocity[0];
385 Velocity[1] = ALSource->vVelocity[1];
386 Velocity[2] = ALSource->vVelocity[2];
387 MinDist = ALSource->flRefDistance;
388 MaxDist = ALSource->flMaxDistance;
389 Rolloff = ALSource->flRollOffFactor;
390 InnerAngle = ALSource->flInnerAngle * ConeScale;
391 OuterAngle = ALSource->flOuterAngle * ConeScale;
392 AirAbsorptionFactor = ALSource->AirAbsorptionFactor;
393 DryGainHFAuto = ALSource->DryGainHFAuto;
394 WetGainAuto = ALSource->WetGainAuto;
395 WetGainHFAuto = ALSource->WetGainHFAuto;
396 RoomRolloffBase = ALSource->RoomRolloffFactor;
397 for(i = 0;i < NumSends;i++)
399 ALeffectslot *Slot = ALSource->Send[i].Slot;
401 if(!Slot && i == 0)
402 Slot = Device->DefaultSlot;
403 if(!Slot || Slot->effect.type == AL_EFFECT_NULL)
405 Slot = NULL;
406 RoomRolloff[i] = 0.0f;
407 DecayDistance[i] = 0.0f;
408 RoomAirAbsorption[i] = 1.0f;
410 else if(Slot->AuxSendAuto)
412 RoomRolloff[i] = RoomRolloffBase;
413 if(IsReverbEffect(Slot->effect.type))
415 RoomRolloff[i] += Slot->effect.Reverb.RoomRolloffFactor;
416 DecayDistance[i] = Slot->effect.Reverb.DecayTime *
417 SPEEDOFSOUNDMETRESPERSEC;
418 RoomAirAbsorption[i] = Slot->effect.Reverb.AirAbsorptionGainHF;
420 else
422 DecayDistance[i] = 0.0f;
423 RoomAirAbsorption[i] = 1.0f;
426 else
428 /* If the slot's auxiliary send auto is off, the data sent to the
429 * effect slot is the same as the dry path, sans filter effects */
430 RoomRolloff[i] = Rolloff;
431 DecayDistance[i] = 0.0f;
432 RoomAirAbsorption[i] = AIRABSORBGAINHF;
435 ALSource->Params.Send[i].Slot = Slot;
438 //1. Translate Listener to origin (convert to head relative)
439 if(ALSource->bHeadRelative == AL_FALSE)
441 ALfloat Matrix[4][4];
442 for(i = 0;i < 4;i++)
444 ALint i2;
445 for(i2 = 0;i2 < 4;i2++)
446 Matrix[i][i2] = ALContext->Listener.Matrix[i][i2];
449 /* Translate position */
450 Position[0] -= ALContext->Listener.Position[0];
451 Position[1] -= ALContext->Listener.Position[1];
452 Position[2] -= ALContext->Listener.Position[2];
454 /* Transform source vectors into listener space */
455 aluMatrixVector(Position, 1.0f, Matrix);
456 aluMatrixVector(Direction, 0.0f, Matrix);
457 aluMatrixVector(Velocity, 0.0f, Matrix);
459 else
461 ListenerVel[0] = 0.0f;
462 ListenerVel[1] = 0.0f;
463 ListenerVel[2] = 0.0f;
466 SourceToListener[0] = -Position[0];
467 SourceToListener[1] = -Position[1];
468 SourceToListener[2] = -Position[2];
469 aluNormalize(SourceToListener);
470 aluNormalize(Direction);
472 //2. Calculate distance attenuation
473 Distance = aluSqrt(aluDotproduct(Position, Position));
474 ClampedDist = Distance;
476 Attenuation = 1.0f;
477 for(i = 0;i < NumSends;i++)
478 RoomAttenuation[i] = 1.0f;
479 switch(ALContext->SourceDistanceModel ? ALSource->DistanceModel :
480 ALContext->DistanceModel)
482 case InverseDistanceClamped:
483 ClampedDist = clampf(ClampedDist, MinDist, MaxDist);
484 if(MaxDist < MinDist)
485 break;
486 //fall-through
487 case InverseDistance:
488 if(MinDist > 0.0f)
490 if((MinDist + (Rolloff * (ClampedDist - MinDist))) > 0.0f)
491 Attenuation = MinDist / (MinDist + (Rolloff * (ClampedDist - MinDist)));
492 for(i = 0;i < NumSends;i++)
494 if((MinDist + (RoomRolloff[i] * (ClampedDist - MinDist))) > 0.0f)
495 RoomAttenuation[i] = MinDist / (MinDist + (RoomRolloff[i] * (ClampedDist - MinDist)));
498 break;
500 case LinearDistanceClamped:
501 ClampedDist = clampf(ClampedDist, MinDist, MaxDist);
502 if(MaxDist < MinDist)
503 break;
504 //fall-through
505 case LinearDistance:
506 if(MaxDist != MinDist)
508 Attenuation = 1.0f - (Rolloff*(ClampedDist-MinDist)/(MaxDist - MinDist));
509 Attenuation = maxf(Attenuation, 0.0f);
510 for(i = 0;i < NumSends;i++)
512 RoomAttenuation[i] = 1.0f - (RoomRolloff[i]*(ClampedDist-MinDist)/(MaxDist - MinDist));
513 RoomAttenuation[i] = maxf(RoomAttenuation[i], 0.0f);
516 break;
518 case ExponentDistanceClamped:
519 ClampedDist = clampf(ClampedDist, MinDist, MaxDist);
520 if(MaxDist < MinDist)
521 break;
522 //fall-through
523 case ExponentDistance:
524 if(ClampedDist > 0.0f && MinDist > 0.0f)
526 Attenuation = aluPow(ClampedDist/MinDist, -Rolloff);
527 for(i = 0;i < NumSends;i++)
528 RoomAttenuation[i] = aluPow(ClampedDist/MinDist, -RoomRolloff[i]);
530 break;
532 case DisableDistance:
533 break;
536 // Source Gain + Attenuation
537 DryGain = SourceVolume * Attenuation;
538 for(i = 0;i < NumSends;i++)
539 WetGain[i] = SourceVolume * RoomAttenuation[i];
541 // Distance-based air absorption
542 EffectiveDist = 0.0f;
543 if(MinDist > 0.0f && Attenuation < 1.0f)
544 EffectiveDist = (MinDist/Attenuation - MinDist)*MetersPerUnit;
545 if(AirAbsorptionFactor > 0.0f && EffectiveDist > 0.0f)
547 DryGainHF *= aluPow(AIRABSORBGAINHF, AirAbsorptionFactor*EffectiveDist);
548 for(i = 0;i < NumSends;i++)
549 WetGainHF[i] *= aluPow(RoomAirAbsorption[i],
550 AirAbsorptionFactor*EffectiveDist);
553 if(WetGainAuto)
555 /* Apply a decay-time transformation to the wet path, based on the
556 * attenuation of the dry path.
558 * Using the approximate (effective) source to listener distance, the
559 * initial decay of the reverb effect is calculated and applied to the
560 * wet path.
562 for(i = 0;i < NumSends;i++)
564 if(DecayDistance[i] > 0.0f)
565 WetGain[i] *= aluPow(0.001f /* -60dB */,
566 EffectiveDist / DecayDistance[i]);
570 /* Calculate directional soundcones */
571 Angle = aluAcos(aluDotproduct(Direction,SourceToListener)) * (180.0f/F_PI);
572 if(Angle >= InnerAngle && Angle <= OuterAngle)
574 ALfloat scale = (Angle-InnerAngle) / (OuterAngle-InnerAngle);
575 ConeVolume = lerp(1.0f, ALSource->flOuterGain, scale);
576 ConeHF = lerp(1.0f, ALSource->OuterGainHF, scale);
578 else if(Angle > OuterAngle)
580 ConeVolume = ALSource->flOuterGain;
581 ConeHF = ALSource->OuterGainHF;
583 else
585 ConeVolume = 1.0f;
586 ConeHF = 1.0f;
589 DryGain *= ConeVolume;
590 if(WetGainAuto)
592 for(i = 0;i < NumSends;i++)
593 WetGain[i] *= ConeVolume;
595 if(DryGainHFAuto)
596 DryGainHF *= ConeHF;
597 if(WetGainHFAuto)
599 for(i = 0;i < NumSends;i++)
600 WetGainHF[i] *= ConeHF;
603 // Clamp to Min/Max Gain
604 DryGain = clampf(DryGain, MinVolume, MaxVolume);
605 for(i = 0;i < NumSends;i++)
606 WetGain[i] = clampf(WetGain[i], MinVolume, MaxVolume);
608 // Apply filter gains and filters
609 DryGain *= ALSource->DirectGain * ListenerGain;
610 DryGainHF *= ALSource->DirectGainHF;
611 for(i = 0;i < NumSends;i++)
613 WetGain[i] *= ALSource->Send[i].WetGain * ListenerGain;
614 WetGainHF[i] *= ALSource->Send[i].WetGainHF;
617 // Calculate Velocity
618 if(DopplerFactor != 0.0f)
620 ALfloat VSS, VLS;
621 ALfloat MaxVelocity = (SpeedOfSound*DopplerVelocity) /
622 DopplerFactor;
624 VSS = aluDotproduct(Velocity, SourceToListener);
625 if(VSS >= MaxVelocity)
626 VSS = (MaxVelocity - 1.0f);
627 else if(VSS <= -MaxVelocity)
628 VSS = -MaxVelocity + 1.0f;
630 VLS = aluDotproduct(ListenerVel, SourceToListener);
631 if(VLS >= MaxVelocity)
632 VLS = (MaxVelocity - 1.0f);
633 else if(VLS <= -MaxVelocity)
634 VLS = -MaxVelocity + 1.0f;
636 Pitch *= ((SpeedOfSound*DopplerVelocity) - (DopplerFactor*VLS)) /
637 ((SpeedOfSound*DopplerVelocity) - (DopplerFactor*VSS));
640 BufferListItem = ALSource->queue;
641 while(BufferListItem != NULL)
643 ALbuffer *ALBuffer;
644 if((ALBuffer=BufferListItem->buffer) != NULL)
646 ALsizei maxstep = STACK_DATA_SIZE/sizeof(ALfloat) /
647 ALSource->NumChannels;
648 maxstep -= ResamplerPadding[Resampler] +
649 ResamplerPrePadding[Resampler] + 1;
650 maxstep = mini(maxstep, INT_MAX>>FRACTIONBITS);
652 Pitch = Pitch * ALBuffer->Frequency / Frequency;
653 if(Pitch > (ALfloat)maxstep)
654 ALSource->Params.Step = maxstep<<FRACTIONBITS;
655 else
657 ALSource->Params.Step = fastf2i(Pitch*FRACTIONONE);
658 if(ALSource->Params.Step == 0)
659 ALSource->Params.Step = 1;
662 break;
664 BufferListItem = BufferListItem->next;
666 if(Device->Hrtf)
667 ALSource->Params.DoMix = SelectHrtfMixer((ALSource->Params.Step==FRACTIONONE) ?
668 POINT_RESAMPLER : Resampler);
669 else
670 ALSource->Params.DoMix = SelectMixer((ALSource->Params.Step==FRACTIONONE) ?
671 POINT_RESAMPLER : Resampler);
673 if(Device->Hrtf)
675 // Use a binaural HRTF algorithm for stereo headphone playback
676 ALfloat delta, ev = 0.0f, az = 0.0f;
678 if(Distance > 0.0f)
680 ALfloat invlen = 1.0f/Distance;
681 Position[0] *= invlen;
682 Position[1] *= invlen;
683 Position[2] *= invlen;
685 // Calculate elevation and azimuth only when the source is not at
686 // the listener. This prevents +0 and -0 Z from producing
687 // inconsistent panning.
688 ev = aluAsin(Position[1]);
689 az = aluAtan2(Position[0], -Position[2]*ZScale);
692 // Check to see if the HRIR is already moving.
693 if(ALSource->HrtfMoving)
695 // Calculate the normalized HRTF transition factor (delta).
696 delta = CalcHrtfDelta(ALSource->Params.HrtfGain, DryGain,
697 ALSource->Params.HrtfDir, Position);
698 // If the delta is large enough, get the moving HRIR target
699 // coefficients, target delays, steppping values, and counter.
700 if(delta > 0.001f)
702 ALSource->HrtfCounter = GetMovingHrtfCoeffs(Device->Hrtf,
703 ev, az, DryGain, delta,
704 ALSource->HrtfCounter,
705 ALSource->Params.HrtfCoeffs[0],
706 ALSource->Params.HrtfDelay[0],
707 ALSource->Params.HrtfCoeffStep,
708 ALSource->Params.HrtfDelayStep);
709 ALSource->Params.HrtfGain = DryGain;
710 ALSource->Params.HrtfDir[0] = Position[0];
711 ALSource->Params.HrtfDir[1] = Position[1];
712 ALSource->Params.HrtfDir[2] = Position[2];
715 else
717 // Get the initial (static) HRIR coefficients and delays.
718 GetLerpedHrtfCoeffs(Device->Hrtf, ev, az, DryGain,
719 ALSource->Params.HrtfCoeffs[0],
720 ALSource->Params.HrtfDelay[0]);
721 ALSource->HrtfCounter = 0;
722 ALSource->Params.HrtfGain = DryGain;
723 ALSource->Params.HrtfDir[0] = Position[0];
724 ALSource->Params.HrtfDir[1] = Position[1];
725 ALSource->Params.HrtfDir[2] = Position[2];
728 else
730 // Use energy-preserving panning algorithm for multi-speaker playback
731 ALfloat DirGain, AmbientGain;
732 const ALfloat *SpeakerGain;
733 ALfloat length;
734 ALint pos;
736 length = maxf(Distance, MinDist);
737 if(length > 0.0f)
739 ALfloat invlen = 1.0f/length;
740 Position[0] *= invlen;
741 Position[1] *= invlen;
742 Position[2] *= invlen;
745 pos = aluCart2LUTpos(-Position[2]*ZScale, Position[0]);
746 SpeakerGain = Device->PanningLUT[pos];
748 DirGain = aluSqrt(Position[0]*Position[0] + Position[2]*Position[2]);
749 // elevation adjustment for directional gain. this sucks, but
750 // has low complexity
751 AmbientGain = aluSqrt(1.0f/Device->NumChan);
752 for(i = 0;i < MAXCHANNELS;i++)
754 ALuint i2;
755 for(i2 = 0;i2 < MAXCHANNELS;i2++)
756 ALSource->Params.DryGains[i][i2] = 0.0f;
758 for(i = 0;i < (ALint)Device->NumChan;i++)
760 enum Channel chan = Device->Speaker2Chan[i];
761 ALfloat gain = lerp(AmbientGain, SpeakerGain[chan], DirGain);
762 ALSource->Params.DryGains[0][chan] = DryGain * gain;
765 for(i = 0;i < NumSends;i++)
766 ALSource->Params.Send[i].WetGain = WetGain[i];
768 /* Update filter coefficients. */
769 cw = aluCos(F_PI*2.0f * LOWPASSFREQREF / Frequency);
771 ALSource->Params.iirFilter.coeff = lpCoeffCalc(DryGainHF, cw);
772 for(i = 0;i < NumSends;i++)
774 ALfloat a = lpCoeffCalc(WetGainHF[i]*WetGainHF[i], cw);
775 ALSource->Params.Send[i].iirFilter.coeff = a;
780 static __inline ALfloat aluF2F(ALfloat val)
781 { return val; }
782 static __inline ALshort aluF2S(ALfloat val)
784 if(val > 1.0f) return 32767;
785 if(val < -1.0f) return -32768;
786 return fastf2i(val*32767.0f);
788 static __inline ALushort aluF2US(ALfloat val)
789 { return aluF2S(val)+32768; }
790 static __inline ALbyte aluF2B(ALfloat val)
791 { return aluF2S(val)>>8; }
792 static __inline ALubyte aluF2UB(ALfloat val)
793 { return aluF2US(val)>>8; }
795 #define DECL_TEMPLATE(T, N, func) \
796 static void Write_##T##_##N(ALCdevice *device, T *RESTRICT buffer, \
797 ALuint SamplesToDo) \
799 ALfloat (*RESTRICT DryBuffer)[MAXCHANNELS] = device->DryBuffer; \
800 const enum Channel *ChanMap = device->DevChannels; \
801 ALuint i, j; \
803 for(i = 0;i < SamplesToDo;i++) \
805 for(j = 0;j < N;j++) \
806 *(buffer++) = func(DryBuffer[i][ChanMap[j]]); \
810 DECL_TEMPLATE(ALfloat, 1, aluF2F)
811 DECL_TEMPLATE(ALfloat, 4, aluF2F)
812 DECL_TEMPLATE(ALfloat, 6, aluF2F)
813 DECL_TEMPLATE(ALfloat, 7, aluF2F)
814 DECL_TEMPLATE(ALfloat, 8, aluF2F)
816 DECL_TEMPLATE(ALushort, 1, aluF2US)
817 DECL_TEMPLATE(ALushort, 4, aluF2US)
818 DECL_TEMPLATE(ALushort, 6, aluF2US)
819 DECL_TEMPLATE(ALushort, 7, aluF2US)
820 DECL_TEMPLATE(ALushort, 8, aluF2US)
822 DECL_TEMPLATE(ALshort, 1, aluF2S)
823 DECL_TEMPLATE(ALshort, 4, aluF2S)
824 DECL_TEMPLATE(ALshort, 6, aluF2S)
825 DECL_TEMPLATE(ALshort, 7, aluF2S)
826 DECL_TEMPLATE(ALshort, 8, aluF2S)
828 DECL_TEMPLATE(ALubyte, 1, aluF2UB)
829 DECL_TEMPLATE(ALubyte, 4, aluF2UB)
830 DECL_TEMPLATE(ALubyte, 6, aluF2UB)
831 DECL_TEMPLATE(ALubyte, 7, aluF2UB)
832 DECL_TEMPLATE(ALubyte, 8, aluF2UB)
834 DECL_TEMPLATE(ALbyte, 1, aluF2B)
835 DECL_TEMPLATE(ALbyte, 4, aluF2B)
836 DECL_TEMPLATE(ALbyte, 6, aluF2B)
837 DECL_TEMPLATE(ALbyte, 7, aluF2B)
838 DECL_TEMPLATE(ALbyte, 8, aluF2B)
840 #undef DECL_TEMPLATE
842 #define DECL_TEMPLATE(T, N, func) \
843 static void Write_##T##_##N(ALCdevice *device, T *RESTRICT buffer, \
844 ALuint SamplesToDo) \
846 ALfloat (*RESTRICT DryBuffer)[MAXCHANNELS] = device->DryBuffer; \
847 const enum Channel *ChanMap = device->DevChannels; \
848 ALuint i, j; \
850 if(device->Bs2b) \
852 for(i = 0;i < SamplesToDo;i++) \
854 float samples[2]; \
855 samples[0] = DryBuffer[i][ChanMap[0]]; \
856 samples[1] = DryBuffer[i][ChanMap[1]]; \
857 bs2b_cross_feed(device->Bs2b, samples); \
858 *(buffer++) = func(samples[0]); \
859 *(buffer++) = func(samples[1]); \
862 else \
864 for(i = 0;i < SamplesToDo;i++) \
866 for(j = 0;j < N;j++) \
867 *(buffer++) = func(DryBuffer[i][ChanMap[j]]); \
872 DECL_TEMPLATE(ALfloat, 2, aluF2F)
873 DECL_TEMPLATE(ALushort, 2, aluF2US)
874 DECL_TEMPLATE(ALshort, 2, aluF2S)
875 DECL_TEMPLATE(ALubyte, 2, aluF2UB)
876 DECL_TEMPLATE(ALbyte, 2, aluF2B)
878 #undef DECL_TEMPLATE
880 #define DECL_TEMPLATE(T) \
881 static void Write_##T(ALCdevice *device, T *buffer, ALuint SamplesToDo) \
883 switch(device->FmtChans) \
885 case DevFmtMono: \
886 Write_##T##_1(device, buffer, SamplesToDo); \
887 break; \
888 case DevFmtStereo: \
889 Write_##T##_2(device, buffer, SamplesToDo); \
890 break; \
891 case DevFmtQuad: \
892 Write_##T##_4(device, buffer, SamplesToDo); \
893 break; \
894 case DevFmtX51: \
895 case DevFmtX51Side: \
896 Write_##T##_6(device, buffer, SamplesToDo); \
897 break; \
898 case DevFmtX61: \
899 Write_##T##_7(device, buffer, SamplesToDo); \
900 break; \
901 case DevFmtX71: \
902 Write_##T##_8(device, buffer, SamplesToDo); \
903 break; \
907 DECL_TEMPLATE(ALfloat)
908 DECL_TEMPLATE(ALushort)
909 DECL_TEMPLATE(ALshort)
910 DECL_TEMPLATE(ALubyte)
911 DECL_TEMPLATE(ALbyte)
913 #undef DECL_TEMPLATE
915 ALvoid aluMixData(ALCdevice *device, ALvoid *buffer, ALsizei size)
917 ALuint SamplesToDo;
918 ALeffectslot **slot, **slot_end;
919 ALsource **src, **src_end;
920 ALCcontext *ctx;
921 int fpuState;
922 ALuint i, c;
924 fpuState = SetMixerFPUMode();
926 while(size > 0)
928 /* Setup variables */
929 SamplesToDo = minu(size, BUFFERSIZE);
931 /* Clear mixing buffer */
932 memset(device->DryBuffer, 0, SamplesToDo*MAXCHANNELS*sizeof(ALfloat));
934 LockDevice(device);
935 ctx = device->ContextList;
936 while(ctx)
938 ALenum DeferUpdates = ctx->DeferUpdates;
939 ALenum UpdateSources = AL_FALSE;
941 if(!DeferUpdates)
942 UpdateSources = ExchangeInt(&ctx->UpdateSources, AL_FALSE);
944 src = ctx->ActiveSources;
945 src_end = src + ctx->ActiveSourceCount;
946 while(src != src_end)
948 if((*src)->state != AL_PLAYING)
950 --(ctx->ActiveSourceCount);
951 *src = *(--src_end);
952 continue;
955 if(!DeferUpdates && (ExchangeInt(&(*src)->NeedsUpdate, AL_FALSE) ||
956 UpdateSources))
957 ALsource_Update(*src, ctx);
959 MixSource(*src, device, SamplesToDo);
960 src++;
963 /* effect slot processing */
964 slot = ctx->ActiveEffectSlots;
965 slot_end = slot + ctx->ActiveEffectSlotCount;
966 while(slot != slot_end)
968 for(c = 0;c < SamplesToDo;c++)
970 (*slot)->WetBuffer[c] += (*slot)->ClickRemoval[0];
971 (*slot)->ClickRemoval[0] -= (*slot)->ClickRemoval[0] * (1.0f/256.0f);
973 (*slot)->ClickRemoval[0] += (*slot)->PendingClicks[0];
974 (*slot)->PendingClicks[0] = 0.0f;
976 if(!DeferUpdates && ExchangeInt(&(*slot)->NeedsUpdate, AL_FALSE))
977 ALeffectState_Update((*slot)->EffectState, ctx, *slot);
979 ALeffectState_Process((*slot)->EffectState, SamplesToDo,
980 (*slot)->WetBuffer, device->DryBuffer);
982 for(i = 0;i < SamplesToDo;i++)
983 (*slot)->WetBuffer[i] = 0.0f;
985 slot++;
988 ctx = ctx->next;
991 slot = &device->DefaultSlot;
992 if(*slot != NULL)
994 for(c = 0;c < SamplesToDo;c++)
996 (*slot)->WetBuffer[c] += (*slot)->ClickRemoval[0];
997 (*slot)->ClickRemoval[0] -= (*slot)->ClickRemoval[0] * (1.0f/256.0f);
999 (*slot)->ClickRemoval[0] += (*slot)->PendingClicks[0];
1000 (*slot)->PendingClicks[0] = 0.0f;
1002 if(ExchangeInt(&(*slot)->NeedsUpdate, AL_FALSE))
1003 ALeffectState_Update((*slot)->EffectState, ctx, *slot);
1005 ALeffectState_Process((*slot)->EffectState, SamplesToDo,
1006 (*slot)->WetBuffer, device->DryBuffer);
1008 for(i = 0;i < SamplesToDo;i++)
1009 (*slot)->WetBuffer[i] = 0.0f;
1011 UnlockDevice(device);
1013 //Post processing loop
1014 if(device->FmtChans == DevFmtMono)
1016 for(i = 0;i < SamplesToDo;i++)
1018 device->DryBuffer[i][FRONT_CENTER] += device->ClickRemoval[FRONT_CENTER];
1019 device->ClickRemoval[FRONT_CENTER] -= device->ClickRemoval[FRONT_CENTER] * (1.0f/256.0f);
1021 device->ClickRemoval[FRONT_CENTER] += device->PendingClicks[FRONT_CENTER];
1022 device->PendingClicks[FRONT_CENTER] = 0.0f;
1024 else if(device->FmtChans == DevFmtStereo)
1026 /* Assumes the first two channels are FRONT_LEFT and FRONT_RIGHT */
1027 for(i = 0;i < SamplesToDo;i++)
1029 for(c = 0;c < 2;c++)
1031 device->DryBuffer[i][c] += device->ClickRemoval[c];
1032 device->ClickRemoval[c] -= device->ClickRemoval[c] * (1.0f/256.0f);
1035 for(c = 0;c < 2;c++)
1037 device->ClickRemoval[c] += device->PendingClicks[c];
1038 device->PendingClicks[c] = 0.0f;
1041 else
1043 for(i = 0;i < SamplesToDo;i++)
1045 for(c = 0;c < MAXCHANNELS;c++)
1047 device->DryBuffer[i][c] += device->ClickRemoval[c];
1048 device->ClickRemoval[c] -= device->ClickRemoval[c] * (1.0f/256.0f);
1051 for(c = 0;c < MAXCHANNELS;c++)
1053 device->ClickRemoval[c] += device->PendingClicks[c];
1054 device->PendingClicks[c] = 0.0f;
1058 if(buffer)
1060 switch(device->FmtType)
1062 case DevFmtByte:
1063 Write_ALbyte(device, buffer, SamplesToDo);
1064 break;
1065 case DevFmtUByte:
1066 Write_ALubyte(device, buffer, SamplesToDo);
1067 break;
1068 case DevFmtShort:
1069 Write_ALshort(device, buffer, SamplesToDo);
1070 break;
1071 case DevFmtUShort:
1072 Write_ALushort(device, buffer, SamplesToDo);
1073 break;
1074 case DevFmtFloat:
1075 Write_ALfloat(device, buffer, SamplesToDo);
1076 break;
1080 size -= SamplesToDo;
1083 RestoreFPUMode(fpuState);
1087 ALvoid aluHandleDisconnect(ALCdevice *device)
1089 ALCcontext *Context;
1091 LockDevice(device);
1092 device->Connected = ALC_FALSE;
1094 Context = device->ContextList;
1095 while(Context)
1097 ALsource **src, **src_end;
1099 src = Context->ActiveSources;
1100 src_end = src + Context->ActiveSourceCount;
1101 while(src != src_end)
1103 if((*src)->state == AL_PLAYING)
1105 (*src)->state = AL_STOPPED;
1106 (*src)->BuffersPlayed = (*src)->BuffersInQueue;
1107 (*src)->position = 0;
1108 (*src)->position_fraction = 0;
1110 src++;
1112 Context->ActiveSourceCount = 0;
1114 Context = Context->next;
1116 UnlockDevice(device);