Avoid calling alDelete* from alGen*
[openal-soft.git] / Alc / ALu.c
blobe35d87343a82854a592240fabbe9fb9bd043615e
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 ALint 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] == 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(ALCcontext *Context)
231 ALint pos, offset, s;
232 ALfloat Alpha, Theta;
233 ALfloat SpeakerAngle[OUTPUTCHANNELS];
234 ALint Speaker2Chan[OUTPUTCHANNELS];
236 for(s = 0;s < OUTPUTCHANNELS;s++)
238 int s2;
239 for(s2 = 0;s2 < OUTPUTCHANNELS;s2++)
240 Context->ChannelMatrix[s][s2] = ((s==s2) ? 1.0f : 0.0f);
243 switch(Context->Device->Format)
245 case AL_FORMAT_MONO8:
246 case AL_FORMAT_MONO16:
247 case AL_FORMAT_MONO_FLOAT32:
248 Context->ChannelMatrix[FRONT_LEFT][FRONT_CENTER] = aluSqrt(0.5);
249 Context->ChannelMatrix[FRONT_RIGHT][FRONT_CENTER] = aluSqrt(0.5);
250 Context->ChannelMatrix[SIDE_LEFT][FRONT_CENTER] = aluSqrt(0.5);
251 Context->ChannelMatrix[SIDE_RIGHT][FRONT_CENTER] = aluSqrt(0.5);
252 Context->ChannelMatrix[BACK_LEFT][FRONT_CENTER] = aluSqrt(0.5);
253 Context->ChannelMatrix[BACK_RIGHT][FRONT_CENTER] = aluSqrt(0.5);
254 Context->ChannelMatrix[BACK_CENTER][FRONT_CENTER] = 1.0f;
255 Context->NumChan = 1;
256 Speaker2Chan[0] = FRONT_CENTER;
257 SpeakerAngle[0] = 0.0f * M_PI/180.0f;
258 break;
260 case AL_FORMAT_STEREO8:
261 case AL_FORMAT_STEREO16:
262 case AL_FORMAT_STEREO_FLOAT32:
263 Context->ChannelMatrix[FRONT_CENTER][FRONT_LEFT] = aluSqrt(0.5);
264 Context->ChannelMatrix[FRONT_CENTER][FRONT_RIGHT] = aluSqrt(0.5);
265 Context->ChannelMatrix[SIDE_LEFT][FRONT_LEFT] = 1.0f;
266 Context->ChannelMatrix[SIDE_RIGHT][FRONT_RIGHT] = 1.0f;
267 Context->ChannelMatrix[BACK_LEFT][FRONT_LEFT] = 1.0f;
268 Context->ChannelMatrix[BACK_RIGHT][FRONT_RIGHT] = 1.0f;
269 Context->ChannelMatrix[BACK_CENTER][FRONT_LEFT] = aluSqrt(0.5);
270 Context->ChannelMatrix[BACK_CENTER][FRONT_RIGHT] = aluSqrt(0.5);
271 Context->NumChan = 2;
272 Speaker2Chan[0] = FRONT_LEFT;
273 Speaker2Chan[1] = FRONT_RIGHT;
274 SpeakerAngle[0] = -90.0f * M_PI/180.0f;
275 SpeakerAngle[1] = 90.0f * M_PI/180.0f;
276 SetSpeakerArrangement("layout_STEREO", SpeakerAngle, Speaker2Chan, Context->NumChan);
277 break;
279 case AL_FORMAT_QUAD8:
280 case AL_FORMAT_QUAD16:
281 case AL_FORMAT_QUAD32:
282 Context->ChannelMatrix[FRONT_CENTER][FRONT_LEFT] = aluSqrt(0.5);
283 Context->ChannelMatrix[FRONT_CENTER][FRONT_RIGHT] = aluSqrt(0.5);
284 Context->ChannelMatrix[SIDE_LEFT][FRONT_LEFT] = aluSqrt(0.5);
285 Context->ChannelMatrix[SIDE_LEFT][BACK_LEFT] = aluSqrt(0.5);
286 Context->ChannelMatrix[SIDE_RIGHT][FRONT_RIGHT] = aluSqrt(0.5);
287 Context->ChannelMatrix[SIDE_RIGHT][BACK_RIGHT] = aluSqrt(0.5);
288 Context->ChannelMatrix[BACK_CENTER][BACK_LEFT] = aluSqrt(0.5);
289 Context->ChannelMatrix[BACK_CENTER][BACK_RIGHT] = aluSqrt(0.5);
290 Context->NumChan = 4;
291 Speaker2Chan[0] = BACK_LEFT;
292 Speaker2Chan[1] = FRONT_LEFT;
293 Speaker2Chan[2] = FRONT_RIGHT;
294 Speaker2Chan[3] = BACK_RIGHT;
295 SpeakerAngle[0] = -135.0f * M_PI/180.0f;
296 SpeakerAngle[1] = -45.0f * M_PI/180.0f;
297 SpeakerAngle[2] = 45.0f * M_PI/180.0f;
298 SpeakerAngle[3] = 135.0f * M_PI/180.0f;
299 SetSpeakerArrangement("layout_QUAD", SpeakerAngle, Speaker2Chan, Context->NumChan);
300 break;
302 case AL_FORMAT_51CHN8:
303 case AL_FORMAT_51CHN16:
304 case AL_FORMAT_51CHN32:
305 Context->ChannelMatrix[SIDE_LEFT][FRONT_LEFT] = aluSqrt(0.5);
306 Context->ChannelMatrix[SIDE_LEFT][BACK_LEFT] = aluSqrt(0.5);
307 Context->ChannelMatrix[SIDE_RIGHT][FRONT_RIGHT] = aluSqrt(0.5);
308 Context->ChannelMatrix[SIDE_RIGHT][BACK_RIGHT] = aluSqrt(0.5);
309 Context->ChannelMatrix[BACK_CENTER][BACK_LEFT] = aluSqrt(0.5);
310 Context->ChannelMatrix[BACK_CENTER][BACK_RIGHT] = aluSqrt(0.5);
311 Context->NumChan = 5;
312 Speaker2Chan[0] = BACK_LEFT;
313 Speaker2Chan[1] = FRONT_LEFT;
314 Speaker2Chan[2] = FRONT_CENTER;
315 Speaker2Chan[3] = FRONT_RIGHT;
316 Speaker2Chan[4] = BACK_RIGHT;
317 SpeakerAngle[0] = -110.0f * M_PI/180.0f;
318 SpeakerAngle[1] = -30.0f * M_PI/180.0f;
319 SpeakerAngle[2] = 0.0f * M_PI/180.0f;
320 SpeakerAngle[3] = 30.0f * M_PI/180.0f;
321 SpeakerAngle[4] = 110.0f * M_PI/180.0f;
322 SetSpeakerArrangement("layout_51CHN", SpeakerAngle, Speaker2Chan, Context->NumChan);
323 break;
325 case AL_FORMAT_61CHN8:
326 case AL_FORMAT_61CHN16:
327 case AL_FORMAT_61CHN32:
328 Context->ChannelMatrix[BACK_LEFT][BACK_CENTER] = aluSqrt(0.5);
329 Context->ChannelMatrix[BACK_LEFT][SIDE_LEFT] = aluSqrt(0.5);
330 Context->ChannelMatrix[BACK_RIGHT][BACK_CENTER] = aluSqrt(0.5);
331 Context->ChannelMatrix[BACK_RIGHT][SIDE_RIGHT] = aluSqrt(0.5);
332 Context->NumChan = 6;
333 Speaker2Chan[0] = SIDE_LEFT;
334 Speaker2Chan[1] = FRONT_LEFT;
335 Speaker2Chan[2] = FRONT_CENTER;
336 Speaker2Chan[3] = FRONT_RIGHT;
337 Speaker2Chan[4] = SIDE_RIGHT;
338 Speaker2Chan[5] = BACK_CENTER;
339 SpeakerAngle[0] = -90.0f * M_PI/180.0f;
340 SpeakerAngle[1] = -30.0f * M_PI/180.0f;
341 SpeakerAngle[2] = 0.0f * M_PI/180.0f;
342 SpeakerAngle[3] = 30.0f * M_PI/180.0f;
343 SpeakerAngle[4] = 90.0f * M_PI/180.0f;
344 SpeakerAngle[5] = 180.0f * M_PI/180.0f;
345 SetSpeakerArrangement("layout_61CHN", SpeakerAngle, Speaker2Chan, Context->NumChan);
346 break;
348 case AL_FORMAT_71CHN8:
349 case AL_FORMAT_71CHN16:
350 case AL_FORMAT_71CHN32:
351 Context->ChannelMatrix[BACK_CENTER][BACK_LEFT] = aluSqrt(0.5);
352 Context->ChannelMatrix[BACK_CENTER][BACK_RIGHT] = aluSqrt(0.5);
353 Context->NumChan = 7;
354 Speaker2Chan[0] = BACK_LEFT;
355 Speaker2Chan[1] = SIDE_LEFT;
356 Speaker2Chan[2] = FRONT_LEFT;
357 Speaker2Chan[3] = FRONT_CENTER;
358 Speaker2Chan[4] = FRONT_RIGHT;
359 Speaker2Chan[5] = SIDE_RIGHT;
360 Speaker2Chan[6] = BACK_RIGHT;
361 SpeakerAngle[0] = -150.0f * M_PI/180.0f;
362 SpeakerAngle[1] = -90.0f * M_PI/180.0f;
363 SpeakerAngle[2] = -30.0f * M_PI/180.0f;
364 SpeakerAngle[3] = 0.0f * M_PI/180.0f;
365 SpeakerAngle[4] = 30.0f * M_PI/180.0f;
366 SpeakerAngle[5] = 90.0f * M_PI/180.0f;
367 SpeakerAngle[6] = 150.0f * M_PI/180.0f;
368 SetSpeakerArrangement("layout_71CHN", SpeakerAngle, Speaker2Chan, Context->NumChan);
369 break;
371 default:
372 assert(0);
375 for(pos = 0; pos < LUT_NUM; pos++)
377 /* clear all values */
378 offset = OUTPUTCHANNELS * pos;
379 for(s = 0; s < OUTPUTCHANNELS; s++)
380 Context->PanningLUT[offset+s] = 0.0f;
382 if(Context->NumChan == 1)
384 Context->PanningLUT[offset + Speaker2Chan[0]] = 1.0f;
385 continue;
388 /* source angle */
389 Theta = aluLUTpos2Angle(pos);
391 /* set panning values */
392 for(s = 0; s < Context->NumChan - 1; s++)
394 if(Theta >= SpeakerAngle[s] && Theta < SpeakerAngle[s+1])
396 /* source between speaker s and speaker s+1 */
397 Alpha = M_PI_2 * (Theta-SpeakerAngle[s]) /
398 (SpeakerAngle[s+1]-SpeakerAngle[s]);
399 Context->PanningLUT[offset + Speaker2Chan[s]] = cos(Alpha);
400 Context->PanningLUT[offset + Speaker2Chan[s+1]] = sin(Alpha);
401 break;
404 if(s == Context->NumChan - 1)
406 /* source between last and first speaker */
407 if(Theta < SpeakerAngle[0])
408 Theta += 2.0f * M_PI;
409 Alpha = M_PI_2 * (Theta-SpeakerAngle[s]) /
410 (2.0f * M_PI + SpeakerAngle[0]-SpeakerAngle[s]);
411 Context->PanningLUT[offset + Speaker2Chan[s]] = cos(Alpha);
412 Context->PanningLUT[offset + Speaker2Chan[0]] = sin(Alpha);
417 static ALvoid CalcNonAttnSourceParams(const ALCcontext *ALContext, ALsource *ALSource)
419 ALfloat SourceVolume,ListenerGain,MinVolume,MaxVolume;
420 ALfloat DryGain, DryGainHF;
421 ALfloat WetGain[MAX_SENDS];
422 ALfloat WetGainHF[MAX_SENDS];
423 ALint NumSends, Frequency;
424 ALfloat cw;
425 ALint i;
427 //Get context properties
428 NumSends = ALContext->Device->NumAuxSends;
429 Frequency = ALContext->Device->Frequency;
431 //Get listener properties
432 ListenerGain = ALContext->Listener.Gain;
434 //Get source properties
435 SourceVolume = ALSource->flGain;
436 MinVolume = ALSource->flMinGain;
437 MaxVolume = ALSource->flMaxGain;
439 //1. Multi-channel buffers always play "normal"
440 ALSource->Params.Pitch = ALSource->flPitch;
442 DryGain = SourceVolume;
443 DryGain = __min(DryGain,MaxVolume);
444 DryGain = __max(DryGain,MinVolume);
445 DryGainHF = 1.0f;
447 switch(ALSource->DirectFilter.type)
449 case AL_FILTER_LOWPASS:
450 DryGain *= ALSource->DirectFilter.Gain;
451 DryGainHF *= ALSource->DirectFilter.GainHF;
452 break;
455 ALSource->Params.DryGains[FRONT_LEFT] = DryGain * ListenerGain;
456 ALSource->Params.DryGains[FRONT_RIGHT] = DryGain * ListenerGain;
457 ALSource->Params.DryGains[SIDE_LEFT] = DryGain * ListenerGain;
458 ALSource->Params.DryGains[SIDE_RIGHT] = DryGain * ListenerGain;
459 ALSource->Params.DryGains[BACK_LEFT] = DryGain * ListenerGain;
460 ALSource->Params.DryGains[BACK_RIGHT] = DryGain * ListenerGain;
461 ALSource->Params.DryGains[FRONT_CENTER] = DryGain * ListenerGain;
462 ALSource->Params.DryGains[BACK_CENTER] = DryGain * ListenerGain;
463 ALSource->Params.DryGains[LFE] = DryGain * ListenerGain;
465 for(i = 0;i < NumSends;i++)
467 WetGain[i] = SourceVolume;
468 WetGain[i] = __min(WetGain[i],MaxVolume);
469 WetGain[i] = __max(WetGain[i],MinVolume);
470 WetGainHF[i] = 1.0f;
472 switch(ALSource->Send[i].WetFilter.type)
474 case AL_FILTER_LOWPASS:
475 WetGain[i] *= ALSource->Send[i].WetFilter.Gain;
476 WetGainHF[i] *= ALSource->Send[i].WetFilter.GainHF;
477 break;
480 ALSource->Params.WetGains[i] = WetGain[i] * ListenerGain;
482 for(i = NumSends;i < MAX_SENDS;i++)
484 ALSource->Params.WetGains[i] = 0.0f;
485 WetGainHF[i] = 1.0f;
488 /* Update filter coefficients. Calculations based on the I3DL2
489 * spec. */
490 cw = cos(2.0*M_PI * LOWPASSFREQCUTOFF / Frequency);
492 /* We use two chained one-pole filters, so we need to take the
493 * square root of the squared gain, which is the same as the base
494 * gain. */
495 ALSource->Params.iirFilter.coeff = lpCoeffCalc(DryGainHF, cw);
497 for(i = 0;i < NumSends;i++)
499 /* We use a one-pole filter, so we need to take the squared gain */
500 ALfloat a = lpCoeffCalc(WetGainHF[i]*WetGainHF[i], cw);
501 ALSource->Params.Send[i].iirFilter.coeff = a;
505 static ALvoid CalcSourceParams(const ALCcontext *ALContext, ALsource *ALSource)
507 ALfloat InnerAngle,OuterAngle,Angle,Distance,DryMix,OrigDist;
508 ALfloat Direction[3],Position[3],SourceToListener[3];
509 ALfloat Velocity[3],ListenerVel[3];
510 ALfloat MinVolume,MaxVolume,MinDist,MaxDist,Rolloff,OuterGainHF;
511 ALfloat ConeVolume,ConeHF,SourceVolume,ListenerGain;
512 ALfloat DopplerFactor, DopplerVelocity, flSpeedOfSound;
513 ALfloat Matrix[4][4];
514 ALfloat flAttenuation, effectiveDist;
515 ALfloat RoomAttenuation[MAX_SENDS];
516 ALfloat MetersPerUnit;
517 ALfloat RoomRolloff[MAX_SENDS];
518 ALfloat DryGainHF = 1.0f;
519 ALfloat WetGain[MAX_SENDS];
520 ALfloat WetGainHF[MAX_SENDS];
521 ALfloat DirGain, AmbientGain;
522 ALfloat length;
523 const ALfloat *SpeakerGain;
524 ALuint Frequency;
525 ALint NumSends;
526 ALint pos, s, i;
527 ALfloat cw;
529 for(i = 0;i < MAX_SENDS;i++)
530 WetGainHF[i] = 1.0f;
532 //Get context properties
533 DopplerFactor = ALContext->DopplerFactor * ALSource->DopplerFactor;
534 DopplerVelocity = ALContext->DopplerVelocity;
535 flSpeedOfSound = ALContext->flSpeedOfSound;
536 NumSends = ALContext->Device->NumAuxSends;
537 Frequency = ALContext->Device->Frequency;
539 //Get listener properties
540 ListenerGain = ALContext->Listener.Gain;
541 MetersPerUnit = ALContext->Listener.MetersPerUnit;
542 memcpy(ListenerVel, ALContext->Listener.Velocity, sizeof(ALContext->Listener.Velocity));
544 //Get source properties
545 SourceVolume = ALSource->flGain;
546 memcpy(Position, ALSource->vPosition, sizeof(ALSource->vPosition));
547 memcpy(Direction, ALSource->vOrientation, sizeof(ALSource->vOrientation));
548 memcpy(Velocity, ALSource->vVelocity, sizeof(ALSource->vVelocity));
549 MinVolume = ALSource->flMinGain;
550 MaxVolume = ALSource->flMaxGain;
551 MinDist = ALSource->flRefDistance;
552 MaxDist = ALSource->flMaxDistance;
553 Rolloff = ALSource->flRollOffFactor;
554 InnerAngle = ALSource->flInnerAngle;
555 OuterAngle = ALSource->flOuterAngle;
556 OuterGainHF = ALSource->OuterGainHF;
558 //1. Translate Listener to origin (convert to head relative)
559 if(ALSource->bHeadRelative==AL_FALSE)
561 ALfloat U[3],V[3],N[3],P[3];
563 // Build transform matrix
564 memcpy(N, ALContext->Listener.Forward, sizeof(N)); // At-vector
565 aluNormalize(N); // Normalized At-vector
566 memcpy(V, ALContext->Listener.Up, sizeof(V)); // Up-vector
567 aluNormalize(V); // Normalized Up-vector
568 aluCrossproduct(N, V, U); // Right-vector
569 aluNormalize(U); // Normalized Right-vector
570 P[0] = -(ALContext->Listener.Position[0]*U[0] + // Translation
571 ALContext->Listener.Position[1]*U[1] +
572 ALContext->Listener.Position[2]*U[2]);
573 P[1] = -(ALContext->Listener.Position[0]*V[0] +
574 ALContext->Listener.Position[1]*V[1] +
575 ALContext->Listener.Position[2]*V[2]);
576 P[2] = -(ALContext->Listener.Position[0]*-N[0] +
577 ALContext->Listener.Position[1]*-N[1] +
578 ALContext->Listener.Position[2]*-N[2]);
579 Matrix[0][0] = U[0]; Matrix[0][1] = V[0]; Matrix[0][2] = -N[0]; Matrix[0][3] = 0.0f;
580 Matrix[1][0] = U[1]; Matrix[1][1] = V[1]; Matrix[1][2] = -N[1]; Matrix[1][3] = 0.0f;
581 Matrix[2][0] = U[2]; Matrix[2][1] = V[2]; Matrix[2][2] = -N[2]; Matrix[2][3] = 0.0f;
582 Matrix[3][0] = P[0]; Matrix[3][1] = P[1]; Matrix[3][2] = P[2]; Matrix[3][3] = 1.0f;
584 // Transform source position and direction into listener space
585 aluMatrixVector(Position, 1.0f, Matrix);
586 aluMatrixVector(Direction, 0.0f, Matrix);
587 // Transform source and listener velocity into listener space
588 aluMatrixVector(Velocity, 0.0f, Matrix);
589 aluMatrixVector(ListenerVel, 0.0f, Matrix);
591 else
592 ListenerVel[0] = ListenerVel[1] = ListenerVel[2] = 0.0f;
594 SourceToListener[0] = -Position[0];
595 SourceToListener[1] = -Position[1];
596 SourceToListener[2] = -Position[2];
597 aluNormalize(SourceToListener);
598 aluNormalize(Direction);
600 //2. Calculate distance attenuation
601 Distance = aluSqrt(aluDotproduct(Position, Position));
602 OrigDist = Distance;
604 flAttenuation = 1.0f;
605 for(i = 0;i < NumSends;i++)
607 RoomAttenuation[i] = 1.0f;
609 RoomRolloff[i] = ALSource->RoomRolloffFactor;
610 if(ALSource->Send[i].Slot &&
611 (ALSource->Send[i].Slot->effect.type == AL_EFFECT_REVERB ||
612 ALSource->Send[i].Slot->effect.type == AL_EFFECT_EAXREVERB))
613 RoomRolloff[i] += ALSource->Send[i].Slot->effect.Reverb.RoomRolloffFactor;
616 switch(ALContext->SourceDistanceModel ? ALSource->DistanceModel :
617 ALContext->DistanceModel)
619 case AL_INVERSE_DISTANCE_CLAMPED:
620 Distance=__max(Distance,MinDist);
621 Distance=__min(Distance,MaxDist);
622 if(MaxDist < MinDist)
623 break;
624 //fall-through
625 case AL_INVERSE_DISTANCE:
626 if(MinDist > 0.0f)
628 if((MinDist + (Rolloff * (Distance - MinDist))) > 0.0f)
629 flAttenuation = MinDist / (MinDist + (Rolloff * (Distance - MinDist)));
630 for(i = 0;i < NumSends;i++)
632 if((MinDist + (RoomRolloff[i] * (Distance - MinDist))) > 0.0f)
633 RoomAttenuation[i] = MinDist / (MinDist + (RoomRolloff[i] * (Distance - MinDist)));
636 break;
638 case AL_LINEAR_DISTANCE_CLAMPED:
639 Distance=__max(Distance,MinDist);
640 Distance=__min(Distance,MaxDist);
641 if(MaxDist < MinDist)
642 break;
643 //fall-through
644 case AL_LINEAR_DISTANCE:
645 Distance=__min(Distance,MaxDist);
646 if(MaxDist != MinDist)
648 flAttenuation = 1.0f - (Rolloff*(Distance-MinDist)/(MaxDist - MinDist));
649 for(i = 0;i < NumSends;i++)
650 RoomAttenuation[i] = 1.0f - (RoomRolloff[i]*(Distance-MinDist)/(MaxDist - MinDist));
652 break;
654 case AL_EXPONENT_DISTANCE_CLAMPED:
655 Distance=__max(Distance,MinDist);
656 Distance=__min(Distance,MaxDist);
657 if(MaxDist < MinDist)
658 break;
659 //fall-through
660 case AL_EXPONENT_DISTANCE:
661 if(Distance > 0.0f && MinDist > 0.0f)
663 flAttenuation = aluPow(Distance/MinDist, -Rolloff);
664 for(i = 0;i < NumSends;i++)
665 RoomAttenuation[i] = aluPow(Distance/MinDist, -RoomRolloff[i]);
667 break;
669 case AL_NONE:
670 break;
673 // Source Gain + Attenuation
674 DryMix = SourceVolume * flAttenuation;
675 for(i = 0;i < NumSends;i++)
676 WetGain[i] = SourceVolume * RoomAttenuation[i];
678 effectiveDist = 0.0f;
679 if(MinDist > 0.0f)
680 effectiveDist = (MinDist/flAttenuation - MinDist)*MetersPerUnit;
682 // Distance-based air absorption
683 if(ALSource->AirAbsorptionFactor > 0.0f && effectiveDist > 0.0f)
685 ALfloat absorb;
687 // Absorption calculation is done in dB
688 absorb = (ALSource->AirAbsorptionFactor*AIRABSORBGAINDBHF) *
689 effectiveDist;
690 // Convert dB to linear gain before applying
691 absorb = aluPow(10.0f, absorb/20.0f);
693 DryGainHF *= absorb;
696 //3. Apply directional soundcones
697 Angle = aluAcos(aluDotproduct(Direction,SourceToListener)) * 180.0f/M_PI;
698 if(Angle >= InnerAngle && Angle <= OuterAngle)
700 ALfloat scale = (Angle-InnerAngle) / (OuterAngle-InnerAngle);
701 ConeVolume = (1.0f+(ALSource->flOuterGain-1.0f)*scale);
702 ConeHF = (1.0f+(OuterGainHF-1.0f)*scale);
704 else if(Angle > OuterAngle)
706 ConeVolume = (1.0f+(ALSource->flOuterGain-1.0f));
707 ConeHF = (1.0f+(OuterGainHF-1.0f));
709 else
711 ConeVolume = 1.0f;
712 ConeHF = 1.0f;
715 // Apply some high-frequency attenuation for sources behind the listener
716 // NOTE: This should be aluDotproduct({0,0,-1}, ListenerToSource), however
717 // that is equivalent to aluDotproduct({0,0,1}, SourceToListener), which is
718 // the same as SourceToListener[2]
719 Angle = aluAcos(SourceToListener[2]) * 180.0f/M_PI;
720 // Sources within the minimum distance attenuate less
721 if(OrigDist < MinDist)
722 Angle *= OrigDist/MinDist;
723 if(Angle > 90.0f)
725 ALfloat scale = (Angle-90.0f) / (180.1f-90.0f); // .1 to account for fp errors
726 ConeHF *= 1.0f - (ALContext->Device->HeadDampen*scale);
729 DryMix *= ConeVolume;
730 if(ALSource->DryGainHFAuto)
731 DryGainHF *= ConeHF;
733 // Clamp to Min/Max Gain
734 DryMix = __min(DryMix,MaxVolume);
735 DryMix = __max(DryMix,MinVolume);
737 for(i = 0;i < NumSends;i++)
739 ALeffectslot *Slot = ALSource->Send[i].Slot;
741 if(!Slot || Slot->effect.type == AL_EFFECT_NULL)
743 ALSource->Params.WetGains[i] = 0.0f;
744 WetGainHF[i] = 1.0f;
745 continue;
748 if(Slot->AuxSendAuto)
750 if(ALSource->WetGainAuto)
751 WetGain[i] *= ConeVolume;
752 if(ALSource->WetGainHFAuto)
753 WetGainHF[i] *= ConeHF;
755 // Clamp to Min/Max Gain
756 WetGain[i] = __min(WetGain[i],MaxVolume);
757 WetGain[i] = __max(WetGain[i],MinVolume);
759 if(Slot->effect.type == AL_EFFECT_REVERB ||
760 Slot->effect.type == AL_EFFECT_EAXREVERB)
762 /* Apply a decay-time transformation to the wet path, based on
763 * the attenuation of the dry path.
765 * Using the approximate (effective) source to listener
766 * distance, the initial decay of the reverb effect is
767 * calculated and applied to the wet path.
769 WetGain[i] *= aluPow(10.0f, effectiveDist /
770 (SPEEDOFSOUNDMETRESPERSEC *
771 Slot->effect.Reverb.DecayTime) *
772 -60.0 / 20.0);
774 WetGainHF[i] *= aluPow(10.0f,
775 log10(Slot->effect.Reverb.AirAbsorptionGainHF) *
776 ALSource->AirAbsorptionFactor * effectiveDist);
779 else
781 /* If the slot's auxiliary send auto is off, the data sent to the
782 * effect slot is the same as the dry path, sans filter effects */
783 WetGain[i] = DryMix;
784 WetGainHF[i] = DryGainHF;
787 switch(ALSource->Send[i].WetFilter.type)
789 case AL_FILTER_LOWPASS:
790 WetGain[i] *= ALSource->Send[i].WetFilter.Gain;
791 WetGainHF[i] *= ALSource->Send[i].WetFilter.GainHF;
792 break;
794 ALSource->Params.WetGains[i] = WetGain[i] * ListenerGain;
796 for(i = NumSends;i < MAX_SENDS;i++)
798 ALSource->Params.WetGains[i] = 0.0f;
799 WetGainHF[i] = 1.0f;
802 // Apply filter gains and filters
803 switch(ALSource->DirectFilter.type)
805 case AL_FILTER_LOWPASS:
806 DryMix *= ALSource->DirectFilter.Gain;
807 DryGainHF *= ALSource->DirectFilter.GainHF;
808 break;
810 DryMix *= ListenerGain;
812 // Calculate Velocity
813 if(DopplerFactor != 0.0f)
815 ALfloat flVSS, flVLS;
816 ALfloat flMaxVelocity = (DopplerVelocity * flSpeedOfSound) /
817 DopplerFactor;
819 flVSS = aluDotproduct(Velocity, SourceToListener);
820 if(flVSS >= flMaxVelocity)
821 flVSS = (flMaxVelocity - 1.0f);
822 else if(flVSS <= -flMaxVelocity)
823 flVSS = -flMaxVelocity + 1.0f;
825 flVLS = aluDotproduct(ListenerVel, SourceToListener);
826 if(flVLS >= flMaxVelocity)
827 flVLS = (flMaxVelocity - 1.0f);
828 else if(flVLS <= -flMaxVelocity)
829 flVLS = -flMaxVelocity + 1.0f;
831 ALSource->Params.Pitch = ALSource->flPitch *
832 ((flSpeedOfSound * DopplerVelocity) - (DopplerFactor * flVLS)) /
833 ((flSpeedOfSound * DopplerVelocity) - (DopplerFactor * flVSS));
835 else
836 ALSource->Params.Pitch = ALSource->flPitch;
838 // Use energy-preserving panning algorithm for multi-speaker playback
839 length = __max(OrigDist, MinDist);
840 if(length > 0.0f)
842 ALfloat invlen = 1.0f/length;
843 Position[0] *= invlen;
844 Position[1] *= invlen;
845 Position[2] *= invlen;
848 pos = aluCart2LUTpos(-Position[2], Position[0]);
849 SpeakerGain = &ALContext->PanningLUT[OUTPUTCHANNELS * pos];
851 DirGain = aluSqrt(Position[0]*Position[0] + Position[2]*Position[2]);
852 // elevation adjustment for directional gain. this sucks, but
853 // has low complexity
854 AmbientGain = 1.0/aluSqrt(ALContext->NumChan) * (1.0-DirGain);
855 for(s = 0; s < OUTPUTCHANNELS; s++)
857 ALfloat gain = SpeakerGain[s]*DirGain + AmbientGain;
858 ALSource->Params.DryGains[s] = DryMix * gain;
861 /* Update filter coefficients. */
862 cw = cos(2.0*M_PI * LOWPASSFREQCUTOFF / Frequency);
864 /* Spatialized sources use four chained one-pole filters, so we need to
865 * take the fourth root of the squared gain, which is the same as the
866 * square root of the base gain. */
867 ALSource->Params.iirFilter.coeff = lpCoeffCalc(aluSqrt(DryGainHF), cw);
869 for(i = 0;i < NumSends;i++)
871 /* The wet path uses two chained one-pole filters, so take the
872 * base gain (square root of the squared gain) */
873 ALSource->Params.Send[i].iirFilter.coeff = lpCoeffCalc(WetGainHF[i], cw);
877 static __inline ALfloat point(ALfloat val1, ALfloat val2, ALint frac)
879 return val1;
880 (void)val2;
881 (void)frac;
883 static __inline ALfloat lerp(ALfloat val1, ALfloat val2, ALint frac)
885 return val1 + ((val2-val1)*(frac * (1.0f/(1<<FRACTIONBITS))));
887 static __inline ALfloat cos_lerp(ALfloat val1, ALfloat val2, ALint frac)
889 ALfloat mult = (1.0f-cos(frac * (1.0f/(1<<FRACTIONBITS)) * M_PI)) * 0.5f;
890 return val1 + ((val2-val1)*mult);
893 static void MixSomeSources(ALCcontext *ALContext, float (*DryBuffer)[OUTPUTCHANNELS], ALuint SamplesToDo)
895 static float DummyBuffer[BUFFERSIZE];
896 ALfloat *WetBuffer[MAX_SENDS];
897 ALfloat (*Matrix)[OUTPUTCHANNELS] = ALContext->ChannelMatrix;
898 ALfloat DrySend[OUTPUTCHANNELS];
899 ALfloat dryGainStep[OUTPUTCHANNELS];
900 ALfloat wetGainStep[MAX_SENDS];
901 ALuint i, j, k, out;
902 ALsource *ALSource;
903 ALfloat value, outsamp;
904 ALbufferlistitem *BufferListItem;
905 ALint64 DataSize64,DataPos64;
906 FILTER *DryFilter, *WetFilter[MAX_SENDS];
907 ALfloat WetSend[MAX_SENDS];
908 ALuint rampLength;
909 ALuint DeviceFreq;
910 ALint increment;
911 ALuint DataPosInt, DataPosFrac;
912 ALuint Channels, Bytes;
913 ALuint Frequency;
914 resampler_t Resampler;
915 ALuint BuffersPlayed;
916 ALfloat Pitch;
917 ALenum State;
919 if(!(ALSource=ALContext->SourceList))
920 return;
922 DeviceFreq = ALContext->Device->Frequency;
924 rampLength = DeviceFreq * MIN_RAMP_LENGTH / 1000;
925 rampLength = max(rampLength, SamplesToDo);
927 another_source:
928 if(ALSource->state != AL_PLAYING)
930 if((ALSource=ALSource->next) != NULL)
931 goto another_source;
932 return;
934 j = 0;
936 /* Find buffer format */
937 Frequency = 0;
938 Channels = 0;
939 Bytes = 0;
940 BufferListItem = ALSource->queue;
941 while(BufferListItem != NULL)
943 ALbuffer *ALBuffer;
944 if((ALBuffer=BufferListItem->buffer) != NULL)
946 Channels = aluChannelsFromFormat(ALBuffer->format);
947 Bytes = aluBytesFromFormat(ALBuffer->format);
948 Frequency = ALBuffer->frequency;
949 break;
951 BufferListItem = BufferListItem->next;
954 if(ALSource->NeedsUpdate)
956 //Only apply 3D calculations for mono buffers
957 if(Channels == 1)
958 CalcSourceParams(ALContext, ALSource);
959 else
960 CalcNonAttnSourceParams(ALContext, ALSource);
961 ALSource->NeedsUpdate = AL_FALSE;
964 /* Get source info */
965 Resampler = ALSource->Resampler;
966 State = ALSource->state;
967 BuffersPlayed = ALSource->BuffersPlayed;
968 DataPosInt = ALSource->position;
969 DataPosFrac = ALSource->position_fraction;
971 /* Compute 18.14 fixed point step */
972 Pitch = (ALSource->Params.Pitch*Frequency) / DeviceFreq;
973 if(Pitch > (float)MAX_PITCH) Pitch = (float)MAX_PITCH;
974 increment = (ALint)(Pitch*(ALfloat)(1L<<FRACTIONBITS));
975 if(increment <= 0) increment = (1<<FRACTIONBITS);
977 if(ALSource->FirstStart)
979 for(i = 0;i < OUTPUTCHANNELS;i++)
980 DrySend[i] = ALSource->Params.DryGains[i];
981 for(i = 0;i < MAX_SENDS;i++)
982 WetSend[i] = ALSource->Params.WetGains[i];
984 else
986 for(i = 0;i < OUTPUTCHANNELS;i++)
987 DrySend[i] = ALSource->DryGains[i];
988 for(i = 0;i < MAX_SENDS;i++)
989 WetSend[i] = ALSource->WetGains[i];
992 DryFilter = &ALSource->Params.iirFilter;
993 for(i = 0;i < MAX_SENDS;i++)
995 WetFilter[i] = &ALSource->Params.Send[i].iirFilter;
996 WetBuffer[i] = (ALSource->Send[i].Slot ?
997 ALSource->Send[i].Slot->WetBuffer :
998 DummyBuffer);
1001 if(DuplicateStereo && Channels == 2)
1003 Matrix[FRONT_LEFT][SIDE_LEFT] = 1.0f;
1004 Matrix[FRONT_RIGHT][SIDE_RIGHT] = 1.0f;
1005 Matrix[FRONT_LEFT][BACK_LEFT] = 1.0f;
1006 Matrix[FRONT_RIGHT][BACK_RIGHT] = 1.0f;
1008 else if(DuplicateStereo)
1010 Matrix[FRONT_LEFT][SIDE_LEFT] = 0.0f;
1011 Matrix[FRONT_RIGHT][SIDE_RIGHT] = 0.0f;
1012 Matrix[FRONT_LEFT][BACK_LEFT] = 0.0f;
1013 Matrix[FRONT_RIGHT][BACK_RIGHT] = 0.0f;
1016 /* Get current buffer queue item */
1017 BufferListItem = ALSource->queue;
1018 for(i = 0;i < BuffersPlayed && BufferListItem;i++)
1019 BufferListItem = BufferListItem->next;
1021 while(State == AL_PLAYING && j < SamplesToDo)
1023 ALuint DataSize = 0;
1024 ALbuffer *ALBuffer;
1025 ALfloat *Data;
1026 ALuint BufferSize;
1028 /* Get buffer info */
1029 if((ALBuffer=BufferListItem->buffer) != NULL)
1031 Data = ALBuffer->data;
1032 DataSize = ALBuffer->size;
1033 DataSize /= Channels * Bytes;
1035 if(DataPosInt >= DataSize)
1036 goto skipmix;
1038 if(BufferListItem->next)
1040 ALbuffer *NextBuf = BufferListItem->next->buffer;
1041 if(NextBuf && NextBuf->size)
1043 ALint ulExtraSamples = BUFFER_PADDING*Channels*Bytes;
1044 ulExtraSamples = min(NextBuf->size, ulExtraSamples);
1045 memcpy(&Data[DataSize*Channels], NextBuf->data, ulExtraSamples);
1048 else if(ALSource->bLooping)
1050 ALbuffer *NextBuf = ALSource->queue->buffer;
1051 if(NextBuf && NextBuf->size)
1053 ALint ulExtraSamples = BUFFER_PADDING*Channels*Bytes;
1054 ulExtraSamples = min(NextBuf->size, ulExtraSamples);
1055 memcpy(&Data[DataSize*Channels], NextBuf->data, ulExtraSamples);
1058 else
1059 memset(&Data[DataSize*Channels], 0, (BUFFER_PADDING*Channels*Bytes));
1061 /* Compute the gain steps for each output channel */
1062 for(i = 0;i < OUTPUTCHANNELS;i++)
1063 dryGainStep[i] = (ALSource->Params.DryGains[i]-DrySend[i]) /
1064 rampLength;
1065 for(i = 0;i < MAX_SENDS;i++)
1066 wetGainStep[i] = (ALSource->Params.WetGains[i]-WetSend[i]) /
1067 rampLength;
1069 /* Figure out how many samples we can mix. */
1070 DataSize64 = DataSize;
1071 DataSize64 <<= FRACTIONBITS;
1072 DataPos64 = DataPosInt;
1073 DataPos64 <<= FRACTIONBITS;
1074 DataPos64 += DataPosFrac;
1075 BufferSize = (ALuint)((DataSize64-DataPos64+(increment-1)) / increment);
1077 BufferSize = min(BufferSize, (SamplesToDo-j));
1079 /* Actual sample mixing loop */
1080 k = 0;
1081 Data += DataPosInt*Channels;
1083 if(Channels == 1) /* Mono */
1085 #define DO_MIX(resampler) do { \
1086 while(BufferSize--) \
1088 for(i = 0;i < OUTPUTCHANNELS;i++) \
1089 DrySend[i] += dryGainStep[i]; \
1090 for(i = 0;i < MAX_SENDS;i++) \
1091 WetSend[i] += wetGainStep[i]; \
1093 /* First order interpolator */ \
1094 value = (resampler)(Data[k], Data[k+1], DataPosFrac); \
1096 /* Direct path final mix buffer and panning */ \
1097 outsamp = lpFilter4P(DryFilter, 0, value); \
1098 DryBuffer[j][FRONT_LEFT] += outsamp*DrySend[FRONT_LEFT]; \
1099 DryBuffer[j][FRONT_RIGHT] += outsamp*DrySend[FRONT_RIGHT]; \
1100 DryBuffer[j][SIDE_LEFT] += outsamp*DrySend[SIDE_LEFT]; \
1101 DryBuffer[j][SIDE_RIGHT] += outsamp*DrySend[SIDE_RIGHT]; \
1102 DryBuffer[j][BACK_LEFT] += outsamp*DrySend[BACK_LEFT]; \
1103 DryBuffer[j][BACK_RIGHT] += outsamp*DrySend[BACK_RIGHT]; \
1104 DryBuffer[j][FRONT_CENTER] += outsamp*DrySend[FRONT_CENTER]; \
1105 DryBuffer[j][BACK_CENTER] += outsamp*DrySend[BACK_CENTER]; \
1107 /* Room path final mix buffer and panning */ \
1108 for(i = 0;i < MAX_SENDS;i++) \
1110 outsamp = lpFilter2P(WetFilter[i], 0, value); \
1111 WetBuffer[i][j] += outsamp*WetSend[i]; \
1114 DataPosFrac += increment; \
1115 k += DataPosFrac>>FRACTIONBITS; \
1116 DataPosFrac &= FRACTIONMASK; \
1117 j++; \
1119 } while(0)
1121 switch(Resampler)
1123 case POINT_RESAMPLER:
1124 DO_MIX(point); break;
1125 case LINEAR_RESAMPLER:
1126 DO_MIX(lerp); break;
1127 case COSINE_RESAMPLER:
1128 DO_MIX(cos_lerp); break;
1129 case RESAMPLER_MIN:
1130 case RESAMPLER_MAX:
1131 break;
1133 #undef DO_MIX
1135 else if(Channels == 2) /* Stereo */
1137 const int chans[] = {
1138 FRONT_LEFT, FRONT_RIGHT
1140 const ALfloat scaler = aluSqrt(1.0f/Channels);
1142 #define DO_MIX(resampler) do { \
1143 while(BufferSize--) \
1145 for(i = 0;i < OUTPUTCHANNELS;i++) \
1146 DrySend[i] += dryGainStep[i]; \
1147 for(i = 0;i < MAX_SENDS;i++) \
1148 WetSend[i] += wetGainStep[i]; \
1150 for(i = 0;i < Channels;i++) \
1152 value = (resampler)(Data[k*Channels + i], Data[(k+1)*Channels + i], \
1153 DataPosFrac); \
1154 outsamp = lpFilter2P(DryFilter, chans[i]*2, value)*DrySend[chans[i]]; \
1155 for(out = 0;out < OUTPUTCHANNELS;out++) \
1156 DryBuffer[j][out] += outsamp*Matrix[chans[i]][out]; \
1157 for(out = 0;out < MAX_SENDS;out++) \
1159 outsamp = lpFilter1P(WetFilter[out], chans[i], value); \
1160 WetBuffer[out][j] += outsamp*WetSend[out]*scaler; \
1164 DataPosFrac += increment; \
1165 k += DataPosFrac>>FRACTIONBITS; \
1166 DataPosFrac &= FRACTIONMASK; \
1167 j++; \
1169 } while(0)
1171 switch(Resampler)
1173 case POINT_RESAMPLER:
1174 DO_MIX(point); break;
1175 case LINEAR_RESAMPLER:
1176 DO_MIX(lerp); break;
1177 case COSINE_RESAMPLER:
1178 DO_MIX(cos_lerp); break;
1179 case RESAMPLER_MIN:
1180 case RESAMPLER_MAX:
1181 break;
1184 else if(Channels == 4) /* Quad */
1186 const int chans[] = {
1187 FRONT_LEFT, FRONT_RIGHT,
1188 BACK_LEFT, BACK_RIGHT
1190 const ALfloat scaler = aluSqrt(1.0f/Channels);
1192 switch(Resampler)
1194 case POINT_RESAMPLER:
1195 DO_MIX(point); break;
1196 case LINEAR_RESAMPLER:
1197 DO_MIX(lerp); break;
1198 case COSINE_RESAMPLER:
1199 DO_MIX(cos_lerp); break;
1200 case RESAMPLER_MIN:
1201 case RESAMPLER_MAX:
1202 break;
1205 else if(Channels == 6) /* 5.1 */
1207 const int chans[] = {
1208 FRONT_LEFT, FRONT_RIGHT,
1209 FRONT_CENTER, LFE,
1210 BACK_LEFT, BACK_RIGHT
1212 const ALfloat scaler = aluSqrt(1.0f/Channels);
1214 switch(Resampler)
1216 case POINT_RESAMPLER:
1217 DO_MIX(point); break;
1218 case LINEAR_RESAMPLER:
1219 DO_MIX(lerp); break;
1220 case COSINE_RESAMPLER:
1221 DO_MIX(cos_lerp); break;
1222 case RESAMPLER_MIN:
1223 case RESAMPLER_MAX:
1224 break;
1227 else if(Channels == 7) /* 6.1 */
1229 const int chans[] = {
1230 FRONT_LEFT, FRONT_RIGHT,
1231 FRONT_CENTER, LFE,
1232 BACK_CENTER,
1233 SIDE_LEFT, SIDE_RIGHT
1235 const ALfloat scaler = aluSqrt(1.0f/Channels);
1237 switch(Resampler)
1239 case POINT_RESAMPLER:
1240 DO_MIX(point); break;
1241 case LINEAR_RESAMPLER:
1242 DO_MIX(lerp); break;
1243 case COSINE_RESAMPLER:
1244 DO_MIX(cos_lerp); break;
1245 case RESAMPLER_MIN:
1246 case RESAMPLER_MAX:
1247 break;
1250 else if(Channels == 8) /* 7.1 */
1252 const int chans[] = {
1253 FRONT_LEFT, FRONT_RIGHT,
1254 FRONT_CENTER, LFE,
1255 BACK_LEFT, BACK_RIGHT,
1256 SIDE_LEFT, SIDE_RIGHT
1258 const ALfloat scaler = aluSqrt(1.0f/Channels);
1260 switch(Resampler)
1262 case POINT_RESAMPLER:
1263 DO_MIX(point); break;
1264 case LINEAR_RESAMPLER:
1265 DO_MIX(lerp); break;
1266 case COSINE_RESAMPLER:
1267 DO_MIX(cos_lerp); break;
1268 case RESAMPLER_MIN:
1269 case RESAMPLER_MAX:
1270 break;
1272 #undef DO_MIX
1274 else /* Unknown? */
1276 for(i = 0;i < OUTPUTCHANNELS;i++)
1277 DrySend[i] += dryGainStep[i]*BufferSize;
1278 for(i = 0;i < MAX_SENDS;i++)
1279 WetSend[i] += wetGainStep[i]*BufferSize;
1280 while(BufferSize--)
1282 DataPosFrac += increment;
1283 k += DataPosFrac>>FRACTIONBITS;
1284 DataPosFrac &= FRACTIONMASK;
1285 j++;
1288 DataPosInt += k;
1290 skipmix:
1291 /* Handle looping sources */
1292 if(DataPosInt >= DataSize)
1294 if(BuffersPlayed < (ALSource->BuffersInQueue-1))
1296 BufferListItem = BufferListItem->next;
1297 BuffersPlayed++;
1298 DataPosInt -= DataSize;
1300 else if(ALSource->bLooping)
1302 BufferListItem = ALSource->queue;
1303 BuffersPlayed = 0;
1304 if(ALSource->BuffersInQueue == 1)
1305 DataPosInt %= DataSize;
1306 else
1307 DataPosInt -= DataSize;
1309 else
1311 State = AL_STOPPED;
1312 BufferListItem = ALSource->queue;
1313 BuffersPlayed = ALSource->BuffersInQueue;
1314 DataPosInt = 0;
1315 DataPosFrac = 0;
1320 /* Update source info */
1321 ALSource->state = State;
1322 ALSource->BuffersPlayed = BuffersPlayed;
1323 ALSource->position = DataPosInt;
1324 ALSource->position_fraction = DataPosFrac;
1325 ALSource->Buffer = BufferListItem->buffer;
1327 for(i = 0;i < OUTPUTCHANNELS;i++)
1328 ALSource->DryGains[i] = DrySend[i];
1329 for(i = 0;i < MAX_SENDS;i++)
1330 ALSource->WetGains[i] = WetSend[i];
1332 ALSource->FirstStart = AL_FALSE;
1334 if((ALSource=ALSource->next) != NULL)
1335 goto another_source;
1338 ALvoid aluMixData(ALCdevice *device, ALvoid *buffer, ALsizei size)
1340 float (*DryBuffer)[OUTPUTCHANNELS];
1341 const Channel *ChanMap;
1342 ALuint SamplesToDo;
1343 ALeffectslot *ALEffectSlot;
1344 ALCcontext *ALContext;
1345 int fpuState;
1346 ALuint i, c;
1348 #if defined(HAVE_FESETROUND)
1349 fpuState = fegetround();
1350 fesetround(FE_TOWARDZERO);
1351 #elif defined(HAVE__CONTROLFP)
1352 fpuState = _controlfp(0, 0);
1353 _controlfp(_RC_CHOP, _MCW_RC);
1354 #else
1355 (void)fpuState;
1356 #endif
1358 DryBuffer = device->DryBuffer;
1359 while(size > 0)
1361 /* Setup variables */
1362 SamplesToDo = min(size, BUFFERSIZE);
1364 /* Clear mixing buffer */
1365 memset(DryBuffer, 0, SamplesToDo*OUTPUTCHANNELS*sizeof(ALfloat));
1367 SuspendContext(NULL);
1368 for(c = 0;c < device->NumContexts;c++)
1370 ALContext = device->Contexts[c];
1371 SuspendContext(ALContext);
1373 MixSomeSources(ALContext, DryBuffer, SamplesToDo);
1375 /* effect slot processing */
1376 ALEffectSlot = ALContext->EffectSlotList;
1377 while(ALEffectSlot)
1379 if(ALEffectSlot->EffectState)
1380 ALEffect_Process(ALEffectSlot->EffectState, ALEffectSlot, SamplesToDo, ALEffectSlot->WetBuffer, DryBuffer);
1382 for(i = 0;i < SamplesToDo;i++)
1383 ALEffectSlot->WetBuffer[i] = 0.0f;
1384 ALEffectSlot = ALEffectSlot->next;
1386 ProcessContext(ALContext);
1388 ProcessContext(NULL);
1390 //Post processing loop
1391 ChanMap = device->DevChannels;
1392 switch(device->Format)
1394 #define CHECK_WRITE_FORMAT(bits, type, func) \
1395 case AL_FORMAT_MONO##bits: \
1396 for(i = 0;i < SamplesToDo;i++) \
1398 ((type*)buffer)[0] = (func)(DryBuffer[i][ChanMap[0]]); \
1399 buffer = ((type*)buffer) + 1; \
1401 break; \
1402 case AL_FORMAT_STEREO##bits: \
1403 if(device->Bs2b) \
1405 for(i = 0;i < SamplesToDo;i++) \
1407 float samples[2]; \
1408 samples[0] = DryBuffer[i][ChanMap[0]]; \
1409 samples[1] = DryBuffer[i][ChanMap[1]]; \
1410 bs2b_cross_feed(device->Bs2b, samples); \
1411 ((type*)buffer)[0] = (func)(samples[0]); \
1412 ((type*)buffer)[1] = (func)(samples[1]); \
1413 buffer = ((type*)buffer) + 2; \
1416 else \
1418 for(i = 0;i < SamplesToDo;i++) \
1420 ((type*)buffer)[0] = (func)(DryBuffer[i][ChanMap[0]]); \
1421 ((type*)buffer)[1] = (func)(DryBuffer[i][ChanMap[1]]); \
1422 buffer = ((type*)buffer) + 2; \
1425 break; \
1426 case AL_FORMAT_QUAD##bits: \
1427 for(i = 0;i < SamplesToDo;i++) \
1429 ((type*)buffer)[0] = (func)(DryBuffer[i][ChanMap[0]]); \
1430 ((type*)buffer)[1] = (func)(DryBuffer[i][ChanMap[1]]); \
1431 ((type*)buffer)[2] = (func)(DryBuffer[i][ChanMap[2]]); \
1432 ((type*)buffer)[3] = (func)(DryBuffer[i][ChanMap[3]]); \
1433 buffer = ((type*)buffer) + 4; \
1435 break; \
1436 case AL_FORMAT_51CHN##bits: \
1437 for(i = 0;i < SamplesToDo;i++) \
1439 ((type*)buffer)[0] = (func)(DryBuffer[i][ChanMap[0]]); \
1440 ((type*)buffer)[1] = (func)(DryBuffer[i][ChanMap[1]]); \
1441 ((type*)buffer)[2] = (func)(DryBuffer[i][ChanMap[2]]); \
1442 ((type*)buffer)[3] = (func)(DryBuffer[i][ChanMap[3]]); \
1443 ((type*)buffer)[4] = (func)(DryBuffer[i][ChanMap[4]]); \
1444 ((type*)buffer)[5] = (func)(DryBuffer[i][ChanMap[5]]); \
1445 buffer = ((type*)buffer) + 6; \
1447 break; \
1448 case AL_FORMAT_61CHN##bits: \
1449 for(i = 0;i < SamplesToDo;i++) \
1451 ((type*)buffer)[0] = (func)(DryBuffer[i][ChanMap[0]]); \
1452 ((type*)buffer)[1] = (func)(DryBuffer[i][ChanMap[1]]); \
1453 ((type*)buffer)[2] = (func)(DryBuffer[i][ChanMap[2]]); \
1454 ((type*)buffer)[3] = (func)(DryBuffer[i][ChanMap[3]]); \
1455 ((type*)buffer)[4] = (func)(DryBuffer[i][ChanMap[4]]); \
1456 ((type*)buffer)[5] = (func)(DryBuffer[i][ChanMap[5]]); \
1457 ((type*)buffer)[6] = (func)(DryBuffer[i][ChanMap[6]]); \
1458 buffer = ((type*)buffer) + 7; \
1460 break; \
1461 case AL_FORMAT_71CHN##bits: \
1462 for(i = 0;i < SamplesToDo;i++) \
1464 ((type*)buffer)[0] = (func)(DryBuffer[i][ChanMap[0]]); \
1465 ((type*)buffer)[1] = (func)(DryBuffer[i][ChanMap[1]]); \
1466 ((type*)buffer)[2] = (func)(DryBuffer[i][ChanMap[2]]); \
1467 ((type*)buffer)[3] = (func)(DryBuffer[i][ChanMap[3]]); \
1468 ((type*)buffer)[4] = (func)(DryBuffer[i][ChanMap[4]]); \
1469 ((type*)buffer)[5] = (func)(DryBuffer[i][ChanMap[5]]); \
1470 ((type*)buffer)[6] = (func)(DryBuffer[i][ChanMap[6]]); \
1471 ((type*)buffer)[7] = (func)(DryBuffer[i][ChanMap[7]]); \
1472 buffer = ((type*)buffer) + 8; \
1474 break;
1476 #define AL_FORMAT_MONO32 AL_FORMAT_MONO_FLOAT32
1477 #define AL_FORMAT_STEREO32 AL_FORMAT_STEREO_FLOAT32
1478 CHECK_WRITE_FORMAT(8, ALubyte, aluF2UB)
1479 CHECK_WRITE_FORMAT(16, ALshort, aluF2S)
1480 CHECK_WRITE_FORMAT(32, ALfloat, aluF2F)
1481 #undef AL_FORMAT_STEREO32
1482 #undef AL_FORMAT_MONO32
1483 #undef CHECK_WRITE_FORMAT
1485 default:
1486 break;
1489 size -= SamplesToDo;
1492 #if defined(HAVE_FESETROUND)
1493 fesetround(fpuState);
1494 #elif defined(HAVE__CONTROLFP)
1495 _controlfp(fpuState, 0xfffff);
1496 #endif
1499 ALvoid aluHandleDisconnect(ALCdevice *device)
1501 ALuint i;
1503 SuspendContext(NULL);
1504 for(i = 0;i < device->NumContexts;i++)
1506 ALsource *source;
1508 SuspendContext(device->Contexts[i]);
1510 source = device->Contexts[i]->SourceList;
1511 while(source)
1513 if(source->state == AL_PLAYING)
1515 source->state = AL_STOPPED;
1516 source->BuffersPlayed = source->BuffersInQueue;
1517 source->position = 0;
1518 source->position_fraction = 0;
1520 source = source->next;
1522 ProcessContext(device->Contexts[i]);
1525 device->Connected = ALC_FALSE;
1526 ProcessContext(NULL);