Avoid hard-coding the channel count
[openal-soft.git] / Alc / ALu.c
blobe5ec2e1b0376f1d3125e8e45cc5ffb6947977083
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 "alThunk.h"
35 #include "alListener.h"
36 #include "alAuxEffectSlot.h"
37 #include "alu.h"
38 #include "bs2b.h"
40 #define FRACTIONBITS 14
41 #define FRACTIONMASK ((1L<<FRACTIONBITS)-1)
42 #define MAX_PITCH 65536
44 /* Minimum ramp length in milliseconds. The value below was chosen to
45 * adequately reduce clicks and pops from harsh gain changes. */
46 #define MIN_RAMP_LENGTH 16
48 ALboolean DuplicateStereo = AL_FALSE;
51 static __inline ALfloat aluF2F(ALfloat Value)
53 return Value;
56 static __inline ALshort aluF2S(ALfloat Value)
58 ALint i;
60 if(Value < 0.0f)
62 i = (ALint)(Value*32768.0f);
63 i = max(-32768, i);
65 else
67 i = (ALint)(Value*32767.0f);
68 i = min( 32767, i);
70 return ((ALshort)i);
73 static __inline ALubyte aluF2UB(ALfloat Value)
75 ALshort i = aluF2S(Value);
76 return (i>>8)+128;
80 static __inline ALvoid aluCrossproduct(const ALfloat *inVector1, const ALfloat *inVector2, ALfloat *outVector)
82 outVector[0] = inVector1[1]*inVector2[2] - inVector1[2]*inVector2[1];
83 outVector[1] = inVector1[2]*inVector2[0] - inVector1[0]*inVector2[2];
84 outVector[2] = inVector1[0]*inVector2[1] - inVector1[1]*inVector2[0];
87 static __inline ALfloat aluDotproduct(const ALfloat *inVector1, const ALfloat *inVector2)
89 return inVector1[0]*inVector2[0] + inVector1[1]*inVector2[1] +
90 inVector1[2]*inVector2[2];
93 static __inline ALvoid aluNormalize(ALfloat *inVector)
95 ALfloat length, inverse_length;
97 length = aluSqrt(aluDotproduct(inVector, inVector));
98 if(length != 0.0f)
100 inverse_length = 1.0f/length;
101 inVector[0] *= inverse_length;
102 inVector[1] *= inverse_length;
103 inVector[2] *= inverse_length;
107 static __inline ALvoid aluMatrixVector(ALfloat *vector,ALfloat w,ALfloat matrix[4][4])
109 ALfloat temp[4] = {
110 vector[0], vector[1], vector[2], w
113 vector[0] = temp[0]*matrix[0][0] + temp[1]*matrix[1][0] + temp[2]*matrix[2][0] + temp[3]*matrix[3][0];
114 vector[1] = temp[0]*matrix[0][1] + temp[1]*matrix[1][1] + temp[2]*matrix[2][1] + temp[3]*matrix[3][1];
115 vector[2] = temp[0]*matrix[0][2] + temp[1]*matrix[1][2] + temp[2]*matrix[2][2] + temp[3]*matrix[3][2];
118 static ALvoid SetSpeakerArrangement(const char *name, ALfloat SpeakerAngle[OUTPUTCHANNELS],
119 Channel Speaker2Chan[OUTPUTCHANNELS], ALint chans)
121 char layout_str[256];
122 char *confkey, *next;
123 char *sep, *end;
124 int i, val;
126 strncpy(layout_str, GetConfigValue(NULL, name, ""), sizeof(layout_str));
127 layout_str[255] = 0;
129 next = confkey = layout_str;
130 while(next && *next)
132 confkey = next;
133 next = strchr(confkey, ',');
134 if(next)
136 *next = 0;
137 do {
138 next++;
139 } while(isspace(*next) || *next == ',');
142 sep = strchr(confkey, '=');
143 if(!sep || confkey == sep)
144 continue;
146 end = sep - 1;
147 while(isspace(*end) && end != confkey)
148 end--;
149 *(++end) = 0;
151 if(strcmp(confkey, "fl") == 0 || strcmp(confkey, "front-left") == 0)
152 val = FRONT_LEFT;
153 else if(strcmp(confkey, "fr") == 0 || strcmp(confkey, "front-right") == 0)
154 val = FRONT_RIGHT;
155 else if(strcmp(confkey, "fc") == 0 || strcmp(confkey, "front-center") == 0)
156 val = FRONT_CENTER;
157 else if(strcmp(confkey, "bl") == 0 || strcmp(confkey, "back-left") == 0)
158 val = BACK_LEFT;
159 else if(strcmp(confkey, "br") == 0 || strcmp(confkey, "back-right") == 0)
160 val = BACK_RIGHT;
161 else if(strcmp(confkey, "bc") == 0 || strcmp(confkey, "back-center") == 0)
162 val = BACK_CENTER;
163 else if(strcmp(confkey, "sl") == 0 || strcmp(confkey, "side-left") == 0)
164 val = SIDE_LEFT;
165 else if(strcmp(confkey, "sr") == 0 || strcmp(confkey, "side-right") == 0)
166 val = SIDE_RIGHT;
167 else
169 AL_PRINT("Unknown speaker for %s: \"%s\"\n", name, confkey);
170 continue;
173 *(sep++) = 0;
174 while(isspace(*sep))
175 sep++;
177 for(i = 0;i < chans;i++)
179 if(Speaker2Chan[i] == (Channel)val)
181 val = strtol(sep, NULL, 10);
182 if(val >= -180 && val <= 180)
183 SpeakerAngle[i] = val * M_PI/180.0f;
184 else
185 AL_PRINT("Invalid angle for speaker \"%s\": %d\n", confkey, val);
186 break;
191 for(i = 0;i < chans;i++)
193 int min = i;
194 int i2;
196 for(i2 = i+1;i2 < chans;i2++)
198 if(SpeakerAngle[i2] < SpeakerAngle[min])
199 min = i2;
202 if(min != i)
204 ALfloat tmpf;
205 ALint tmpi;
207 tmpf = SpeakerAngle[i];
208 SpeakerAngle[i] = SpeakerAngle[min];
209 SpeakerAngle[min] = tmpf;
211 tmpi = Speaker2Chan[i];
212 Speaker2Chan[i] = Speaker2Chan[min];
213 Speaker2Chan[min] = tmpi;
218 static __inline ALfloat aluLUTpos2Angle(ALint pos)
220 if(pos < QUADRANT_NUM)
221 return aluAtan((ALfloat)pos / (ALfloat)(QUADRANT_NUM - pos));
222 if(pos < 2 * QUADRANT_NUM)
223 return M_PI_2 + aluAtan((ALfloat)(pos - QUADRANT_NUM) / (ALfloat)(2 * QUADRANT_NUM - pos));
224 if(pos < 3 * QUADRANT_NUM)
225 return aluAtan((ALfloat)(pos - 2 * QUADRANT_NUM) / (ALfloat)(3 * QUADRANT_NUM - pos)) - M_PI;
226 return aluAtan((ALfloat)(pos - 3 * QUADRANT_NUM) / (ALfloat)(4 * QUADRANT_NUM - pos)) - M_PI_2;
229 ALvoid aluInitPanning(ALCdevice *Device)
231 ALfloat SpeakerAngle[OUTPUTCHANNELS];
232 Channel Speaker2Chan[OUTPUTCHANNELS];
233 ALfloat Alpha, Theta;
234 ALint pos, offset;
235 ALfloat maxout;
236 ALuint s, s2;
238 /* Exclude LFE */
239 Device->NumChan = OUTPUTCHANNELS - 1;
240 Speaker2Chan[0] = BACK_LEFT;
241 Speaker2Chan[1] = SIDE_LEFT;
242 Speaker2Chan[2] = FRONT_LEFT;
243 Speaker2Chan[3] = FRONT_CENTER;
244 Speaker2Chan[4] = FRONT_RIGHT;
245 Speaker2Chan[5] = SIDE_RIGHT;
246 Speaker2Chan[6] = BACK_RIGHT;
247 Speaker2Chan[7] = BACK_CENTER;
248 SpeakerAngle[0] = -150.0f * M_PI/180.0f;
249 SpeakerAngle[1] = -90.0f * M_PI/180.0f;
250 SpeakerAngle[2] = -30.0f * M_PI/180.0f;
251 SpeakerAngle[3] = 0.0f * M_PI/180.0f;
252 SpeakerAngle[4] = 30.0f * M_PI/180.0f;
253 SpeakerAngle[5] = 90.0f * M_PI/180.0f;
254 SpeakerAngle[6] = 150.0f * M_PI/180.0f;
255 SpeakerAngle[7] = 180.0f * M_PI/180.0f;
256 SetSpeakerArrangement("layout", SpeakerAngle, Speaker2Chan, Device->NumChan);
258 for(s = 0;s < OUTPUTCHANNELS;s++)
260 for(s2 = 0;s2 < OUTPUTCHANNELS;s2++)
261 Device->ChannelMatrix[s][s2] = ((s==s2) ? 1.0f : 0.0f);
264 switch(Device->Format)
266 case AL_FORMAT_MONO8:
267 case AL_FORMAT_MONO16:
268 case AL_FORMAT_MONO_FLOAT32:
269 Device->ChannelMatrix[FRONT_LEFT][FRONT_CENTER] = aluSqrt(0.5);
270 Device->ChannelMatrix[FRONT_RIGHT][FRONT_CENTER] = aluSqrt(0.5);
271 Device->ChannelMatrix[SIDE_LEFT][FRONT_CENTER] = aluSqrt(0.5);
272 Device->ChannelMatrix[SIDE_RIGHT][FRONT_CENTER] = aluSqrt(0.5);
273 Device->ChannelMatrix[BACK_LEFT][FRONT_CENTER] = aluSqrt(0.5);
274 Device->ChannelMatrix[BACK_RIGHT][FRONT_CENTER] = aluSqrt(0.5);
275 Device->ChannelMatrix[BACK_CENTER][FRONT_CENTER] = 1.0f;
276 break;
278 case AL_FORMAT_STEREO8:
279 case AL_FORMAT_STEREO16:
280 case AL_FORMAT_STEREO_FLOAT32:
281 Device->ChannelMatrix[FRONT_CENTER][FRONT_LEFT] = aluSqrt(0.5);
282 Device->ChannelMatrix[FRONT_CENTER][FRONT_RIGHT] = aluSqrt(0.5);
283 Device->ChannelMatrix[SIDE_LEFT][FRONT_LEFT] = 1.0f;
284 Device->ChannelMatrix[SIDE_RIGHT][FRONT_RIGHT] = 1.0f;
285 Device->ChannelMatrix[BACK_LEFT][FRONT_LEFT] = 1.0f;
286 Device->ChannelMatrix[BACK_RIGHT][FRONT_RIGHT] = 1.0f;
287 Device->ChannelMatrix[BACK_CENTER][FRONT_LEFT] = aluSqrt(0.5);
288 Device->ChannelMatrix[BACK_CENTER][FRONT_RIGHT] = aluSqrt(0.5);
289 break;
291 case AL_FORMAT_QUAD8:
292 case AL_FORMAT_QUAD16:
293 case AL_FORMAT_QUAD32:
294 Device->ChannelMatrix[FRONT_CENTER][FRONT_LEFT] = aluSqrt(0.5);
295 Device->ChannelMatrix[FRONT_CENTER][FRONT_RIGHT] = aluSqrt(0.5);
296 Device->ChannelMatrix[SIDE_LEFT][FRONT_LEFT] = aluSqrt(0.5);
297 Device->ChannelMatrix[SIDE_LEFT][BACK_LEFT] = aluSqrt(0.5);
298 Device->ChannelMatrix[SIDE_RIGHT][FRONT_RIGHT] = aluSqrt(0.5);
299 Device->ChannelMatrix[SIDE_RIGHT][BACK_RIGHT] = aluSqrt(0.5);
300 Device->ChannelMatrix[BACK_CENTER][BACK_LEFT] = aluSqrt(0.5);
301 Device->ChannelMatrix[BACK_CENTER][BACK_RIGHT] = aluSqrt(0.5);
302 break;
304 case AL_FORMAT_51CHN8:
305 case AL_FORMAT_51CHN16:
306 case AL_FORMAT_51CHN32:
307 Device->ChannelMatrix[SIDE_LEFT][FRONT_LEFT] = aluSqrt(0.5);
308 Device->ChannelMatrix[SIDE_LEFT][BACK_LEFT] = aluSqrt(0.5);
309 Device->ChannelMatrix[SIDE_RIGHT][FRONT_RIGHT] = aluSqrt(0.5);
310 Device->ChannelMatrix[SIDE_RIGHT][BACK_RIGHT] = aluSqrt(0.5);
311 Device->ChannelMatrix[BACK_CENTER][BACK_LEFT] = aluSqrt(0.5);
312 Device->ChannelMatrix[BACK_CENTER][BACK_RIGHT] = aluSqrt(0.5);
313 break;
315 case AL_FORMAT_61CHN8:
316 case AL_FORMAT_61CHN16:
317 case AL_FORMAT_61CHN32:
318 Device->ChannelMatrix[BACK_LEFT][BACK_CENTER] = aluSqrt(0.5);
319 Device->ChannelMatrix[BACK_LEFT][SIDE_LEFT] = aluSqrt(0.5);
320 Device->ChannelMatrix[BACK_RIGHT][BACK_CENTER] = aluSqrt(0.5);
321 Device->ChannelMatrix[BACK_RIGHT][SIDE_RIGHT] = aluSqrt(0.5);
322 break;
324 case AL_FORMAT_71CHN8:
325 case AL_FORMAT_71CHN16:
326 case AL_FORMAT_71CHN32:
327 Device->ChannelMatrix[BACK_CENTER][BACK_LEFT] = aluSqrt(0.5);
328 Device->ChannelMatrix[BACK_CENTER][BACK_RIGHT] = aluSqrt(0.5);
329 break;
331 default:
332 assert(0);
335 maxout = 1.0f;
336 for(s = 0;s < OUTPUTCHANNELS;s++)
338 ALfloat out = 0.0f;
339 for(s2 = 0;s2 < OUTPUTCHANNELS;s2++)
340 out += Device->ChannelMatrix[s2][s];
341 maxout = __max(maxout, out);
344 maxout = 1.0f/maxout;
345 for(s = 0;s < OUTPUTCHANNELS;s++)
347 for(s2 = 0;s2 < OUTPUTCHANNELS;s2++)
348 Device->ChannelMatrix[s2][s] *= maxout;
352 for(pos = 0; pos < LUT_NUM; pos++)
354 /* clear all values */
355 offset = OUTPUTCHANNELS * pos;
356 for(s = 0; s < OUTPUTCHANNELS; s++)
357 Device->PanningLUT[offset+s] = 0.0f;
359 /* source angle */
360 Theta = aluLUTpos2Angle(pos);
362 /* set panning values */
363 for(s = 0; s < Device->NumChan - 1; s++)
365 if(Theta >= SpeakerAngle[s] && Theta < SpeakerAngle[s+1])
367 /* source between speaker s and speaker s+1 */
368 Alpha = M_PI_2 * (Theta-SpeakerAngle[s]) /
369 (SpeakerAngle[s+1]-SpeakerAngle[s]);
370 Device->PanningLUT[offset + Speaker2Chan[s]] = cos(Alpha);
371 Device->PanningLUT[offset + Speaker2Chan[s+1]] = sin(Alpha);
372 break;
375 if(s == Device->NumChan - 1)
377 /* source between last and first speaker */
378 if(Theta < SpeakerAngle[0])
379 Theta += 2.0f * M_PI;
380 Alpha = M_PI_2 * (Theta-SpeakerAngle[s]) /
381 (2.0f * M_PI + SpeakerAngle[0]-SpeakerAngle[s]);
382 Device->PanningLUT[offset + Speaker2Chan[s]] = cos(Alpha);
383 Device->PanningLUT[offset + Speaker2Chan[0]] = sin(Alpha);
388 static ALvoid CalcNonAttnSourceParams(const ALCcontext *ALContext, ALsource *ALSource)
390 ALfloat SourceVolume,ListenerGain,MinVolume,MaxVolume;
391 ALfloat DryGain, DryGainHF;
392 ALfloat WetGain[MAX_SENDS];
393 ALfloat WetGainHF[MAX_SENDS];
394 ALint NumSends, Frequency;
395 ALfloat cw;
396 ALint i;
398 //Get context properties
399 NumSends = ALContext->Device->NumAuxSends;
400 Frequency = ALContext->Device->Frequency;
402 //Get listener properties
403 ListenerGain = ALContext->Listener.Gain;
405 //Get source properties
406 SourceVolume = ALSource->flGain;
407 MinVolume = ALSource->flMinGain;
408 MaxVolume = ALSource->flMaxGain;
410 //1. Multi-channel buffers always play "normal"
411 ALSource->Params.Pitch = ALSource->flPitch;
413 DryGain = SourceVolume;
414 DryGain = __min(DryGain,MaxVolume);
415 DryGain = __max(DryGain,MinVolume);
416 DryGainHF = 1.0f;
418 switch(ALSource->DirectFilter.type)
420 case AL_FILTER_LOWPASS:
421 DryGain *= ALSource->DirectFilter.Gain;
422 DryGainHF *= ALSource->DirectFilter.GainHF;
423 break;
426 ALSource->Params.DryGains[FRONT_LEFT] = DryGain * ListenerGain;
427 ALSource->Params.DryGains[FRONT_RIGHT] = DryGain * ListenerGain;
428 ALSource->Params.DryGains[SIDE_LEFT] = DryGain * ListenerGain;
429 ALSource->Params.DryGains[SIDE_RIGHT] = DryGain * ListenerGain;
430 ALSource->Params.DryGains[BACK_LEFT] = DryGain * ListenerGain;
431 ALSource->Params.DryGains[BACK_RIGHT] = DryGain * ListenerGain;
432 ALSource->Params.DryGains[FRONT_CENTER] = DryGain * ListenerGain;
433 ALSource->Params.DryGains[BACK_CENTER] = DryGain * ListenerGain;
434 ALSource->Params.DryGains[LFE] = DryGain * ListenerGain;
436 for(i = 0;i < NumSends;i++)
438 WetGain[i] = SourceVolume;
439 WetGain[i] = __min(WetGain[i],MaxVolume);
440 WetGain[i] = __max(WetGain[i],MinVolume);
441 WetGainHF[i] = 1.0f;
443 switch(ALSource->Send[i].WetFilter.type)
445 case AL_FILTER_LOWPASS:
446 WetGain[i] *= ALSource->Send[i].WetFilter.Gain;
447 WetGainHF[i] *= ALSource->Send[i].WetFilter.GainHF;
448 break;
451 ALSource->Params.WetGains[i] = WetGain[i] * ListenerGain;
453 for(i = NumSends;i < MAX_SENDS;i++)
455 ALSource->Params.WetGains[i] = 0.0f;
456 WetGainHF[i] = 1.0f;
459 /* Update filter coefficients. Calculations based on the I3DL2
460 * spec. */
461 cw = cos(2.0*M_PI * LOWPASSFREQCUTOFF / Frequency);
463 /* We use two chained one-pole filters, so we need to take the
464 * square root of the squared gain, which is the same as the base
465 * gain. */
466 ALSource->Params.iirFilter.coeff = lpCoeffCalc(DryGainHF, cw);
468 for(i = 0;i < NumSends;i++)
470 /* We use a one-pole filter, so we need to take the squared gain */
471 ALfloat a = lpCoeffCalc(WetGainHF[i]*WetGainHF[i], cw);
472 ALSource->Params.Send[i].iirFilter.coeff = a;
476 static ALvoid CalcSourceParams(const ALCcontext *ALContext, ALsource *ALSource)
478 ALfloat InnerAngle,OuterAngle,Angle,Distance,DryMix,OrigDist;
479 ALfloat Direction[3],Position[3],SourceToListener[3];
480 ALfloat Velocity[3],ListenerVel[3];
481 ALfloat MinVolume,MaxVolume,MinDist,MaxDist,Rolloff,OuterGainHF;
482 ALfloat ConeVolume,ConeHF,SourceVolume,ListenerGain;
483 ALfloat DopplerFactor, DopplerVelocity, flSpeedOfSound;
484 ALfloat Matrix[4][4];
485 ALfloat flAttenuation, effectiveDist;
486 ALfloat RoomAttenuation[MAX_SENDS];
487 ALfloat MetersPerUnit;
488 ALfloat RoomRolloff[MAX_SENDS];
489 ALfloat DryGainHF = 1.0f;
490 ALfloat WetGain[MAX_SENDS];
491 ALfloat WetGainHF[MAX_SENDS];
492 ALfloat DirGain, AmbientGain;
493 ALfloat length;
494 const ALfloat *SpeakerGain;
495 ALuint Frequency;
496 ALint NumSends;
497 ALint pos, s, i;
498 ALfloat cw;
500 for(i = 0;i < MAX_SENDS;i++)
501 WetGainHF[i] = 1.0f;
503 //Get context properties
504 DopplerFactor = ALContext->DopplerFactor * ALSource->DopplerFactor;
505 DopplerVelocity = ALContext->DopplerVelocity;
506 flSpeedOfSound = ALContext->flSpeedOfSound;
507 NumSends = ALContext->Device->NumAuxSends;
508 Frequency = ALContext->Device->Frequency;
510 //Get listener properties
511 ListenerGain = ALContext->Listener.Gain;
512 MetersPerUnit = ALContext->Listener.MetersPerUnit;
513 memcpy(ListenerVel, ALContext->Listener.Velocity, sizeof(ALContext->Listener.Velocity));
515 //Get source properties
516 SourceVolume = ALSource->flGain;
517 memcpy(Position, ALSource->vPosition, sizeof(ALSource->vPosition));
518 memcpy(Direction, ALSource->vOrientation, sizeof(ALSource->vOrientation));
519 memcpy(Velocity, ALSource->vVelocity, sizeof(ALSource->vVelocity));
520 MinVolume = ALSource->flMinGain;
521 MaxVolume = ALSource->flMaxGain;
522 MinDist = ALSource->flRefDistance;
523 MaxDist = ALSource->flMaxDistance;
524 Rolloff = ALSource->flRollOffFactor;
525 InnerAngle = ALSource->flInnerAngle;
526 OuterAngle = ALSource->flOuterAngle;
527 OuterGainHF = ALSource->OuterGainHF;
529 //1. Translate Listener to origin (convert to head relative)
530 if(ALSource->bHeadRelative==AL_FALSE)
532 ALfloat U[3],V[3],N[3],P[3];
534 // Build transform matrix
535 memcpy(N, ALContext->Listener.Forward, sizeof(N)); // At-vector
536 aluNormalize(N); // Normalized At-vector
537 memcpy(V, ALContext->Listener.Up, sizeof(V)); // Up-vector
538 aluNormalize(V); // Normalized Up-vector
539 aluCrossproduct(N, V, U); // Right-vector
540 aluNormalize(U); // Normalized Right-vector
541 P[0] = -(ALContext->Listener.Position[0]*U[0] + // Translation
542 ALContext->Listener.Position[1]*U[1] +
543 ALContext->Listener.Position[2]*U[2]);
544 P[1] = -(ALContext->Listener.Position[0]*V[0] +
545 ALContext->Listener.Position[1]*V[1] +
546 ALContext->Listener.Position[2]*V[2]);
547 P[2] = -(ALContext->Listener.Position[0]*-N[0] +
548 ALContext->Listener.Position[1]*-N[1] +
549 ALContext->Listener.Position[2]*-N[2]);
550 Matrix[0][0] = U[0]; Matrix[0][1] = V[0]; Matrix[0][2] = -N[0]; Matrix[0][3] = 0.0f;
551 Matrix[1][0] = U[1]; Matrix[1][1] = V[1]; Matrix[1][2] = -N[1]; Matrix[1][3] = 0.0f;
552 Matrix[2][0] = U[2]; Matrix[2][1] = V[2]; Matrix[2][2] = -N[2]; Matrix[2][3] = 0.0f;
553 Matrix[3][0] = P[0]; Matrix[3][1] = P[1]; Matrix[3][2] = P[2]; Matrix[3][3] = 1.0f;
555 // Transform source position and direction into listener space
556 aluMatrixVector(Position, 1.0f, Matrix);
557 aluMatrixVector(Direction, 0.0f, Matrix);
558 // Transform source and listener velocity into listener space
559 aluMatrixVector(Velocity, 0.0f, Matrix);
560 aluMatrixVector(ListenerVel, 0.0f, Matrix);
562 else
563 ListenerVel[0] = ListenerVel[1] = ListenerVel[2] = 0.0f;
565 SourceToListener[0] = -Position[0];
566 SourceToListener[1] = -Position[1];
567 SourceToListener[2] = -Position[2];
568 aluNormalize(SourceToListener);
569 aluNormalize(Direction);
571 //2. Calculate distance attenuation
572 Distance = aluSqrt(aluDotproduct(Position, Position));
573 OrigDist = Distance;
575 flAttenuation = 1.0f;
576 for(i = 0;i < NumSends;i++)
578 RoomAttenuation[i] = 1.0f;
580 RoomRolloff[i] = ALSource->RoomRolloffFactor;
581 if(ALSource->Send[i].Slot &&
582 (ALSource->Send[i].Slot->effect.type == AL_EFFECT_REVERB ||
583 ALSource->Send[i].Slot->effect.type == AL_EFFECT_EAXREVERB))
584 RoomRolloff[i] += ALSource->Send[i].Slot->effect.Reverb.RoomRolloffFactor;
587 switch(ALContext->SourceDistanceModel ? ALSource->DistanceModel :
588 ALContext->DistanceModel)
590 case AL_INVERSE_DISTANCE_CLAMPED:
591 Distance=__max(Distance,MinDist);
592 Distance=__min(Distance,MaxDist);
593 if(MaxDist < MinDist)
594 break;
595 //fall-through
596 case AL_INVERSE_DISTANCE:
597 if(MinDist > 0.0f)
599 if((MinDist + (Rolloff * (Distance - MinDist))) > 0.0f)
600 flAttenuation = MinDist / (MinDist + (Rolloff * (Distance - MinDist)));
601 for(i = 0;i < NumSends;i++)
603 if((MinDist + (RoomRolloff[i] * (Distance - MinDist))) > 0.0f)
604 RoomAttenuation[i] = MinDist / (MinDist + (RoomRolloff[i] * (Distance - MinDist)));
607 break;
609 case AL_LINEAR_DISTANCE_CLAMPED:
610 Distance=__max(Distance,MinDist);
611 Distance=__min(Distance,MaxDist);
612 if(MaxDist < MinDist)
613 break;
614 //fall-through
615 case AL_LINEAR_DISTANCE:
616 Distance=__min(Distance,MaxDist);
617 if(MaxDist != MinDist)
619 flAttenuation = 1.0f - (Rolloff*(Distance-MinDist)/(MaxDist - MinDist));
620 for(i = 0;i < NumSends;i++)
621 RoomAttenuation[i] = 1.0f - (RoomRolloff[i]*(Distance-MinDist)/(MaxDist - MinDist));
623 break;
625 case AL_EXPONENT_DISTANCE_CLAMPED:
626 Distance=__max(Distance,MinDist);
627 Distance=__min(Distance,MaxDist);
628 if(MaxDist < MinDist)
629 break;
630 //fall-through
631 case AL_EXPONENT_DISTANCE:
632 if(Distance > 0.0f && MinDist > 0.0f)
634 flAttenuation = aluPow(Distance/MinDist, -Rolloff);
635 for(i = 0;i < NumSends;i++)
636 RoomAttenuation[i] = aluPow(Distance/MinDist, -RoomRolloff[i]);
638 break;
640 case AL_NONE:
641 break;
644 // Source Gain + Attenuation
645 DryMix = SourceVolume * flAttenuation;
646 for(i = 0;i < NumSends;i++)
647 WetGain[i] = SourceVolume * RoomAttenuation[i];
649 effectiveDist = 0.0f;
650 if(MinDist > 0.0f)
651 effectiveDist = (MinDist/flAttenuation - MinDist)*MetersPerUnit;
653 // Distance-based air absorption
654 if(ALSource->AirAbsorptionFactor > 0.0f && effectiveDist > 0.0f)
656 ALfloat absorb;
658 // Absorption calculation is done in dB
659 absorb = (ALSource->AirAbsorptionFactor*AIRABSORBGAINDBHF) *
660 effectiveDist;
661 // Convert dB to linear gain before applying
662 absorb = aluPow(10.0f, absorb/20.0f);
664 DryGainHF *= absorb;
667 //3. Apply directional soundcones
668 Angle = aluAcos(aluDotproduct(Direction,SourceToListener)) * 180.0f/M_PI;
669 if(Angle >= InnerAngle && Angle <= OuterAngle)
671 ALfloat scale = (Angle-InnerAngle) / (OuterAngle-InnerAngle);
672 ConeVolume = (1.0f+(ALSource->flOuterGain-1.0f)*scale);
673 ConeHF = (1.0f+(OuterGainHF-1.0f)*scale);
675 else if(Angle > OuterAngle)
677 ConeVolume = (1.0f+(ALSource->flOuterGain-1.0f));
678 ConeHF = (1.0f+(OuterGainHF-1.0f));
680 else
682 ConeVolume = 1.0f;
683 ConeHF = 1.0f;
686 // Apply some high-frequency attenuation for sources behind the listener
687 // NOTE: This should be aluDotproduct({0,0,-1}, ListenerToSource), however
688 // that is equivalent to aluDotproduct({0,0,1}, SourceToListener), which is
689 // the same as SourceToListener[2]
690 Angle = aluAcos(SourceToListener[2]) * 180.0f/M_PI;
691 // Sources within the minimum distance attenuate less
692 if(OrigDist < MinDist)
693 Angle *= OrigDist/MinDist;
694 if(Angle > 90.0f)
696 ALfloat scale = (Angle-90.0f) / (180.1f-90.0f); // .1 to account for fp errors
697 ConeHF *= 1.0f - (ALContext->Device->HeadDampen*scale);
700 DryMix *= ConeVolume;
701 if(ALSource->DryGainHFAuto)
702 DryGainHF *= ConeHF;
704 // Clamp to Min/Max Gain
705 DryMix = __min(DryMix,MaxVolume);
706 DryMix = __max(DryMix,MinVolume);
708 for(i = 0;i < NumSends;i++)
710 ALeffectslot *Slot = ALSource->Send[i].Slot;
712 if(!Slot || Slot->effect.type == AL_EFFECT_NULL)
714 ALSource->Params.WetGains[i] = 0.0f;
715 WetGainHF[i] = 1.0f;
716 continue;
719 if(Slot->AuxSendAuto)
721 if(ALSource->WetGainAuto)
722 WetGain[i] *= ConeVolume;
723 if(ALSource->WetGainHFAuto)
724 WetGainHF[i] *= ConeHF;
726 // Clamp to Min/Max Gain
727 WetGain[i] = __min(WetGain[i],MaxVolume);
728 WetGain[i] = __max(WetGain[i],MinVolume);
730 if(Slot->effect.type == AL_EFFECT_REVERB ||
731 Slot->effect.type == AL_EFFECT_EAXREVERB)
733 /* Apply a decay-time transformation to the wet path, based on
734 * the attenuation of the dry path.
736 * Using the approximate (effective) source to listener
737 * distance, the initial decay of the reverb effect is
738 * calculated and applied to the wet path.
740 WetGain[i] *= aluPow(10.0f, effectiveDist /
741 (SPEEDOFSOUNDMETRESPERSEC *
742 Slot->effect.Reverb.DecayTime) *
743 -60.0 / 20.0);
745 WetGainHF[i] *= aluPow(10.0f,
746 log10(Slot->effect.Reverb.AirAbsorptionGainHF) *
747 ALSource->AirAbsorptionFactor * effectiveDist);
750 else
752 /* If the slot's auxiliary send auto is off, the data sent to the
753 * effect slot is the same as the dry path, sans filter effects */
754 WetGain[i] = DryMix;
755 WetGainHF[i] = DryGainHF;
758 switch(ALSource->Send[i].WetFilter.type)
760 case AL_FILTER_LOWPASS:
761 WetGain[i] *= ALSource->Send[i].WetFilter.Gain;
762 WetGainHF[i] *= ALSource->Send[i].WetFilter.GainHF;
763 break;
765 ALSource->Params.WetGains[i] = WetGain[i] * ListenerGain;
767 for(i = NumSends;i < MAX_SENDS;i++)
769 ALSource->Params.WetGains[i] = 0.0f;
770 WetGainHF[i] = 1.0f;
773 // Apply filter gains and filters
774 switch(ALSource->DirectFilter.type)
776 case AL_FILTER_LOWPASS:
777 DryMix *= ALSource->DirectFilter.Gain;
778 DryGainHF *= ALSource->DirectFilter.GainHF;
779 break;
781 DryMix *= ListenerGain;
783 // Calculate Velocity
784 if(DopplerFactor != 0.0f)
786 ALfloat flVSS, flVLS;
787 ALfloat flMaxVelocity = (DopplerVelocity * flSpeedOfSound) /
788 DopplerFactor;
790 flVSS = aluDotproduct(Velocity, SourceToListener);
791 if(flVSS >= flMaxVelocity)
792 flVSS = (flMaxVelocity - 1.0f);
793 else if(flVSS <= -flMaxVelocity)
794 flVSS = -flMaxVelocity + 1.0f;
796 flVLS = aluDotproduct(ListenerVel, SourceToListener);
797 if(flVLS >= flMaxVelocity)
798 flVLS = (flMaxVelocity - 1.0f);
799 else if(flVLS <= -flMaxVelocity)
800 flVLS = -flMaxVelocity + 1.0f;
802 ALSource->Params.Pitch = ALSource->flPitch *
803 ((flSpeedOfSound * DopplerVelocity) - (DopplerFactor * flVLS)) /
804 ((flSpeedOfSound * DopplerVelocity) - (DopplerFactor * flVSS));
806 else
807 ALSource->Params.Pitch = ALSource->flPitch;
809 // Use energy-preserving panning algorithm for multi-speaker playback
810 length = __max(OrigDist, MinDist);
811 if(length > 0.0f)
813 ALfloat invlen = 1.0f/length;
814 Position[0] *= invlen;
815 Position[1] *= invlen;
816 Position[2] *= invlen;
819 pos = aluCart2LUTpos(-Position[2], Position[0]);
820 SpeakerGain = &ALContext->Device->PanningLUT[OUTPUTCHANNELS * pos];
822 DirGain = aluSqrt(Position[0]*Position[0] + Position[2]*Position[2]);
823 // elevation adjustment for directional gain. this sucks, but
824 // has low complexity
825 AmbientGain = 1.0/aluSqrt(ALContext->Device->NumChan) * (1.0-DirGain);
826 for(s = 0; s < OUTPUTCHANNELS; s++)
828 ALfloat gain = SpeakerGain[s]*DirGain + AmbientGain;
829 ALSource->Params.DryGains[s] = DryMix * gain;
832 /* Update filter coefficients. */
833 cw = cos(2.0*M_PI * LOWPASSFREQCUTOFF / Frequency);
835 /* Spatialized sources use four chained one-pole filters, so we need to
836 * take the fourth root of the squared gain, which is the same as the
837 * square root of the base gain. */
838 ALSource->Params.iirFilter.coeff = lpCoeffCalc(aluSqrt(DryGainHF), cw);
840 for(i = 0;i < NumSends;i++)
842 /* The wet path uses two chained one-pole filters, so take the
843 * base gain (square root of the squared gain) */
844 ALSource->Params.Send[i].iirFilter.coeff = lpCoeffCalc(WetGainHF[i], cw);
848 static __inline ALfloat point(ALfloat val1, ALfloat val2, ALint frac)
850 return val1;
851 (void)val2;
852 (void)frac;
854 static __inline ALfloat lerp(ALfloat val1, ALfloat val2, ALint frac)
856 return val1 + ((val2-val1)*(frac * (1.0f/(1<<FRACTIONBITS))));
858 static __inline ALfloat cos_lerp(ALfloat val1, ALfloat val2, ALint frac)
860 ALfloat mult = (1.0f-cos(frac * (1.0f/(1<<FRACTIONBITS)) * M_PI)) * 0.5f;
861 return val1 + ((val2-val1)*mult);
864 static void MixSomeSources(ALCcontext *ALContext, float (*DryBuffer)[OUTPUTCHANNELS], ALuint SamplesToDo)
866 static float DummyBuffer[BUFFERSIZE];
867 ALfloat *WetBuffer[MAX_SENDS];
868 ALfloat DrySend[OUTPUTCHANNELS];
869 ALfloat dryGainStep[OUTPUTCHANNELS];
870 ALfloat wetGainStep[MAX_SENDS];
871 ALuint i, j, k, out;
872 ALsource *ALSource;
873 ALfloat value, outsamp;
874 ALbufferlistitem *BufferListItem;
875 ALint64 DataSize64,DataPos64;
876 FILTER *DryFilter, *WetFilter[MAX_SENDS];
877 ALfloat WetSend[MAX_SENDS];
878 ALuint rampLength;
879 ALuint DeviceFreq;
880 ALint increment;
881 ALuint DataPosInt, DataPosFrac;
882 ALuint Channels, Bytes;
883 ALuint Frequency;
884 resampler_t Resampler;
885 ALuint BuffersPlayed;
886 ALfloat Pitch;
887 ALenum State;
889 if(!(ALSource=ALContext->SourceList))
890 return;
892 DeviceFreq = ALContext->Device->Frequency;
894 rampLength = DeviceFreq * MIN_RAMP_LENGTH / 1000;
895 rampLength = max(rampLength, SamplesToDo);
897 another_source:
898 if(ALSource->state != AL_PLAYING)
900 if((ALSource=ALSource->next) != NULL)
901 goto another_source;
902 return;
904 j = 0;
906 /* Find buffer format */
907 Frequency = 0;
908 Channels = 0;
909 Bytes = 0;
910 BufferListItem = ALSource->queue;
911 while(BufferListItem != NULL)
913 ALbuffer *ALBuffer;
914 if((ALBuffer=BufferListItem->buffer) != NULL)
916 Channels = aluChannelsFromFormat(ALBuffer->format);
917 Bytes = aluBytesFromFormat(ALBuffer->format);
918 Frequency = ALBuffer->frequency;
919 break;
921 BufferListItem = BufferListItem->next;
924 if(ALSource->NeedsUpdate)
926 //Only apply 3D calculations for mono buffers
927 if(Channels == 1)
928 CalcSourceParams(ALContext, ALSource);
929 else
930 CalcNonAttnSourceParams(ALContext, ALSource);
931 ALSource->NeedsUpdate = AL_FALSE;
934 /* Get source info */
935 Resampler = ALSource->Resampler;
936 State = ALSource->state;
937 BuffersPlayed = ALSource->BuffersPlayed;
938 DataPosInt = ALSource->position;
939 DataPosFrac = ALSource->position_fraction;
941 /* Compute 18.14 fixed point step */
942 Pitch = (ALSource->Params.Pitch*Frequency) / DeviceFreq;
943 if(Pitch > (float)MAX_PITCH) Pitch = (float)MAX_PITCH;
944 increment = (ALint)(Pitch*(ALfloat)(1L<<FRACTIONBITS));
945 if(increment <= 0) increment = (1<<FRACTIONBITS);
947 if(ALSource->FirstStart)
949 for(i = 0;i < OUTPUTCHANNELS;i++)
950 DrySend[i] = ALSource->Params.DryGains[i];
951 for(i = 0;i < MAX_SENDS;i++)
952 WetSend[i] = ALSource->Params.WetGains[i];
954 else
956 for(i = 0;i < OUTPUTCHANNELS;i++)
957 DrySend[i] = ALSource->DryGains[i];
958 for(i = 0;i < MAX_SENDS;i++)
959 WetSend[i] = ALSource->WetGains[i];
962 DryFilter = &ALSource->Params.iirFilter;
963 for(i = 0;i < MAX_SENDS;i++)
965 WetFilter[i] = &ALSource->Params.Send[i].iirFilter;
966 WetBuffer[i] = (ALSource->Send[i].Slot ?
967 ALSource->Send[i].Slot->WetBuffer :
968 DummyBuffer);
971 /* Get current buffer queue item */
972 BufferListItem = ALSource->queue;
973 for(i = 0;i < BuffersPlayed && BufferListItem;i++)
974 BufferListItem = BufferListItem->next;
976 while(State == AL_PLAYING && j < SamplesToDo)
978 ALuint DataSize = 0;
979 ALbuffer *ALBuffer;
980 ALfloat *Data;
981 ALuint BufferSize;
983 /* Get buffer info */
984 if((ALBuffer=BufferListItem->buffer) != NULL)
986 Data = ALBuffer->data;
987 DataSize = ALBuffer->size;
988 DataSize /= Channels * Bytes;
990 if(DataPosInt >= DataSize)
991 goto skipmix;
993 if(BufferListItem->next)
995 ALbuffer *NextBuf = BufferListItem->next->buffer;
996 if(NextBuf && NextBuf->size)
998 ALint ulExtraSamples = BUFFER_PADDING*Channels*Bytes;
999 ulExtraSamples = min(NextBuf->size, ulExtraSamples);
1000 memcpy(&Data[DataSize*Channels], NextBuf->data, ulExtraSamples);
1003 else if(ALSource->bLooping)
1005 ALbuffer *NextBuf = ALSource->queue->buffer;
1006 if(NextBuf && NextBuf->size)
1008 ALint ulExtraSamples = BUFFER_PADDING*Channels*Bytes;
1009 ulExtraSamples = min(NextBuf->size, ulExtraSamples);
1010 memcpy(&Data[DataSize*Channels], NextBuf->data, ulExtraSamples);
1013 else
1014 memset(&Data[DataSize*Channels], 0, (BUFFER_PADDING*Channels*Bytes));
1016 /* Compute the gain steps for each output channel */
1017 for(i = 0;i < OUTPUTCHANNELS;i++)
1018 dryGainStep[i] = (ALSource->Params.DryGains[i]-DrySend[i]) /
1019 rampLength;
1020 for(i = 0;i < MAX_SENDS;i++)
1021 wetGainStep[i] = (ALSource->Params.WetGains[i]-WetSend[i]) /
1022 rampLength;
1024 /* Figure out how many samples we can mix. */
1025 DataSize64 = DataSize;
1026 DataSize64 <<= FRACTIONBITS;
1027 DataPos64 = DataPosInt;
1028 DataPos64 <<= FRACTIONBITS;
1029 DataPos64 += DataPosFrac;
1030 BufferSize = (ALuint)((DataSize64-DataPos64+(increment-1)) / increment);
1032 BufferSize = min(BufferSize, (SamplesToDo-j));
1034 /* Actual sample mixing loop */
1035 k = 0;
1036 Data += DataPosInt*Channels;
1038 if(Channels == 1) /* Mono */
1040 #define DO_MIX(resampler) do { \
1041 while(BufferSize--) \
1043 for(i = 0;i < OUTPUTCHANNELS;i++) \
1044 DrySend[i] += dryGainStep[i]; \
1045 for(i = 0;i < MAX_SENDS;i++) \
1046 WetSend[i] += wetGainStep[i]; \
1048 /* First order interpolator */ \
1049 value = (resampler)(Data[k], Data[k+1], DataPosFrac); \
1051 /* Direct path final mix buffer and panning */ \
1052 outsamp = lpFilter4P(DryFilter, 0, value); \
1053 DryBuffer[j][FRONT_LEFT] += outsamp*DrySend[FRONT_LEFT]; \
1054 DryBuffer[j][FRONT_RIGHT] += outsamp*DrySend[FRONT_RIGHT]; \
1055 DryBuffer[j][SIDE_LEFT] += outsamp*DrySend[SIDE_LEFT]; \
1056 DryBuffer[j][SIDE_RIGHT] += outsamp*DrySend[SIDE_RIGHT]; \
1057 DryBuffer[j][BACK_LEFT] += outsamp*DrySend[BACK_LEFT]; \
1058 DryBuffer[j][BACK_RIGHT] += outsamp*DrySend[BACK_RIGHT]; \
1059 DryBuffer[j][FRONT_CENTER] += outsamp*DrySend[FRONT_CENTER]; \
1060 DryBuffer[j][BACK_CENTER] += outsamp*DrySend[BACK_CENTER]; \
1062 /* Room path final mix buffer and panning */ \
1063 for(i = 0;i < MAX_SENDS;i++) \
1065 outsamp = lpFilter2P(WetFilter[i], 0, value); \
1066 WetBuffer[i][j] += outsamp*WetSend[i]; \
1069 DataPosFrac += increment; \
1070 k += DataPosFrac>>FRACTIONBITS; \
1071 DataPosFrac &= FRACTIONMASK; \
1072 j++; \
1074 } while(0)
1076 switch(Resampler)
1078 case POINT_RESAMPLER:
1079 DO_MIX(point); break;
1080 case LINEAR_RESAMPLER:
1081 DO_MIX(lerp); break;
1082 case COSINE_RESAMPLER:
1083 DO_MIX(cos_lerp); break;
1084 case RESAMPLER_MIN:
1085 case RESAMPLER_MAX:
1086 break;
1088 #undef DO_MIX
1090 else if(Channels == 2 && DuplicateStereo) /* Stereo */
1092 const int chans[] = {
1093 FRONT_LEFT, FRONT_RIGHT
1095 const int chans2[] = {
1096 BACK_LEFT, SIDE_LEFT, BACK_RIGHT, SIDE_RIGHT
1098 const ALfloat scaler = aluSqrt(1.0f/Channels);
1099 const ALfloat dupscaler = aluSqrt(1.0f/3.0f);
1101 #define DO_MIX(resampler) do { \
1102 while(BufferSize--) \
1104 for(i = 0;i < OUTPUTCHANNELS;i++) \
1105 DrySend[i] += dryGainStep[i]; \
1106 for(i = 0;i < MAX_SENDS;i++) \
1107 WetSend[i] += wetGainStep[i]; \
1109 for(i = 0;i < Channels;i++) \
1111 value = (resampler)(Data[k*Channels + i],Data[(k+1)*Channels + i],\
1112 DataPosFrac); \
1113 outsamp = lpFilter2P(DryFilter, chans[i]*2, value) * dupscaler; \
1114 DryBuffer[j][chans[i]] += outsamp*DrySend[chans[i]]; \
1115 DryBuffer[j][chans2[i*2+0]] += outsamp*DrySend[chans2[i*2+0]]; \
1116 DryBuffer[j][chans2[i*2+1]] += outsamp*DrySend[chans2[i*2+1]]; \
1117 for(out = 0;out < MAX_SENDS;out++) \
1119 outsamp = lpFilter1P(WetFilter[out], chans[i], value); \
1120 WetBuffer[out][j] += outsamp*WetSend[out]*scaler; \
1124 DataPosFrac += increment; \
1125 k += DataPosFrac>>FRACTIONBITS; \
1126 DataPosFrac &= FRACTIONMASK; \
1127 j++; \
1129 } while(0)
1131 switch(Resampler)
1133 case POINT_RESAMPLER:
1134 DO_MIX(point); break;
1135 case LINEAR_RESAMPLER:
1136 DO_MIX(lerp); break;
1137 case COSINE_RESAMPLER:
1138 DO_MIX(cos_lerp); break;
1139 case RESAMPLER_MIN:
1140 case RESAMPLER_MAX:
1141 break;
1143 #undef DO_MIX
1145 else if(Channels == 2) /* Stereo */
1147 const int chans[] = {
1148 FRONT_LEFT, FRONT_RIGHT
1150 const ALfloat scaler = aluSqrt(1.0f/Channels);
1152 #define DO_MIX(resampler) do { \
1153 while(BufferSize--) \
1155 for(i = 0;i < OUTPUTCHANNELS;i++) \
1156 DrySend[i] += dryGainStep[i]; \
1157 for(i = 0;i < MAX_SENDS;i++) \
1158 WetSend[i] += wetGainStep[i]; \
1160 for(i = 0;i < Channels;i++) \
1162 value = (resampler)(Data[k*Channels + i],Data[(k+1)*Channels + i],\
1163 DataPosFrac); \
1164 outsamp = lpFilter2P(DryFilter, chans[i]*2, value); \
1165 DryBuffer[j][chans[i]] += outsamp*DrySend[chans[i]]; \
1166 for(out = 0;out < MAX_SENDS;out++) \
1168 outsamp = lpFilter1P(WetFilter[out], chans[i], value); \
1169 WetBuffer[out][j] += outsamp*WetSend[out]*scaler; \
1173 DataPosFrac += increment; \
1174 k += DataPosFrac>>FRACTIONBITS; \
1175 DataPosFrac &= FRACTIONMASK; \
1176 j++; \
1178 } while(0)
1180 switch(Resampler)
1182 case POINT_RESAMPLER:
1183 DO_MIX(point); break;
1184 case LINEAR_RESAMPLER:
1185 DO_MIX(lerp); break;
1186 case COSINE_RESAMPLER:
1187 DO_MIX(cos_lerp); break;
1188 case RESAMPLER_MIN:
1189 case RESAMPLER_MAX:
1190 break;
1193 else if(Channels == 4) /* Quad */
1195 const int chans[] = {
1196 FRONT_LEFT, FRONT_RIGHT,
1197 BACK_LEFT, BACK_RIGHT
1199 const ALfloat scaler = aluSqrt(1.0f/Channels);
1201 switch(Resampler)
1203 case POINT_RESAMPLER:
1204 DO_MIX(point); break;
1205 case LINEAR_RESAMPLER:
1206 DO_MIX(lerp); break;
1207 case COSINE_RESAMPLER:
1208 DO_MIX(cos_lerp); break;
1209 case RESAMPLER_MIN:
1210 case RESAMPLER_MAX:
1211 break;
1214 else if(Channels == 6) /* 5.1 */
1216 const int chans[] = {
1217 FRONT_LEFT, FRONT_RIGHT,
1218 FRONT_CENTER, LFE,
1219 BACK_LEFT, BACK_RIGHT
1221 const ALfloat scaler = aluSqrt(1.0f/Channels);
1223 switch(Resampler)
1225 case POINT_RESAMPLER:
1226 DO_MIX(point); break;
1227 case LINEAR_RESAMPLER:
1228 DO_MIX(lerp); break;
1229 case COSINE_RESAMPLER:
1230 DO_MIX(cos_lerp); break;
1231 case RESAMPLER_MIN:
1232 case RESAMPLER_MAX:
1233 break;
1236 else if(Channels == 7) /* 6.1 */
1238 const int chans[] = {
1239 FRONT_LEFT, FRONT_RIGHT,
1240 FRONT_CENTER, LFE,
1241 BACK_CENTER,
1242 SIDE_LEFT, SIDE_RIGHT
1244 const ALfloat scaler = aluSqrt(1.0f/Channels);
1246 switch(Resampler)
1248 case POINT_RESAMPLER:
1249 DO_MIX(point); break;
1250 case LINEAR_RESAMPLER:
1251 DO_MIX(lerp); break;
1252 case COSINE_RESAMPLER:
1253 DO_MIX(cos_lerp); break;
1254 case RESAMPLER_MIN:
1255 case RESAMPLER_MAX:
1256 break;
1259 else if(Channels == 8) /* 7.1 */
1261 const int chans[] = {
1262 FRONT_LEFT, FRONT_RIGHT,
1263 FRONT_CENTER, LFE,
1264 BACK_LEFT, BACK_RIGHT,
1265 SIDE_LEFT, SIDE_RIGHT
1267 const ALfloat scaler = aluSqrt(1.0f/Channels);
1269 switch(Resampler)
1271 case POINT_RESAMPLER:
1272 DO_MIX(point); break;
1273 case LINEAR_RESAMPLER:
1274 DO_MIX(lerp); break;
1275 case COSINE_RESAMPLER:
1276 DO_MIX(cos_lerp); break;
1277 case RESAMPLER_MIN:
1278 case RESAMPLER_MAX:
1279 break;
1281 #undef DO_MIX
1283 else /* Unknown? */
1285 for(i = 0;i < OUTPUTCHANNELS;i++)
1286 DrySend[i] += dryGainStep[i]*BufferSize;
1287 for(i = 0;i < MAX_SENDS;i++)
1288 WetSend[i] += wetGainStep[i]*BufferSize;
1289 while(BufferSize--)
1291 DataPosFrac += increment;
1292 k += DataPosFrac>>FRACTIONBITS;
1293 DataPosFrac &= FRACTIONMASK;
1294 j++;
1297 DataPosInt += k;
1299 skipmix:
1300 /* Handle looping sources */
1301 if(DataPosInt >= DataSize)
1303 if(BuffersPlayed < (ALSource->BuffersInQueue-1))
1305 BufferListItem = BufferListItem->next;
1306 BuffersPlayed++;
1307 DataPosInt -= DataSize;
1309 else if(ALSource->bLooping)
1311 BufferListItem = ALSource->queue;
1312 BuffersPlayed = 0;
1313 if(ALSource->BuffersInQueue == 1)
1314 DataPosInt %= DataSize;
1315 else
1316 DataPosInt -= DataSize;
1318 else
1320 State = AL_STOPPED;
1321 BufferListItem = ALSource->queue;
1322 BuffersPlayed = ALSource->BuffersInQueue;
1323 DataPosInt = 0;
1324 DataPosFrac = 0;
1329 /* Update source info */
1330 ALSource->state = State;
1331 ALSource->BuffersPlayed = BuffersPlayed;
1332 ALSource->position = DataPosInt;
1333 ALSource->position_fraction = DataPosFrac;
1334 ALSource->Buffer = BufferListItem->buffer;
1336 for(i = 0;i < OUTPUTCHANNELS;i++)
1337 ALSource->DryGains[i] = DrySend[i];
1338 for(i = 0;i < MAX_SENDS;i++)
1339 ALSource->WetGains[i] = WetSend[i];
1341 ALSource->FirstStart = AL_FALSE;
1343 if((ALSource=ALSource->next) != NULL)
1344 goto another_source;
1347 ALvoid aluMixData(ALCdevice *device, ALvoid *buffer, ALsizei size)
1349 float (*DryBuffer)[OUTPUTCHANNELS];
1350 ALfloat (*Matrix)[OUTPUTCHANNELS];
1351 const ALuint *ChanMap;
1352 ALuint SamplesToDo;
1353 ALeffectslot *ALEffectSlot;
1354 ALCcontext *ALContext;
1355 ALfloat samp;
1356 int fpuState;
1357 ALuint i, j, c;
1359 #if defined(HAVE_FESETROUND)
1360 fpuState = fegetround();
1361 fesetround(FE_TOWARDZERO);
1362 #elif defined(HAVE__CONTROLFP)
1363 fpuState = _controlfp(0, 0);
1364 _controlfp(_RC_CHOP, _MCW_RC);
1365 #else
1366 (void)fpuState;
1367 #endif
1369 DryBuffer = device->DryBuffer;
1370 while(size > 0)
1372 /* Setup variables */
1373 SamplesToDo = min(size, BUFFERSIZE);
1375 /* Clear mixing buffer */
1376 memset(DryBuffer, 0, SamplesToDo*OUTPUTCHANNELS*sizeof(ALfloat));
1378 SuspendContext(NULL);
1379 for(c = 0;c < device->NumContexts;c++)
1381 ALContext = device->Contexts[c];
1382 SuspendContext(ALContext);
1384 MixSomeSources(ALContext, DryBuffer, SamplesToDo);
1386 /* effect slot processing */
1387 ALEffectSlot = ALContext->EffectSlotList;
1388 while(ALEffectSlot)
1390 if(ALEffectSlot->EffectState)
1391 ALEffect_Process(ALEffectSlot->EffectState, ALEffectSlot, SamplesToDo, ALEffectSlot->WetBuffer, DryBuffer);
1393 for(i = 0;i < SamplesToDo;i++)
1394 ALEffectSlot->WetBuffer[i] = 0.0f;
1395 ALEffectSlot = ALEffectSlot->next;
1397 ProcessContext(ALContext);
1399 ProcessContext(NULL);
1401 //Post processing loop
1402 ChanMap = device->DevChannels;
1403 Matrix = device->ChannelMatrix;
1404 switch(device->Format)
1406 #define CHECK_WRITE_FORMAT(bits, type, func) \
1407 case AL_FORMAT_MONO##bits: \
1408 for(i = 0;i < SamplesToDo;i++) \
1410 samp = 0.0f; \
1411 for(c = 0;c < OUTPUTCHANNELS;c++) \
1412 samp += DryBuffer[i][c] * Matrix[c][FRONT_CENTER]; \
1413 ((type*)buffer)[ChanMap[FRONT_CENTER]] = (func)(samp); \
1414 buffer = ((type*)buffer) + 1; \
1416 break; \
1417 case AL_FORMAT_STEREO##bits: \
1418 if(device->Bs2b) \
1420 for(i = 0;i < SamplesToDo;i++) \
1422 float samples[2] = { 0.0f, 0.0f }; \
1423 for(c = 0;c < OUTPUTCHANNELS;c++) \
1425 samples[0] += DryBuffer[i][c]*Matrix[c][FRONT_LEFT]; \
1426 samples[1] += DryBuffer[i][c]*Matrix[c][FRONT_RIGHT]; \
1428 bs2b_cross_feed(device->Bs2b, samples); \
1429 ((type*)buffer)[ChanMap[FRONT_LEFT]] = (func)(samples[0]);\
1430 ((type*)buffer)[ChanMap[FRONT_RIGHT]]= (func)(samples[1]);\
1431 buffer = ((type*)buffer) + 2; \
1434 else \
1436 for(i = 0;i < SamplesToDo;i++) \
1438 static const Channel chans[] = { \
1439 FRONT_LEFT, FRONT_RIGHT \
1440 }; \
1441 for(j = 0;j < 2;j++) \
1443 samp = 0.0f; \
1444 for(c = 0;c < OUTPUTCHANNELS;c++) \
1445 samp += DryBuffer[i][c] * Matrix[c][chans[j]]; \
1446 ((type*)buffer)[ChanMap[chans[j]]] = (func)(samp); \
1448 buffer = ((type*)buffer) + 2; \
1451 break; \
1452 case AL_FORMAT_QUAD##bits: \
1453 for(i = 0;i < SamplesToDo;i++) \
1455 static const Channel chans[] = { \
1456 FRONT_LEFT, FRONT_RIGHT, \
1457 BACK_LEFT, BACK_RIGHT, \
1458 }; \
1459 for(j = 0;j < 4;j++) \
1461 samp = 0.0f; \
1462 for(c = 0;c < OUTPUTCHANNELS;c++) \
1463 samp += DryBuffer[i][c] * Matrix[c][chans[j]]; \
1464 ((type*)buffer)[ChanMap[chans[j]]] = (func)(samp); \
1466 buffer = ((type*)buffer) + 4; \
1468 break; \
1469 case AL_FORMAT_51CHN##bits: \
1470 for(i = 0;i < SamplesToDo;i++) \
1472 static const Channel chans[] = { \
1473 FRONT_LEFT, FRONT_RIGHT, \
1474 FRONT_CENTER, LFE, \
1475 BACK_LEFT, BACK_RIGHT, \
1476 }; \
1477 for(j = 0;j < 6;j++) \
1479 samp = 0.0f; \
1480 for(c = 0;c < OUTPUTCHANNELS;c++) \
1481 samp += DryBuffer[i][c] * Matrix[c][chans[j]]; \
1482 ((type*)buffer)[ChanMap[chans[j]]] = (func)(samp); \
1484 buffer = ((type*)buffer) + 6; \
1486 break; \
1487 case AL_FORMAT_61CHN##bits: \
1488 for(i = 0;i < SamplesToDo;i++) \
1490 static const Channel chans[] = { \
1491 FRONT_LEFT, FRONT_RIGHT, \
1492 FRONT_CENTER, LFE, BACK_CENTER, \
1493 SIDE_LEFT, SIDE_RIGHT, \
1494 }; \
1495 for(j = 0;j < 7;j++) \
1497 samp = 0.0f; \
1498 for(c = 0;c < OUTPUTCHANNELS;c++) \
1499 samp += DryBuffer[i][c] * Matrix[c][chans[j]]; \
1500 ((type*)buffer)[ChanMap[chans[j]]] = (func)(samp); \
1502 buffer = ((type*)buffer) + 7; \
1504 break; \
1505 case AL_FORMAT_71CHN##bits: \
1506 for(i = 0;i < SamplesToDo;i++) \
1508 static const Channel chans[] = { \
1509 FRONT_LEFT, FRONT_RIGHT, \
1510 FRONT_CENTER, LFE, \
1511 BACK_LEFT, BACK_RIGHT, \
1512 SIDE_LEFT, SIDE_RIGHT \
1513 }; \
1514 for(j = 0;j < 8;j++) \
1516 samp = 0.0f; \
1517 for(c = 0;c < OUTPUTCHANNELS;c++) \
1518 samp += DryBuffer[i][c] * Matrix[c][chans[j]]; \
1519 ((type*)buffer)[ChanMap[chans[j]]] = (func)(samp); \
1521 buffer = ((type*)buffer) + 8; \
1523 break;
1525 #define AL_FORMAT_MONO32 AL_FORMAT_MONO_FLOAT32
1526 #define AL_FORMAT_STEREO32 AL_FORMAT_STEREO_FLOAT32
1527 CHECK_WRITE_FORMAT(8, ALubyte, aluF2UB)
1528 CHECK_WRITE_FORMAT(16, ALshort, aluF2S)
1529 CHECK_WRITE_FORMAT(32, ALfloat, aluF2F)
1530 #undef AL_FORMAT_STEREO32
1531 #undef AL_FORMAT_MONO32
1532 #undef CHECK_WRITE_FORMAT
1534 default:
1535 break;
1538 size -= SamplesToDo;
1541 #if defined(HAVE_FESETROUND)
1542 fesetround(fpuState);
1543 #elif defined(HAVE__CONTROLFP)
1544 _controlfp(fpuState, 0xfffff);
1545 #endif
1548 ALvoid aluHandleDisconnect(ALCdevice *device)
1550 ALuint i;
1552 SuspendContext(NULL);
1553 for(i = 0;i < device->NumContexts;i++)
1555 ALsource *source;
1557 SuspendContext(device->Contexts[i]);
1559 source = device->Contexts[i]->SourceList;
1560 while(source)
1562 if(source->state == AL_PLAYING)
1564 source->state = AL_STOPPED;
1565 source->BuffersPlayed = source->BuffersInQueue;
1566 source->position = 0;
1567 source->position_fraction = 0;
1569 source = source->next;
1571 ProcessContext(device->Contexts[i]);
1574 device->Connected = ALC_FALSE;
1575 ProcessContext(NULL);