Use a linear scaling when sending multi-channel sources to auxiliary slots
[openal-soft/android/lowlatency.git] / Alc / ALu.c
blob76c49d7607afdc17e386ddfa2684f60e63adb5e9
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 Channel val;
125 int i;
127 strncpy(layout_str, GetConfigValue(NULL, name, ""), sizeof(layout_str));
128 layout_str[255] = 0;
130 next = confkey = layout_str;
131 while(next && *next)
133 confkey = next;
134 next = strchr(confkey, ',');
135 if(next)
137 *next = 0;
138 do {
139 next++;
140 } while(isspace(*next) || *next == ',');
143 sep = strchr(confkey, '=');
144 if(!sep || confkey == sep)
145 continue;
147 end = sep - 1;
148 while(isspace(*end) && end != confkey)
149 end--;
150 *(++end) = 0;
152 if(strcmp(confkey, "fl") == 0 || strcmp(confkey, "front-left") == 0)
153 val = FRONT_LEFT;
154 else if(strcmp(confkey, "fr") == 0 || strcmp(confkey, "front-right") == 0)
155 val = FRONT_RIGHT;
156 else if(strcmp(confkey, "fc") == 0 || strcmp(confkey, "front-center") == 0)
157 val = FRONT_CENTER;
158 else if(strcmp(confkey, "bl") == 0 || strcmp(confkey, "back-left") == 0)
159 val = BACK_LEFT;
160 else if(strcmp(confkey, "br") == 0 || strcmp(confkey, "back-right") == 0)
161 val = BACK_RIGHT;
162 else if(strcmp(confkey, "bc") == 0 || strcmp(confkey, "back-center") == 0)
163 val = BACK_CENTER;
164 else if(strcmp(confkey, "sl") == 0 || strcmp(confkey, "side-left") == 0)
165 val = SIDE_LEFT;
166 else if(strcmp(confkey, "sr") == 0 || strcmp(confkey, "side-right") == 0)
167 val = SIDE_RIGHT;
168 else
170 AL_PRINT("Unknown speaker for %s: \"%s\"\n", name, confkey);
171 continue;
174 *(sep++) = 0;
175 while(isspace(*sep))
176 sep++;
178 for(i = 0;i < chans;i++)
180 if(Speaker2Chan[i] == val)
182 long angle = strtol(sep, NULL, 10);
183 if(angle >= -180 && angle <= 180)
184 SpeakerAngle[i] = angle * M_PI/180.0f;
185 else
186 AL_PRINT("Invalid angle for speaker \"%s\": %ld\n", confkey, angle);
187 break;
192 for(i = 0;i < chans;i++)
194 int min = i;
195 int i2;
197 for(i2 = i+1;i2 < chans;i2++)
199 if(SpeakerAngle[i2] < SpeakerAngle[min])
200 min = i2;
203 if(min != i)
205 ALfloat tmpf;
206 ALint tmpi;
208 tmpf = SpeakerAngle[i];
209 SpeakerAngle[i] = SpeakerAngle[min];
210 SpeakerAngle[min] = tmpf;
212 tmpi = Speaker2Chan[i];
213 Speaker2Chan[i] = Speaker2Chan[min];
214 Speaker2Chan[min] = tmpi;
219 static __inline ALfloat aluLUTpos2Angle(ALint pos)
221 if(pos < QUADRANT_NUM)
222 return aluAtan((ALfloat)pos / (ALfloat)(QUADRANT_NUM - pos));
223 if(pos < 2 * QUADRANT_NUM)
224 return M_PI_2 + aluAtan((ALfloat)(pos - QUADRANT_NUM) / (ALfloat)(2 * QUADRANT_NUM - pos));
225 if(pos < 3 * QUADRANT_NUM)
226 return aluAtan((ALfloat)(pos - 2 * QUADRANT_NUM) / (ALfloat)(3 * QUADRANT_NUM - pos)) - M_PI;
227 return aluAtan((ALfloat)(pos - 3 * QUADRANT_NUM) / (ALfloat)(4 * QUADRANT_NUM - pos)) - M_PI_2;
230 ALvoid aluInitPanning(ALCdevice *Device)
232 ALfloat SpeakerAngle[OUTPUTCHANNELS];
233 Channel Speaker2Chan[OUTPUTCHANNELS];
234 ALfloat Alpha, Theta;
235 ALint pos, offset;
236 ALfloat maxout;
237 ALuint s, s2;
239 for(s = 0;s < OUTPUTCHANNELS;s++)
241 for(s2 = 0;s2 < OUTPUTCHANNELS;s2++)
242 Device->ChannelMatrix[s][s2] = ((s==s2) ? 1.0f : 0.0f);
245 switch(Device->Format)
247 case AL_FORMAT_MONO8:
248 case AL_FORMAT_MONO16:
249 case AL_FORMAT_MONO_FLOAT32:
250 Device->ChannelMatrix[FRONT_LEFT][FRONT_CENTER] = aluSqrt(0.5);
251 Device->ChannelMatrix[FRONT_RIGHT][FRONT_CENTER] = aluSqrt(0.5);
252 Device->ChannelMatrix[SIDE_LEFT][FRONT_CENTER] = aluSqrt(0.5);
253 Device->ChannelMatrix[SIDE_RIGHT][FRONT_CENTER] = aluSqrt(0.5);
254 Device->ChannelMatrix[BACK_LEFT][FRONT_CENTER] = aluSqrt(0.5);
255 Device->ChannelMatrix[BACK_RIGHT][FRONT_CENTER] = aluSqrt(0.5);
256 Device->ChannelMatrix[BACK_CENTER][FRONT_CENTER] = 1.0f;
257 Device->NumChan = 1;
258 Speaker2Chan[0] = FRONT_CENTER;
259 SpeakerAngle[0] = 0.0f * M_PI/180.0f;
260 break;
262 case AL_FORMAT_STEREO8:
263 case AL_FORMAT_STEREO16:
264 case AL_FORMAT_STEREO_FLOAT32:
265 Device->ChannelMatrix[FRONT_CENTER][FRONT_LEFT] = aluSqrt(0.5);
266 Device->ChannelMatrix[FRONT_CENTER][FRONT_RIGHT] = aluSqrt(0.5);
267 Device->ChannelMatrix[SIDE_LEFT][FRONT_LEFT] = 1.0f;
268 Device->ChannelMatrix[SIDE_RIGHT][FRONT_RIGHT] = 1.0f;
269 Device->ChannelMatrix[BACK_LEFT][FRONT_LEFT] = 1.0f;
270 Device->ChannelMatrix[BACK_RIGHT][FRONT_RIGHT] = 1.0f;
271 Device->ChannelMatrix[BACK_CENTER][FRONT_LEFT] = aluSqrt(0.5);
272 Device->ChannelMatrix[BACK_CENTER][FRONT_RIGHT] = aluSqrt(0.5);
273 Device->NumChan = 2;
274 Speaker2Chan[0] = FRONT_LEFT;
275 Speaker2Chan[1] = FRONT_RIGHT;
276 SpeakerAngle[0] = -90.0f * M_PI/180.0f;
277 SpeakerAngle[1] = 90.0f * M_PI/180.0f;
278 SetSpeakerArrangement("layout", SpeakerAngle, Speaker2Chan, Device->NumChan);
279 break;
281 case AL_FORMAT_QUAD8:
282 case AL_FORMAT_QUAD16:
283 case AL_FORMAT_QUAD32:
284 Device->ChannelMatrix[FRONT_CENTER][FRONT_LEFT] = aluSqrt(0.5);
285 Device->ChannelMatrix[FRONT_CENTER][FRONT_RIGHT] = aluSqrt(0.5);
286 Device->ChannelMatrix[SIDE_LEFT][FRONT_LEFT] = aluSqrt(0.5);
287 Device->ChannelMatrix[SIDE_LEFT][BACK_LEFT] = aluSqrt(0.5);
288 Device->ChannelMatrix[SIDE_RIGHT][FRONT_RIGHT] = aluSqrt(0.5);
289 Device->ChannelMatrix[SIDE_RIGHT][BACK_RIGHT] = aluSqrt(0.5);
290 Device->ChannelMatrix[BACK_CENTER][BACK_LEFT] = aluSqrt(0.5);
291 Device->ChannelMatrix[BACK_CENTER][BACK_RIGHT] = aluSqrt(0.5);
292 Device->NumChan = 4;
293 Speaker2Chan[0] = BACK_LEFT;
294 Speaker2Chan[1] = FRONT_LEFT;
295 Speaker2Chan[2] = FRONT_RIGHT;
296 Speaker2Chan[3] = BACK_RIGHT;
297 SpeakerAngle[0] = -135.0f * M_PI/180.0f;
298 SpeakerAngle[1] = -45.0f * M_PI/180.0f;
299 SpeakerAngle[2] = 45.0f * M_PI/180.0f;
300 SpeakerAngle[3] = 135.0f * M_PI/180.0f;
301 SetSpeakerArrangement("layout", SpeakerAngle, Speaker2Chan, Device->NumChan);
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 Device->NumChan = 5;
314 Speaker2Chan[0] = BACK_LEFT;
315 Speaker2Chan[1] = FRONT_LEFT;
316 Speaker2Chan[2] = FRONT_CENTER;
317 Speaker2Chan[3] = FRONT_RIGHT;
318 Speaker2Chan[4] = BACK_RIGHT;
319 SpeakerAngle[0] = -110.0f * M_PI/180.0f;
320 SpeakerAngle[1] = -30.0f * M_PI/180.0f;
321 SpeakerAngle[2] = 0.0f * M_PI/180.0f;
322 SpeakerAngle[3] = 30.0f * M_PI/180.0f;
323 SpeakerAngle[4] = 110.0f * M_PI/180.0f;
324 SetSpeakerArrangement("layout", SpeakerAngle, Speaker2Chan, Device->NumChan);
325 break;
327 case AL_FORMAT_61CHN8:
328 case AL_FORMAT_61CHN16:
329 case AL_FORMAT_61CHN32:
330 Device->ChannelMatrix[BACK_LEFT][BACK_CENTER] = aluSqrt(0.5);
331 Device->ChannelMatrix[BACK_LEFT][SIDE_LEFT] = aluSqrt(0.5);
332 Device->ChannelMatrix[BACK_RIGHT][BACK_CENTER] = aluSqrt(0.5);
333 Device->ChannelMatrix[BACK_RIGHT][SIDE_RIGHT] = aluSqrt(0.5);
334 Device->NumChan = 6;
335 Speaker2Chan[0] = SIDE_LEFT;
336 Speaker2Chan[1] = FRONT_LEFT;
337 Speaker2Chan[2] = FRONT_CENTER;
338 Speaker2Chan[3] = FRONT_RIGHT;
339 Speaker2Chan[4] = SIDE_RIGHT;
340 Speaker2Chan[5] = BACK_CENTER;
341 SpeakerAngle[0] = -90.0f * M_PI/180.0f;
342 SpeakerAngle[1] = -30.0f * M_PI/180.0f;
343 SpeakerAngle[2] = 0.0f * M_PI/180.0f;
344 SpeakerAngle[3] = 30.0f * M_PI/180.0f;
345 SpeakerAngle[4] = 90.0f * M_PI/180.0f;
346 SpeakerAngle[5] = 180.0f * M_PI/180.0f;
347 SetSpeakerArrangement("layout", SpeakerAngle, Speaker2Chan, Device->NumChan);
348 break;
350 case AL_FORMAT_71CHN8:
351 case AL_FORMAT_71CHN16:
352 case AL_FORMAT_71CHN32:
353 Device->ChannelMatrix[BACK_CENTER][BACK_LEFT] = aluSqrt(0.5);
354 Device->ChannelMatrix[BACK_CENTER][BACK_RIGHT] = aluSqrt(0.5);
355 Device->NumChan = 7;
356 Speaker2Chan[0] = BACK_LEFT;
357 Speaker2Chan[1] = SIDE_LEFT;
358 Speaker2Chan[2] = FRONT_LEFT;
359 Speaker2Chan[3] = FRONT_CENTER;
360 Speaker2Chan[4] = FRONT_RIGHT;
361 Speaker2Chan[5] = SIDE_RIGHT;
362 Speaker2Chan[6] = BACK_RIGHT;
363 SpeakerAngle[0] = -150.0f * M_PI/180.0f;
364 SpeakerAngle[1] = -90.0f * M_PI/180.0f;
365 SpeakerAngle[2] = -30.0f * M_PI/180.0f;
366 SpeakerAngle[3] = 0.0f * M_PI/180.0f;
367 SpeakerAngle[4] = 30.0f * M_PI/180.0f;
368 SpeakerAngle[5] = 90.0f * M_PI/180.0f;
369 SpeakerAngle[6] = 150.0f * M_PI/180.0f;
370 SetSpeakerArrangement("layout", SpeakerAngle, Speaker2Chan, Device->NumChan);
371 break;
373 default:
374 assert(0);
377 maxout = 1.0f;
378 for(s = 0;s < OUTPUTCHANNELS;s++)
380 ALfloat out = 0.0f;
381 for(s2 = 0;s2 < OUTPUTCHANNELS;s2++)
382 out += Device->ChannelMatrix[s2][s];
383 maxout = __max(maxout, out);
386 maxout = 1.0f/maxout;
387 for(s = 0;s < OUTPUTCHANNELS;s++)
389 for(s2 = 0;s2 < OUTPUTCHANNELS;s2++)
390 Device->ChannelMatrix[s2][s] *= maxout;
394 for(pos = 0; pos < LUT_NUM; pos++)
396 /* clear all values */
397 offset = OUTPUTCHANNELS * pos;
398 for(s = 0; s < OUTPUTCHANNELS; s++)
399 Device->PanningLUT[offset+s] = 0.0f;
401 if(Device->NumChan == 1)
403 Device->PanningLUT[offset + Speaker2Chan[0]] = 1.0f;
404 continue;
407 /* source angle */
408 Theta = aluLUTpos2Angle(pos);
410 /* set panning values */
411 for(s = 0; s < Device->NumChan - 1; s++)
413 if(Theta >= SpeakerAngle[s] && Theta < SpeakerAngle[s+1])
415 /* source between speaker s and speaker s+1 */
416 Alpha = M_PI_2 * (Theta-SpeakerAngle[s]) /
417 (SpeakerAngle[s+1]-SpeakerAngle[s]);
418 Device->PanningLUT[offset + Speaker2Chan[s]] = cos(Alpha);
419 Device->PanningLUT[offset + Speaker2Chan[s+1]] = sin(Alpha);
420 break;
423 if(s == Device->NumChan - 1)
425 /* source between last and first speaker */
426 if(Theta < SpeakerAngle[0])
427 Theta += 2.0f * M_PI;
428 Alpha = M_PI_2 * (Theta-SpeakerAngle[s]) /
429 (2.0f * M_PI + SpeakerAngle[0]-SpeakerAngle[s]);
430 Device->PanningLUT[offset + Speaker2Chan[s]] = cos(Alpha);
431 Device->PanningLUT[offset + Speaker2Chan[0]] = sin(Alpha);
436 static ALvoid CalcNonAttnSourceParams(const ALCcontext *ALContext, ALsource *ALSource)
438 ALfloat SourceVolume,ListenerGain,MinVolume,MaxVolume;
439 ALfloat DryGain, DryGainHF;
440 ALfloat WetGain[MAX_SENDS];
441 ALfloat WetGainHF[MAX_SENDS];
442 ALint NumSends, Frequency;
443 ALfloat cw;
444 ALint i;
446 //Get context properties
447 NumSends = ALContext->Device->NumAuxSends;
448 Frequency = ALContext->Device->Frequency;
450 //Get listener properties
451 ListenerGain = ALContext->Listener.Gain;
453 //Get source properties
454 SourceVolume = ALSource->flGain;
455 MinVolume = ALSource->flMinGain;
456 MaxVolume = ALSource->flMaxGain;
458 //1. Multi-channel buffers always play "normal"
459 ALSource->Params.Pitch = ALSource->flPitch;
461 DryGain = SourceVolume;
462 DryGain = __min(DryGain,MaxVolume);
463 DryGain = __max(DryGain,MinVolume);
464 DryGainHF = 1.0f;
466 switch(ALSource->DirectFilter.type)
468 case AL_FILTER_LOWPASS:
469 DryGain *= ALSource->DirectFilter.Gain;
470 DryGainHF *= ALSource->DirectFilter.GainHF;
471 break;
474 ALSource->Params.DryGains[FRONT_LEFT] = DryGain * ListenerGain;
475 ALSource->Params.DryGains[FRONT_RIGHT] = DryGain * ListenerGain;
476 ALSource->Params.DryGains[SIDE_LEFT] = DryGain * ListenerGain;
477 ALSource->Params.DryGains[SIDE_RIGHT] = DryGain * ListenerGain;
478 ALSource->Params.DryGains[BACK_LEFT] = DryGain * ListenerGain;
479 ALSource->Params.DryGains[BACK_RIGHT] = DryGain * ListenerGain;
480 ALSource->Params.DryGains[FRONT_CENTER] = DryGain * ListenerGain;
481 ALSource->Params.DryGains[BACK_CENTER] = DryGain * ListenerGain;
482 ALSource->Params.DryGains[LFE] = DryGain * ListenerGain;
484 for(i = 0;i < NumSends;i++)
486 WetGain[i] = SourceVolume;
487 WetGain[i] = __min(WetGain[i],MaxVolume);
488 WetGain[i] = __max(WetGain[i],MinVolume);
489 WetGainHF[i] = 1.0f;
491 switch(ALSource->Send[i].WetFilter.type)
493 case AL_FILTER_LOWPASS:
494 WetGain[i] *= ALSource->Send[i].WetFilter.Gain;
495 WetGainHF[i] *= ALSource->Send[i].WetFilter.GainHF;
496 break;
499 ALSource->Params.WetGains[i] = WetGain[i] * ListenerGain;
501 for(i = NumSends;i < MAX_SENDS;i++)
503 ALSource->Params.WetGains[i] = 0.0f;
504 WetGainHF[i] = 1.0f;
507 /* Update filter coefficients. Calculations based on the I3DL2
508 * spec. */
509 cw = cos(2.0*M_PI * LOWPASSFREQCUTOFF / Frequency);
511 /* We use two chained one-pole filters, so we need to take the
512 * square root of the squared gain, which is the same as the base
513 * gain. */
514 ALSource->Params.iirFilter.coeff = lpCoeffCalc(DryGainHF, cw);
516 for(i = 0;i < NumSends;i++)
518 /* We use a one-pole filter, so we need to take the squared gain */
519 ALfloat a = lpCoeffCalc(WetGainHF[i]*WetGainHF[i], cw);
520 ALSource->Params.Send[i].iirFilter.coeff = a;
524 static ALvoid CalcSourceParams(const ALCcontext *ALContext, ALsource *ALSource)
526 ALfloat InnerAngle,OuterAngle,Angle,Distance,DryMix,OrigDist;
527 ALfloat Direction[3],Position[3],SourceToListener[3];
528 ALfloat Velocity[3],ListenerVel[3];
529 ALfloat MinVolume,MaxVolume,MinDist,MaxDist,Rolloff,OuterGainHF;
530 ALfloat ConeVolume,ConeHF,SourceVolume,ListenerGain;
531 ALfloat DopplerFactor, DopplerVelocity, flSpeedOfSound;
532 ALfloat Matrix[4][4];
533 ALfloat flAttenuation, effectiveDist;
534 ALfloat RoomAttenuation[MAX_SENDS];
535 ALfloat MetersPerUnit;
536 ALfloat RoomRolloff[MAX_SENDS];
537 ALfloat DryGainHF = 1.0f;
538 ALfloat WetGain[MAX_SENDS];
539 ALfloat WetGainHF[MAX_SENDS];
540 ALfloat DirGain, AmbientGain;
541 ALfloat length;
542 const ALfloat *SpeakerGain;
543 ALuint Frequency;
544 ALint NumSends;
545 ALint pos, s, i;
546 ALfloat cw;
548 for(i = 0;i < MAX_SENDS;i++)
549 WetGainHF[i] = 1.0f;
551 //Get context properties
552 DopplerFactor = ALContext->DopplerFactor * ALSource->DopplerFactor;
553 DopplerVelocity = ALContext->DopplerVelocity;
554 flSpeedOfSound = ALContext->flSpeedOfSound;
555 NumSends = ALContext->Device->NumAuxSends;
556 Frequency = ALContext->Device->Frequency;
558 //Get listener properties
559 ListenerGain = ALContext->Listener.Gain;
560 MetersPerUnit = ALContext->Listener.MetersPerUnit;
561 memcpy(ListenerVel, ALContext->Listener.Velocity, sizeof(ALContext->Listener.Velocity));
563 //Get source properties
564 SourceVolume = ALSource->flGain;
565 memcpy(Position, ALSource->vPosition, sizeof(ALSource->vPosition));
566 memcpy(Direction, ALSource->vOrientation, sizeof(ALSource->vOrientation));
567 memcpy(Velocity, ALSource->vVelocity, sizeof(ALSource->vVelocity));
568 MinVolume = ALSource->flMinGain;
569 MaxVolume = ALSource->flMaxGain;
570 MinDist = ALSource->flRefDistance;
571 MaxDist = ALSource->flMaxDistance;
572 Rolloff = ALSource->flRollOffFactor;
573 InnerAngle = ALSource->flInnerAngle;
574 OuterAngle = ALSource->flOuterAngle;
575 OuterGainHF = ALSource->OuterGainHF;
577 //1. Translate Listener to origin (convert to head relative)
578 if(ALSource->bHeadRelative==AL_FALSE)
580 ALfloat U[3],V[3],N[3],P[3];
582 // Build transform matrix
583 memcpy(N, ALContext->Listener.Forward, sizeof(N)); // At-vector
584 aluNormalize(N); // Normalized At-vector
585 memcpy(V, ALContext->Listener.Up, sizeof(V)); // Up-vector
586 aluNormalize(V); // Normalized Up-vector
587 aluCrossproduct(N, V, U); // Right-vector
588 aluNormalize(U); // Normalized Right-vector
589 P[0] = -(ALContext->Listener.Position[0]*U[0] + // Translation
590 ALContext->Listener.Position[1]*U[1] +
591 ALContext->Listener.Position[2]*U[2]);
592 P[1] = -(ALContext->Listener.Position[0]*V[0] +
593 ALContext->Listener.Position[1]*V[1] +
594 ALContext->Listener.Position[2]*V[2]);
595 P[2] = -(ALContext->Listener.Position[0]*-N[0] +
596 ALContext->Listener.Position[1]*-N[1] +
597 ALContext->Listener.Position[2]*-N[2]);
598 Matrix[0][0] = U[0]; Matrix[0][1] = V[0]; Matrix[0][2] = -N[0]; Matrix[0][3] = 0.0f;
599 Matrix[1][0] = U[1]; Matrix[1][1] = V[1]; Matrix[1][2] = -N[1]; Matrix[1][3] = 0.0f;
600 Matrix[2][0] = U[2]; Matrix[2][1] = V[2]; Matrix[2][2] = -N[2]; Matrix[2][3] = 0.0f;
601 Matrix[3][0] = P[0]; Matrix[3][1] = P[1]; Matrix[3][2] = P[2]; Matrix[3][3] = 1.0f;
603 // Transform source position and direction into listener space
604 aluMatrixVector(Position, 1.0f, Matrix);
605 aluMatrixVector(Direction, 0.0f, Matrix);
606 // Transform source and listener velocity into listener space
607 aluMatrixVector(Velocity, 0.0f, Matrix);
608 aluMatrixVector(ListenerVel, 0.0f, Matrix);
610 else
611 ListenerVel[0] = ListenerVel[1] = ListenerVel[2] = 0.0f;
613 SourceToListener[0] = -Position[0];
614 SourceToListener[1] = -Position[1];
615 SourceToListener[2] = -Position[2];
616 aluNormalize(SourceToListener);
617 aluNormalize(Direction);
619 //2. Calculate distance attenuation
620 Distance = aluSqrt(aluDotproduct(Position, Position));
621 OrigDist = Distance;
623 flAttenuation = 1.0f;
624 for(i = 0;i < NumSends;i++)
626 RoomAttenuation[i] = 1.0f;
628 RoomRolloff[i] = ALSource->RoomRolloffFactor;
629 if(ALSource->Send[i].Slot &&
630 (ALSource->Send[i].Slot->effect.type == AL_EFFECT_REVERB ||
631 ALSource->Send[i].Slot->effect.type == AL_EFFECT_EAXREVERB))
632 RoomRolloff[i] += ALSource->Send[i].Slot->effect.Reverb.RoomRolloffFactor;
635 switch(ALContext->SourceDistanceModel ? ALSource->DistanceModel :
636 ALContext->DistanceModel)
638 case AL_INVERSE_DISTANCE_CLAMPED:
639 Distance=__max(Distance,MinDist);
640 Distance=__min(Distance,MaxDist);
641 if(MaxDist < MinDist)
642 break;
643 //fall-through
644 case AL_INVERSE_DISTANCE:
645 if(MinDist > 0.0f)
647 if((MinDist + (Rolloff * (Distance - MinDist))) > 0.0f)
648 flAttenuation = MinDist / (MinDist + (Rolloff * (Distance - MinDist)));
649 for(i = 0;i < NumSends;i++)
651 if((MinDist + (RoomRolloff[i] * (Distance - MinDist))) > 0.0f)
652 RoomAttenuation[i] = MinDist / (MinDist + (RoomRolloff[i] * (Distance - MinDist)));
655 break;
657 case AL_LINEAR_DISTANCE_CLAMPED:
658 Distance=__max(Distance,MinDist);
659 Distance=__min(Distance,MaxDist);
660 if(MaxDist < MinDist)
661 break;
662 //fall-through
663 case AL_LINEAR_DISTANCE:
664 Distance=__min(Distance,MaxDist);
665 if(MaxDist != MinDist)
667 flAttenuation = 1.0f - (Rolloff*(Distance-MinDist)/(MaxDist - MinDist));
668 for(i = 0;i < NumSends;i++)
669 RoomAttenuation[i] = 1.0f - (RoomRolloff[i]*(Distance-MinDist)/(MaxDist - MinDist));
671 break;
673 case AL_EXPONENT_DISTANCE_CLAMPED:
674 Distance=__max(Distance,MinDist);
675 Distance=__min(Distance,MaxDist);
676 if(MaxDist < MinDist)
677 break;
678 //fall-through
679 case AL_EXPONENT_DISTANCE:
680 if(Distance > 0.0f && MinDist > 0.0f)
682 flAttenuation = aluPow(Distance/MinDist, -Rolloff);
683 for(i = 0;i < NumSends;i++)
684 RoomAttenuation[i] = aluPow(Distance/MinDist, -RoomRolloff[i]);
686 break;
688 case AL_NONE:
689 break;
692 // Source Gain + Attenuation
693 DryMix = SourceVolume * flAttenuation;
694 for(i = 0;i < NumSends;i++)
695 WetGain[i] = SourceVolume * RoomAttenuation[i];
697 effectiveDist = 0.0f;
698 if(MinDist > 0.0f)
699 effectiveDist = (MinDist/flAttenuation - MinDist)*MetersPerUnit;
701 // Distance-based air absorption
702 if(ALSource->AirAbsorptionFactor > 0.0f && effectiveDist > 0.0f)
704 ALfloat absorb;
706 // Absorption calculation is done in dB
707 absorb = (ALSource->AirAbsorptionFactor*AIRABSORBGAINDBHF) *
708 effectiveDist;
709 // Convert dB to linear gain before applying
710 absorb = aluPow(10.0f, absorb/20.0f);
712 DryGainHF *= absorb;
715 //3. Apply directional soundcones
716 Angle = aluAcos(aluDotproduct(Direction,SourceToListener)) * 180.0f/M_PI;
717 if(Angle >= InnerAngle && Angle <= OuterAngle)
719 ALfloat scale = (Angle-InnerAngle) / (OuterAngle-InnerAngle);
720 ConeVolume = (1.0f+(ALSource->flOuterGain-1.0f)*scale);
721 ConeHF = (1.0f+(OuterGainHF-1.0f)*scale);
723 else if(Angle > OuterAngle)
725 ConeVolume = (1.0f+(ALSource->flOuterGain-1.0f));
726 ConeHF = (1.0f+(OuterGainHF-1.0f));
728 else
730 ConeVolume = 1.0f;
731 ConeHF = 1.0f;
734 // Apply some high-frequency attenuation for sources behind the listener
735 // NOTE: This should be aluDotproduct({0,0,-1}, ListenerToSource), however
736 // that is equivalent to aluDotproduct({0,0,1}, SourceToListener), which is
737 // the same as SourceToListener[2]
738 Angle = aluAcos(SourceToListener[2]) * 180.0f/M_PI;
739 // Sources within the minimum distance attenuate less
740 if(OrigDist < MinDist)
741 Angle *= OrigDist/MinDist;
742 if(Angle > 90.0f)
744 ALfloat scale = (Angle-90.0f) / (180.1f-90.0f); // .1 to account for fp errors
745 ConeHF *= 1.0f - (ALContext->Device->HeadDampen*scale);
748 DryMix *= ConeVolume;
749 if(ALSource->DryGainHFAuto)
750 DryGainHF *= ConeHF;
752 // Clamp to Min/Max Gain
753 DryMix = __min(DryMix,MaxVolume);
754 DryMix = __max(DryMix,MinVolume);
756 for(i = 0;i < NumSends;i++)
758 ALeffectslot *Slot = ALSource->Send[i].Slot;
760 if(!Slot || Slot->effect.type == AL_EFFECT_NULL)
762 ALSource->Params.WetGains[i] = 0.0f;
763 WetGainHF[i] = 1.0f;
764 continue;
767 if(Slot->AuxSendAuto)
769 if(ALSource->WetGainAuto)
770 WetGain[i] *= ConeVolume;
771 if(ALSource->WetGainHFAuto)
772 WetGainHF[i] *= ConeHF;
774 // Clamp to Min/Max Gain
775 WetGain[i] = __min(WetGain[i],MaxVolume);
776 WetGain[i] = __max(WetGain[i],MinVolume);
778 if(Slot->effect.type == AL_EFFECT_REVERB ||
779 Slot->effect.type == AL_EFFECT_EAXREVERB)
781 /* Apply a decay-time transformation to the wet path, based on
782 * the attenuation of the dry path.
784 * Using the approximate (effective) source to listener
785 * distance, the initial decay of the reverb effect is
786 * calculated and applied to the wet path.
788 WetGain[i] *= aluPow(10.0f, effectiveDist /
789 (SPEEDOFSOUNDMETRESPERSEC *
790 Slot->effect.Reverb.DecayTime) *
791 -60.0 / 20.0);
793 WetGainHF[i] *= aluPow(10.0f,
794 log10(Slot->effect.Reverb.AirAbsorptionGainHF) *
795 ALSource->AirAbsorptionFactor * effectiveDist);
798 else
800 /* If the slot's auxiliary send auto is off, the data sent to the
801 * effect slot is the same as the dry path, sans filter effects */
802 WetGain[i] = DryMix;
803 WetGainHF[i] = DryGainHF;
806 switch(ALSource->Send[i].WetFilter.type)
808 case AL_FILTER_LOWPASS:
809 WetGain[i] *= ALSource->Send[i].WetFilter.Gain;
810 WetGainHF[i] *= ALSource->Send[i].WetFilter.GainHF;
811 break;
813 ALSource->Params.WetGains[i] = WetGain[i] * ListenerGain;
815 for(i = NumSends;i < MAX_SENDS;i++)
817 ALSource->Params.WetGains[i] = 0.0f;
818 WetGainHF[i] = 1.0f;
821 // Apply filter gains and filters
822 switch(ALSource->DirectFilter.type)
824 case AL_FILTER_LOWPASS:
825 DryMix *= ALSource->DirectFilter.Gain;
826 DryGainHF *= ALSource->DirectFilter.GainHF;
827 break;
829 DryMix *= ListenerGain;
831 // Calculate Velocity
832 if(DopplerFactor != 0.0f)
834 ALfloat flVSS, flVLS;
835 ALfloat flMaxVelocity = (DopplerVelocity * flSpeedOfSound) /
836 DopplerFactor;
838 flVSS = aluDotproduct(Velocity, SourceToListener);
839 if(flVSS >= flMaxVelocity)
840 flVSS = (flMaxVelocity - 1.0f);
841 else if(flVSS <= -flMaxVelocity)
842 flVSS = -flMaxVelocity + 1.0f;
844 flVLS = aluDotproduct(ListenerVel, SourceToListener);
845 if(flVLS >= flMaxVelocity)
846 flVLS = (flMaxVelocity - 1.0f);
847 else if(flVLS <= -flMaxVelocity)
848 flVLS = -flMaxVelocity + 1.0f;
850 ALSource->Params.Pitch = ALSource->flPitch *
851 ((flSpeedOfSound * DopplerVelocity) - (DopplerFactor * flVLS)) /
852 ((flSpeedOfSound * DopplerVelocity) - (DopplerFactor * flVSS));
854 else
855 ALSource->Params.Pitch = ALSource->flPitch;
857 // Use energy-preserving panning algorithm for multi-speaker playback
858 length = __max(OrigDist, MinDist);
859 if(length > 0.0f)
861 ALfloat invlen = 1.0f/length;
862 Position[0] *= invlen;
863 Position[1] *= invlen;
864 Position[2] *= invlen;
867 pos = aluCart2LUTpos(-Position[2], Position[0]);
868 SpeakerGain = &ALContext->Device->PanningLUT[OUTPUTCHANNELS * pos];
870 DirGain = aluSqrt(Position[0]*Position[0] + Position[2]*Position[2]);
871 // elevation adjustment for directional gain. this sucks, but
872 // has low complexity
873 AmbientGain = 1.0/aluSqrt(ALContext->Device->NumChan) * (1.0-DirGain);
874 for(s = 0; s < OUTPUTCHANNELS; s++)
876 ALfloat gain = SpeakerGain[s]*DirGain + AmbientGain;
877 ALSource->Params.DryGains[s] = DryMix * gain;
880 /* Update filter coefficients. */
881 cw = cos(2.0*M_PI * LOWPASSFREQCUTOFF / Frequency);
883 /* Spatialized sources use four chained one-pole filters, so we need to
884 * take the fourth root of the squared gain, which is the same as the
885 * square root of the base gain. */
886 ALSource->Params.iirFilter.coeff = lpCoeffCalc(aluSqrt(DryGainHF), cw);
888 for(i = 0;i < NumSends;i++)
890 /* The wet path uses two chained one-pole filters, so take the
891 * base gain (square root of the squared gain) */
892 ALSource->Params.Send[i].iirFilter.coeff = lpCoeffCalc(WetGainHF[i], cw);
896 static __inline ALfloat point(ALfloat val1, ALfloat val2, ALint frac)
898 return val1;
899 (void)val2;
900 (void)frac;
902 static __inline ALfloat lerp(ALfloat val1, ALfloat val2, ALint frac)
904 return val1 + ((val2-val1)*(frac * (1.0f/(1<<FRACTIONBITS))));
906 static __inline ALfloat cos_lerp(ALfloat val1, ALfloat val2, ALint frac)
908 ALfloat mult = (1.0f-cos(frac * (1.0f/(1<<FRACTIONBITS)) * M_PI)) * 0.5f;
909 return val1 + ((val2-val1)*mult);
912 static void MixSomeSources(ALCcontext *ALContext, float (*DryBuffer)[OUTPUTCHANNELS], ALuint SamplesToDo)
914 static float DummyBuffer[BUFFERSIZE];
915 ALfloat *WetBuffer[MAX_SENDS];
916 ALfloat DrySend[OUTPUTCHANNELS];
917 ALfloat dryGainStep[OUTPUTCHANNELS];
918 ALfloat wetGainStep[MAX_SENDS];
919 ALuint i, j, k, out;
920 ALsource *ALSource;
921 ALfloat value, outsamp;
922 ALbufferlistitem *BufferListItem;
923 ALint64 DataSize64,DataPos64;
924 FILTER *DryFilter, *WetFilter[MAX_SENDS];
925 ALfloat WetSend[MAX_SENDS];
926 ALuint rampLength;
927 ALuint DeviceFreq;
928 ALint increment;
929 ALuint DataPosInt, DataPosFrac;
930 ALuint Channels, Bytes;
931 ALuint Frequency;
932 resampler_t Resampler;
933 ALuint BuffersPlayed;
934 ALfloat Pitch;
935 ALenum State;
937 if(!(ALSource=ALContext->SourceList))
938 return;
940 DeviceFreq = ALContext->Device->Frequency;
942 rampLength = DeviceFreq * MIN_RAMP_LENGTH / 1000;
943 rampLength = max(rampLength, SamplesToDo);
945 another_source:
946 if(ALSource->state != AL_PLAYING)
948 if((ALSource=ALSource->next) != NULL)
949 goto another_source;
950 return;
952 j = 0;
954 /* Find buffer format */
955 Frequency = 0;
956 Channels = 0;
957 Bytes = 0;
958 BufferListItem = ALSource->queue;
959 while(BufferListItem != NULL)
961 ALbuffer *ALBuffer;
962 if((ALBuffer=BufferListItem->buffer) != NULL)
964 Channels = aluChannelsFromFormat(ALBuffer->format);
965 Bytes = aluBytesFromFormat(ALBuffer->format);
966 Frequency = ALBuffer->frequency;
967 break;
969 BufferListItem = BufferListItem->next;
972 if(ALSource->NeedsUpdate)
974 //Only apply 3D calculations for mono buffers
975 if(Channels == 1)
976 CalcSourceParams(ALContext, ALSource);
977 else
978 CalcNonAttnSourceParams(ALContext, ALSource);
979 ALSource->NeedsUpdate = AL_FALSE;
982 /* Get source info */
983 Resampler = ALSource->Resampler;
984 State = ALSource->state;
985 BuffersPlayed = ALSource->BuffersPlayed;
986 DataPosInt = ALSource->position;
987 DataPosFrac = ALSource->position_fraction;
989 /* Compute 18.14 fixed point step */
990 Pitch = (ALSource->Params.Pitch*Frequency) / DeviceFreq;
991 if(Pitch > (float)MAX_PITCH) Pitch = (float)MAX_PITCH;
992 increment = (ALint)(Pitch*(ALfloat)(1L<<FRACTIONBITS));
993 if(increment <= 0) increment = (1<<FRACTIONBITS);
995 if(ALSource->FirstStart)
997 for(i = 0;i < OUTPUTCHANNELS;i++)
998 DrySend[i] = ALSource->Params.DryGains[i];
999 for(i = 0;i < MAX_SENDS;i++)
1000 WetSend[i] = ALSource->Params.WetGains[i];
1002 else
1004 for(i = 0;i < OUTPUTCHANNELS;i++)
1005 DrySend[i] = ALSource->DryGains[i];
1006 for(i = 0;i < MAX_SENDS;i++)
1007 WetSend[i] = ALSource->WetGains[i];
1010 DryFilter = &ALSource->Params.iirFilter;
1011 for(i = 0;i < MAX_SENDS;i++)
1013 WetFilter[i] = &ALSource->Params.Send[i].iirFilter;
1014 WetBuffer[i] = (ALSource->Send[i].Slot ?
1015 ALSource->Send[i].Slot->WetBuffer :
1016 DummyBuffer);
1019 /* Get current buffer queue item */
1020 BufferListItem = ALSource->queue;
1021 for(i = 0;i < BuffersPlayed && BufferListItem;i++)
1022 BufferListItem = BufferListItem->next;
1024 while(State == AL_PLAYING && j < SamplesToDo)
1026 ALuint DataSize = 0;
1027 ALbuffer *ALBuffer;
1028 ALfloat *Data;
1029 ALuint BufferSize;
1031 /* Get buffer info */
1032 if((ALBuffer=BufferListItem->buffer) != NULL)
1034 Data = ALBuffer->data;
1035 DataSize = ALBuffer->size;
1036 DataSize /= Channels * Bytes;
1038 if(DataPosInt >= DataSize)
1039 goto skipmix;
1041 if(BufferListItem->next)
1043 ALbuffer *NextBuf = BufferListItem->next->buffer;
1044 if(NextBuf && NextBuf->size)
1046 ALint ulExtraSamples = BUFFER_PADDING*Channels*Bytes;
1047 ulExtraSamples = min(NextBuf->size, ulExtraSamples);
1048 memcpy(&Data[DataSize*Channels], NextBuf->data, ulExtraSamples);
1051 else if(ALSource->bLooping)
1053 ALbuffer *NextBuf = ALSource->queue->buffer;
1054 if(NextBuf && NextBuf->size)
1056 ALint ulExtraSamples = BUFFER_PADDING*Channels*Bytes;
1057 ulExtraSamples = min(NextBuf->size, ulExtraSamples);
1058 memcpy(&Data[DataSize*Channels], NextBuf->data, ulExtraSamples);
1061 else
1062 memset(&Data[DataSize*Channels], 0, (BUFFER_PADDING*Channels*Bytes));
1064 /* Compute the gain steps for each output channel */
1065 for(i = 0;i < OUTPUTCHANNELS;i++)
1066 dryGainStep[i] = (ALSource->Params.DryGains[i]-DrySend[i]) /
1067 rampLength;
1068 for(i = 0;i < MAX_SENDS;i++)
1069 wetGainStep[i] = (ALSource->Params.WetGains[i]-WetSend[i]) /
1070 rampLength;
1072 /* Figure out how many samples we can mix. */
1073 DataSize64 = DataSize;
1074 DataSize64 <<= FRACTIONBITS;
1075 DataPos64 = DataPosInt;
1076 DataPos64 <<= FRACTIONBITS;
1077 DataPos64 += DataPosFrac;
1078 BufferSize = (ALuint)((DataSize64-DataPos64+(increment-1)) / increment);
1080 BufferSize = min(BufferSize, (SamplesToDo-j));
1082 /* Actual sample mixing loop */
1083 k = 0;
1084 Data += DataPosInt*Channels;
1086 if(Channels == 1) /* Mono */
1088 #define DO_MIX(resampler) do { \
1089 while(BufferSize--) \
1091 for(i = 0;i < OUTPUTCHANNELS;i++) \
1092 DrySend[i] += dryGainStep[i]; \
1093 for(i = 0;i < MAX_SENDS;i++) \
1094 WetSend[i] += wetGainStep[i]; \
1096 /* First order interpolator */ \
1097 value = (resampler)(Data[k], Data[k+1], DataPosFrac); \
1099 /* Direct path final mix buffer and panning */ \
1100 outsamp = lpFilter4P(DryFilter, 0, value); \
1101 DryBuffer[j][FRONT_LEFT] += outsamp*DrySend[FRONT_LEFT]; \
1102 DryBuffer[j][FRONT_RIGHT] += outsamp*DrySend[FRONT_RIGHT]; \
1103 DryBuffer[j][SIDE_LEFT] += outsamp*DrySend[SIDE_LEFT]; \
1104 DryBuffer[j][SIDE_RIGHT] += outsamp*DrySend[SIDE_RIGHT]; \
1105 DryBuffer[j][BACK_LEFT] += outsamp*DrySend[BACK_LEFT]; \
1106 DryBuffer[j][BACK_RIGHT] += outsamp*DrySend[BACK_RIGHT]; \
1107 DryBuffer[j][FRONT_CENTER] += outsamp*DrySend[FRONT_CENTER]; \
1108 DryBuffer[j][BACK_CENTER] += outsamp*DrySend[BACK_CENTER]; \
1110 /* Room path final mix buffer and panning */ \
1111 for(i = 0;i < MAX_SENDS;i++) \
1113 outsamp = lpFilter2P(WetFilter[i], 0, value); \
1114 WetBuffer[i][j] += outsamp*WetSend[i]; \
1117 DataPosFrac += increment; \
1118 k += DataPosFrac>>FRACTIONBITS; \
1119 DataPosFrac &= FRACTIONMASK; \
1120 j++; \
1122 } while(0)
1124 switch(Resampler)
1126 case POINT_RESAMPLER:
1127 DO_MIX(point); break;
1128 case LINEAR_RESAMPLER:
1129 DO_MIX(lerp); break;
1130 case COSINE_RESAMPLER:
1131 DO_MIX(cos_lerp); break;
1132 case RESAMPLER_MIN:
1133 case RESAMPLER_MAX:
1134 break;
1136 #undef DO_MIX
1138 else if(Channels == 2 && DuplicateStereo) /* Stereo */
1140 const int chans[] = {
1141 FRONT_LEFT, FRONT_RIGHT
1143 const int chans2[] = {
1144 BACK_LEFT, SIDE_LEFT, BACK_RIGHT, SIDE_RIGHT
1146 const ALfloat scaler = 1.0f/Channels;
1147 const ALfloat dupscaler = aluSqrt(1.0f/3.0f);
1149 #define DO_MIX(resampler) do { \
1150 while(BufferSize--) \
1152 for(i = 0;i < OUTPUTCHANNELS;i++) \
1153 DrySend[i] += dryGainStep[i]; \
1154 for(i = 0;i < MAX_SENDS;i++) \
1155 WetSend[i] += wetGainStep[i]; \
1157 for(i = 0;i < Channels;i++) \
1159 value = (resampler)(Data[k*Channels + i],Data[(k+1)*Channels + i],\
1160 DataPosFrac); \
1161 outsamp = lpFilter2P(DryFilter, chans[i]*2, value) * dupscaler; \
1162 DryBuffer[j][chans[i]] += outsamp*DrySend[chans[i]]; \
1163 DryBuffer[j][chans2[i*2+0]] += outsamp*DrySend[chans2[i*2+0]]; \
1164 DryBuffer[j][chans2[i*2+1]] += outsamp*DrySend[chans2[i*2+1]]; \
1165 for(out = 0;out < MAX_SENDS;out++) \
1167 outsamp = lpFilter1P(WetFilter[out], chans[i], value); \
1168 WetBuffer[out][j] += outsamp*WetSend[out]*scaler; \
1172 DataPosFrac += increment; \
1173 k += DataPosFrac>>FRACTIONBITS; \
1174 DataPosFrac &= FRACTIONMASK; \
1175 j++; \
1177 } while(0)
1179 switch(Resampler)
1181 case POINT_RESAMPLER:
1182 DO_MIX(point); break;
1183 case LINEAR_RESAMPLER:
1184 DO_MIX(lerp); break;
1185 case COSINE_RESAMPLER:
1186 DO_MIX(cos_lerp); break;
1187 case RESAMPLER_MIN:
1188 case RESAMPLER_MAX:
1189 break;
1191 #undef DO_MIX
1193 else if(Channels == 2) /* Stereo */
1195 const int chans[] = {
1196 FRONT_LEFT, FRONT_RIGHT
1198 const ALfloat scaler = 1.0f/Channels;
1200 #define DO_MIX(resampler) do { \
1201 while(BufferSize--) \
1203 for(i = 0;i < OUTPUTCHANNELS;i++) \
1204 DrySend[i] += dryGainStep[i]; \
1205 for(i = 0;i < MAX_SENDS;i++) \
1206 WetSend[i] += wetGainStep[i]; \
1208 for(i = 0;i < Channels;i++) \
1210 value = (resampler)(Data[k*Channels + i],Data[(k+1)*Channels + i],\
1211 DataPosFrac); \
1212 outsamp = lpFilter2P(DryFilter, chans[i]*2, value); \
1213 DryBuffer[j][chans[i]] += outsamp*DrySend[chans[i]]; \
1214 for(out = 0;out < MAX_SENDS;out++) \
1216 outsamp = lpFilter1P(WetFilter[out], chans[i], value); \
1217 WetBuffer[out][j] += outsamp*WetSend[out]*scaler; \
1221 DataPosFrac += increment; \
1222 k += DataPosFrac>>FRACTIONBITS; \
1223 DataPosFrac &= FRACTIONMASK; \
1224 j++; \
1226 } while(0)
1228 switch(Resampler)
1230 case POINT_RESAMPLER:
1231 DO_MIX(point); break;
1232 case LINEAR_RESAMPLER:
1233 DO_MIX(lerp); break;
1234 case COSINE_RESAMPLER:
1235 DO_MIX(cos_lerp); break;
1236 case RESAMPLER_MIN:
1237 case RESAMPLER_MAX:
1238 break;
1241 else if(Channels == 4) /* Quad */
1243 const int chans[] = {
1244 FRONT_LEFT, FRONT_RIGHT,
1245 BACK_LEFT, BACK_RIGHT
1247 const ALfloat scaler = 1.0f/Channels;
1249 switch(Resampler)
1251 case POINT_RESAMPLER:
1252 DO_MIX(point); break;
1253 case LINEAR_RESAMPLER:
1254 DO_MIX(lerp); break;
1255 case COSINE_RESAMPLER:
1256 DO_MIX(cos_lerp); break;
1257 case RESAMPLER_MIN:
1258 case RESAMPLER_MAX:
1259 break;
1262 else if(Channels == 6) /* 5.1 */
1264 const int chans[] = {
1265 FRONT_LEFT, FRONT_RIGHT,
1266 FRONT_CENTER, LFE,
1267 BACK_LEFT, BACK_RIGHT
1269 const ALfloat scaler = 1.0f/Channels;
1271 switch(Resampler)
1273 case POINT_RESAMPLER:
1274 DO_MIX(point); break;
1275 case LINEAR_RESAMPLER:
1276 DO_MIX(lerp); break;
1277 case COSINE_RESAMPLER:
1278 DO_MIX(cos_lerp); break;
1279 case RESAMPLER_MIN:
1280 case RESAMPLER_MAX:
1281 break;
1284 else if(Channels == 7) /* 6.1 */
1286 const int chans[] = {
1287 FRONT_LEFT, FRONT_RIGHT,
1288 FRONT_CENTER, LFE,
1289 BACK_CENTER,
1290 SIDE_LEFT, SIDE_RIGHT
1292 const ALfloat scaler = 1.0f/Channels;
1294 switch(Resampler)
1296 case POINT_RESAMPLER:
1297 DO_MIX(point); break;
1298 case LINEAR_RESAMPLER:
1299 DO_MIX(lerp); break;
1300 case COSINE_RESAMPLER:
1301 DO_MIX(cos_lerp); break;
1302 case RESAMPLER_MIN:
1303 case RESAMPLER_MAX:
1304 break;
1307 else if(Channels == 8) /* 7.1 */
1309 const int chans[] = {
1310 FRONT_LEFT, FRONT_RIGHT,
1311 FRONT_CENTER, LFE,
1312 BACK_LEFT, BACK_RIGHT,
1313 SIDE_LEFT, SIDE_RIGHT
1315 const ALfloat scaler = 1.0f/Channels;
1317 switch(Resampler)
1319 case POINT_RESAMPLER:
1320 DO_MIX(point); break;
1321 case LINEAR_RESAMPLER:
1322 DO_MIX(lerp); break;
1323 case COSINE_RESAMPLER:
1324 DO_MIX(cos_lerp); break;
1325 case RESAMPLER_MIN:
1326 case RESAMPLER_MAX:
1327 break;
1329 #undef DO_MIX
1331 else /* Unknown? */
1333 for(i = 0;i < OUTPUTCHANNELS;i++)
1334 DrySend[i] += dryGainStep[i]*BufferSize;
1335 for(i = 0;i < MAX_SENDS;i++)
1336 WetSend[i] += wetGainStep[i]*BufferSize;
1337 while(BufferSize--)
1339 DataPosFrac += increment;
1340 k += DataPosFrac>>FRACTIONBITS;
1341 DataPosFrac &= FRACTIONMASK;
1342 j++;
1345 DataPosInt += k;
1347 skipmix:
1348 /* Handle looping sources */
1349 if(DataPosInt >= DataSize)
1351 if(BuffersPlayed < (ALSource->BuffersInQueue-1))
1353 BufferListItem = BufferListItem->next;
1354 BuffersPlayed++;
1355 DataPosInt -= DataSize;
1357 else if(ALSource->bLooping)
1359 BufferListItem = ALSource->queue;
1360 BuffersPlayed = 0;
1361 if(ALSource->BuffersInQueue == 1)
1362 DataPosInt %= DataSize;
1363 else
1364 DataPosInt -= DataSize;
1366 else
1368 State = AL_STOPPED;
1369 BufferListItem = ALSource->queue;
1370 BuffersPlayed = ALSource->BuffersInQueue;
1371 DataPosInt = 0;
1372 DataPosFrac = 0;
1377 /* Update source info */
1378 ALSource->state = State;
1379 ALSource->BuffersPlayed = BuffersPlayed;
1380 ALSource->position = DataPosInt;
1381 ALSource->position_fraction = DataPosFrac;
1382 ALSource->Buffer = BufferListItem->buffer;
1384 for(i = 0;i < OUTPUTCHANNELS;i++)
1385 ALSource->DryGains[i] = DrySend[i];
1386 for(i = 0;i < MAX_SENDS;i++)
1387 ALSource->WetGains[i] = WetSend[i];
1389 ALSource->FirstStart = AL_FALSE;
1391 if((ALSource=ALSource->next) != NULL)
1392 goto another_source;
1395 ALvoid aluMixData(ALCdevice *device, ALvoid *buffer, ALsizei size)
1397 float (*DryBuffer)[OUTPUTCHANNELS];
1398 ALfloat (*Matrix)[OUTPUTCHANNELS];
1399 const ALuint *ChanMap;
1400 ALuint SamplesToDo;
1401 ALeffectslot *ALEffectSlot;
1402 ALCcontext *ALContext;
1403 ALfloat samp;
1404 int fpuState;
1405 ALuint i, j, c;
1407 #if defined(HAVE_FESETROUND)
1408 fpuState = fegetround();
1409 fesetround(FE_TOWARDZERO);
1410 #elif defined(HAVE__CONTROLFP)
1411 fpuState = _controlfp(0, 0);
1412 _controlfp(_RC_CHOP, _MCW_RC);
1413 #else
1414 (void)fpuState;
1415 #endif
1417 DryBuffer = device->DryBuffer;
1418 while(size > 0)
1420 /* Setup variables */
1421 SamplesToDo = min(size, BUFFERSIZE);
1423 /* Clear mixing buffer */
1424 memset(DryBuffer, 0, SamplesToDo*OUTPUTCHANNELS*sizeof(ALfloat));
1426 SuspendContext(NULL);
1427 for(c = 0;c < device->NumContexts;c++)
1429 ALContext = device->Contexts[c];
1430 SuspendContext(ALContext);
1432 MixSomeSources(ALContext, DryBuffer, SamplesToDo);
1434 /* effect slot processing */
1435 ALEffectSlot = ALContext->EffectSlotList;
1436 while(ALEffectSlot)
1438 if(ALEffectSlot->EffectState)
1439 ALEffect_Process(ALEffectSlot->EffectState, ALEffectSlot, SamplesToDo, ALEffectSlot->WetBuffer, DryBuffer);
1441 for(i = 0;i < SamplesToDo;i++)
1442 ALEffectSlot->WetBuffer[i] = 0.0f;
1443 ALEffectSlot = ALEffectSlot->next;
1445 ProcessContext(ALContext);
1447 ProcessContext(NULL);
1449 //Post processing loop
1450 ChanMap = device->DevChannels;
1451 Matrix = device->ChannelMatrix;
1452 switch(device->Format)
1454 #define CHECK_WRITE_FORMAT(bits, type, func) \
1455 case AL_FORMAT_MONO##bits: \
1456 for(i = 0;i < SamplesToDo;i++) \
1458 samp = 0.0f; \
1459 for(c = 0;c < OUTPUTCHANNELS;c++) \
1460 samp += DryBuffer[i][c] * Matrix[c][FRONT_CENTER]; \
1461 ((type*)buffer)[ChanMap[FRONT_CENTER]] = (func)(samp); \
1462 buffer = ((type*)buffer) + 1; \
1464 break; \
1465 case AL_FORMAT_STEREO##bits: \
1466 if(device->Bs2b) \
1468 for(i = 0;i < SamplesToDo;i++) \
1470 float samples[2] = { 0.0f, 0.0f }; \
1471 for(c = 0;c < OUTPUTCHANNELS;c++) \
1473 samples[0] += DryBuffer[i][c]*Matrix[c][FRONT_LEFT]; \
1474 samples[1] += DryBuffer[i][c]*Matrix[c][FRONT_RIGHT]; \
1476 bs2b_cross_feed(device->Bs2b, samples); \
1477 ((type*)buffer)[ChanMap[FRONT_LEFT]] = (func)(samples[0]);\
1478 ((type*)buffer)[ChanMap[FRONT_RIGHT]]= (func)(samples[1]);\
1479 buffer = ((type*)buffer) + 2; \
1482 else \
1484 for(i = 0;i < SamplesToDo;i++) \
1486 static const Channel chans[] = { \
1487 FRONT_LEFT, FRONT_RIGHT \
1488 }; \
1489 for(j = 0;j < 2;j++) \
1491 samp = 0.0f; \
1492 for(c = 0;c < OUTPUTCHANNELS;c++) \
1493 samp += DryBuffer[i][c] * Matrix[c][chans[j]]; \
1494 ((type*)buffer)[ChanMap[chans[j]]] = (func)(samp); \
1496 buffer = ((type*)buffer) + 2; \
1499 break; \
1500 case AL_FORMAT_QUAD##bits: \
1501 for(i = 0;i < SamplesToDo;i++) \
1503 static const Channel chans[] = { \
1504 FRONT_LEFT, FRONT_RIGHT, \
1505 BACK_LEFT, BACK_RIGHT, \
1506 }; \
1507 for(j = 0;j < 4;j++) \
1509 samp = 0.0f; \
1510 for(c = 0;c < OUTPUTCHANNELS;c++) \
1511 samp += DryBuffer[i][c] * Matrix[c][chans[j]]; \
1512 ((type*)buffer)[ChanMap[chans[j]]] = (func)(samp); \
1514 buffer = ((type*)buffer) + 4; \
1516 break; \
1517 case AL_FORMAT_51CHN##bits: \
1518 for(i = 0;i < SamplesToDo;i++) \
1520 static const Channel chans[] = { \
1521 FRONT_LEFT, FRONT_RIGHT, \
1522 FRONT_CENTER, LFE, \
1523 BACK_LEFT, BACK_RIGHT, \
1524 }; \
1525 for(j = 0;j < 6;j++) \
1527 samp = 0.0f; \
1528 for(c = 0;c < OUTPUTCHANNELS;c++) \
1529 samp += DryBuffer[i][c] * Matrix[c][chans[j]]; \
1530 ((type*)buffer)[ChanMap[chans[j]]] = (func)(samp); \
1532 buffer = ((type*)buffer) + 6; \
1534 break; \
1535 case AL_FORMAT_61CHN##bits: \
1536 for(i = 0;i < SamplesToDo;i++) \
1538 static const Channel chans[] = { \
1539 FRONT_LEFT, FRONT_RIGHT, \
1540 FRONT_CENTER, LFE, BACK_CENTER, \
1541 SIDE_LEFT, SIDE_RIGHT, \
1542 }; \
1543 for(j = 0;j < 7;j++) \
1545 samp = 0.0f; \
1546 for(c = 0;c < OUTPUTCHANNELS;c++) \
1547 samp += DryBuffer[i][c] * Matrix[c][chans[j]]; \
1548 ((type*)buffer)[ChanMap[chans[j]]] = (func)(samp); \
1550 buffer = ((type*)buffer) + 7; \
1552 break; \
1553 case AL_FORMAT_71CHN##bits: \
1554 for(i = 0;i < SamplesToDo;i++) \
1556 static const Channel chans[] = { \
1557 FRONT_LEFT, FRONT_RIGHT, \
1558 FRONT_CENTER, LFE, \
1559 BACK_LEFT, BACK_RIGHT, \
1560 SIDE_LEFT, SIDE_RIGHT \
1561 }; \
1562 for(j = 0;j < 8;j++) \
1564 samp = 0.0f; \
1565 for(c = 0;c < OUTPUTCHANNELS;c++) \
1566 samp += DryBuffer[i][c] * Matrix[c][chans[j]]; \
1567 ((type*)buffer)[ChanMap[chans[j]]] = (func)(samp); \
1569 buffer = ((type*)buffer) + 8; \
1571 break;
1573 #define AL_FORMAT_MONO32 AL_FORMAT_MONO_FLOAT32
1574 #define AL_FORMAT_STEREO32 AL_FORMAT_STEREO_FLOAT32
1575 CHECK_WRITE_FORMAT(8, ALubyte, aluF2UB)
1576 CHECK_WRITE_FORMAT(16, ALshort, aluF2S)
1577 CHECK_WRITE_FORMAT(32, ALfloat, aluF2F)
1578 #undef AL_FORMAT_STEREO32
1579 #undef AL_FORMAT_MONO32
1580 #undef CHECK_WRITE_FORMAT
1582 default:
1583 break;
1586 size -= SamplesToDo;
1589 #if defined(HAVE_FESETROUND)
1590 fesetround(fpuState);
1591 #elif defined(HAVE__CONTROLFP)
1592 _controlfp(fpuState, 0xfffff);
1593 #endif
1596 ALvoid aluHandleDisconnect(ALCdevice *device)
1598 ALuint i;
1600 SuspendContext(NULL);
1601 for(i = 0;i < device->NumContexts;i++)
1603 ALsource *source;
1605 SuspendContext(device->Contexts[i]);
1607 source = device->Contexts[i]->SourceList;
1608 while(source)
1610 if(source->state == AL_PLAYING)
1612 source->state = AL_STOPPED;
1613 source->BuffersPlayed = source->BuffersInQueue;
1614 source->position = 0;
1615 source->position_fraction = 0;
1617 source = source->next;
1619 ProcessContext(device->Contexts[i]);
1622 device->Connected = ALC_FALSE;
1623 ProcessContext(NULL);