Send multi-channel sources to auxiliary effect slots
[openal-soft.git] / Alc / ALu.c
blobfa2c92eadf3ebbd7f7c49082ccd25ef76be08b69
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 #if defined(HAVE_STDINT_H)
41 #include <stdint.h>
42 typedef int64_t ALint64;
43 #elif defined(HAVE___INT64)
44 typedef __int64 ALint64;
45 #elif (SIZEOF_LONG == 8)
46 typedef long ALint64;
47 #elif (SIZEOF_LONG_LONG == 8)
48 typedef long long ALint64;
49 #endif
51 #define FRACTIONBITS 14
52 #define FRACTIONMASK ((1L<<FRACTIONBITS)-1)
53 #define MAX_PITCH 65536
55 /* Minimum ramp length in milliseconds. The value below was chosen to
56 * adequately reduce clicks and pops from harsh gain changes. */
57 #define MIN_RAMP_LENGTH 16
59 ALboolean DuplicateStereo = AL_FALSE;
62 static __inline ALfloat aluF2F(ALfloat Value)
64 if(Value < 0.f) return Value/32768.f;
65 if(Value > 0.f) return Value/32767.f;
66 return 0.f;
69 static __inline ALshort aluF2S(ALfloat Value)
71 ALint i;
73 i = (ALint)Value;
74 i = __min( 32767, i);
75 i = __max(-32768, i);
76 return ((ALshort)i);
79 static __inline ALubyte aluF2UB(ALfloat Value)
81 ALshort i = aluF2S(Value);
82 return (i>>8)+128;
86 static __inline ALvoid aluCrossproduct(const ALfloat *inVector1, const ALfloat *inVector2, ALfloat *outVector)
88 outVector[0] = inVector1[1]*inVector2[2] - inVector1[2]*inVector2[1];
89 outVector[1] = inVector1[2]*inVector2[0] - inVector1[0]*inVector2[2];
90 outVector[2] = inVector1[0]*inVector2[1] - inVector1[1]*inVector2[0];
93 static __inline ALfloat aluDotproduct(const ALfloat *inVector1, const ALfloat *inVector2)
95 return inVector1[0]*inVector2[0] + inVector1[1]*inVector2[1] +
96 inVector1[2]*inVector2[2];
99 static __inline ALvoid aluNormalize(ALfloat *inVector)
101 ALfloat length, inverse_length;
103 length = aluSqrt(aluDotproduct(inVector, inVector));
104 if(length != 0.0f)
106 inverse_length = 1.0f/length;
107 inVector[0] *= inverse_length;
108 inVector[1] *= inverse_length;
109 inVector[2] *= inverse_length;
113 static __inline ALvoid aluMatrixVector(ALfloat *vector,ALfloat w,ALfloat matrix[4][4])
115 ALfloat temp[4] = {
116 vector[0], vector[1], vector[2], w
119 vector[0] = temp[0]*matrix[0][0] + temp[1]*matrix[1][0] + temp[2]*matrix[2][0] + temp[3]*matrix[3][0];
120 vector[1] = temp[0]*matrix[0][1] + temp[1]*matrix[1][1] + temp[2]*matrix[2][1] + temp[3]*matrix[3][1];
121 vector[2] = temp[0]*matrix[0][2] + temp[1]*matrix[1][2] + temp[2]*matrix[2][2] + temp[3]*matrix[3][2];
124 static ALvoid SetSpeakerArrangement(const char *name, ALfloat SpeakerAngle[OUTPUTCHANNELS],
125 ALint Speaker2Chan[OUTPUTCHANNELS], ALint chans)
127 const char *confkey;
128 const char *next;
129 const char *sep;
130 const char *end;
131 int i, val;
133 confkey = GetConfigValue(NULL, name, "");
134 next = confkey;
135 while(next && *next)
137 confkey = next;
138 next = strchr(confkey, ',');
139 if(next)
141 do {
142 next++;
143 } while(isspace(*next));
146 sep = strchr(confkey, '=');
147 if(!sep || confkey == sep)
148 continue;
150 end = sep - 1;
151 while(isspace(*end) && end != confkey)
152 end--;
153 end++;
155 if(strncmp(confkey, "fl", end-confkey) == 0)
156 val = FRONT_LEFT;
157 else if(strncmp(confkey, "fr", end-confkey) == 0)
158 val = FRONT_RIGHT;
159 else if(strncmp(confkey, "fc", end-confkey) == 0)
160 val = FRONT_CENTER;
161 else if(strncmp(confkey, "bl", end-confkey) == 0)
162 val = BACK_LEFT;
163 else if(strncmp(confkey, "br", end-confkey) == 0)
164 val = BACK_RIGHT;
165 else if(strncmp(confkey, "bc", end-confkey) == 0)
166 val = BACK_CENTER;
167 else if(strncmp(confkey, "sl", end-confkey) == 0)
168 val = SIDE_LEFT;
169 else if(strncmp(confkey, "sr", end-confkey) == 0)
170 val = SIDE_RIGHT;
171 else
173 AL_PRINT("Unknown speaker for %s: \"%c%c\"\n", name, confkey[0], confkey[1]);
174 continue;
177 sep++;
178 while(isspace(*sep))
179 sep++;
181 for(i = 0;i < chans;i++)
183 if(Speaker2Chan[i] == val)
185 val = strtol(sep, NULL, 10);
186 if(val >= -180 && val <= 180)
187 SpeakerAngle[i] = val * M_PI/180.0f;
188 else
189 AL_PRINT("Invalid angle for speaker \"%c%c\": %d\n", confkey[0], confkey[1], val);
190 break;
195 for(i = 1;i < chans;i++)
197 if(SpeakerAngle[i] <= SpeakerAngle[i-1])
199 AL_PRINT("Speaker %d of %d does not follow previous: %f > %f\n", i, chans,
200 SpeakerAngle[i-1] * 180.0f/M_PI, SpeakerAngle[i] * 180.0f/M_PI);
201 SpeakerAngle[i] = SpeakerAngle[i-1] + 1 * 180.0f/M_PI;
206 static __inline ALfloat aluLUTpos2Angle(ALint pos)
208 if(pos < QUADRANT_NUM)
209 return aluAtan((ALfloat)pos / (ALfloat)(QUADRANT_NUM - pos));
210 if(pos < 2 * QUADRANT_NUM)
211 return M_PI_2 + aluAtan((ALfloat)(pos - QUADRANT_NUM) / (ALfloat)(2 * QUADRANT_NUM - pos));
212 if(pos < 3 * QUADRANT_NUM)
213 return aluAtan((ALfloat)(pos - 2 * QUADRANT_NUM) / (ALfloat)(3 * QUADRANT_NUM - pos)) - M_PI;
214 return aluAtan((ALfloat)(pos - 3 * QUADRANT_NUM) / (ALfloat)(4 * QUADRANT_NUM - pos)) - M_PI_2;
217 ALvoid aluInitPanning(ALCcontext *Context)
219 ALint pos, offset, s;
220 ALfloat Alpha, Theta;
221 ALfloat SpeakerAngle[OUTPUTCHANNELS];
222 ALint Speaker2Chan[OUTPUTCHANNELS];
224 for(s = 0;s < OUTPUTCHANNELS;s++)
226 int s2;
227 for(s2 = 0;s2 < OUTPUTCHANNELS;s2++)
228 Context->ChannelMatrix[s][s2] = ((s==s2) ? 1.0f : 0.0f);
231 switch(Context->Device->Format)
233 /* Mono is rendered as stereo, then downmixed during post-process */
234 case AL_FORMAT_MONO8:
235 case AL_FORMAT_MONO16:
236 case AL_FORMAT_MONO_FLOAT32:
237 Context->ChannelMatrix[FRONT_CENTER][FRONT_LEFT] = aluSqrt(0.5);
238 Context->ChannelMatrix[FRONT_CENTER][FRONT_RIGHT] = aluSqrt(0.5);
239 Context->ChannelMatrix[SIDE_LEFT][FRONT_LEFT] = 1.0f;
240 Context->ChannelMatrix[SIDE_RIGHT][FRONT_RIGHT] = 1.0f;
241 Context->ChannelMatrix[BACK_LEFT][FRONT_LEFT] = 1.0f;
242 Context->ChannelMatrix[BACK_RIGHT][FRONT_RIGHT] = 1.0f;
243 Context->ChannelMatrix[BACK_CENTER][FRONT_LEFT] = aluSqrt(0.5);
244 Context->ChannelMatrix[BACK_CENTER][FRONT_RIGHT] = aluSqrt(0.5);
245 Context->NumChan = 2;
246 Speaker2Chan[0] = FRONT_LEFT;
247 Speaker2Chan[1] = FRONT_RIGHT;
248 SpeakerAngle[0] = -90.0f * M_PI/180.0f;
249 SpeakerAngle[1] = 90.0f * M_PI/180.0f;
250 break;
252 case AL_FORMAT_STEREO8:
253 case AL_FORMAT_STEREO16:
254 case AL_FORMAT_STEREO_FLOAT32:
255 Context->ChannelMatrix[FRONT_CENTER][FRONT_LEFT] = aluSqrt(0.5);
256 Context->ChannelMatrix[FRONT_CENTER][FRONT_RIGHT] = aluSqrt(0.5);
257 Context->ChannelMatrix[SIDE_LEFT][FRONT_LEFT] = 1.0f;
258 Context->ChannelMatrix[SIDE_RIGHT][FRONT_RIGHT] = 1.0f;
259 Context->ChannelMatrix[BACK_LEFT][FRONT_LEFT] = 1.0f;
260 Context->ChannelMatrix[BACK_RIGHT][FRONT_RIGHT] = 1.0f;
261 Context->ChannelMatrix[BACK_CENTER][FRONT_LEFT] = aluSqrt(0.5);
262 Context->ChannelMatrix[BACK_CENTER][FRONT_RIGHT] = aluSqrt(0.5);
263 Context->NumChan = 2;
264 Speaker2Chan[0] = FRONT_LEFT;
265 Speaker2Chan[1] = FRONT_RIGHT;
266 SpeakerAngle[0] = -90.0f * M_PI/180.0f;
267 SpeakerAngle[1] = 90.0f * M_PI/180.0f;
268 SetSpeakerArrangement("layout_STEREO", SpeakerAngle, Speaker2Chan, Context->NumChan);
269 break;
271 case AL_FORMAT_QUAD8:
272 case AL_FORMAT_QUAD16:
273 case AL_FORMAT_QUAD32:
274 Context->ChannelMatrix[FRONT_CENTER][FRONT_LEFT] = aluSqrt(0.5);
275 Context->ChannelMatrix[FRONT_CENTER][FRONT_RIGHT] = aluSqrt(0.5);
276 Context->ChannelMatrix[SIDE_LEFT][FRONT_LEFT] = aluSqrt(0.5);
277 Context->ChannelMatrix[SIDE_LEFT][BACK_LEFT] = aluSqrt(0.5);
278 Context->ChannelMatrix[SIDE_RIGHT][FRONT_RIGHT] = aluSqrt(0.5);
279 Context->ChannelMatrix[SIDE_RIGHT][BACK_RIGHT] = aluSqrt(0.5);
280 Context->ChannelMatrix[BACK_CENTER][BACK_LEFT] = aluSqrt(0.5);
281 Context->ChannelMatrix[BACK_CENTER][BACK_RIGHT] = aluSqrt(0.5);
282 Context->NumChan = 4;
283 Speaker2Chan[0] = BACK_LEFT;
284 Speaker2Chan[1] = FRONT_LEFT;
285 Speaker2Chan[2] = FRONT_RIGHT;
286 Speaker2Chan[3] = BACK_RIGHT;
287 SpeakerAngle[0] = -135.0f * M_PI/180.0f;
288 SpeakerAngle[1] = -45.0f * M_PI/180.0f;
289 SpeakerAngle[2] = 45.0f * M_PI/180.0f;
290 SpeakerAngle[3] = 135.0f * M_PI/180.0f;
291 SetSpeakerArrangement("layout_QUAD", SpeakerAngle, Speaker2Chan, Context->NumChan);
292 break;
294 case AL_FORMAT_51CHN8:
295 case AL_FORMAT_51CHN16:
296 case AL_FORMAT_51CHN32:
297 Context->ChannelMatrix[SIDE_LEFT][FRONT_LEFT] = aluSqrt(0.5);
298 Context->ChannelMatrix[SIDE_LEFT][BACK_LEFT] = aluSqrt(0.5);
299 Context->ChannelMatrix[SIDE_RIGHT][FRONT_RIGHT] = aluSqrt(0.5);
300 Context->ChannelMatrix[SIDE_RIGHT][BACK_RIGHT] = aluSqrt(0.5);
301 Context->ChannelMatrix[BACK_CENTER][BACK_LEFT] = aluSqrt(0.5);
302 Context->ChannelMatrix[BACK_CENTER][BACK_RIGHT] = aluSqrt(0.5);
303 Context->NumChan = 5;
304 Speaker2Chan[0] = BACK_LEFT;
305 Speaker2Chan[1] = FRONT_LEFT;
306 Speaker2Chan[2] = FRONT_CENTER;
307 Speaker2Chan[3] = FRONT_RIGHT;
308 Speaker2Chan[4] = BACK_RIGHT;
309 SpeakerAngle[0] = -110.0f * M_PI/180.0f;
310 SpeakerAngle[1] = -30.0f * M_PI/180.0f;
311 SpeakerAngle[2] = 0.0f * M_PI/180.0f;
312 SpeakerAngle[3] = 30.0f * M_PI/180.0f;
313 SpeakerAngle[4] = 110.0f * M_PI/180.0f;
314 SetSpeakerArrangement("layout_51CHN", SpeakerAngle, Speaker2Chan, Context->NumChan);
315 break;
317 case AL_FORMAT_61CHN8:
318 case AL_FORMAT_61CHN16:
319 case AL_FORMAT_61CHN32:
320 Context->ChannelMatrix[BACK_LEFT][BACK_CENTER] = aluSqrt(0.5);
321 Context->ChannelMatrix[BACK_LEFT][SIDE_LEFT] = aluSqrt(0.5);
322 Context->ChannelMatrix[BACK_RIGHT][BACK_CENTER] = aluSqrt(0.5);
323 Context->ChannelMatrix[BACK_RIGHT][SIDE_RIGHT] = aluSqrt(0.5);
324 Context->NumChan = 6;
325 Speaker2Chan[0] = SIDE_LEFT;
326 Speaker2Chan[1] = FRONT_LEFT;
327 Speaker2Chan[2] = FRONT_CENTER;
328 Speaker2Chan[3] = FRONT_RIGHT;
329 Speaker2Chan[4] = SIDE_RIGHT;
330 Speaker2Chan[5] = BACK_CENTER;
331 SpeakerAngle[0] = -90.0f * M_PI/180.0f;
332 SpeakerAngle[1] = -30.0f * M_PI/180.0f;
333 SpeakerAngle[2] = 0.0f * M_PI/180.0f;
334 SpeakerAngle[3] = 30.0f * M_PI/180.0f;
335 SpeakerAngle[4] = 90.0f * M_PI/180.0f;
336 SpeakerAngle[5] = 180.0f * M_PI/180.0f;
337 SetSpeakerArrangement("layout_61CHN", SpeakerAngle, Speaker2Chan, Context->NumChan);
338 break;
340 case AL_FORMAT_71CHN8:
341 case AL_FORMAT_71CHN16:
342 case AL_FORMAT_71CHN32:
343 Context->ChannelMatrix[BACK_CENTER][BACK_LEFT] = aluSqrt(0.5);
344 Context->ChannelMatrix[BACK_CENTER][BACK_RIGHT] = aluSqrt(0.5);
345 Context->NumChan = 7;
346 Speaker2Chan[0] = BACK_LEFT;
347 Speaker2Chan[1] = SIDE_LEFT;
348 Speaker2Chan[2] = FRONT_LEFT;
349 Speaker2Chan[3] = FRONT_CENTER;
350 Speaker2Chan[4] = FRONT_RIGHT;
351 Speaker2Chan[5] = SIDE_RIGHT;
352 Speaker2Chan[6] = BACK_RIGHT;
353 SpeakerAngle[0] = -150.0f * M_PI/180.0f;
354 SpeakerAngle[1] = -90.0f * M_PI/180.0f;
355 SpeakerAngle[2] = -30.0f * M_PI/180.0f;
356 SpeakerAngle[3] = 0.0f * M_PI/180.0f;
357 SpeakerAngle[4] = 30.0f * M_PI/180.0f;
358 SpeakerAngle[5] = 90.0f * M_PI/180.0f;
359 SpeakerAngle[6] = 150.0f * M_PI/180.0f;
360 SetSpeakerArrangement("layout_71CHN", SpeakerAngle, Speaker2Chan, Context->NumChan);
361 break;
363 default:
364 assert(0);
367 for(pos = 0; pos < LUT_NUM; pos++)
369 /* source angle */
370 Theta = aluLUTpos2Angle(pos);
372 /* clear all values */
373 offset = OUTPUTCHANNELS * pos;
374 for(s = 0; s < OUTPUTCHANNELS; s++)
375 Context->PanningLUT[offset+s] = 0.0f;
377 /* set panning values */
378 for(s = 0; s < Context->NumChan - 1; s++)
380 if(Theta >= SpeakerAngle[s] && Theta < SpeakerAngle[s+1])
382 /* source between speaker s and speaker s+1 */
383 Alpha = M_PI_2 * (Theta-SpeakerAngle[s]) /
384 (SpeakerAngle[s+1]-SpeakerAngle[s]);
385 Context->PanningLUT[offset + Speaker2Chan[s]] = cos(Alpha);
386 Context->PanningLUT[offset + Speaker2Chan[s+1]] = sin(Alpha);
387 break;
390 if(s == Context->NumChan - 1)
392 /* source between last and first speaker */
393 if(Theta < SpeakerAngle[0])
394 Theta += 2.0f * M_PI;
395 Alpha = M_PI_2 * (Theta-SpeakerAngle[s]) /
396 (2.0f * M_PI + SpeakerAngle[0]-SpeakerAngle[s]);
397 Context->PanningLUT[offset + Speaker2Chan[s]] = cos(Alpha);
398 Context->PanningLUT[offset + Speaker2Chan[0]] = sin(Alpha);
403 static ALvoid CalcSourceParams(const ALCcontext *ALContext, ALsource *ALSource,
404 ALboolean isMono)
406 ALfloat InnerAngle,OuterAngle,Angle,Distance,DryMix;
407 ALfloat Direction[3],Position[3],SourceToListener[3];
408 ALfloat Velocity[3],ListenerVel[3];
409 ALfloat MinVolume,MaxVolume,MinDist,MaxDist,Rolloff,OuterGainHF;
410 ALfloat ConeVolume,ConeHF,SourceVolume,ListenerGain;
411 ALfloat DopplerFactor, DopplerVelocity, flSpeedOfSound;
412 ALfloat Matrix[4][4];
413 ALfloat flAttenuation;
414 ALfloat RoomAttenuation[MAX_SENDS];
415 ALfloat MetersPerUnit;
416 ALfloat RoomRolloff[MAX_SENDS];
417 ALfloat DryGainHF = 1.0f;
418 ALfloat WetGain[MAX_SENDS];
419 ALfloat WetGainHF[MAX_SENDS];
420 ALfloat DirGain, AmbientGain;
421 ALfloat length;
422 const ALfloat *SpeakerGain;
423 ALuint Frequency;
424 ALint NumSends;
425 ALint pos, s, i;
426 ALfloat cw, a, g;
428 //Get context properties
429 DopplerFactor = ALContext->DopplerFactor * ALSource->DopplerFactor;
430 DopplerVelocity = ALContext->DopplerVelocity;
431 flSpeedOfSound = ALContext->flSpeedOfSound;
432 NumSends = ALContext->Device->NumAuxSends;
433 Frequency = ALContext->Device->Frequency;
435 //Get listener properties
436 ListenerGain = ALContext->Listener.Gain;
437 MetersPerUnit = ALContext->Listener.MetersPerUnit;
438 memcpy(ListenerVel, ALContext->Listener.Velocity, sizeof(ALContext->Listener.Velocity));
440 //Get source properties
441 SourceVolume = ALSource->flGain;
442 memcpy(Position, ALSource->vPosition, sizeof(ALSource->vPosition));
443 memcpy(Direction, ALSource->vOrientation, sizeof(ALSource->vOrientation));
444 memcpy(Velocity, ALSource->vVelocity, sizeof(ALSource->vVelocity));
445 MinVolume = ALSource->flMinGain;
446 MaxVolume = ALSource->flMaxGain;
447 MinDist = ALSource->flRefDistance;
448 MaxDist = ALSource->flMaxDistance;
449 Rolloff = ALSource->flRollOffFactor;
450 InnerAngle = ALSource->flInnerAngle;
451 OuterAngle = ALSource->flOuterAngle;
452 OuterGainHF = ALSource->OuterGainHF;
454 //Only apply 3D calculations for mono buffers
455 if(isMono == AL_FALSE)
457 //1. Multi-channel buffers always play "normal"
458 ALSource->Params.Pitch = ALSource->flPitch;
460 DryMix = SourceVolume;
461 DryMix = __min(DryMix,MaxVolume);
462 DryMix = __max(DryMix,MinVolume);
464 switch(ALSource->DirectFilter.type)
466 case AL_FILTER_LOWPASS:
467 DryMix *= ALSource->DirectFilter.Gain;
468 DryGainHF *= ALSource->DirectFilter.GainHF;
469 break;
472 ALSource->Params.DryGains[FRONT_LEFT] = DryMix * ListenerGain;
473 ALSource->Params.DryGains[FRONT_RIGHT] = DryMix * ListenerGain;
474 ALSource->Params.DryGains[SIDE_LEFT] = DryMix * ListenerGain;
475 ALSource->Params.DryGains[SIDE_RIGHT] = DryMix * ListenerGain;
476 ALSource->Params.DryGains[BACK_LEFT] = DryMix * ListenerGain;
477 ALSource->Params.DryGains[BACK_RIGHT] = DryMix * ListenerGain;
478 ALSource->Params.DryGains[FRONT_CENTER] = DryMix * ListenerGain;
479 ALSource->Params.DryGains[BACK_CENTER] = DryMix * ListenerGain;
480 ALSource->Params.DryGains[LFE] = DryMix * ListenerGain;
482 for(i = 0;i < NumSends;i++)
484 WetGain[i] = SourceVolume;
485 WetGain[i] = __min(WetGain[i],MaxVolume);
486 WetGain[i] = __max(WetGain[i],MinVolume);
487 WetGainHF[i] = 1.0f;
489 switch(ALSource->Send[i].WetFilter.type)
491 case AL_FILTER_LOWPASS:
492 WetGain[i] *= ALSource->Send[i].WetFilter.Gain;
493 WetGainHF[i] *= ALSource->Send[i].WetFilter.GainHF;
494 break;
497 ALSource->Params.WetGains[i] = WetGain[i] * ListenerGain;
499 for(i = NumSends;i < MAX_SENDS;i++)
501 ALSource->Params.WetGains[i] = 0.0f;
502 WetGainHF[i] = 1.0f;
505 /* Update filter coefficients. Calculations based on the I3DL2
506 * spec. */
507 cw = cos(2.0*M_PI * LOWPASSFREQCUTOFF / Frequency);
508 /* We use two chained one-pole filters, so we need to take the
509 * square root of the squared gain, which is the same as the base
510 * gain. */
511 g = __max(DryGainHF, 0.01f);
512 a = 0.0f;
513 /* Be careful with gains < 0.0001, as that causes the coefficient
514 * head towards 1, which will flatten the signal */
515 if(g < 0.9999f) /* 1-epsilon */
516 a = (1 - g*cw - aluSqrt(2*g*(1-cw) - g*g*(1 - cw*cw))) /
517 (1 - g);
518 ALSource->Params.iirFilter.coeff = a;
520 for(i = 0;i < NumSends;i++)
522 /* We use a one-pole filter, so we need to take the squared gain */
523 g = __max(WetGainHF[i], 0.1f);
524 g *= g;
525 a = 0.0f;
526 if(g < 0.9999f) /* 1-epsilon */
527 a = (1 - g*cw - aluSqrt(2*g*(1-cw) - g*g*(1 - cw*cw))) /
528 (1 - g);
529 ALSource->Params.Send[i].iirFilter.coeff = a;
532 return;
535 //1. Translate Listener to origin (convert to head relative)
536 if(ALSource->bHeadRelative==AL_FALSE)
538 ALfloat U[3],V[3],N[3],P[3];
540 // Build transform matrix
541 memcpy(N, ALContext->Listener.Forward, sizeof(N)); // At-vector
542 aluNormalize(N); // Normalized At-vector
543 memcpy(V, ALContext->Listener.Up, sizeof(V)); // Up-vector
544 aluNormalize(V); // Normalized Up-vector
545 aluCrossproduct(N, V, U); // Right-vector
546 aluNormalize(U); // Normalized Right-vector
547 P[0] = -(ALContext->Listener.Position[0]*U[0] + // Translation
548 ALContext->Listener.Position[1]*U[1] +
549 ALContext->Listener.Position[2]*U[2]);
550 P[1] = -(ALContext->Listener.Position[0]*V[0] +
551 ALContext->Listener.Position[1]*V[1] +
552 ALContext->Listener.Position[2]*V[2]);
553 P[2] = -(ALContext->Listener.Position[0]*-N[0] +
554 ALContext->Listener.Position[1]*-N[1] +
555 ALContext->Listener.Position[2]*-N[2]);
556 Matrix[0][0] = U[0]; Matrix[0][1] = V[0]; Matrix[0][2] = -N[0]; Matrix[0][3] = 0.0f;
557 Matrix[1][0] = U[1]; Matrix[1][1] = V[1]; Matrix[1][2] = -N[1]; Matrix[1][3] = 0.0f;
558 Matrix[2][0] = U[2]; Matrix[2][1] = V[2]; Matrix[2][2] = -N[2]; Matrix[2][3] = 0.0f;
559 Matrix[3][0] = P[0]; Matrix[3][1] = P[1]; Matrix[3][2] = P[2]; Matrix[3][3] = 1.0f;
561 // Transform source position and direction into listener space
562 aluMatrixVector(Position, 1.0f, Matrix);
563 aluMatrixVector(Direction, 0.0f, Matrix);
564 // Transform source and listener velocity into listener space
565 aluMatrixVector(Velocity, 0.0f, Matrix);
566 aluMatrixVector(ListenerVel, 0.0f, Matrix);
568 else
569 ListenerVel[0] = ListenerVel[1] = ListenerVel[2] = 0.0f;
571 SourceToListener[0] = -Position[0];
572 SourceToListener[1] = -Position[1];
573 SourceToListener[2] = -Position[2];
574 aluNormalize(SourceToListener);
575 aluNormalize(Direction);
577 //2. Calculate distance attenuation
578 Distance = aluSqrt(aluDotproduct(Position, Position));
580 flAttenuation = 1.0f;
581 for(i = 0;i < MAX_SENDS;i++)
583 RoomAttenuation[i] = 1.0f;
585 RoomRolloff[i] = ALSource->RoomRolloffFactor;
586 if(ALSource->Send[i].Slot &&
587 (ALSource->Send[i].Slot->effect.type == AL_EFFECT_REVERB ||
588 ALSource->Send[i].Slot->effect.type == AL_EFFECT_EAXREVERB))
589 RoomRolloff[i] += ALSource->Send[i].Slot->effect.Reverb.RoomRolloffFactor;
592 switch(ALSource->DistanceModel)
594 case AL_INVERSE_DISTANCE_CLAMPED:
595 Distance=__max(Distance,MinDist);
596 Distance=__min(Distance,MaxDist);
597 if(MaxDist < MinDist)
598 break;
599 //fall-through
600 case AL_INVERSE_DISTANCE:
601 if(MinDist > 0.0f)
603 if((MinDist + (Rolloff * (Distance - MinDist))) > 0.0f)
604 flAttenuation = MinDist / (MinDist + (Rolloff * (Distance - MinDist)));
605 for(i = 0;i < NumSends;i++)
607 if((MinDist + (RoomRolloff[i] * (Distance - MinDist))) > 0.0f)
608 RoomAttenuation[i] = MinDist / (MinDist + (RoomRolloff[i] * (Distance - MinDist)));
611 break;
613 case AL_LINEAR_DISTANCE_CLAMPED:
614 Distance=__max(Distance,MinDist);
615 Distance=__min(Distance,MaxDist);
616 if(MaxDist < MinDist)
617 break;
618 //fall-through
619 case AL_LINEAR_DISTANCE:
620 Distance=__min(Distance,MaxDist);
621 if(MaxDist != MinDist)
623 flAttenuation = 1.0f - (Rolloff*(Distance-MinDist)/(MaxDist - MinDist));
624 for(i = 0;i < NumSends;i++)
625 RoomAttenuation[i] = 1.0f - (RoomRolloff[i]*(Distance-MinDist)/(MaxDist - MinDist));
627 break;
629 case AL_EXPONENT_DISTANCE_CLAMPED:
630 Distance=__max(Distance,MinDist);
631 Distance=__min(Distance,MaxDist);
632 if(MaxDist < MinDist)
633 break;
634 //fall-through
635 case AL_EXPONENT_DISTANCE:
636 if(Distance > 0.0f && MinDist > 0.0f)
638 flAttenuation = (ALfloat)pow(Distance/MinDist, -Rolloff);
639 for(i = 0;i < NumSends;i++)
640 RoomAttenuation[i] = (ALfloat)pow(Distance/MinDist, -RoomRolloff[i]);
642 break;
644 case AL_NONE:
645 break;
648 // Source Gain + Attenuation and clamp to Min/Max Gain
649 DryMix = SourceVolume * flAttenuation;
650 DryMix = __min(DryMix,MaxVolume);
651 DryMix = __max(DryMix,MinVolume);
653 for(i = 0;i < NumSends;i++)
655 ALfloat WetMix = SourceVolume * RoomAttenuation[i];
656 WetMix = __min(WetMix,MaxVolume);
657 WetGain[i] = __max(WetMix,MinVolume);
658 WetGainHF[i] = 1.0f;
661 // Distance-based air absorption
662 if(ALSource->AirAbsorptionFactor > 0.0f && flAttenuation < 1.0f)
664 ALfloat absorb = 0.0f;
666 // Absorption calculation is done in dB
667 if(flAttenuation > 0.0f)
669 absorb = (MinDist/flAttenuation - MinDist)*MetersPerUnit *
670 (ALSource->AirAbsorptionFactor*AIRABSORBGAINDBHF);
671 // Convert dB to linear gain before applying
672 absorb = pow(10.0, absorb/20.0);
674 DryGainHF *= absorb;
675 for(i = 0;i < MAX_SENDS;i++)
676 WetGainHF[i] *= absorb;
679 //3. Apply directional soundcones
680 Angle = aluAcos(aluDotproduct(Direction,SourceToListener)) * 180.0f/M_PI;
681 if(Angle >= InnerAngle && Angle <= OuterAngle)
683 ALfloat scale = (Angle-InnerAngle) / (OuterAngle-InnerAngle);
684 ConeVolume = (1.0f+(ALSource->flOuterGain-1.0f)*scale);
685 ConeHF = (1.0f+(OuterGainHF-1.0f)*scale);
686 DryMix *= ConeVolume;
687 if(ALSource->DryGainHFAuto)
688 DryGainHF *= ConeHF;
690 else if(Angle > OuterAngle)
692 ConeVolume = (1.0f+(ALSource->flOuterGain-1.0f));
693 ConeHF = (1.0f+(OuterGainHF-1.0f));
694 DryMix *= ConeVolume;
695 if(ALSource->DryGainHFAuto)
696 DryGainHF *= ConeHF;
698 else
700 ConeVolume = 1.0f;
701 ConeHF = 1.0f;
704 //4. Calculate Velocity
705 if(DopplerFactor != 0.0f)
707 ALfloat flVSS, flVLS;
708 ALfloat flMaxVelocity = (DopplerVelocity * flSpeedOfSound) /
709 DopplerFactor;
711 flVSS = aluDotproduct(Velocity, SourceToListener);
712 if(flVSS >= flMaxVelocity)
713 flVSS = (flMaxVelocity - 1.0f);
714 else if(flVSS <= -flMaxVelocity)
715 flVSS = -flMaxVelocity + 1.0f;
717 flVLS = aluDotproduct(ListenerVel, SourceToListener);
718 if(flVLS >= flMaxVelocity)
719 flVLS = (flMaxVelocity - 1.0f);
720 else if(flVLS <= -flMaxVelocity)
721 flVLS = -flMaxVelocity + 1.0f;
723 ALSource->Params.Pitch = ALSource->flPitch *
724 ((flSpeedOfSound * DopplerVelocity) - (DopplerFactor * flVLS)) /
725 ((flSpeedOfSound * DopplerVelocity) - (DopplerFactor * flVSS));
727 else
728 ALSource->Params.Pitch = ALSource->flPitch;
730 for(i = 0;i < NumSends;i++)
732 if(ALSource->Send[i].Slot &&
733 ALSource->Send[i].Slot->effect.type != AL_EFFECT_NULL)
735 if(ALSource->Send[i].Slot->AuxSendAuto)
737 if(ALSource->WetGainAuto)
738 WetGain[i] *= ConeVolume;
739 if(ALSource->WetGainHFAuto)
740 WetGainHF[i] *= ConeHF;
742 if(ALSource->Send[i].Slot->effect.type == AL_EFFECT_REVERB ||
743 ALSource->Send[i].Slot->effect.type == AL_EFFECT_EAXREVERB)
745 /* Apply a decay-time transformation to the wet path,
746 * based on the attenuation of the dry path. This should
747 * better approximate the statistical attenuation model
748 * for the reverb effect.
750 * This simple equation converts the distance attenuation
751 * into the time it would take to reach -60 dB. From
752 * there it establishes an origin (0.333s; the decay time
753 * that will produce equal attenuation) and applies the
754 * current decay time. Finally, it converts the result
755 * back to an attenuation for the reverb path.
757 WetGain[i] *= pow(10.0f, log10(flAttenuation) * 0.333f /
758 ALSource->Send[i].Slot->effect.Reverb.DecayTime);
761 else
763 // If the slot's auxiliary send auto is off, the data sent to
764 // the effect slot is the same as the dry path, sans filter
765 // effects
766 WetGain[i] = DryMix;
767 WetGainHF[i] = DryGainHF;
770 switch(ALSource->Send[i].WetFilter.type)
772 case AL_FILTER_LOWPASS:
773 WetGain[i] *= ALSource->Send[i].WetFilter.Gain;
774 WetGainHF[i] *= ALSource->Send[i].WetFilter.GainHF;
775 break;
777 ALSource->Params.WetGains[i] = WetGain[i] * ListenerGain;
779 else
781 ALSource->Params.WetGains[i] = 0.0f;
782 WetGainHF[i] = 1.0f;
785 for(i = NumSends;i < MAX_SENDS;i++)
787 ALSource->Params.WetGains[i] = 0.0f;
788 WetGainHF[i] = 1.0f;
791 //5. Apply filter gains and filters
792 switch(ALSource->DirectFilter.type)
794 case AL_FILTER_LOWPASS:
795 DryMix *= ALSource->DirectFilter.Gain;
796 DryGainHF *= ALSource->DirectFilter.GainHF;
797 break;
799 DryMix *= ListenerGain;
801 // Use energy-preserving panning algorithm for multi-speaker playback
802 length = aluSqrt(Position[0]*Position[0] + Position[1]*Position[1] +
803 Position[2]*Position[2]);
804 length = __max(length, MinDist);
805 if(length > 0.0f)
807 ALfloat invlen = 1.0f/length;
808 Position[0] *= invlen;
809 Position[1] *= invlen;
810 Position[2] *= invlen;
813 pos = aluCart2LUTpos(-Position[2], Position[0]);
814 SpeakerGain = &ALContext->PanningLUT[OUTPUTCHANNELS * pos];
816 DirGain = aluSqrt(Position[0]*Position[0] + Position[2]*Position[2]);
817 // elevation adjustment for directional gain. this sucks, but
818 // has low complexity
819 AmbientGain = 1.0/aluSqrt(ALContext->NumChan) * (1.0-DirGain);
820 for(s = 0; s < OUTPUTCHANNELS; s++)
822 ALfloat gain = SpeakerGain[s]*DirGain + AmbientGain;
823 ALSource->Params.DryGains[s] = DryMix * gain;
826 /* Update filter coefficients. */
827 cw = cos(2.0*M_PI * LOWPASSFREQCUTOFF / Frequency);
828 /* Spatialized sources use four chained one-pole filters, so we need to
829 * take the fourth root of the squared gain, which is the same as the
830 * square root of the base gain. */
831 g = aluSqrt(__max(DryGainHF, 0.0001f));
832 a = 0.0f;
833 if(g < 0.9999f) /* 1-epsilon */
834 a = (1 - g*cw - aluSqrt(2*g*(1-cw) - g*g*(1 - cw*cw))) /
835 (1 - g);
836 ALSource->Params.iirFilter.coeff = a;
838 for(i = 0;i < NumSends;i++)
840 /* The wet path uses two chained one-pole filters, so take the
841 * base gain (square root of the squared gain) */
842 g = __max(WetGainHF[i], 0.01f);
843 a = 0.0f;
844 if(g < 0.9999f) /* 1-epsilon */
845 a = (1 - g*cw - aluSqrt(2*g*(1-cw) - g*g*(1 - cw*cw))) /
846 (1 - g);
847 ALSource->Params.Send[i].iirFilter.coeff = a;
851 static __inline ALshort lerp(ALshort val1, ALshort val2, ALint frac)
853 return val1 + (((val2-val1)*frac)>>FRACTIONBITS);
856 static void MixSomeSources(ALCcontext *ALContext, float (*DryBuffer)[OUTPUTCHANNELS], ALuint SamplesToDo)
858 static float DummyBuffer[BUFFERSIZE];
859 ALfloat *WetBuffer[MAX_SENDS];
860 ALfloat (*Matrix)[OUTPUTCHANNELS] = ALContext->ChannelMatrix;
861 ALfloat DrySend[OUTPUTCHANNELS];
862 ALfloat dryGainStep[OUTPUTCHANNELS];
863 ALfloat wetGainStep[MAX_SENDS];
864 ALuint i, j, k, out;
865 ALsource *ALSource;
866 ALfloat value, outsamp;
867 ALbufferlistitem *BufferListItem;
868 ALint64 DataSize64,DataPos64;
869 FILTER *DryFilter, *WetFilter[MAX_SENDS];
870 ALfloat WetSend[MAX_SENDS];
871 ALuint rampLength;
872 ALuint DeviceFreq;
873 ALint increment;
874 ALuint DataPosInt, DataPosFrac;
875 ALuint Channels, Bytes;
876 ALuint Frequency;
877 ALuint BuffersPlayed;
878 ALfloat Pitch;
879 ALenum State;
881 if(!(ALSource=ALContext->Source))
882 return;
884 DeviceFreq = ALContext->Device->Frequency;
886 rampLength = DeviceFreq * MIN_RAMP_LENGTH / 1000;
887 rampLength = max(rampLength, SamplesToDo);
889 another_source:
890 State = ALSource->state;
891 if(State != AL_PLAYING)
893 if((ALSource=ALSource->next) != NULL)
894 goto another_source;
895 return;
897 j = 0;
899 /* Find buffer format */
900 Frequency = 0;
901 Channels = 0;
902 Bytes = 0;
903 BufferListItem = ALSource->queue;
904 while(BufferListItem != NULL)
906 ALbuffer *ALBuffer;
907 if((ALBuffer=BufferListItem->buffer) != NULL)
909 Channels = aluChannelsFromFormat(ALBuffer->format);
910 Bytes = aluBytesFromFormat(ALBuffer->format);
911 Frequency = ALBuffer->frequency;
912 break;
914 BufferListItem = BufferListItem->next;
917 /* Get source info */
918 BuffersPlayed = ALSource->BuffersPlayed;
919 DataPosInt = ALSource->position;
920 DataPosFrac = ALSource->position_fraction;
922 if(ALSource->NeedsUpdate)
924 CalcSourceParams(ALContext, ALSource, (Channels==1)?AL_TRUE:AL_FALSE);
925 ALSource->NeedsUpdate = AL_FALSE;
928 /* Compute 18.14 fixed point step */
929 Pitch = (ALSource->Params.Pitch*Frequency) / DeviceFreq;
930 if(Pitch > (float)MAX_PITCH) Pitch = (float)MAX_PITCH;
931 increment = (ALint)(Pitch*(ALfloat)(1L<<FRACTIONBITS));
932 if(increment <= 0) increment = (1<<FRACTIONBITS);
934 /* Compute the gain steps for each output channel */
935 if(ALSource->FirstStart)
937 for(i = 0;i < OUTPUTCHANNELS;i++)
938 DrySend[i] = ALSource->Params.DryGains[i];
939 for(i = 0;i < MAX_SENDS;i++)
940 WetSend[i] = ALSource->Params.WetGains[i];
942 else
944 for(i = 0;i < OUTPUTCHANNELS;i++)
945 DrySend[i] = ALSource->DryGains[i];
946 for(i = 0;i < MAX_SENDS;i++)
947 WetSend[i] = ALSource->WetGains[i];
950 DryFilter = &ALSource->Params.iirFilter;
951 for(i = 0;i < MAX_SENDS;i++)
953 WetFilter[i] = &ALSource->Params.Send[i].iirFilter;
954 WetBuffer[i] = (ALSource->Send[i].Slot ?
955 ALSource->Send[i].Slot->WetBuffer :
956 DummyBuffer);
959 if(DuplicateStereo && Channels == 2)
961 Matrix[FRONT_LEFT][SIDE_LEFT] = 1.0f;
962 Matrix[FRONT_RIGHT][SIDE_RIGHT] = 1.0f;
963 Matrix[FRONT_LEFT][BACK_LEFT] = 1.0f;
964 Matrix[FRONT_RIGHT][BACK_RIGHT] = 1.0f;
966 else if(DuplicateStereo)
968 Matrix[FRONT_LEFT][SIDE_LEFT] = 0.0f;
969 Matrix[FRONT_RIGHT][SIDE_RIGHT] = 0.0f;
970 Matrix[FRONT_LEFT][BACK_LEFT] = 0.0f;
971 Matrix[FRONT_RIGHT][BACK_RIGHT] = 0.0f;
974 /* Get current buffer queue item */
975 BufferListItem = ALSource->queue;
976 for(i = 0;i < BuffersPlayed && BufferListItem;i++)
977 BufferListItem = BufferListItem->next;
979 while(State == AL_PLAYING && j < SamplesToDo)
981 ALuint DataSize = 0;
982 ALbuffer *ALBuffer;
983 ALshort *Data;
984 ALuint BufferSize;
986 /* Get buffer info */
987 if((ALBuffer=BufferListItem->buffer) != NULL)
989 Data = ALBuffer->data;
990 DataSize = ALBuffer->size;
991 DataSize /= Channels * Bytes;
993 if(DataPosInt >= DataSize)
994 goto skipmix;
996 if(BufferListItem->next)
998 ALbuffer *NextBuf = BufferListItem->next->buffer;
999 if(NextBuf && NextBuf->data)
1001 ALint ulExtraSamples = BUFFER_PADDING*Channels*Bytes;
1002 ulExtraSamples = min(NextBuf->size, ulExtraSamples);
1003 memcpy(&Data[DataSize*Channels], NextBuf->data, ulExtraSamples);
1006 else if(ALSource->bLooping)
1008 ALbuffer *NextBuf = ALSource->queue->buffer;
1009 if(NextBuf && NextBuf->data)
1011 ALint ulExtraSamples = BUFFER_PADDING*Channels*Bytes;
1012 ulExtraSamples = min(NextBuf->size, ulExtraSamples);
1013 memcpy(&Data[DataSize*Channels], NextBuf->data, ulExtraSamples);
1016 else
1017 memset(&Data[DataSize*Channels], 0, (BUFFER_PADDING*Channels*Bytes));
1019 /* Compute the gain steps for each output channel */
1020 for(i = 0;i < OUTPUTCHANNELS;i++)
1021 dryGainStep[i] = (ALSource->Params.DryGains[i]-
1022 DrySend[i]) / rampLength;
1023 for(i = 0;i < MAX_SENDS;i++)
1024 wetGainStep[i] = (ALSource->Params.WetGains[i]-
1025 WetSend[i]) / rampLength;
1027 /* Figure out how many samples we can mix. */
1028 DataSize64 = DataSize;
1029 DataSize64 <<= FRACTIONBITS;
1030 DataPos64 = DataPosInt;
1031 DataPos64 <<= FRACTIONBITS;
1032 DataPos64 += DataPosFrac;
1033 BufferSize = (ALuint)((DataSize64-DataPos64+(increment-1)) / increment);
1035 BufferSize = min(BufferSize, (SamplesToDo-j));
1037 /* Actual sample mixing loop */
1038 k = 0;
1039 Data += DataPosInt*Channels;
1041 if(Channels == 1) /* Mono */
1043 while(BufferSize--)
1045 for(i = 0;i < OUTPUTCHANNELS;i++)
1046 DrySend[i] += dryGainStep[i];
1047 for(i = 0;i < MAX_SENDS;i++)
1048 WetSend[i] += wetGainStep[i];
1050 /* First order interpolator */
1051 value = lerp(Data[k], Data[k+1], DataPosFrac);
1053 /* Direct path final mix buffer and panning */
1054 outsamp = lpFilter4P(DryFilter, 0, value);
1055 DryBuffer[j][FRONT_LEFT] += outsamp*DrySend[FRONT_LEFT];
1056 DryBuffer[j][FRONT_RIGHT] += outsamp*DrySend[FRONT_RIGHT];
1057 DryBuffer[j][SIDE_LEFT] += outsamp*DrySend[SIDE_LEFT];
1058 DryBuffer[j][SIDE_RIGHT] += outsamp*DrySend[SIDE_RIGHT];
1059 DryBuffer[j][BACK_LEFT] += outsamp*DrySend[BACK_LEFT];
1060 DryBuffer[j][BACK_RIGHT] += outsamp*DrySend[BACK_RIGHT];
1061 DryBuffer[j][FRONT_CENTER] += outsamp*DrySend[FRONT_CENTER];
1062 DryBuffer[j][BACK_CENTER] += outsamp*DrySend[BACK_CENTER];
1064 /* Room path final mix buffer and panning */
1065 for(i = 0;i < MAX_SENDS;i++)
1067 outsamp = lpFilter2P(WetFilter[i], 0, value);
1068 WetBuffer[i][j] += outsamp*WetSend[i];
1071 DataPosFrac += increment;
1072 k += DataPosFrac>>FRACTIONBITS;
1073 DataPosFrac &= FRACTIONMASK;
1074 j++;
1077 else if(Channels == 2) /* Stereo */
1079 const int chans[] = {
1080 FRONT_LEFT, FRONT_RIGHT
1082 const ALfloat scaler = aluSqrt(1.0f/Channels);
1084 #define DO_MIX() do { \
1085 while(BufferSize--) \
1087 for(i = 0;i < OUTPUTCHANNELS;i++) \
1088 DrySend[i] += dryGainStep[i]; \
1089 for(i = 0;i < MAX_SENDS;i++) \
1090 WetSend[i] += wetGainStep[i]; \
1092 for(i = 0;i < Channels;i++) \
1094 value = lerp(Data[k*Channels + i], Data[(k+1)*Channels + i], DataPosFrac); \
1095 outsamp = lpFilter2P(DryFilter, chans[i]*2, value)*DrySend[chans[i]]; \
1096 for(out = 0;out < OUTPUTCHANNELS;out++) \
1097 DryBuffer[j][out] += outsamp*Matrix[chans[i]][out]; \
1098 for(out = 0;out < MAX_SENDS;out++) \
1100 outsamp = lpFilter1P(WetFilter[out], chans[out], value); \
1101 WetBuffer[out][j] += outsamp*WetSend[out]*scaler; \
1105 DataPosFrac += increment; \
1106 k += DataPosFrac>>FRACTIONBITS; \
1107 DataPosFrac &= FRACTIONMASK; \
1108 j++; \
1110 } while(0)
1112 DO_MIX();
1114 else if(Channels == 4) /* Quad */
1116 const int chans[] = {
1117 FRONT_LEFT, FRONT_RIGHT,
1118 BACK_LEFT, BACK_RIGHT
1120 const ALfloat scaler = aluSqrt(1.0f/Channels);
1122 DO_MIX();
1124 else if(Channels == 6) /* 5.1 */
1126 const int chans[] = {
1127 FRONT_LEFT, FRONT_RIGHT,
1128 FRONT_CENTER, LFE,
1129 BACK_LEFT, BACK_RIGHT
1131 const ALfloat scaler = aluSqrt(1.0f/Channels);
1133 DO_MIX();
1135 else if(Channels == 7) /* 6.1 */
1137 const int chans[] = {
1138 FRONT_LEFT, FRONT_RIGHT,
1139 FRONT_CENTER, LFE,
1140 BACK_CENTER,
1141 SIDE_LEFT, SIDE_RIGHT
1143 const ALfloat scaler = aluSqrt(1.0f/Channels);
1145 DO_MIX();
1147 else if(Channels == 8) /* 7.1 */
1149 const int chans[] = {
1150 FRONT_LEFT, FRONT_RIGHT,
1151 FRONT_CENTER, LFE,
1152 BACK_LEFT, BACK_RIGHT,
1153 SIDE_LEFT, SIDE_RIGHT
1155 const ALfloat scaler = aluSqrt(1.0f/Channels);
1157 DO_MIX();
1158 #undef DO_MIX
1160 else /* Unknown? */
1162 for(i = 0;i < OUTPUTCHANNELS;i++)
1163 DrySend[i] += dryGainStep[i]*BufferSize;
1164 for(i = 0;i < MAX_SENDS;i++)
1165 WetSend[i] += wetGainStep[i]*BufferSize;
1166 while(BufferSize--)
1168 DataPosFrac += increment;
1169 k += DataPosFrac>>FRACTIONBITS;
1170 DataPosFrac &= FRACTIONMASK;
1171 j++;
1174 DataPosInt += k;
1176 skipmix:
1177 /* Handle looping sources */
1178 if(DataPosInt >= DataSize)
1180 if(BuffersPlayed < (ALSource->BuffersInQueue-1))
1182 BufferListItem = BufferListItem->next;
1183 BuffersPlayed++;
1184 DataPosInt -= DataSize;
1186 else
1188 if(!ALSource->bLooping)
1190 State = AL_STOPPED;
1191 BufferListItem = ALSource->queue;
1192 BuffersPlayed = ALSource->BuffersInQueue;
1193 DataPosInt = 0;
1194 DataPosFrac = 0;
1196 else
1198 BufferListItem = ALSource->queue;
1199 BuffersPlayed = 0;
1200 if(ALSource->BuffersInQueue == 1)
1201 DataPosInt %= DataSize;
1202 else
1203 DataPosInt -= DataSize;
1209 /* Update source info */
1210 ALSource->state = State;
1211 ALSource->BuffersPlayed = BuffersPlayed;
1212 ALSource->position = DataPosInt;
1213 ALSource->position_fraction = DataPosFrac;
1214 ALSource->Buffer = BufferListItem->buffer;
1216 for(i = 0;i < OUTPUTCHANNELS;i++)
1217 ALSource->DryGains[i] = DrySend[i];
1218 for(i = 0;i < MAX_SENDS;i++)
1219 ALSource->WetGains[i] = WetSend[i];
1221 ALSource->FirstStart = AL_FALSE;
1223 if((ALSource=ALSource->next) != NULL)
1224 goto another_source;
1227 ALvoid aluMixData(ALCdevice *device, ALvoid *buffer, ALsizei size)
1229 float (*DryBuffer)[OUTPUTCHANNELS];
1230 ALuint SamplesToDo;
1231 ALeffectslot *ALEffectSlot;
1232 ALCcontext *ALContext;
1233 int fpuState;
1234 ALuint i, c;
1236 SuspendContext(NULL);
1238 #if defined(HAVE_FESETROUND)
1239 fpuState = fegetround();
1240 fesetround(FE_TOWARDZERO);
1241 #elif defined(HAVE__CONTROLFP)
1242 fpuState = _controlfp(0, 0);
1243 _controlfp(_RC_CHOP, _MCW_RC);
1244 #else
1245 (void)fpuState;
1246 #endif
1248 DryBuffer = device->DryBuffer;
1249 while(size > 0)
1251 /* Setup variables */
1252 SamplesToDo = min(size, BUFFERSIZE);
1254 /* Clear mixing buffer */
1255 memset(DryBuffer, 0, SamplesToDo*OUTPUTCHANNELS*sizeof(ALfloat));
1257 for(c = 0;c < device->NumContexts;c++)
1259 ALContext = device->Contexts[c];
1260 SuspendContext(ALContext);
1262 MixSomeSources(ALContext, DryBuffer, SamplesToDo);
1264 /* effect slot processing */
1265 ALEffectSlot = ALContext->AuxiliaryEffectSlot;
1266 while(ALEffectSlot)
1268 if(ALEffectSlot->EffectState)
1269 ALEffect_Process(ALEffectSlot->EffectState, ALEffectSlot, SamplesToDo, ALEffectSlot->WetBuffer, DryBuffer);
1271 for(i = 0;i < SamplesToDo;i++)
1272 ALEffectSlot->WetBuffer[i] = 0.0f;
1273 ALEffectSlot = ALEffectSlot->next;
1275 ProcessContext(ALContext);
1278 //Post processing loop
1279 switch(device->Format)
1281 #define CHECK_WRITE_FORMAT(bits, type, func, isWin) \
1282 case AL_FORMAT_MONO##bits: \
1283 for(i = 0;i < SamplesToDo;i++) \
1285 ((type*)buffer)[0] = (func)(DryBuffer[i][FRONT_LEFT] + \
1286 DryBuffer[i][FRONT_RIGHT]); \
1287 buffer = ((type*)buffer) + 1; \
1289 break; \
1290 case AL_FORMAT_STEREO##bits: \
1291 if(device->Bs2b) \
1293 for(i = 0;i < SamplesToDo;i++) \
1295 float samples[2]; \
1296 samples[0] = DryBuffer[i][FRONT_LEFT]; \
1297 samples[1] = DryBuffer[i][FRONT_RIGHT]; \
1298 bs2b_cross_feed(device->Bs2b, samples); \
1299 ((type*)buffer)[0] = (func)(samples[0]); \
1300 ((type*)buffer)[1] = (func)(samples[1]); \
1301 buffer = ((type*)buffer) + 2; \
1304 else \
1306 for(i = 0;i < SamplesToDo;i++) \
1308 ((type*)buffer)[0] = (func)(DryBuffer[i][FRONT_LEFT]); \
1309 ((type*)buffer)[1] = (func)(DryBuffer[i][FRONT_RIGHT]); \
1310 buffer = ((type*)buffer) + 2; \
1313 break; \
1314 case AL_FORMAT_QUAD##bits: \
1315 for(i = 0;i < SamplesToDo;i++) \
1317 ((type*)buffer)[0] = (func)(DryBuffer[i][FRONT_LEFT]); \
1318 ((type*)buffer)[1] = (func)(DryBuffer[i][FRONT_RIGHT]); \
1319 ((type*)buffer)[2] = (func)(DryBuffer[i][BACK_LEFT]); \
1320 ((type*)buffer)[3] = (func)(DryBuffer[i][BACK_RIGHT]); \
1321 buffer = ((type*)buffer) + 4; \
1323 break; \
1324 case AL_FORMAT_51CHN##bits: \
1325 for(i = 0;i < SamplesToDo;i++) \
1327 ((type*)buffer)[0] = (func)(DryBuffer[i][FRONT_LEFT]); \
1328 ((type*)buffer)[1] = (func)(DryBuffer[i][FRONT_RIGHT]); \
1329 if(isWin) { \
1330 /* Of course, Windows can't use the same ordering... */ \
1331 ((type*)buffer)[2] = (func)(DryBuffer[i][FRONT_CENTER]); \
1332 ((type*)buffer)[3] = (func)(DryBuffer[i][LFE]); \
1333 ((type*)buffer)[4] = (func)(DryBuffer[i][BACK_LEFT]); \
1334 ((type*)buffer)[5] = (func)(DryBuffer[i][BACK_RIGHT]); \
1335 } else { \
1336 ((type*)buffer)[2] = (func)(DryBuffer[i][BACK_LEFT]); \
1337 ((type*)buffer)[3] = (func)(DryBuffer[i][BACK_RIGHT]); \
1338 ((type*)buffer)[4] = (func)(DryBuffer[i][FRONT_CENTER]); \
1339 ((type*)buffer)[5] = (func)(DryBuffer[i][LFE]); \
1341 buffer = ((type*)buffer) + 6; \
1343 break; \
1344 case AL_FORMAT_61CHN##bits: \
1345 for(i = 0;i < SamplesToDo;i++) \
1347 ((type*)buffer)[0] = (func)(DryBuffer[i][FRONT_LEFT]); \
1348 ((type*)buffer)[1] = (func)(DryBuffer[i][FRONT_RIGHT]); \
1349 ((type*)buffer)[2] = (func)(DryBuffer[i][FRONT_CENTER]); \
1350 ((type*)buffer)[3] = (func)(DryBuffer[i][LFE]); \
1351 ((type*)buffer)[4] = (func)(DryBuffer[i][BACK_CENTER]); \
1352 ((type*)buffer)[5] = (func)(DryBuffer[i][SIDE_LEFT]); \
1353 ((type*)buffer)[6] = (func)(DryBuffer[i][SIDE_RIGHT]); \
1354 buffer = ((type*)buffer) + 7; \
1356 break; \
1357 case AL_FORMAT_71CHN##bits: \
1358 for(i = 0;i < SamplesToDo;i++) \
1360 ((type*)buffer)[0] = (func)(DryBuffer[i][FRONT_LEFT]); \
1361 ((type*)buffer)[1] = (func)(DryBuffer[i][FRONT_RIGHT]); \
1362 if(isWin) { \
1363 ((type*)buffer)[2] = (func)(DryBuffer[i][FRONT_CENTER]); \
1364 ((type*)buffer)[3] = (func)(DryBuffer[i][LFE]); \
1365 ((type*)buffer)[4] = (func)(DryBuffer[i][BACK_LEFT]); \
1366 ((type*)buffer)[5] = (func)(DryBuffer[i][BACK_RIGHT]); \
1367 } else { \
1368 ((type*)buffer)[2] = (func)(DryBuffer[i][BACK_LEFT]); \
1369 ((type*)buffer)[3] = (func)(DryBuffer[i][BACK_RIGHT]); \
1370 ((type*)buffer)[4] = (func)(DryBuffer[i][FRONT_CENTER]); \
1371 ((type*)buffer)[5] = (func)(DryBuffer[i][LFE]); \
1373 ((type*)buffer)[6] = (func)(DryBuffer[i][SIDE_LEFT]); \
1374 ((type*)buffer)[7] = (func)(DryBuffer[i][SIDE_RIGHT]); \
1375 buffer = ((type*)buffer) + 8; \
1377 break;
1379 #define AL_FORMAT_MONO32 AL_FORMAT_MONO_FLOAT32
1380 #define AL_FORMAT_STEREO32 AL_FORMAT_STEREO_FLOAT32
1381 #ifdef _WIN32
1382 CHECK_WRITE_FORMAT(8, ALubyte, aluF2UB, 1)
1383 CHECK_WRITE_FORMAT(16, ALshort, aluF2S, 1)
1384 CHECK_WRITE_FORMAT(32, ALfloat, aluF2F, 1)
1385 #else
1386 CHECK_WRITE_FORMAT(8, ALubyte, aluF2UB, 0)
1387 CHECK_WRITE_FORMAT(16, ALshort, aluF2S, 0)
1388 CHECK_WRITE_FORMAT(32, ALfloat, aluF2F, 0)
1389 #endif
1390 #undef AL_FORMAT_STEREO32
1391 #undef AL_FORMAT_MONO32
1392 #undef CHECK_WRITE_FORMAT
1394 default:
1395 break;
1398 size -= SamplesToDo;
1401 #if defined(HAVE_FESETROUND)
1402 fesetround(fpuState);
1403 #elif defined(HAVE__CONTROLFP)
1404 _controlfp(fpuState, 0xfffff);
1405 #endif
1407 ProcessContext(NULL);
1410 ALvoid aluHandleDisconnect(ALCdevice *device)
1412 ALuint i;
1414 SuspendContext(NULL);
1415 for(i = 0;i < device->NumContexts;i++)
1417 ALsource *source;
1419 SuspendContext(device->Contexts[i]);
1421 source = device->Contexts[i]->Source;
1422 while(source)
1424 if(source->state == AL_PLAYING)
1426 source->state = AL_STOPPED;
1427 source->BuffersPlayed = source->BuffersInQueue;
1428 source->position = 0;
1429 source->position_fraction = 0;
1431 source = source->next;
1433 ProcessContext(device->Contexts[i]);
1436 device->Connected = ALC_FALSE;
1437 ProcessContext(NULL);