Internally store 32-bit float buffer data, and mix accordingly
[openal-soft.git] / Alc / ALu.c
blob22531d130cfe55456d9b250b694626e11256e0ce
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 return Value;
67 static __inline ALshort aluF2S(ALfloat Value)
69 ALint i;
71 if(Value < 0.0f)
73 i = (ALint)(Value*32768.0f);
74 i = max(-32768, i);
76 else
78 i = (ALint)(Value*32767.0f);
79 i = min( 32767, i);
81 return ((ALshort)i);
84 static __inline ALubyte aluF2UB(ALfloat Value)
86 ALshort i = aluF2S(Value);
87 return (i>>8)+128;
91 static __inline ALvoid aluCrossproduct(const ALfloat *inVector1, const ALfloat *inVector2, ALfloat *outVector)
93 outVector[0] = inVector1[1]*inVector2[2] - inVector1[2]*inVector2[1];
94 outVector[1] = inVector1[2]*inVector2[0] - inVector1[0]*inVector2[2];
95 outVector[2] = inVector1[0]*inVector2[1] - inVector1[1]*inVector2[0];
98 static __inline ALfloat aluDotproduct(const ALfloat *inVector1, const ALfloat *inVector2)
100 return inVector1[0]*inVector2[0] + inVector1[1]*inVector2[1] +
101 inVector1[2]*inVector2[2];
104 static __inline ALvoid aluNormalize(ALfloat *inVector)
106 ALfloat length, inverse_length;
108 length = aluSqrt(aluDotproduct(inVector, inVector));
109 if(length != 0.0f)
111 inverse_length = 1.0f/length;
112 inVector[0] *= inverse_length;
113 inVector[1] *= inverse_length;
114 inVector[2] *= inverse_length;
118 static __inline ALvoid aluMatrixVector(ALfloat *vector,ALfloat w,ALfloat matrix[4][4])
120 ALfloat temp[4] = {
121 vector[0], vector[1], vector[2], w
124 vector[0] = temp[0]*matrix[0][0] + temp[1]*matrix[1][0] + temp[2]*matrix[2][0] + temp[3]*matrix[3][0];
125 vector[1] = temp[0]*matrix[0][1] + temp[1]*matrix[1][1] + temp[2]*matrix[2][1] + temp[3]*matrix[3][1];
126 vector[2] = temp[0]*matrix[0][2] + temp[1]*matrix[1][2] + temp[2]*matrix[2][2] + temp[3]*matrix[3][2];
129 static ALvoid SetSpeakerArrangement(const char *name, ALfloat SpeakerAngle[OUTPUTCHANNELS],
130 ALint Speaker2Chan[OUTPUTCHANNELS], ALint chans)
132 const char *confkey;
133 const char *next;
134 const char *sep;
135 const char *end;
136 int i, val;
138 confkey = GetConfigValue(NULL, name, "");
139 next = confkey;
140 while(next && *next)
142 confkey = next;
143 next = strchr(confkey, ',');
144 if(next)
146 do {
147 next++;
148 } while(isspace(*next));
151 sep = strchr(confkey, '=');
152 if(!sep || confkey == sep)
153 continue;
155 end = sep - 1;
156 while(isspace(*end) && end != confkey)
157 end--;
158 end++;
160 if(strncmp(confkey, "fl", end-confkey) == 0)
161 val = FRONT_LEFT;
162 else if(strncmp(confkey, "fr", end-confkey) == 0)
163 val = FRONT_RIGHT;
164 else if(strncmp(confkey, "fc", end-confkey) == 0)
165 val = FRONT_CENTER;
166 else if(strncmp(confkey, "bl", end-confkey) == 0)
167 val = BACK_LEFT;
168 else if(strncmp(confkey, "br", end-confkey) == 0)
169 val = BACK_RIGHT;
170 else if(strncmp(confkey, "bc", end-confkey) == 0)
171 val = BACK_CENTER;
172 else if(strncmp(confkey, "sl", end-confkey) == 0)
173 val = SIDE_LEFT;
174 else if(strncmp(confkey, "sr", end-confkey) == 0)
175 val = SIDE_RIGHT;
176 else
178 AL_PRINT("Unknown speaker for %s: \"%c%c\"\n", name, confkey[0], confkey[1]);
179 continue;
182 sep++;
183 while(isspace(*sep))
184 sep++;
186 for(i = 0;i < chans;i++)
188 if(Speaker2Chan[i] == val)
190 val = strtol(sep, NULL, 10);
191 if(val >= -180 && val <= 180)
192 SpeakerAngle[i] = val * M_PI/180.0f;
193 else
194 AL_PRINT("Invalid angle for speaker \"%c%c\": %d\n", confkey[0], confkey[1], val);
195 break;
200 for(i = 1;i < chans;i++)
202 if(SpeakerAngle[i] <= SpeakerAngle[i-1])
204 AL_PRINT("Speaker %d of %d does not follow previous: %f > %f\n", i, chans,
205 SpeakerAngle[i-1] * 180.0f/M_PI, SpeakerAngle[i] * 180.0f/M_PI);
206 SpeakerAngle[i] = SpeakerAngle[i-1] + 1 * 180.0f/M_PI;
211 static __inline ALfloat aluLUTpos2Angle(ALint pos)
213 if(pos < QUADRANT_NUM)
214 return aluAtan((ALfloat)pos / (ALfloat)(QUADRANT_NUM - pos));
215 if(pos < 2 * QUADRANT_NUM)
216 return M_PI_2 + aluAtan((ALfloat)(pos - QUADRANT_NUM) / (ALfloat)(2 * QUADRANT_NUM - pos));
217 if(pos < 3 * QUADRANT_NUM)
218 return aluAtan((ALfloat)(pos - 2 * QUADRANT_NUM) / (ALfloat)(3 * QUADRANT_NUM - pos)) - M_PI;
219 return aluAtan((ALfloat)(pos - 3 * QUADRANT_NUM) / (ALfloat)(4 * QUADRANT_NUM - pos)) - M_PI_2;
222 ALvoid aluInitPanning(ALCcontext *Context)
224 ALint pos, offset, s;
225 ALfloat Alpha, Theta;
226 ALfloat SpeakerAngle[OUTPUTCHANNELS];
227 ALint Speaker2Chan[OUTPUTCHANNELS];
229 for(s = 0;s < OUTPUTCHANNELS;s++)
231 int s2;
232 for(s2 = 0;s2 < OUTPUTCHANNELS;s2++)
233 Context->ChannelMatrix[s][s2] = ((s==s2) ? 1.0f : 0.0f);
236 switch(Context->Device->Format)
238 /* Mono is rendered as stereo, then downmixed during post-process */
239 case AL_FORMAT_MONO8:
240 case AL_FORMAT_MONO16:
241 case AL_FORMAT_MONO_FLOAT32:
242 Context->ChannelMatrix[FRONT_CENTER][FRONT_LEFT] = aluSqrt(0.5);
243 Context->ChannelMatrix[FRONT_CENTER][FRONT_RIGHT] = aluSqrt(0.5);
244 Context->ChannelMatrix[SIDE_LEFT][FRONT_LEFT] = 1.0f;
245 Context->ChannelMatrix[SIDE_RIGHT][FRONT_RIGHT] = 1.0f;
246 Context->ChannelMatrix[BACK_LEFT][FRONT_LEFT] = 1.0f;
247 Context->ChannelMatrix[BACK_RIGHT][FRONT_RIGHT] = 1.0f;
248 Context->ChannelMatrix[BACK_CENTER][FRONT_LEFT] = aluSqrt(0.5);
249 Context->ChannelMatrix[BACK_CENTER][FRONT_RIGHT] = aluSqrt(0.5);
250 Context->NumChan = 2;
251 Speaker2Chan[0] = FRONT_LEFT;
252 Speaker2Chan[1] = FRONT_RIGHT;
253 SpeakerAngle[0] = -90.0f * M_PI/180.0f;
254 SpeakerAngle[1] = 90.0f * M_PI/180.0f;
255 break;
257 case AL_FORMAT_STEREO8:
258 case AL_FORMAT_STEREO16:
259 case AL_FORMAT_STEREO_FLOAT32:
260 Context->ChannelMatrix[FRONT_CENTER][FRONT_LEFT] = aluSqrt(0.5);
261 Context->ChannelMatrix[FRONT_CENTER][FRONT_RIGHT] = aluSqrt(0.5);
262 Context->ChannelMatrix[SIDE_LEFT][FRONT_LEFT] = 1.0f;
263 Context->ChannelMatrix[SIDE_RIGHT][FRONT_RIGHT] = 1.0f;
264 Context->ChannelMatrix[BACK_LEFT][FRONT_LEFT] = 1.0f;
265 Context->ChannelMatrix[BACK_RIGHT][FRONT_RIGHT] = 1.0f;
266 Context->ChannelMatrix[BACK_CENTER][FRONT_LEFT] = aluSqrt(0.5);
267 Context->ChannelMatrix[BACK_CENTER][FRONT_RIGHT] = aluSqrt(0.5);
268 Context->NumChan = 2;
269 Speaker2Chan[0] = FRONT_LEFT;
270 Speaker2Chan[1] = FRONT_RIGHT;
271 SpeakerAngle[0] = -90.0f * M_PI/180.0f;
272 SpeakerAngle[1] = 90.0f * M_PI/180.0f;
273 SetSpeakerArrangement("layout_STEREO", SpeakerAngle, Speaker2Chan, Context->NumChan);
274 break;
276 case AL_FORMAT_QUAD8:
277 case AL_FORMAT_QUAD16:
278 case AL_FORMAT_QUAD32:
279 Context->ChannelMatrix[FRONT_CENTER][FRONT_LEFT] = aluSqrt(0.5);
280 Context->ChannelMatrix[FRONT_CENTER][FRONT_RIGHT] = aluSqrt(0.5);
281 Context->ChannelMatrix[SIDE_LEFT][FRONT_LEFT] = aluSqrt(0.5);
282 Context->ChannelMatrix[SIDE_LEFT][BACK_LEFT] = aluSqrt(0.5);
283 Context->ChannelMatrix[SIDE_RIGHT][FRONT_RIGHT] = aluSqrt(0.5);
284 Context->ChannelMatrix[SIDE_RIGHT][BACK_RIGHT] = aluSqrt(0.5);
285 Context->ChannelMatrix[BACK_CENTER][BACK_LEFT] = aluSqrt(0.5);
286 Context->ChannelMatrix[BACK_CENTER][BACK_RIGHT] = aluSqrt(0.5);
287 Context->NumChan = 4;
288 Speaker2Chan[0] = BACK_LEFT;
289 Speaker2Chan[1] = FRONT_LEFT;
290 Speaker2Chan[2] = FRONT_RIGHT;
291 Speaker2Chan[3] = BACK_RIGHT;
292 SpeakerAngle[0] = -135.0f * M_PI/180.0f;
293 SpeakerAngle[1] = -45.0f * M_PI/180.0f;
294 SpeakerAngle[2] = 45.0f * M_PI/180.0f;
295 SpeakerAngle[3] = 135.0f * M_PI/180.0f;
296 SetSpeakerArrangement("layout_QUAD", SpeakerAngle, Speaker2Chan, Context->NumChan);
297 break;
299 case AL_FORMAT_51CHN8:
300 case AL_FORMAT_51CHN16:
301 case AL_FORMAT_51CHN32:
302 Context->ChannelMatrix[SIDE_LEFT][FRONT_LEFT] = aluSqrt(0.5);
303 Context->ChannelMatrix[SIDE_LEFT][BACK_LEFT] = aluSqrt(0.5);
304 Context->ChannelMatrix[SIDE_RIGHT][FRONT_RIGHT] = aluSqrt(0.5);
305 Context->ChannelMatrix[SIDE_RIGHT][BACK_RIGHT] = aluSqrt(0.5);
306 Context->ChannelMatrix[BACK_CENTER][BACK_LEFT] = aluSqrt(0.5);
307 Context->ChannelMatrix[BACK_CENTER][BACK_RIGHT] = aluSqrt(0.5);
308 Context->NumChan = 5;
309 Speaker2Chan[0] = BACK_LEFT;
310 Speaker2Chan[1] = FRONT_LEFT;
311 Speaker2Chan[2] = FRONT_CENTER;
312 Speaker2Chan[3] = FRONT_RIGHT;
313 Speaker2Chan[4] = BACK_RIGHT;
314 SpeakerAngle[0] = -110.0f * M_PI/180.0f;
315 SpeakerAngle[1] = -30.0f * M_PI/180.0f;
316 SpeakerAngle[2] = 0.0f * M_PI/180.0f;
317 SpeakerAngle[3] = 30.0f * M_PI/180.0f;
318 SpeakerAngle[4] = 110.0f * M_PI/180.0f;
319 SetSpeakerArrangement("layout_51CHN", SpeakerAngle, Speaker2Chan, Context->NumChan);
320 break;
322 case AL_FORMAT_61CHN8:
323 case AL_FORMAT_61CHN16:
324 case AL_FORMAT_61CHN32:
325 Context->ChannelMatrix[BACK_LEFT][BACK_CENTER] = aluSqrt(0.5);
326 Context->ChannelMatrix[BACK_LEFT][SIDE_LEFT] = aluSqrt(0.5);
327 Context->ChannelMatrix[BACK_RIGHT][BACK_CENTER] = aluSqrt(0.5);
328 Context->ChannelMatrix[BACK_RIGHT][SIDE_RIGHT] = aluSqrt(0.5);
329 Context->NumChan = 6;
330 Speaker2Chan[0] = SIDE_LEFT;
331 Speaker2Chan[1] = FRONT_LEFT;
332 Speaker2Chan[2] = FRONT_CENTER;
333 Speaker2Chan[3] = FRONT_RIGHT;
334 Speaker2Chan[4] = SIDE_RIGHT;
335 Speaker2Chan[5] = BACK_CENTER;
336 SpeakerAngle[0] = -90.0f * M_PI/180.0f;
337 SpeakerAngle[1] = -30.0f * M_PI/180.0f;
338 SpeakerAngle[2] = 0.0f * M_PI/180.0f;
339 SpeakerAngle[3] = 30.0f * M_PI/180.0f;
340 SpeakerAngle[4] = 90.0f * M_PI/180.0f;
341 SpeakerAngle[5] = 180.0f * M_PI/180.0f;
342 SetSpeakerArrangement("layout_61CHN", SpeakerAngle, Speaker2Chan, Context->NumChan);
343 break;
345 case AL_FORMAT_71CHN8:
346 case AL_FORMAT_71CHN16:
347 case AL_FORMAT_71CHN32:
348 Context->ChannelMatrix[BACK_CENTER][BACK_LEFT] = aluSqrt(0.5);
349 Context->ChannelMatrix[BACK_CENTER][BACK_RIGHT] = aluSqrt(0.5);
350 Context->NumChan = 7;
351 Speaker2Chan[0] = BACK_LEFT;
352 Speaker2Chan[1] = SIDE_LEFT;
353 Speaker2Chan[2] = FRONT_LEFT;
354 Speaker2Chan[3] = FRONT_CENTER;
355 Speaker2Chan[4] = FRONT_RIGHT;
356 Speaker2Chan[5] = SIDE_RIGHT;
357 Speaker2Chan[6] = BACK_RIGHT;
358 SpeakerAngle[0] = -150.0f * M_PI/180.0f;
359 SpeakerAngle[1] = -90.0f * M_PI/180.0f;
360 SpeakerAngle[2] = -30.0f * M_PI/180.0f;
361 SpeakerAngle[3] = 0.0f * M_PI/180.0f;
362 SpeakerAngle[4] = 30.0f * M_PI/180.0f;
363 SpeakerAngle[5] = 90.0f * M_PI/180.0f;
364 SpeakerAngle[6] = 150.0f * M_PI/180.0f;
365 SetSpeakerArrangement("layout_71CHN", SpeakerAngle, Speaker2Chan, Context->NumChan);
366 break;
368 default:
369 assert(0);
372 for(pos = 0; pos < LUT_NUM; pos++)
374 /* source angle */
375 Theta = aluLUTpos2Angle(pos);
377 /* clear all values */
378 offset = OUTPUTCHANNELS * pos;
379 for(s = 0; s < OUTPUTCHANNELS; s++)
380 Context->PanningLUT[offset+s] = 0.0f;
382 /* set panning values */
383 for(s = 0; s < Context->NumChan - 1; s++)
385 if(Theta >= SpeakerAngle[s] && Theta < SpeakerAngle[s+1])
387 /* source between speaker s and speaker s+1 */
388 Alpha = M_PI_2 * (Theta-SpeakerAngle[s]) /
389 (SpeakerAngle[s+1]-SpeakerAngle[s]);
390 Context->PanningLUT[offset + Speaker2Chan[s]] = cos(Alpha);
391 Context->PanningLUT[offset + Speaker2Chan[s+1]] = sin(Alpha);
392 break;
395 if(s == Context->NumChan - 1)
397 /* source between last and first speaker */
398 if(Theta < SpeakerAngle[0])
399 Theta += 2.0f * M_PI;
400 Alpha = M_PI_2 * (Theta-SpeakerAngle[s]) /
401 (2.0f * M_PI + SpeakerAngle[0]-SpeakerAngle[s]);
402 Context->PanningLUT[offset + Speaker2Chan[s]] = cos(Alpha);
403 Context->PanningLUT[offset + Speaker2Chan[0]] = sin(Alpha);
408 static ALvoid CalcSourceParams(const ALCcontext *ALContext, ALsource *ALSource,
409 ALboolean isMono)
411 ALfloat InnerAngle,OuterAngle,Angle,Distance,DryMix;
412 ALfloat Direction[3],Position[3],SourceToListener[3];
413 ALfloat Velocity[3],ListenerVel[3];
414 ALfloat MinVolume,MaxVolume,MinDist,MaxDist,Rolloff,OuterGainHF;
415 ALfloat ConeVolume,ConeHF,SourceVolume,ListenerGain;
416 ALfloat DopplerFactor, DopplerVelocity, flSpeedOfSound;
417 ALfloat Matrix[4][4];
418 ALfloat flAttenuation;
419 ALfloat RoomAttenuation[MAX_SENDS];
420 ALfloat MetersPerUnit;
421 ALfloat RoomRolloff[MAX_SENDS];
422 ALfloat DryGainHF = 1.0f;
423 ALfloat WetGain[MAX_SENDS];
424 ALfloat WetGainHF[MAX_SENDS];
425 ALfloat DirGain, AmbientGain;
426 ALfloat length;
427 const ALfloat *SpeakerGain;
428 ALuint Frequency;
429 ALint NumSends;
430 ALint pos, s, i;
431 ALfloat cw, a, g;
433 for(i = 0;i < MAX_SENDS;i++)
434 WetGainHF[i] = 1.0f;
436 //Get context properties
437 DopplerFactor = ALContext->DopplerFactor * ALSource->DopplerFactor;
438 DopplerVelocity = ALContext->DopplerVelocity;
439 flSpeedOfSound = ALContext->flSpeedOfSound;
440 NumSends = ALContext->Device->NumAuxSends;
441 Frequency = ALContext->Device->Frequency;
443 //Get listener properties
444 ListenerGain = ALContext->Listener.Gain;
445 MetersPerUnit = ALContext->Listener.MetersPerUnit;
446 memcpy(ListenerVel, ALContext->Listener.Velocity, sizeof(ALContext->Listener.Velocity));
448 //Get source properties
449 SourceVolume = ALSource->flGain;
450 memcpy(Position, ALSource->vPosition, sizeof(ALSource->vPosition));
451 memcpy(Direction, ALSource->vOrientation, sizeof(ALSource->vOrientation));
452 memcpy(Velocity, ALSource->vVelocity, sizeof(ALSource->vVelocity));
453 MinVolume = ALSource->flMinGain;
454 MaxVolume = ALSource->flMaxGain;
455 MinDist = ALSource->flRefDistance;
456 MaxDist = ALSource->flMaxDistance;
457 Rolloff = ALSource->flRollOffFactor;
458 InnerAngle = ALSource->flInnerAngle;
459 OuterAngle = ALSource->flOuterAngle;
460 OuterGainHF = ALSource->OuterGainHF;
462 //Only apply 3D calculations for mono buffers
463 if(isMono == AL_FALSE)
465 //1. Multi-channel buffers always play "normal"
466 ALSource->Params.Pitch = ALSource->flPitch;
468 DryMix = SourceVolume;
469 DryMix = __min(DryMix,MaxVolume);
470 DryMix = __max(DryMix,MinVolume);
472 switch(ALSource->DirectFilter.type)
474 case AL_FILTER_LOWPASS:
475 DryMix *= ALSource->DirectFilter.Gain;
476 DryGainHF *= ALSource->DirectFilter.GainHF;
477 break;
480 ALSource->Params.DryGains[FRONT_LEFT] = DryMix * ListenerGain;
481 ALSource->Params.DryGains[FRONT_RIGHT] = DryMix * ListenerGain;
482 ALSource->Params.DryGains[SIDE_LEFT] = DryMix * ListenerGain;
483 ALSource->Params.DryGains[SIDE_RIGHT] = DryMix * ListenerGain;
484 ALSource->Params.DryGains[BACK_LEFT] = DryMix * ListenerGain;
485 ALSource->Params.DryGains[BACK_RIGHT] = DryMix * ListenerGain;
486 ALSource->Params.DryGains[FRONT_CENTER] = DryMix * ListenerGain;
487 ALSource->Params.DryGains[BACK_CENTER] = DryMix * ListenerGain;
488 ALSource->Params.DryGains[LFE] = DryMix * ListenerGain;
490 for(i = 0;i < NumSends;i++)
492 WetGain[i] = SourceVolume;
493 WetGain[i] = __min(WetGain[i],MaxVolume);
494 WetGain[i] = __max(WetGain[i],MinVolume);
495 WetGainHF[i] = 1.0f;
497 switch(ALSource->Send[i].WetFilter.type)
499 case AL_FILTER_LOWPASS:
500 WetGain[i] *= ALSource->Send[i].WetFilter.Gain;
501 WetGainHF[i] *= ALSource->Send[i].WetFilter.GainHF;
502 break;
505 ALSource->Params.WetGains[i] = WetGain[i] * ListenerGain;
507 for(i = NumSends;i < MAX_SENDS;i++)
509 ALSource->Params.WetGains[i] = 0.0f;
510 WetGainHF[i] = 1.0f;
513 /* Update filter coefficients. Calculations based on the I3DL2
514 * spec. */
515 cw = cos(2.0*M_PI * LOWPASSFREQCUTOFF / Frequency);
516 /* We use two chained one-pole filters, so we need to take the
517 * square root of the squared gain, which is the same as the base
518 * gain. */
519 g = __max(DryGainHF, 0.01f);
520 a = 0.0f;
521 /* Be careful with gains < 0.0001, as that causes the coefficient
522 * head towards 1, which will flatten the signal */
523 if(g < 0.9999f) /* 1-epsilon */
524 a = (1 - g*cw - aluSqrt(2*g*(1-cw) - g*g*(1 - cw*cw))) /
525 (1 - g);
526 ALSource->Params.iirFilter.coeff = a;
528 for(i = 0;i < NumSends;i++)
530 /* We use a one-pole filter, so we need to take the squared gain */
531 g = __max(WetGainHF[i], 0.1f);
532 g *= g;
533 a = 0.0f;
534 if(g < 0.9999f) /* 1-epsilon */
535 a = (1 - g*cw - aluSqrt(2*g*(1-cw) - g*g*(1 - cw*cw))) /
536 (1 - g);
537 ALSource->Params.Send[i].iirFilter.coeff = a;
540 return;
543 //1. Translate Listener to origin (convert to head relative)
544 if(ALSource->bHeadRelative==AL_FALSE)
546 ALfloat U[3],V[3],N[3],P[3];
548 // Build transform matrix
549 memcpy(N, ALContext->Listener.Forward, sizeof(N)); // At-vector
550 aluNormalize(N); // Normalized At-vector
551 memcpy(V, ALContext->Listener.Up, sizeof(V)); // Up-vector
552 aluNormalize(V); // Normalized Up-vector
553 aluCrossproduct(N, V, U); // Right-vector
554 aluNormalize(U); // Normalized Right-vector
555 P[0] = -(ALContext->Listener.Position[0]*U[0] + // Translation
556 ALContext->Listener.Position[1]*U[1] +
557 ALContext->Listener.Position[2]*U[2]);
558 P[1] = -(ALContext->Listener.Position[0]*V[0] +
559 ALContext->Listener.Position[1]*V[1] +
560 ALContext->Listener.Position[2]*V[2]);
561 P[2] = -(ALContext->Listener.Position[0]*-N[0] +
562 ALContext->Listener.Position[1]*-N[1] +
563 ALContext->Listener.Position[2]*-N[2]);
564 Matrix[0][0] = U[0]; Matrix[0][1] = V[0]; Matrix[0][2] = -N[0]; Matrix[0][3] = 0.0f;
565 Matrix[1][0] = U[1]; Matrix[1][1] = V[1]; Matrix[1][2] = -N[1]; Matrix[1][3] = 0.0f;
566 Matrix[2][0] = U[2]; Matrix[2][1] = V[2]; Matrix[2][2] = -N[2]; Matrix[2][3] = 0.0f;
567 Matrix[3][0] = P[0]; Matrix[3][1] = P[1]; Matrix[3][2] = P[2]; Matrix[3][3] = 1.0f;
569 // Transform source position and direction into listener space
570 aluMatrixVector(Position, 1.0f, Matrix);
571 aluMatrixVector(Direction, 0.0f, Matrix);
572 // Transform source and listener velocity into listener space
573 aluMatrixVector(Velocity, 0.0f, Matrix);
574 aluMatrixVector(ListenerVel, 0.0f, Matrix);
576 else
577 ListenerVel[0] = ListenerVel[1] = ListenerVel[2] = 0.0f;
579 SourceToListener[0] = -Position[0];
580 SourceToListener[1] = -Position[1];
581 SourceToListener[2] = -Position[2];
582 aluNormalize(SourceToListener);
583 aluNormalize(Direction);
585 //2. Calculate distance attenuation
586 Distance = aluSqrt(aluDotproduct(Position, Position));
588 flAttenuation = 1.0f;
589 for(i = 0;i < NumSends;i++)
591 RoomAttenuation[i] = 1.0f;
593 RoomRolloff[i] = ALSource->RoomRolloffFactor;
594 if(ALSource->Send[i].Slot &&
595 (ALSource->Send[i].Slot->effect.type == AL_EFFECT_REVERB ||
596 ALSource->Send[i].Slot->effect.type == AL_EFFECT_EAXREVERB))
597 RoomRolloff[i] += ALSource->Send[i].Slot->effect.Reverb.RoomRolloffFactor;
600 switch(ALContext->SourceDistanceModel ? ALSource->DistanceModel :
601 ALContext->DistanceModel)
603 case AL_INVERSE_DISTANCE_CLAMPED:
604 Distance=__max(Distance,MinDist);
605 Distance=__min(Distance,MaxDist);
606 if(MaxDist < MinDist)
607 break;
608 //fall-through
609 case AL_INVERSE_DISTANCE:
610 if(MinDist > 0.0f)
612 if((MinDist + (Rolloff * (Distance - MinDist))) > 0.0f)
613 flAttenuation = MinDist / (MinDist + (Rolloff * (Distance - MinDist)));
614 for(i = 0;i < NumSends;i++)
616 if((MinDist + (RoomRolloff[i] * (Distance - MinDist))) > 0.0f)
617 RoomAttenuation[i] = MinDist / (MinDist + (RoomRolloff[i] * (Distance - MinDist)));
620 break;
622 case AL_LINEAR_DISTANCE_CLAMPED:
623 Distance=__max(Distance,MinDist);
624 Distance=__min(Distance,MaxDist);
625 if(MaxDist < MinDist)
626 break;
627 //fall-through
628 case AL_LINEAR_DISTANCE:
629 Distance=__min(Distance,MaxDist);
630 if(MaxDist != MinDist)
632 flAttenuation = 1.0f - (Rolloff*(Distance-MinDist)/(MaxDist - MinDist));
633 for(i = 0;i < NumSends;i++)
634 RoomAttenuation[i] = 1.0f - (RoomRolloff[i]*(Distance-MinDist)/(MaxDist - MinDist));
636 break;
638 case AL_EXPONENT_DISTANCE_CLAMPED:
639 Distance=__max(Distance,MinDist);
640 Distance=__min(Distance,MaxDist);
641 if(MaxDist < MinDist)
642 break;
643 //fall-through
644 case AL_EXPONENT_DISTANCE:
645 if(Distance > 0.0f && MinDist > 0.0f)
647 flAttenuation = (ALfloat)pow(Distance/MinDist, -Rolloff);
648 for(i = 0;i < NumSends;i++)
649 RoomAttenuation[i] = (ALfloat)pow(Distance/MinDist, -RoomRolloff[i]);
651 break;
653 case AL_NONE:
654 break;
657 // Source Gain + Attenuation
658 DryMix = SourceVolume * flAttenuation;
659 for(i = 0;i < NumSends;i++)
660 WetGain[i] = SourceVolume * RoomAttenuation[i];
662 // Distance-based air absorption
663 if(ALSource->AirAbsorptionFactor > 0.0f && flAttenuation < 1.0f)
665 ALfloat absorb = 0.0f;
667 // Absorption calculation is done in dB
668 if(flAttenuation > 0.0f)
670 absorb = (MinDist/flAttenuation - MinDist)*MetersPerUnit *
671 (ALSource->AirAbsorptionFactor*AIRABSORBGAINDBHF);
672 // Convert dB to linear gain before applying
673 absorb = pow(10.0, absorb/20.0);
675 DryGainHF *= absorb;
676 for(i = 0;i < NumSends;i++)
677 WetGainHF[i] *= absorb;
680 //3. Apply directional soundcones
681 Angle = aluAcos(aluDotproduct(Direction,SourceToListener)) * 180.0f/M_PI;
682 if(Angle >= InnerAngle && Angle <= OuterAngle)
684 ALfloat scale = (Angle-InnerAngle) / (OuterAngle-InnerAngle);
685 ConeVolume = (1.0f+(ALSource->flOuterGain-1.0f)*scale);
686 ConeHF = (1.0f+(OuterGainHF-1.0f)*scale);
687 DryMix *= ConeVolume;
688 if(ALSource->DryGainHFAuto)
689 DryGainHF *= ConeHF;
691 else if(Angle > OuterAngle)
693 ConeVolume = (1.0f+(ALSource->flOuterGain-1.0f));
694 ConeHF = (1.0f+(OuterGainHF-1.0f));
695 DryMix *= ConeVolume;
696 if(ALSource->DryGainHFAuto)
697 DryGainHF *= ConeHF;
699 else
701 ConeVolume = 1.0f;
702 ConeHF = 1.0f;
705 // Clamp to Min/Max Gain
706 DryMix = __min(DryMix,MaxVolume);
707 DryMix = __max(DryMix,MinVolume);
709 for(i = 0;i < NumSends;i++)
711 if(ALSource->Send[i].Slot &&
712 ALSource->Send[i].Slot->effect.type != AL_EFFECT_NULL)
714 if(ALSource->Send[i].Slot->AuxSendAuto)
716 if(ALSource->WetGainAuto)
717 WetGain[i] *= ConeVolume;
718 if(ALSource->WetGainHFAuto)
719 WetGainHF[i] *= ConeHF;
721 // Clamp to Min/Max Gain
722 WetGain[i] = __min(WetGain[i],MaxVolume);
723 WetGain[i] = __max(WetGain[i],MinVolume);
725 if(ALSource->Send[i].Slot->effect.type == AL_EFFECT_REVERB ||
726 ALSource->Send[i].Slot->effect.type == AL_EFFECT_EAXREVERB)
728 /* Apply a decay-time transformation to the wet path,
729 * based on the attenuation of the dry path. This should
730 * better approximate the statistical attenuation model
731 * for the reverb effect.
733 * This simple equation converts the distance attenuation
734 * into the time it would take to reach -60 dB. From
735 * there it establishes an origin (0.333s; the decay time
736 * that will produce equal attenuation) and applies the
737 * current decay time. Finally, it converts the result
738 * back to an attenuation for the reverb path.
740 WetGain[i] *= pow(10.0f, log10(flAttenuation) * 0.333f /
741 ALSource->Send[i].Slot->effect.Reverb.DecayTime);
744 else
746 // If the slot's auxiliary send auto is off, the data sent to
747 // the effect slot is the same as the dry path, sans filter
748 // effects
749 WetGain[i] = DryMix;
750 WetGainHF[i] = DryGainHF;
753 switch(ALSource->Send[i].WetFilter.type)
755 case AL_FILTER_LOWPASS:
756 WetGain[i] *= ALSource->Send[i].WetFilter.Gain;
757 WetGainHF[i] *= ALSource->Send[i].WetFilter.GainHF;
758 break;
760 ALSource->Params.WetGains[i] = WetGain[i] * ListenerGain;
762 else
764 ALSource->Params.WetGains[i] = 0.0f;
765 WetGainHF[i] = 1.0f;
768 for(i = NumSends;i < MAX_SENDS;i++)
770 ALSource->Params.WetGains[i] = 0.0f;
771 WetGainHF[i] = 1.0f;
774 // Apply filter gains and filters
775 switch(ALSource->DirectFilter.type)
777 case AL_FILTER_LOWPASS:
778 DryMix *= ALSource->DirectFilter.Gain;
779 DryGainHF *= ALSource->DirectFilter.GainHF;
780 break;
782 DryMix *= ListenerGain;
784 // Calculate Velocity
785 if(DopplerFactor != 0.0f)
787 ALfloat flVSS, flVLS;
788 ALfloat flMaxVelocity = (DopplerVelocity * flSpeedOfSound) /
789 DopplerFactor;
791 flVSS = aluDotproduct(Velocity, SourceToListener);
792 if(flVSS >= flMaxVelocity)
793 flVSS = (flMaxVelocity - 1.0f);
794 else if(flVSS <= -flMaxVelocity)
795 flVSS = -flMaxVelocity + 1.0f;
797 flVLS = aluDotproduct(ListenerVel, SourceToListener);
798 if(flVLS >= flMaxVelocity)
799 flVLS = (flMaxVelocity - 1.0f);
800 else if(flVLS <= -flMaxVelocity)
801 flVLS = -flMaxVelocity + 1.0f;
803 ALSource->Params.Pitch = ALSource->flPitch *
804 ((flSpeedOfSound * DopplerVelocity) - (DopplerFactor * flVLS)) /
805 ((flSpeedOfSound * DopplerVelocity) - (DopplerFactor * flVSS));
807 else
808 ALSource->Params.Pitch = ALSource->flPitch;
810 // Use energy-preserving panning algorithm for multi-speaker playback
811 length = aluSqrt(Position[0]*Position[0] + Position[1]*Position[1] +
812 Position[2]*Position[2]);
813 length = __max(length, MinDist);
814 if(length > 0.0f)
816 ALfloat invlen = 1.0f/length;
817 Position[0] *= invlen;
818 Position[1] *= invlen;
819 Position[2] *= invlen;
822 pos = aluCart2LUTpos(-Position[2], Position[0]);
823 SpeakerGain = &ALContext->PanningLUT[OUTPUTCHANNELS * pos];
825 DirGain = aluSqrt(Position[0]*Position[0] + Position[2]*Position[2]);
826 // elevation adjustment for directional gain. this sucks, but
827 // has low complexity
828 AmbientGain = 1.0/aluSqrt(ALContext->NumChan) * (1.0-DirGain);
829 for(s = 0; s < OUTPUTCHANNELS; s++)
831 ALfloat gain = SpeakerGain[s]*DirGain + AmbientGain;
832 ALSource->Params.DryGains[s] = DryMix * gain;
835 /* Update filter coefficients. */
836 cw = cos(2.0*M_PI * LOWPASSFREQCUTOFF / Frequency);
837 /* Spatialized sources use four chained one-pole filters, so we need to
838 * take the fourth root of the squared gain, which is the same as the
839 * square root of the base gain. */
840 g = aluSqrt(__max(DryGainHF, 0.0001f));
841 a = 0.0f;
842 if(g < 0.9999f) /* 1-epsilon */
843 a = (1 - g*cw - aluSqrt(2*g*(1-cw) - g*g*(1 - cw*cw))) /
844 (1 - g);
845 ALSource->Params.iirFilter.coeff = a;
847 for(i = 0;i < NumSends;i++)
849 /* The wet path uses two chained one-pole filters, so take the
850 * base gain (square root of the squared gain) */
851 g = __max(WetGainHF[i], 0.01f);
852 a = 0.0f;
853 if(g < 0.9999f) /* 1-epsilon */
854 a = (1 - g*cw - aluSqrt(2*g*(1-cw) - g*g*(1 - cw*cw))) /
855 (1 - g);
856 ALSource->Params.Send[i].iirFilter.coeff = a;
860 static __inline ALfloat lerp(ALfloat val1, ALfloat val2, ALint frac)
862 return val1 + ((val2-val1)*(frac * (1.0f/(1<<FRACTIONBITS))));
865 static void MixSomeSources(ALCcontext *ALContext, float (*DryBuffer)[OUTPUTCHANNELS], ALuint SamplesToDo)
867 static float DummyBuffer[BUFFERSIZE];
868 ALfloat *WetBuffer[MAX_SENDS];
869 ALfloat (*Matrix)[OUTPUTCHANNELS] = ALContext->ChannelMatrix;
870 ALfloat DrySend[OUTPUTCHANNELS];
871 ALfloat dryGainStep[OUTPUTCHANNELS];
872 ALfloat wetGainStep[MAX_SENDS];
873 ALuint i, j, k, out;
874 ALsource *ALSource;
875 ALfloat value, outsamp;
876 ALbufferlistitem *BufferListItem;
877 ALint64 DataSize64,DataPos64;
878 FILTER *DryFilter, *WetFilter[MAX_SENDS];
879 ALfloat WetSend[MAX_SENDS];
880 ALuint rampLength;
881 ALuint DeviceFreq;
882 ALint increment;
883 ALuint DataPosInt, DataPosFrac;
884 ALuint Channels, Bytes;
885 ALuint Frequency;
886 ALuint BuffersPlayed;
887 ALfloat Pitch;
888 ALenum State;
890 if(!(ALSource=ALContext->Source))
891 return;
893 DeviceFreq = ALContext->Device->Frequency;
895 rampLength = DeviceFreq * MIN_RAMP_LENGTH / 1000;
896 rampLength = max(rampLength, SamplesToDo);
898 another_source:
899 State = ALSource->state;
900 if(State != AL_PLAYING)
902 if((ALSource=ALSource->next) != NULL)
903 goto another_source;
904 return;
906 j = 0;
908 /* Find buffer format */
909 Frequency = 0;
910 Channels = 0;
911 Bytes = 0;
912 BufferListItem = ALSource->queue;
913 while(BufferListItem != NULL)
915 ALbuffer *ALBuffer;
916 if((ALBuffer=BufferListItem->buffer) != NULL)
918 Channels = aluChannelsFromFormat(ALBuffer->format);
919 Bytes = aluBytesFromFormat(ALBuffer->format);
920 Frequency = ALBuffer->frequency;
921 break;
923 BufferListItem = BufferListItem->next;
926 /* Get source info */
927 BuffersPlayed = ALSource->BuffersPlayed;
928 DataPosInt = ALSource->position;
929 DataPosFrac = ALSource->position_fraction;
931 if(ALSource->NeedsUpdate)
933 CalcSourceParams(ALContext, ALSource, (Channels==1)?AL_TRUE:AL_FALSE);
934 ALSource->NeedsUpdate = AL_FALSE;
937 /* Compute 18.14 fixed point step */
938 Pitch = (ALSource->Params.Pitch*Frequency) / DeviceFreq;
939 if(Pitch > (float)MAX_PITCH) Pitch = (float)MAX_PITCH;
940 increment = (ALint)(Pitch*(ALfloat)(1L<<FRACTIONBITS));
941 if(increment <= 0) increment = (1<<FRACTIONBITS);
943 /* Compute the gain steps for each output channel */
944 if(ALSource->FirstStart)
946 for(i = 0;i < OUTPUTCHANNELS;i++)
947 DrySend[i] = ALSource->Params.DryGains[i];
948 for(i = 0;i < MAX_SENDS;i++)
949 WetSend[i] = ALSource->Params.WetGains[i];
951 else
953 for(i = 0;i < OUTPUTCHANNELS;i++)
954 DrySend[i] = ALSource->DryGains[i];
955 for(i = 0;i < MAX_SENDS;i++)
956 WetSend[i] = ALSource->WetGains[i];
959 DryFilter = &ALSource->Params.iirFilter;
960 for(i = 0;i < MAX_SENDS;i++)
962 WetFilter[i] = &ALSource->Params.Send[i].iirFilter;
963 WetBuffer[i] = (ALSource->Send[i].Slot ?
964 ALSource->Send[i].Slot->WetBuffer :
965 DummyBuffer);
968 if(DuplicateStereo && Channels == 2)
970 Matrix[FRONT_LEFT][SIDE_LEFT] = 1.0f;
971 Matrix[FRONT_RIGHT][SIDE_RIGHT] = 1.0f;
972 Matrix[FRONT_LEFT][BACK_LEFT] = 1.0f;
973 Matrix[FRONT_RIGHT][BACK_RIGHT] = 1.0f;
975 else if(DuplicateStereo)
977 Matrix[FRONT_LEFT][SIDE_LEFT] = 0.0f;
978 Matrix[FRONT_RIGHT][SIDE_RIGHT] = 0.0f;
979 Matrix[FRONT_LEFT][BACK_LEFT] = 0.0f;
980 Matrix[FRONT_RIGHT][BACK_RIGHT] = 0.0f;
983 /* Get current buffer queue item */
984 BufferListItem = ALSource->queue;
985 for(i = 0;i < BuffersPlayed && BufferListItem;i++)
986 BufferListItem = BufferListItem->next;
988 while(State == AL_PLAYING && j < SamplesToDo)
990 ALuint DataSize = 0;
991 ALbuffer *ALBuffer;
992 ALfloat *Data;
993 ALuint BufferSize;
995 /* Get buffer info */
996 if((ALBuffer=BufferListItem->buffer) != NULL)
998 Data = ALBuffer->data;
999 DataSize = ALBuffer->size;
1000 DataSize /= Channels * Bytes;
1002 if(DataPosInt >= DataSize)
1003 goto skipmix;
1005 if(BufferListItem->next)
1007 ALbuffer *NextBuf = BufferListItem->next->buffer;
1008 if(NextBuf && NextBuf->data)
1010 ALint ulExtraSamples = BUFFER_PADDING*Channels*Bytes;
1011 ulExtraSamples = min(NextBuf->size, ulExtraSamples);
1012 memcpy(&Data[DataSize*Channels], NextBuf->data, ulExtraSamples);
1015 else if(ALSource->bLooping)
1017 ALbuffer *NextBuf = ALSource->queue->buffer;
1018 if(NextBuf && NextBuf->data)
1020 ALint ulExtraSamples = BUFFER_PADDING*Channels*Bytes;
1021 ulExtraSamples = min(NextBuf->size, ulExtraSamples);
1022 memcpy(&Data[DataSize*Channels], NextBuf->data, ulExtraSamples);
1025 else
1026 memset(&Data[DataSize*Channels], 0, (BUFFER_PADDING*Channels*Bytes));
1028 /* Compute the gain steps for each output channel */
1029 for(i = 0;i < OUTPUTCHANNELS;i++)
1030 dryGainStep[i] = (ALSource->Params.DryGains[i]-
1031 DrySend[i]) / rampLength;
1032 for(i = 0;i < MAX_SENDS;i++)
1033 wetGainStep[i] = (ALSource->Params.WetGains[i]-
1034 WetSend[i]) / rampLength;
1036 /* Figure out how many samples we can mix. */
1037 DataSize64 = DataSize;
1038 DataSize64 <<= FRACTIONBITS;
1039 DataPos64 = DataPosInt;
1040 DataPos64 <<= FRACTIONBITS;
1041 DataPos64 += DataPosFrac;
1042 BufferSize = (ALuint)((DataSize64-DataPos64+(increment-1)) / increment);
1044 BufferSize = min(BufferSize, (SamplesToDo-j));
1046 /* Actual sample mixing loop */
1047 k = 0;
1048 Data += DataPosInt*Channels;
1050 if(Channels == 1) /* Mono */
1052 while(BufferSize--)
1054 for(i = 0;i < OUTPUTCHANNELS;i++)
1055 DrySend[i] += dryGainStep[i];
1056 for(i = 0;i < MAX_SENDS;i++)
1057 WetSend[i] += wetGainStep[i];
1059 /* First order interpolator */
1060 value = lerp(Data[k], Data[k+1], DataPosFrac);
1062 /* Direct path final mix buffer and panning */
1063 outsamp = lpFilter4P(DryFilter, 0, value);
1064 DryBuffer[j][FRONT_LEFT] += outsamp*DrySend[FRONT_LEFT];
1065 DryBuffer[j][FRONT_RIGHT] += outsamp*DrySend[FRONT_RIGHT];
1066 DryBuffer[j][SIDE_LEFT] += outsamp*DrySend[SIDE_LEFT];
1067 DryBuffer[j][SIDE_RIGHT] += outsamp*DrySend[SIDE_RIGHT];
1068 DryBuffer[j][BACK_LEFT] += outsamp*DrySend[BACK_LEFT];
1069 DryBuffer[j][BACK_RIGHT] += outsamp*DrySend[BACK_RIGHT];
1070 DryBuffer[j][FRONT_CENTER] += outsamp*DrySend[FRONT_CENTER];
1071 DryBuffer[j][BACK_CENTER] += outsamp*DrySend[BACK_CENTER];
1073 /* Room path final mix buffer and panning */
1074 for(i = 0;i < MAX_SENDS;i++)
1076 outsamp = lpFilter2P(WetFilter[i], 0, value);
1077 WetBuffer[i][j] += outsamp*WetSend[i];
1080 DataPosFrac += increment;
1081 k += DataPosFrac>>FRACTIONBITS;
1082 DataPosFrac &= FRACTIONMASK;
1083 j++;
1086 else if(Channels == 2) /* Stereo */
1088 const int chans[] = {
1089 FRONT_LEFT, FRONT_RIGHT
1091 const ALfloat scaler = aluSqrt(1.0f/Channels);
1093 #define DO_MIX() do { \
1094 while(BufferSize--) \
1096 for(i = 0;i < OUTPUTCHANNELS;i++) \
1097 DrySend[i] += dryGainStep[i]; \
1098 for(i = 0;i < MAX_SENDS;i++) \
1099 WetSend[i] += wetGainStep[i]; \
1101 for(i = 0;i < Channels;i++) \
1103 value = lerp(Data[k*Channels + i], Data[(k+1)*Channels + i], DataPosFrac); \
1104 outsamp = lpFilter2P(DryFilter, chans[i]*2, value)*DrySend[chans[i]]; \
1105 for(out = 0;out < OUTPUTCHANNELS;out++) \
1106 DryBuffer[j][out] += outsamp*Matrix[chans[i]][out]; \
1107 for(out = 0;out < MAX_SENDS;out++) \
1109 outsamp = lpFilter1P(WetFilter[out], chans[out], value); \
1110 WetBuffer[out][j] += outsamp*WetSend[out]*scaler; \
1114 DataPosFrac += increment; \
1115 k += DataPosFrac>>FRACTIONBITS; \
1116 DataPosFrac &= FRACTIONMASK; \
1117 j++; \
1119 } while(0)
1121 DO_MIX();
1123 else if(Channels == 4) /* Quad */
1125 const int chans[] = {
1126 FRONT_LEFT, FRONT_RIGHT,
1127 BACK_LEFT, BACK_RIGHT
1129 const ALfloat scaler = aluSqrt(1.0f/Channels);
1131 DO_MIX();
1133 else if(Channels == 6) /* 5.1 */
1135 const int chans[] = {
1136 FRONT_LEFT, FRONT_RIGHT,
1137 FRONT_CENTER, LFE,
1138 BACK_LEFT, BACK_RIGHT
1140 const ALfloat scaler = aluSqrt(1.0f/Channels);
1142 DO_MIX();
1144 else if(Channels == 7) /* 6.1 */
1146 const int chans[] = {
1147 FRONT_LEFT, FRONT_RIGHT,
1148 FRONT_CENTER, LFE,
1149 BACK_CENTER,
1150 SIDE_LEFT, SIDE_RIGHT
1152 const ALfloat scaler = aluSqrt(1.0f/Channels);
1154 DO_MIX();
1156 else if(Channels == 8) /* 7.1 */
1158 const int chans[] = {
1159 FRONT_LEFT, FRONT_RIGHT,
1160 FRONT_CENTER, LFE,
1161 BACK_LEFT, BACK_RIGHT,
1162 SIDE_LEFT, SIDE_RIGHT
1164 const ALfloat scaler = aluSqrt(1.0f/Channels);
1166 DO_MIX();
1167 #undef DO_MIX
1169 else /* Unknown? */
1171 for(i = 0;i < OUTPUTCHANNELS;i++)
1172 DrySend[i] += dryGainStep[i]*BufferSize;
1173 for(i = 0;i < MAX_SENDS;i++)
1174 WetSend[i] += wetGainStep[i]*BufferSize;
1175 while(BufferSize--)
1177 DataPosFrac += increment;
1178 k += DataPosFrac>>FRACTIONBITS;
1179 DataPosFrac &= FRACTIONMASK;
1180 j++;
1183 DataPosInt += k;
1185 skipmix:
1186 /* Handle looping sources */
1187 if(DataPosInt >= DataSize)
1189 if(BuffersPlayed < (ALSource->BuffersInQueue-1))
1191 BufferListItem = BufferListItem->next;
1192 BuffersPlayed++;
1193 DataPosInt -= DataSize;
1195 else
1197 if(!ALSource->bLooping)
1199 State = AL_STOPPED;
1200 BufferListItem = ALSource->queue;
1201 BuffersPlayed = ALSource->BuffersInQueue;
1202 DataPosInt = 0;
1203 DataPosFrac = 0;
1205 else
1207 BufferListItem = ALSource->queue;
1208 BuffersPlayed = 0;
1209 if(ALSource->BuffersInQueue == 1)
1210 DataPosInt %= DataSize;
1211 else
1212 DataPosInt -= DataSize;
1218 /* Update source info */
1219 ALSource->state = State;
1220 ALSource->BuffersPlayed = BuffersPlayed;
1221 ALSource->position = DataPosInt;
1222 ALSource->position_fraction = DataPosFrac;
1223 ALSource->Buffer = BufferListItem->buffer;
1225 for(i = 0;i < OUTPUTCHANNELS;i++)
1226 ALSource->DryGains[i] = DrySend[i];
1227 for(i = 0;i < MAX_SENDS;i++)
1228 ALSource->WetGains[i] = WetSend[i];
1230 ALSource->FirstStart = AL_FALSE;
1232 if((ALSource=ALSource->next) != NULL)
1233 goto another_source;
1236 ALvoid aluMixData(ALCdevice *device, ALvoid *buffer, ALsizei size)
1238 float (*DryBuffer)[OUTPUTCHANNELS];
1239 const Channel *ChanMap;
1240 ALuint SamplesToDo;
1241 ALeffectslot *ALEffectSlot;
1242 ALCcontext *ALContext;
1243 int fpuState;
1244 ALuint i, c;
1246 SuspendContext(NULL);
1248 #if defined(HAVE_FESETROUND)
1249 fpuState = fegetround();
1250 fesetround(FE_TOWARDZERO);
1251 #elif defined(HAVE__CONTROLFP)
1252 fpuState = _controlfp(0, 0);
1253 _controlfp(_RC_CHOP, _MCW_RC);
1254 #else
1255 (void)fpuState;
1256 #endif
1258 DryBuffer = device->DryBuffer;
1259 while(size > 0)
1261 /* Setup variables */
1262 SamplesToDo = min(size, BUFFERSIZE);
1264 /* Clear mixing buffer */
1265 memset(DryBuffer, 0, SamplesToDo*OUTPUTCHANNELS*sizeof(ALfloat));
1267 for(c = 0;c < device->NumContexts;c++)
1269 ALContext = device->Contexts[c];
1270 SuspendContext(ALContext);
1272 MixSomeSources(ALContext, DryBuffer, SamplesToDo);
1274 /* effect slot processing */
1275 ALEffectSlot = ALContext->AuxiliaryEffectSlot;
1276 while(ALEffectSlot)
1278 if(ALEffectSlot->EffectState)
1279 ALEffect_Process(ALEffectSlot->EffectState, ALEffectSlot, SamplesToDo, ALEffectSlot->WetBuffer, DryBuffer);
1281 for(i = 0;i < SamplesToDo;i++)
1282 ALEffectSlot->WetBuffer[i] = 0.0f;
1283 ALEffectSlot = ALEffectSlot->next;
1285 ProcessContext(ALContext);
1288 //Post processing loop
1289 ChanMap = device->DevChannels;
1290 switch(device->Format)
1292 #define CHECK_WRITE_FORMAT(bits, type, func) \
1293 case AL_FORMAT_MONO##bits: \
1294 for(i = 0;i < SamplesToDo;i++) \
1296 ((type*)buffer)[0] = (func)(DryBuffer[i][ChanMap[0]] + \
1297 DryBuffer[i][ChanMap[1]]); \
1298 buffer = ((type*)buffer) + 1; \
1300 break; \
1301 case AL_FORMAT_STEREO##bits: \
1302 if(device->Bs2b) \
1304 for(i = 0;i < SamplesToDo;i++) \
1306 float samples[2]; \
1307 samples[0] = DryBuffer[i][ChanMap[0]]; \
1308 samples[1] = DryBuffer[i][ChanMap[1]]; \
1309 bs2b_cross_feed(device->Bs2b, samples); \
1310 ((type*)buffer)[0] = (func)(samples[0]); \
1311 ((type*)buffer)[1] = (func)(samples[1]); \
1312 buffer = ((type*)buffer) + 2; \
1315 else \
1317 for(i = 0;i < SamplesToDo;i++) \
1319 ((type*)buffer)[0] = (func)(DryBuffer[i][ChanMap[0]]); \
1320 ((type*)buffer)[1] = (func)(DryBuffer[i][ChanMap[1]]); \
1321 buffer = ((type*)buffer) + 2; \
1324 break; \
1325 case AL_FORMAT_QUAD##bits: \
1326 for(i = 0;i < SamplesToDo;i++) \
1328 ((type*)buffer)[0] = (func)(DryBuffer[i][ChanMap[0]]); \
1329 ((type*)buffer)[1] = (func)(DryBuffer[i][ChanMap[1]]); \
1330 ((type*)buffer)[2] = (func)(DryBuffer[i][ChanMap[2]]); \
1331 ((type*)buffer)[3] = (func)(DryBuffer[i][ChanMap[3]]); \
1332 buffer = ((type*)buffer) + 4; \
1334 break; \
1335 case AL_FORMAT_51CHN##bits: \
1336 for(i = 0;i < SamplesToDo;i++) \
1338 ((type*)buffer)[0] = (func)(DryBuffer[i][ChanMap[0]]); \
1339 ((type*)buffer)[1] = (func)(DryBuffer[i][ChanMap[1]]); \
1340 ((type*)buffer)[2] = (func)(DryBuffer[i][ChanMap[2]]); \
1341 ((type*)buffer)[3] = (func)(DryBuffer[i][ChanMap[3]]); \
1342 ((type*)buffer)[4] = (func)(DryBuffer[i][ChanMap[4]]); \
1343 ((type*)buffer)[5] = (func)(DryBuffer[i][ChanMap[5]]); \
1344 buffer = ((type*)buffer) + 6; \
1346 break; \
1347 case AL_FORMAT_61CHN##bits: \
1348 for(i = 0;i < SamplesToDo;i++) \
1350 ((type*)buffer)[0] = (func)(DryBuffer[i][ChanMap[0]]); \
1351 ((type*)buffer)[1] = (func)(DryBuffer[i][ChanMap[1]]); \
1352 ((type*)buffer)[2] = (func)(DryBuffer[i][ChanMap[2]]); \
1353 ((type*)buffer)[3] = (func)(DryBuffer[i][ChanMap[3]]); \
1354 ((type*)buffer)[4] = (func)(DryBuffer[i][ChanMap[4]]); \
1355 ((type*)buffer)[5] = (func)(DryBuffer[i][ChanMap[5]]); \
1356 ((type*)buffer)[6] = (func)(DryBuffer[i][ChanMap[6]]); \
1357 buffer = ((type*)buffer) + 7; \
1359 break; \
1360 case AL_FORMAT_71CHN##bits: \
1361 for(i = 0;i < SamplesToDo;i++) \
1363 ((type*)buffer)[0] = (func)(DryBuffer[i][ChanMap[0]]); \
1364 ((type*)buffer)[1] = (func)(DryBuffer[i][ChanMap[1]]); \
1365 ((type*)buffer)[2] = (func)(DryBuffer[i][ChanMap[2]]); \
1366 ((type*)buffer)[3] = (func)(DryBuffer[i][ChanMap[3]]); \
1367 ((type*)buffer)[4] = (func)(DryBuffer[i][ChanMap[4]]); \
1368 ((type*)buffer)[5] = (func)(DryBuffer[i][ChanMap[5]]); \
1369 ((type*)buffer)[6] = (func)(DryBuffer[i][ChanMap[6]]); \
1370 ((type*)buffer)[7] = (func)(DryBuffer[i][ChanMap[7]]); \
1371 buffer = ((type*)buffer) + 8; \
1373 break;
1375 #define AL_FORMAT_MONO32 AL_FORMAT_MONO_FLOAT32
1376 #define AL_FORMAT_STEREO32 AL_FORMAT_STEREO_FLOAT32
1377 CHECK_WRITE_FORMAT(8, ALubyte, aluF2UB)
1378 CHECK_WRITE_FORMAT(16, ALshort, aluF2S)
1379 CHECK_WRITE_FORMAT(32, ALfloat, aluF2F)
1380 #undef AL_FORMAT_STEREO32
1381 #undef AL_FORMAT_MONO32
1382 #undef CHECK_WRITE_FORMAT
1384 default:
1385 break;
1388 size -= SamplesToDo;
1391 #if defined(HAVE_FESETROUND)
1392 fesetround(fpuState);
1393 #elif defined(HAVE__CONTROLFP)
1394 _controlfp(fpuState, 0xfffff);
1395 #endif
1397 ProcessContext(NULL);
1400 ALvoid aluHandleDisconnect(ALCdevice *device)
1402 ALuint i;
1404 SuspendContext(NULL);
1405 for(i = 0;i < device->NumContexts;i++)
1407 ALsource *source;
1409 SuspendContext(device->Contexts[i]);
1411 source = device->Contexts[i]->Source;
1412 while(source)
1414 if(source->state == AL_PLAYING)
1416 source->state = AL_STOPPED;
1417 source->BuffersPlayed = source->BuffersInQueue;
1418 source->position = 0;
1419 source->position_fraction = 0;
1421 source = source->next;
1423 ProcessContext(device->Contexts[i]);
1426 device->Connected = ALC_FALSE;
1427 ProcessContext(NULL);