Fixup panning gain calculations
[openal-soft.git] / Alc / alcReverb.c
blob1d89e04d5b7a3f4b375f0a2d6acc3954501e75fe
1 /**
2 * Reverb for the OpenAL cross platform audio library
3 * Copyright (C) 2008-2009 by Christopher Fitzgerald.
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>
26 #include "AL/al.h"
27 #include "AL/alc.h"
28 #include "alMain.h"
29 #include "alAuxEffectSlot.h"
30 #include "alEffect.h"
31 #include "alu.h"
33 typedef struct DelayLine
35 // The delay lines use sample lengths that are powers of 2 to allow
36 // bitmasking instead of modulus wrapping.
37 ALuint Mask;
38 ALfloat *Line;
39 } DelayLine;
41 typedef struct ALverbState {
42 // Must be first in all effects!
43 ALeffectState state;
45 // All delay lines are allocated as a single buffer to reduce memory
46 // fragmentation and management code.
47 ALfloat *SampleBuffer;
48 // Master effect low-pass filter (2 chained 1-pole filters).
49 ALfloat LpCoeff;
50 ALfloat LpSamples[2];
51 // Initial effect delay and decorrelation.
52 DelayLine Delay;
53 // The tap points for the initial delay. First tap goes to early
54 // reflections, the last four decorrelate to late reverb.
55 ALuint Tap[5];
56 struct {
57 // Total gain for early reflections.
58 ALfloat Gain;
59 // Early reflections are done with 4 delay lines.
60 ALfloat Coeff[4];
61 DelayLine Delay[4];
62 ALuint Offset[4];
63 // The gain for each output channel based on 3D panning.
64 ALfloat PanGain[OUTPUTCHANNELS];
65 } Early;
66 struct {
67 // Total gain for late reverb.
68 ALfloat Gain;
69 // Attenuation to compensate for modal density and decay rate.
70 ALfloat DensityGain;
71 // The feed-back and feed-forward all-pass coefficient.
72 ALfloat ApFeedCoeff;
73 // Mixing matrix coefficient.
74 ALfloat MixCoeff;
75 // Late reverb has 4 parallel all-pass filters.
76 ALfloat ApCoeff[4];
77 DelayLine ApDelay[4];
78 ALuint ApOffset[4];
79 // In addition to 4 cyclical delay lines.
80 ALfloat Coeff[4];
81 DelayLine Delay[4];
82 ALuint Offset[4];
83 // The cyclical delay lines are 1-pole low-pass filtered.
84 ALfloat LpCoeff[4];
85 ALfloat LpSample[4];
86 // The gain for each output channel based on 3D panning.
87 ALfloat PanGain[OUTPUTCHANNELS];
88 } Late;
89 // The current read offset for all delay lines.
90 ALuint Offset;
91 } ALverbState;
93 // All delay line lengths are specified in seconds.
95 // The lengths of the early delay lines.
96 static const ALfloat EARLY_LINE_LENGTH[4] =
98 0.0015f, 0.0045f, 0.0135f, 0.0405f
101 // The lengths of the late all-pass delay lines.
102 static const ALfloat ALLPASS_LINE_LENGTH[4] =
104 0.0151f, 0.0167f, 0.0183f, 0.0200f,
107 // The lengths of the late cyclical delay lines.
108 static const ALfloat LATE_LINE_LENGTH[4] =
110 0.0211f, 0.0311f, 0.0461f, 0.0680f
113 // The late cyclical delay lines have a variable length dependent on the
114 // effect's density parameter (inverted for some reason) and this multiplier.
115 static const ALfloat LATE_LINE_MULTIPLIER = 4.0f;
117 // Input into the late reverb is decorrelated between four channels. Their
118 // timings are dependent on a fraction and multiplier. See VerbUpdate() for
119 // the calculations involved.
120 static const ALfloat DECO_FRACTION = 1.0f / 32.0f;
121 static const ALfloat DECO_MULTIPLIER = 2.0f;
123 // The maximum length of initial delay for the master delay line (a sum of
124 // the maximum early reflection and late reverb delays).
125 static const ALfloat MASTER_LINE_LENGTH = 0.3f + 0.1f;
127 // Find the next power of 2. Actually, this will return the input value if
128 // it is already a power of 2.
129 static ALuint NextPowerOf2(ALuint value)
131 ALuint powerOf2 = 1;
133 if(value)
135 value--;
136 while(value)
138 value >>= 1;
139 powerOf2 <<= 1;
142 return powerOf2;
145 // Basic delay line input/output routines.
146 static __inline ALfloat DelayLineOut(DelayLine *Delay, ALuint offset)
148 return Delay->Line[offset&Delay->Mask];
151 static __inline ALvoid DelayLineIn(DelayLine *Delay, ALuint offset, ALfloat in)
153 Delay->Line[offset&Delay->Mask] = in;
156 // Delay line output routine for early reflections.
157 static __inline ALfloat EarlyDelayLineOut(ALverbState *State, ALuint index)
159 return State->Early.Coeff[index] *
160 DelayLineOut(&State->Early.Delay[index],
161 State->Offset - State->Early.Offset[index]);
164 // Given an input sample, this function produces stereo output for early
165 // reflections.
166 static __inline ALvoid EarlyReflection(ALverbState *State, ALfloat in, ALfloat *out)
168 ALfloat d[4], v, f[4];
170 // Obtain the decayed results of each early delay line.
171 d[0] = EarlyDelayLineOut(State, 0);
172 d[1] = EarlyDelayLineOut(State, 1);
173 d[2] = EarlyDelayLineOut(State, 2);
174 d[3] = EarlyDelayLineOut(State, 3);
176 /* The following uses a lossless scattering junction from waveguide
177 * theory. It actually amounts to a householder mixing matrix, which
178 * will produce a maximally diffuse response, and means this can probably
179 * be considered a simple feedback delay network (FDN).
181 * ---
183 * v = 2/N / d_i
184 * ---
185 * i=1
187 v = (d[0] + d[1] + d[2] + d[3]) * 0.5f;
188 // The junction is loaded with the input here.
189 v += in;
191 // Calculate the feed values for the delay lines.
192 f[0] = v - d[0];
193 f[1] = v - d[1];
194 f[2] = v - d[2];
195 f[3] = v - d[3];
197 // Refeed the delay lines.
198 DelayLineIn(&State->Early.Delay[0], State->Offset, f[0]);
199 DelayLineIn(&State->Early.Delay[1], State->Offset, f[1]);
200 DelayLineIn(&State->Early.Delay[2], State->Offset, f[2]);
201 DelayLineIn(&State->Early.Delay[3], State->Offset, f[3]);
203 // Output the results of the junction for all four lines.
204 out[0] = State->Early.Gain * f[0];
205 out[1] = State->Early.Gain * f[1];
206 out[2] = State->Early.Gain * f[2];
207 out[3] = State->Early.Gain * f[3];
210 // All-pass input/output routine for late reverb.
211 static __inline ALfloat LateAllPassInOut(ALverbState *State, ALuint index, ALfloat in)
213 ALfloat out;
215 out = State->Late.ApCoeff[index] *
216 DelayLineOut(&State->Late.ApDelay[index],
217 State->Offset - State->Late.ApOffset[index]);
218 out -= (State->Late.ApFeedCoeff * in);
219 DelayLineIn(&State->Late.ApDelay[index], State->Offset,
220 (State->Late.ApFeedCoeff * out) + in);
221 return out;
224 // Delay line output routine for late reverb.
225 static __inline ALfloat LateDelayLineOut(ALverbState *State, ALuint index)
227 return State->Late.Coeff[index] *
228 DelayLineOut(&State->Late.Delay[index],
229 State->Offset - State->Late.Offset[index]);
232 // Low-pass filter input/output routine for late reverb.
233 static __inline ALfloat LateLowPassInOut(ALverbState *State, ALuint index, ALfloat in)
235 State->Late.LpSample[index] = in +
236 ((State->Late.LpSample[index] - in) * State->Late.LpCoeff[index]);
237 return State->Late.LpSample[index];
240 // Given four decorrelated input samples, this function produces stereo
241 // output for late reverb.
242 static __inline ALvoid LateReverb(ALverbState *State, ALfloat *in, ALfloat *out)
244 ALfloat d[4], f[4];
246 // Obtain the decayed results of the cyclical delay lines, and add the
247 // corresponding input channels attenuated by density. Then pass the
248 // results through the low-pass filters.
249 d[0] = LateLowPassInOut(State, 0, (State->Late.DensityGain * in[0]) +
250 LateDelayLineOut(State, 0));
251 d[1] = LateLowPassInOut(State, 1, (State->Late.DensityGain * in[1]) +
252 LateDelayLineOut(State, 1));
253 d[2] = LateLowPassInOut(State, 2, (State->Late.DensityGain * in[2]) +
254 LateDelayLineOut(State, 2));
255 d[3] = LateLowPassInOut(State, 3, (State->Late.DensityGain * in[3]) +
256 LateDelayLineOut(State, 3));
258 // To help increase diffusion, run each line through an all-pass filter.
259 // The order of the all-pass filters is selected so that the shortest
260 // all-pass filter will feed the shortest delay line.
261 d[0] = LateAllPassInOut(State, 1, d[0]);
262 d[1] = LateAllPassInOut(State, 3, d[1]);
263 d[2] = LateAllPassInOut(State, 0, d[2]);
264 d[3] = LateAllPassInOut(State, 2, d[3]);
266 /* Late reverb is done with a modified feedback delay network (FDN)
267 * topology. Four input lines are each fed through their own all-pass
268 * filter and then into the mixing matrix. The four outputs of the
269 * mixing matrix are then cycled back to the inputs. Each output feeds
270 * a different input to form a circlular feed cycle.
272 * The mixing matrix used is a 4D skew-symmetric rotation matrix derived
273 * using a single unitary rotational parameter:
275 * [ d, a, b, c ] 1 = a^2 + b^2 + c^2 + d^2
276 * [ -a, d, c, -b ]
277 * [ -b, -c, d, a ]
278 * [ -c, b, -a, d ]
280 * The rotation is constructed from the effect's diffusion parameter,
281 * yielding: 1 = x^2 + 3 y^2; where a, b, and c are the coefficient y
282 * with differing signs, and d is the coefficient x. The matrix is thus:
284 * [ x, y, -y, y ] x = 1 - (0.5 diffusion^3)
285 * [ -y, x, y, y ] y = sqrt((1 - x^2) / 3)
286 * [ y, -y, x, y ]
287 * [ -y, -y, -y, x ]
289 * To reduce the number of multiplies, the x coefficient is applied with
290 * the cyclical delay line coefficients. Thus only the y coefficient is
291 * applied when mixing, and is modified to be: y / x.
293 f[0] = d[0] + (State->Late.MixCoeff * ( d[1] - d[2] + d[3]));
294 f[1] = d[1] + (State->Late.MixCoeff * (-d[0] + d[2] + d[3]));
295 f[2] = d[2] + (State->Late.MixCoeff * ( d[0] - d[1] + d[3]));
296 f[3] = d[3] + (State->Late.MixCoeff * (-d[0] - d[1] - d[2]));
298 // Output the results of the matrix for all four cyclical delay lines,
299 // attenuated by the late reverb gain (which is attenuated by the 'x'
300 // mix coefficient).
301 out[0] = State->Late.Gain * f[0];
302 out[1] = State->Late.Gain * f[1];
303 out[2] = State->Late.Gain * f[2];
304 out[3] = State->Late.Gain * f[3];
306 // The delay lines are fed circularly in the order:
307 // 0 -> 1 -> 3 -> 2 -> 0 ...
308 DelayLineIn(&State->Late.Delay[0], State->Offset, f[2]);
309 DelayLineIn(&State->Late.Delay[1], State->Offset, f[0]);
310 DelayLineIn(&State->Late.Delay[2], State->Offset, f[3]);
311 DelayLineIn(&State->Late.Delay[3], State->Offset, f[1]);
314 // Process the reverb for a given input sample, resulting in separate four-
315 // channel output for both early reflections and late reverb.
316 static __inline ALvoid ReverbInOut(ALverbState *State, ALfloat in, ALfloat *early, ALfloat *late)
318 ALfloat taps[4];
320 // Low-pass filter the incoming sample.
321 in = in + ((State->LpSamples[0] - in) * State->LpCoeff);
322 State->LpSamples[0] = in;
323 in = in + ((State->LpSamples[1] - in) * State->LpCoeff);
324 State->LpSamples[1] = in;
326 // Feed the initial delay line.
327 DelayLineIn(&State->Delay, State->Offset, in);
329 // Calculate the early reflection from the first delay tap.
330 in = DelayLineOut(&State->Delay, State->Offset - State->Tap[0]);
331 EarlyReflection(State, in, early);
333 // Calculate the late reverb from the last four delay taps.
334 taps[0] = DelayLineOut(&State->Delay, State->Offset - State->Tap[1]);
335 taps[1] = DelayLineOut(&State->Delay, State->Offset - State->Tap[2]);
336 taps[2] = DelayLineOut(&State->Delay, State->Offset - State->Tap[3]);
337 taps[3] = DelayLineOut(&State->Delay, State->Offset - State->Tap[4]);
338 LateReverb(State, taps, late);
340 // Step all delays forward one sample.
341 State->Offset++;
344 // This destroys the reverb state. It should be called only when the effect
345 // slot has a different (or no) effect loaded over the reverb effect.
346 ALvoid VerbDestroy(ALeffectState *effect)
348 ALverbState *State = (ALverbState*)effect;
349 if(State)
351 free(State->SampleBuffer);
352 State->SampleBuffer = NULL;
353 free(State);
357 // NOTE: Temp, remove later.
358 static __inline ALint aluCart2LUTpos(ALfloat re, ALfloat im)
360 ALint pos = 0;
361 ALfloat denom = aluFabs(re) + aluFabs(im);
362 if(denom > 0.0f)
363 pos = (ALint)(QUADRANT_NUM*aluFabs(im) / denom + 0.5);
365 if(re < 0.0)
366 pos = 2 * QUADRANT_NUM - pos;
367 if(im < 0.0)
368 pos = LUT_NUM - pos;
369 return pos%LUT_NUM;
372 // This updates the reverb state. This is called any time the reverb effect
373 // is loaded into a slot.
374 ALvoid VerbUpdate(ALeffectState *effect, ALCcontext *Context, ALeffect *Effect)
376 ALverbState *State = (ALverbState*)effect;
377 ALuint index;
378 ALfloat length, mixCoeff, cw, g, coeff;
379 ALfloat hfRatio = Effect->Reverb.DecayHFRatio;
381 // Calculate the master low-pass filter (from the master effect HF gain).
382 cw = cos(2.0 * M_PI * Effect->Reverb.HFReference / Context->Frequency);
383 g = __max(Effect->Reverb.GainHF, 0.0001f);
384 State->LpCoeff = 0.0f;
385 if(g < 0.9999f) // 1-epsilon
386 State->LpCoeff = (1 - g*cw - aluSqrt(2*g*(1-cw) - g*g*(1 - cw*cw))) / (1 - g);
388 // Calculate the initial delay taps.
389 length = Effect->Reverb.ReflectionsDelay;
390 State->Tap[0] = (ALuint)(length * Context->Frequency);
392 length += Effect->Reverb.LateReverbDelay;
394 /* The four inputs to the late reverb are decorrelated to smooth the
395 * initial reverb and reduce harsh echos. The timings are calculated as
396 * multiples of a fraction of the smallest cyclical delay time. This
397 * result is then adjusted so that the first tap occurs immediately (all
398 * taps are reduced by the shortest fraction).
400 * offset[index] = ((FRACTION MULTIPLIER^index) - 1) delay
402 for(index = 0;index < 4;index++)
404 length += LATE_LINE_LENGTH[0] *
405 (1.0f + (Effect->Reverb.Density * LATE_LINE_MULTIPLIER)) *
406 (DECO_FRACTION * (pow(DECO_MULTIPLIER, (ALfloat)index) - 1.0f));
407 State->Tap[1 + index] = (ALuint)(length * Context->Frequency);
410 // Calculate the early reflections gain (from the slot gain, master
411 // effect gain, and reflections gain parameters).
412 State->Early.Gain = Effect->Reverb.Gain * Effect->Reverb.ReflectionsGain;
414 // Calculate the gain (coefficient) for each early delay line.
415 for(index = 0;index < 4;index++)
416 State->Early.Coeff[index] = pow(10.0f, EARLY_LINE_LENGTH[index] /
417 Effect->Reverb.LateReverbDelay *
418 -60.0f / 20.0f);
420 // Calculate the first mixing matrix coefficient (x).
421 mixCoeff = 1.0f - (0.5f * pow(Effect->Reverb.Diffusion, 3.0f));
423 // Calculate the late reverb gain (from the slot gain, master effect
424 // gain, and late reverb gain parameters). Since the output is tapped
425 // prior to the application of the delay line coefficients, this gain
426 // needs to be attenuated by the 'x' mix coefficient from above.
427 State->Late.Gain = Effect->Reverb.Gain * Effect->Reverb.LateReverbGain * mixCoeff;
429 /* To compensate for changes in modal density and decay time of the late
430 * reverb signal, the input is attenuated based on the maximal energy of
431 * the outgoing signal. This is calculated as the ratio between a
432 * reference value and the current approximation of energy for the output
433 * signal.
435 * Reverb output matches exponential decay of the form Sum(a^n), where a
436 * is the attenuation coefficient, and n is the sample ranging from 0 to
437 * infinity. The signal energy can thus be approximated using the area
438 * under this curve, calculated as: 1 / (1 - a).
440 * The reference energy is calculated from a signal at the lowest (effect
441 * at 1.0) density with a decay time of one second.
443 * The coefficient is calculated as the average length of the cyclical
444 * delay lines. This produces a better result than calculating the gain
445 * for each line individually (most likely a side effect of diffusion).
447 * The final result is the square root of the ratio bound to a maximum
448 * value of 1 (no amplification).
450 length = (LATE_LINE_LENGTH[0] + LATE_LINE_LENGTH[1] +
451 LATE_LINE_LENGTH[2] + LATE_LINE_LENGTH[3]);
452 g = length * (1.0f + LATE_LINE_MULTIPLIER) * 0.25f;
453 g = pow(10.0f, g * -60.0f / 20.0f);
454 g = 1.0f / (1.0f - (g * g));
455 length *= 1.0f + (Effect->Reverb.Density * LATE_LINE_MULTIPLIER) * 0.25f;
456 length = pow(10.0f, length / Effect->Reverb.DecayTime * -60.0f / 20.0f);
457 length = 1.0f / (1.0f - (length * length));
458 State->Late.DensityGain = __min(aluSqrt(g / length), 1.0f);
460 // Calculate the all-pass feed-back and feed-forward coefficient.
461 State->Late.ApFeedCoeff = 0.6f * pow(Effect->Reverb.Diffusion, 3.0f);
463 // Calculate the mixing matrix coefficient (y / x).
464 g = aluSqrt((1.0f - (mixCoeff * mixCoeff)) / 3.0f);
465 State->Late.MixCoeff = g / mixCoeff;
467 for(index = 0;index < 4;index++)
469 // Calculate the gain (coefficient) for each all-pass line.
470 State->Late.ApCoeff[index] = pow(10.0f, ALLPASS_LINE_LENGTH[index] /
471 Effect->Reverb.DecayTime *
472 -60.0f / 20.0f);
475 // If the HF limit parameter is flagged, calculate an appropriate limit
476 // based on the air absorption parameter.
477 if(Effect->Reverb.DecayHFLimit && Effect->Reverb.AirAbsorptionGainHF < 1.0f)
479 ALfloat limitRatio;
481 // For each of the cyclical delays, find the attenuation due to air
482 // absorption in dB (converting delay time to meters using the speed
483 // of sound). Then reversing the decay equation, solve for HF ratio.
484 // The delay length is cancelled out of the equation, so it can be
485 // calculated once for all lines.
486 limitRatio = 1.0f / (log10(Effect->Reverb.AirAbsorptionGainHF) *
487 SPEEDOFSOUNDMETRESPERSEC *
488 Effect->Reverb.DecayTime / -60.0f * 20.0f);
489 // Need to limit the result to a minimum of 0.1, just like the HF
490 // ratio parameter.
491 limitRatio = __max(limitRatio, 0.1f);
493 // Using the limit calculated above, apply the upper bound to the
494 // HF ratio.
495 hfRatio = __min(hfRatio, limitRatio);
498 // Calculate the low-pass filter frequency.
499 cw = cos(2.0f * M_PI * Effect->Reverb.HFReference / Context->Frequency);
501 for(index = 0;index < 4;index++)
503 // Calculate the length (in seconds) of each cyclical delay line.
504 length = LATE_LINE_LENGTH[index] * (1.0f + (Effect->Reverb.Density *
505 LATE_LINE_MULTIPLIER));
506 // Calculate the delay offset for the cyclical delay lines.
507 State->Late.Offset[index] = (ALuint)(length * Context->Frequency);
509 // Calculate the gain (coefficient) for each cyclical line.
510 State->Late.Coeff[index] = pow(10.0f, length / Effect->Reverb.DecayTime *
511 -60.0f / 20.0f);
513 // Eventually this should boost the high frequencies when the ratio
514 // exceeds 1.
515 coeff = 0.0f;
516 if (hfRatio < 1.0f)
518 // Calculate the decay equation for each low-pass filter.
519 g = pow(10.0f, length / (Effect->Reverb.DecayTime * hfRatio) *
520 -60.0f / 20.0f) / State->Late.Coeff[index];
521 g = __max(g, 0.1f);
522 g *= g;
524 // Calculate the gain (coefficient) for each low-pass filter.
525 if(g < 0.9999f) // 1-epsilon
526 coeff = (1 - g*cw - aluSqrt(2*g*(1-cw) - g*g*(1 - cw*cw))) / (1 - g);
528 // Very low decay times will produce minimal output, so apply an
529 // upper bound to the coefficient.
530 coeff = __min(coeff, 0.98f);
532 State->Late.LpCoeff[index] = coeff;
534 // Attenuate the cyclical line coefficients by the mixing coefficient
535 // (x).
536 State->Late.Coeff[index] *= mixCoeff;
539 // Calculate the 3D-panning gains for the early reflections and late
540 // reverb (for EAX mode).
542 ALfloat earlyPan[3] = { Effect->Reverb.ReflectionsPan[0], Effect->Reverb.ReflectionsPan[1], Effect->Reverb.ReflectionsPan[2] };
543 ALfloat latePan[3] = { Effect->Reverb.LateReverbPan[0], Effect->Reverb.LateReverbPan[1], Effect->Reverb.LateReverbPan[2] };
544 ALfloat *speakerGain, dirGain, ambientGain;
545 ALfloat length;
546 ALint pos;
548 length = earlyPan[0]*earlyPan[0] + earlyPan[1]*earlyPan[1] + earlyPan[2]*earlyPan[2];
549 if(length > 1.0f)
551 length = 1.0f / aluSqrt(length);
552 earlyPan[0] *= length;
553 earlyPan[1] *= length;
554 earlyPan[2] *= length;
556 length = latePan[0]*latePan[0] + latePan[1]*latePan[1] + latePan[2]*latePan[2];
557 if(length > 1.0f)
559 length = 1.0f / aluSqrt(length);
560 latePan[0] *= length;
561 latePan[1] *= length;
562 latePan[2] *= length;
565 // This code applies directional reverb just like the mixer applies
566 // directional sources. It diffuses the sound toward all speakers
567 // as the magnitude of the panning vector drops, which is only an
568 // approximation of the expansion of sound across the speakers from
569 // the panning direction.
570 pos = aluCart2LUTpos(earlyPan[2], earlyPan[0]);
571 speakerGain = &Context->PanningLUT[OUTPUTCHANNELS * pos];
572 dirGain = aluSqrt((earlyPan[0] * earlyPan[0]) + (earlyPan[2] * earlyPan[2]));
573 ambientGain = (1.0 - dirGain);
574 for(index = 0;index < OUTPUTCHANNELS;index++)
575 State->Early.PanGain[index] = dirGain * speakerGain[index] + ambientGain;
577 pos = aluCart2LUTpos(latePan[2], latePan[0]);
578 speakerGain = &Context->PanningLUT[OUTPUTCHANNELS * pos];
579 dirGain = aluSqrt((latePan[0] * latePan[0]) + (latePan[2] * latePan[2]));
580 ambientGain = (1.0 - dirGain);
581 for(index = 0;index < OUTPUTCHANNELS;index++)
582 State->Late.PanGain[index] = dirGain * speakerGain[index] + ambientGain;
586 // This processes the reverb state, given the input samples and an output
587 // buffer.
588 ALvoid VerbProcess(ALeffectState *effect, const ALeffectslot *Slot, ALuint SamplesToDo, const ALfloat *SamplesIn, ALfloat (*SamplesOut)[OUTPUTCHANNELS])
590 ALverbState *State = (ALverbState*)effect;
591 ALuint index;
592 ALfloat early[4], late[4], out[4];
593 ALfloat gain = Slot->Gain;
595 for(index = 0;index < SamplesToDo;index++)
597 // Process reverb for this sample.
598 ReverbInOut(State, SamplesIn[index], early, late);
600 // Mix early reflections and late reverb.
601 out[0] = (early[0] + late[0]) * gain;
602 out[1] = (early[1] + late[1]) * gain;
603 out[2] = (early[2] + late[2]) * gain;
604 out[3] = (early[3] + late[3]) * gain;
606 // Output the results.
607 SamplesOut[index][FRONT_LEFT] += out[0];
608 SamplesOut[index][FRONT_RIGHT] += out[1];
609 SamplesOut[index][FRONT_CENTER] += out[3];
610 SamplesOut[index][SIDE_LEFT] += out[0];
611 SamplesOut[index][SIDE_RIGHT] += out[1];
612 SamplesOut[index][BACK_LEFT] += out[0];
613 SamplesOut[index][BACK_RIGHT] += out[1];
614 SamplesOut[index][BACK_CENTER] += out[2];
618 // This processes the EAX reverb state, given the input samples and an output
619 // buffer.
620 ALvoid EAXVerbProcess(ALeffectState *effect, const ALeffectslot *Slot, ALuint SamplesToDo, const ALfloat *SamplesIn, ALfloat (*SamplesOut)[OUTPUTCHANNELS])
622 ALverbState *State = (ALverbState*)effect;
623 ALuint index;
624 ALfloat early[4], late[4];
625 ALfloat gain = Slot->Gain;
627 for(index = 0;index < SamplesToDo;index++)
629 // Process reverb for this sample.
630 ReverbInOut(State, SamplesIn[index], early, late);
632 // Unfortunately, while the number and configuration of gains for
633 // panning adjust according to OUTPUTCHANNELS, the output from the
634 // reverb engine is not so scalable.
635 SamplesOut[index][FRONT_LEFT] +=
636 (State->Early.PanGain[FRONT_LEFT]*early[0] +
637 State->Late.PanGain[FRONT_LEFT]*late[0]) * gain;
638 SamplesOut[index][FRONT_RIGHT] +=
639 (State->Early.PanGain[FRONT_RIGHT]*early[1] +
640 State->Late.PanGain[FRONT_RIGHT]*late[1]) * gain;
641 SamplesOut[index][FRONT_CENTER] +=
642 (State->Early.PanGain[FRONT_CENTER]*early[3] +
643 State->Late.PanGain[FRONT_CENTER]*late[3]) * gain;
644 SamplesOut[index][SIDE_LEFT] +=
645 (State->Early.PanGain[SIDE_LEFT]*early[0] +
646 State->Late.PanGain[SIDE_LEFT]*late[0]) * gain;
647 SamplesOut[index][SIDE_RIGHT] +=
648 (State->Early.PanGain[SIDE_RIGHT]*early[1] +
649 State->Late.PanGain[SIDE_RIGHT]*late[1]) * gain;
650 SamplesOut[index][BACK_LEFT] +=
651 (State->Early.PanGain[BACK_LEFT]*early[0] +
652 State->Late.PanGain[BACK_LEFT]*late[0]) * gain;
653 SamplesOut[index][BACK_RIGHT] +=
654 (State->Early.PanGain[BACK_RIGHT]*early[1] +
655 State->Late.PanGain[BACK_RIGHT]*late[1]) * gain;
656 SamplesOut[index][BACK_CENTER] +=
657 (State->Early.PanGain[BACK_CENTER]*early[2] +
658 State->Late.PanGain[BACK_CENTER]*late[2]) * gain;
662 // This creates the reverb state. It should be called only when the reverb
663 // effect is loaded into a slot that doesn't already have a reverb effect.
664 ALeffectState *VerbCreate(ALCcontext *Context)
666 ALverbState *State = NULL;
667 ALuint samples, length[13], totalLength, index;
669 State = malloc(sizeof(ALverbState));
670 if(!State)
671 return NULL;
673 State->state.Destroy = VerbDestroy;
674 State->state.Update = VerbUpdate;
675 State->state.Process = VerbProcess;
677 // All line lengths are powers of 2, calculated from their lengths, with
678 // an additional sample in case of rounding errors.
680 // See VerbUpdate() for an explanation of the additional calculation
681 // added to the master line length.
682 samples = (ALuint)
683 ((MASTER_LINE_LENGTH +
684 (LATE_LINE_LENGTH[0] * (1.0f + LATE_LINE_MULTIPLIER) *
685 (DECO_FRACTION * ((DECO_MULTIPLIER * DECO_MULTIPLIER *
686 DECO_MULTIPLIER) - 1.0f)))) *
687 Context->Frequency) + 1;
688 length[0] = NextPowerOf2(samples);
689 totalLength = length[0];
690 for(index = 0;index < 4;index++)
692 samples = (ALuint)(EARLY_LINE_LENGTH[index] * Context->Frequency) + 1;
693 length[1 + index] = NextPowerOf2(samples);
694 totalLength += length[1 + index];
696 for(index = 0;index < 4;index++)
698 samples = (ALuint)(ALLPASS_LINE_LENGTH[index] * Context->Frequency) + 1;
699 length[5 + index] = NextPowerOf2(samples);
700 totalLength += length[5 + index];
702 for(index = 0;index < 4;index++)
704 samples = (ALuint)(LATE_LINE_LENGTH[index] *
705 (1.0f + LATE_LINE_MULTIPLIER) * Context->Frequency) + 1;
706 length[9 + index] = NextPowerOf2(samples);
707 totalLength += length[9 + index];
710 // All lines share a single sample buffer and have their masks and start
711 // addresses calculated once.
712 State->SampleBuffer = malloc(totalLength * sizeof(ALfloat));
713 if(!State->SampleBuffer)
715 free(State);
716 return NULL;
718 for(index = 0; index < totalLength;index++)
719 State->SampleBuffer[index] = 0.0f;
721 State->LpCoeff = 0.0f;
722 State->LpSamples[0] = 0.0f;
723 State->LpSamples[1] = 0.0f;
724 State->Delay.Mask = length[0] - 1;
725 State->Delay.Line = &State->SampleBuffer[0];
726 totalLength = length[0];
728 State->Tap[0] = 0;
729 State->Tap[1] = 0;
730 State->Tap[2] = 0;
731 State->Tap[3] = 0;
732 State->Tap[4] = 0;
734 State->Early.Gain = 0.0f;
735 for(index = 0;index < 4;index++)
737 State->Early.Coeff[index] = 0.0f;
738 State->Early.Delay[index].Mask = length[1 + index] - 1;
739 State->Early.Delay[index].Line = &State->SampleBuffer[totalLength];
740 totalLength += length[1 + index];
742 // The early delay lines have their read offsets calculated once.
743 State->Early.Offset[index] = (ALuint)(EARLY_LINE_LENGTH[index] *
744 Context->Frequency);
747 State->Late.Gain = 0.0f;
748 State->Late.DensityGain = 0.0f;
749 State->Late.ApFeedCoeff = 0.0f;
750 State->Late.MixCoeff = 0.0f;
752 for(index = 0;index < 4;index++)
754 State->Late.ApCoeff[index] = 0.0f;
755 State->Late.ApDelay[index].Mask = length[5 + index] - 1;
756 State->Late.ApDelay[index].Line = &State->SampleBuffer[totalLength];
757 totalLength += length[5 + index];
759 // The late all-pass lines have their read offsets calculated once.
760 State->Late.ApOffset[index] = (ALuint)(ALLPASS_LINE_LENGTH[index] *
761 Context->Frequency);
764 for(index = 0;index < 4;index++)
766 State->Late.Coeff[index] = 0.0f;
767 State->Late.Delay[index].Mask = length[9 + index] - 1;
768 State->Late.Delay[index].Line = &State->SampleBuffer[totalLength];
769 totalLength += length[9 + index];
771 State->Late.Offset[index] = 0;
773 State->Late.LpCoeff[index] = 0.0f;
774 State->Late.LpSample[index] = 0.0f;
777 // Panning is applied as an independent gain for each output channel.
778 for(index = 0;index < OUTPUTCHANNELS;index++)
780 State->Early.PanGain[index] = 0.0f;
781 State->Late.PanGain[index] = 0.0f;
784 State->Offset = 0;
785 return &State->state;
788 ALeffectState *EAXVerbCreate(ALCcontext *Context)
790 ALeffectState *State = VerbCreate(Context);
791 if(State) State->Process = EAXVerbProcess;
792 return State;