Modify some context checks
[openal-soft.git] / Alc / alcReverb.c
blob42c823ced77cb0ab24c42d610d042873ab135fdd
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 "alError.h"
32 #include "alu.h"
34 typedef struct DelayLine
36 // The delay lines use sample lengths that are powers of 2 to allow
37 // bitmasking instead of modulus wrapping.
38 ALuint Mask;
39 ALfloat *Line;
40 } DelayLine;
42 typedef struct ALverbState {
43 // Must be first in all effects!
44 ALeffectState state;
46 // All delay lines are allocated as a single buffer to reduce memory
47 // fragmentation and management code.
48 ALfloat *SampleBuffer;
49 // Master effect low-pass filter (2 chained 1-pole filters).
50 FILTER LpFilter;
51 ALfloat LpHistory[2];
52 // Initial effect delay and decorrelation.
53 DelayLine Delay;
54 // The tap points for the initial delay. First tap goes to early
55 // reflections, the last four decorrelate to late reverb.
56 ALuint Tap[5];
57 struct {
58 // Total gain for early reflections.
59 ALfloat Gain;
60 // Early reflections are done with 4 delay lines.
61 ALfloat Coeff[4];
62 DelayLine Delay[4];
63 ALuint Offset[4];
64 // The gain for each output channel based on 3D panning.
65 ALfloat PanGain[OUTPUTCHANNELS];
66 } Early;
67 struct {
68 // Total gain for late reverb.
69 ALfloat Gain;
70 // Attenuation to compensate for modal density and decay rate.
71 ALfloat DensityGain;
72 // The feed-back and feed-forward all-pass coefficient.
73 ALfloat ApFeedCoeff;
74 // Mixing matrix coefficient.
75 ALfloat MixCoeff;
76 // Late reverb has 4 parallel all-pass filters.
77 ALfloat ApCoeff[4];
78 DelayLine ApDelay[4];
79 ALuint ApOffset[4];
80 // In addition to 4 cyclical delay lines.
81 ALfloat Coeff[4];
82 DelayLine Delay[4];
83 ALuint Offset[4];
84 // The cyclical delay lines are 1-pole low-pass filtered.
85 ALfloat LpCoeff[4];
86 ALfloat LpSample[4];
87 // The gain for each output channel based on 3D panning.
88 ALfloat PanGain[OUTPUTCHANNELS];
89 } Late;
90 // The current read offset for all delay lines.
91 ALuint Offset;
92 } ALverbState;
94 // All delay line lengths are specified in seconds.
96 // The lengths of the early delay lines.
97 static const ALfloat EARLY_LINE_LENGTH[4] =
99 0.0015f, 0.0045f, 0.0135f, 0.0405f
102 // The lengths of the late all-pass delay lines.
103 static const ALfloat ALLPASS_LINE_LENGTH[4] =
105 0.0151f, 0.0167f, 0.0183f, 0.0200f,
108 // The lengths of the late cyclical delay lines.
109 static const ALfloat LATE_LINE_LENGTH[4] =
111 0.0211f, 0.0311f, 0.0461f, 0.0680f
114 // The late cyclical delay lines have a variable length dependent on the
115 // effect's density parameter (inverted for some reason) and this multiplier.
116 static const ALfloat LATE_LINE_MULTIPLIER = 4.0f;
118 // Input into the late reverb is decorrelated between four channels. Their
119 // timings are dependent on a fraction and multiplier. See VerbUpdate() for
120 // the calculations involved.
121 static const ALfloat DECO_FRACTION = 1.0f / 32.0f;
122 static const ALfloat DECO_MULTIPLIER = 2.0f;
124 // The maximum length of initial delay for the master delay line (a sum of
125 // the maximum early reflection and late reverb delays).
126 static const ALfloat MASTER_LINE_LENGTH = 0.3f + 0.1f;
128 // Find the next power of 2. Actually, this will return the input value if
129 // it is already a power of 2.
130 static ALuint NextPowerOf2(ALuint value)
132 ALuint powerOf2 = 1;
134 if(value)
136 value--;
137 while(value)
139 value >>= 1;
140 powerOf2 <<= 1;
143 return powerOf2;
146 // Basic delay line input/output routines.
147 static __inline ALfloat DelayLineOut(DelayLine *Delay, ALuint offset)
149 return Delay->Line[offset&Delay->Mask];
152 static __inline ALvoid DelayLineIn(DelayLine *Delay, ALuint offset, ALfloat in)
154 Delay->Line[offset&Delay->Mask] = in;
157 // Delay line output routine for early reflections.
158 static __inline ALfloat EarlyDelayLineOut(ALverbState *State, ALuint index)
160 return State->Early.Coeff[index] *
161 DelayLineOut(&State->Early.Delay[index],
162 State->Offset - State->Early.Offset[index]);
165 // Given an input sample, this function produces stereo output for early
166 // reflections.
167 static __inline ALvoid EarlyReflection(ALverbState *State, ALfloat in, ALfloat *out)
169 ALfloat d[4], v, f[4];
171 // Obtain the decayed results of each early delay line.
172 d[0] = EarlyDelayLineOut(State, 0);
173 d[1] = EarlyDelayLineOut(State, 1);
174 d[2] = EarlyDelayLineOut(State, 2);
175 d[3] = EarlyDelayLineOut(State, 3);
177 /* The following uses a lossless scattering junction from waveguide
178 * theory. It actually amounts to a householder mixing matrix, which
179 * will produce a maximally diffuse response, and means this can probably
180 * be considered a simple feedback delay network (FDN).
182 * ---
184 * v = 2/N / d_i
185 * ---
186 * i=1
188 v = (d[0] + d[1] + d[2] + d[3]) * 0.5f;
189 // The junction is loaded with the input here.
190 v += in;
192 // Calculate the feed values for the delay lines.
193 f[0] = v - d[0];
194 f[1] = v - d[1];
195 f[2] = v - d[2];
196 f[3] = v - d[3];
198 // Refeed the delay lines.
199 DelayLineIn(&State->Early.Delay[0], State->Offset, f[0]);
200 DelayLineIn(&State->Early.Delay[1], State->Offset, f[1]);
201 DelayLineIn(&State->Early.Delay[2], State->Offset, f[2]);
202 DelayLineIn(&State->Early.Delay[3], State->Offset, f[3]);
204 // Output the results of the junction for all four lines.
205 out[0] = State->Early.Gain * f[0];
206 out[1] = State->Early.Gain * f[1];
207 out[2] = State->Early.Gain * f[2];
208 out[3] = State->Early.Gain * f[3];
211 // All-pass input/output routine for late reverb.
212 static __inline ALfloat LateAllPassInOut(ALverbState *State, ALuint index, ALfloat in)
214 ALfloat out;
216 out = State->Late.ApCoeff[index] *
217 DelayLineOut(&State->Late.ApDelay[index],
218 State->Offset - State->Late.ApOffset[index]);
219 out -= (State->Late.ApFeedCoeff * in);
220 DelayLineIn(&State->Late.ApDelay[index], State->Offset,
221 (State->Late.ApFeedCoeff * out) + in);
222 return out;
225 // Delay line output routine for late reverb.
226 static __inline ALfloat LateDelayLineOut(ALverbState *State, ALuint index)
228 return State->Late.Coeff[index] *
229 DelayLineOut(&State->Late.Delay[index],
230 State->Offset - State->Late.Offset[index]);
233 // Low-pass filter input/output routine for late reverb.
234 static __inline ALfloat LateLowPassInOut(ALverbState *State, ALuint index, ALfloat in)
236 State->Late.LpSample[index] = in +
237 ((State->Late.LpSample[index] - in) * State->Late.LpCoeff[index]);
238 return State->Late.LpSample[index];
241 // Given four decorrelated input samples, this function produces stereo
242 // output for late reverb.
243 static __inline ALvoid LateReverb(ALverbState *State, ALfloat *in, ALfloat *out)
245 ALfloat d[4], f[4];
247 // Obtain the decayed results of the cyclical delay lines, and add the
248 // corresponding input channels attenuated by density. Then pass the
249 // results through the low-pass filters.
250 d[0] = LateLowPassInOut(State, 0, (State->Late.DensityGain * in[0]) +
251 LateDelayLineOut(State, 0));
252 d[1] = LateLowPassInOut(State, 1, (State->Late.DensityGain * in[1]) +
253 LateDelayLineOut(State, 1));
254 d[2] = LateLowPassInOut(State, 2, (State->Late.DensityGain * in[2]) +
255 LateDelayLineOut(State, 2));
256 d[3] = LateLowPassInOut(State, 3, (State->Late.DensityGain * in[3]) +
257 LateDelayLineOut(State, 3));
259 // To help increase diffusion, run each line through an all-pass filter.
260 // The order of the all-pass filters is selected so that the shortest
261 // all-pass filter will feed the shortest delay line.
262 d[0] = LateAllPassInOut(State, 1, d[0]);
263 d[1] = LateAllPassInOut(State, 3, d[1]);
264 d[2] = LateAllPassInOut(State, 0, d[2]);
265 d[3] = LateAllPassInOut(State, 2, d[3]);
267 /* Late reverb is done with a modified feedback delay network (FDN)
268 * topology. Four input lines are each fed through their own all-pass
269 * filter and then into the mixing matrix. The four outputs of the
270 * mixing matrix are then cycled back to the inputs. Each output feeds
271 * a different input to form a circlular feed cycle.
273 * The mixing matrix used is a 4D skew-symmetric rotation matrix derived
274 * using a single unitary rotational parameter:
276 * [ d, a, b, c ] 1 = a^2 + b^2 + c^2 + d^2
277 * [ -a, d, c, -b ]
278 * [ -b, -c, d, a ]
279 * [ -c, b, -a, d ]
281 * The rotation is constructed from the effect's diffusion parameter,
282 * yielding: 1 = x^2 + 3 y^2; where a, b, and c are the coefficient y
283 * with differing signs, and d is the coefficient x. The matrix is thus:
285 * [ x, y, -y, y ] x = 1 - (0.5 diffusion^3)
286 * [ -y, x, y, y ] y = sqrt((1 - x^2) / 3)
287 * [ y, -y, x, y ]
288 * [ -y, -y, -y, x ]
290 * To reduce the number of multiplies, the x coefficient is applied with
291 * the cyclical delay line coefficients. Thus only the y coefficient is
292 * applied when mixing, and is modified to be: y / x.
294 f[0] = d[0] + (State->Late.MixCoeff * ( d[1] - d[2] + d[3]));
295 f[1] = d[1] + (State->Late.MixCoeff * (-d[0] + d[2] + d[3]));
296 f[2] = d[2] + (State->Late.MixCoeff * ( d[0] - d[1] + d[3]));
297 f[3] = d[3] + (State->Late.MixCoeff * (-d[0] - d[1] - d[2]));
299 // Output the results of the matrix for all four cyclical delay lines,
300 // attenuated by the late reverb gain (which is attenuated by the 'x'
301 // mix coefficient).
302 out[0] = State->Late.Gain * f[0];
303 out[1] = State->Late.Gain * f[1];
304 out[2] = State->Late.Gain * f[2];
305 out[3] = State->Late.Gain * f[3];
307 // The delay lines are fed circularly in the order:
308 // 0 -> 1 -> 3 -> 2 -> 0 ...
309 DelayLineIn(&State->Late.Delay[0], State->Offset, f[2]);
310 DelayLineIn(&State->Late.Delay[1], State->Offset, f[0]);
311 DelayLineIn(&State->Late.Delay[2], State->Offset, f[3]);
312 DelayLineIn(&State->Late.Delay[3], State->Offset, f[1]);
315 // Process the reverb for a given input sample, resulting in separate four-
316 // channel output for both early reflections and late reverb.
317 static __inline ALvoid ReverbInOut(ALverbState *State, ALfloat in, ALfloat *early, ALfloat *late)
319 ALfloat taps[4];
321 // Low-pass filter the incoming sample.
322 in = lpFilter2P(&State->LpFilter, 0, in);
324 // Feed the initial delay line.
325 DelayLineIn(&State->Delay, State->Offset, in);
327 // Calculate the early reflection from the first delay tap.
328 in = DelayLineOut(&State->Delay, State->Offset - State->Tap[0]);
329 EarlyReflection(State, in, early);
331 // Calculate the late reverb from the last four delay taps.
332 taps[0] = DelayLineOut(&State->Delay, State->Offset - State->Tap[1]);
333 taps[1] = DelayLineOut(&State->Delay, State->Offset - State->Tap[2]);
334 taps[2] = DelayLineOut(&State->Delay, State->Offset - State->Tap[3]);
335 taps[3] = DelayLineOut(&State->Delay, State->Offset - State->Tap[4]);
336 LateReverb(State, taps, late);
338 // Step all delays forward one sample.
339 State->Offset++;
342 // This destroys the reverb state. It should be called only when the effect
343 // slot has a different (or no) effect loaded over the reverb effect.
344 ALvoid VerbDestroy(ALeffectState *effect)
346 ALverbState *State = (ALverbState*)effect;
347 if(State)
349 free(State->SampleBuffer);
350 State->SampleBuffer = NULL;
351 free(State);
355 // NOTE: Temp, remove later.
356 static __inline ALint aluCart2LUTpos(ALfloat re, ALfloat im)
358 ALint pos = 0;
359 ALfloat denom = aluFabs(re) + aluFabs(im);
360 if(denom > 0.0f)
361 pos = (ALint)(QUADRANT_NUM*aluFabs(im) / denom + 0.5);
363 if(re < 0.0)
364 pos = 2 * QUADRANT_NUM - pos;
365 if(im < 0.0)
366 pos = LUT_NUM - pos;
367 return pos%LUT_NUM;
370 // This updates the reverb state. This is called any time the reverb effect
371 // is loaded into a slot.
372 ALvoid VerbUpdate(ALeffectState *effect, ALCcontext *Context, ALeffect *Effect)
374 ALverbState *State = (ALverbState*)effect;
375 ALuint index;
376 ALfloat length, mixCoeff, cw, g, coeff;
377 ALfloat hfRatio = Effect->Reverb.DecayHFRatio;
379 // Calculate the master low-pass filter (from the master effect HF gain).
380 cw = cos(2.0 * M_PI * Effect->Reverb.HFReference / Context->Frequency);
381 g = __max(Effect->Reverb.GainHF, 0.0001f);
382 State->LpFilter.coeff = 0.0f;
383 if(g < 0.9999f) // 1-epsilon
384 State->LpFilter.coeff = (1 - g*cw - aluSqrt(2*g*(1-cw) - g*g*(1 - cw*cw))) / (1 - g);
386 // Calculate the initial delay taps.
387 length = Effect->Reverb.ReflectionsDelay;
388 State->Tap[0] = (ALuint)(length * Context->Frequency);
390 length += Effect->Reverb.LateReverbDelay;
392 /* The four inputs to the late reverb are decorrelated to smooth the
393 * initial reverb and reduce harsh echos. The timings are calculated as
394 * multiples of a fraction of the smallest cyclical delay time. This
395 * result is then adjusted so that the first tap occurs immediately (all
396 * taps are reduced by the shortest fraction).
398 * offset[index] = ((FRACTION MULTIPLIER^index) - 1) delay
400 for(index = 0;index < 4;index++)
402 length += LATE_LINE_LENGTH[0] *
403 (1.0f + (Effect->Reverb.Density * LATE_LINE_MULTIPLIER)) *
404 (DECO_FRACTION * (pow(DECO_MULTIPLIER, (ALfloat)index) - 1.0f));
405 State->Tap[1 + index] = (ALuint)(length * Context->Frequency);
408 // Calculate the early reflections gain (from the master effect gain, and
409 // reflections gain parameters).
410 State->Early.Gain = Effect->Reverb.Gain * Effect->Reverb.ReflectionsGain;
412 // Calculate the gain (coefficient) for each early delay line.
413 for(index = 0;index < 4;index++)
414 State->Early.Coeff[index] = pow(10.0f, EARLY_LINE_LENGTH[index] /
415 Effect->Reverb.LateReverbDelay *
416 -60.0f / 20.0f);
418 // Calculate the first mixing matrix coefficient (x).
419 mixCoeff = 1.0f - (0.5f * pow(Effect->Reverb.Diffusion, 3.0f));
421 // Calculate the late reverb gain (from the master effect gain, and late
422 // reverb gain parameters). Since the output is tapped prior to the
423 // application of the delay line coefficients, this gain needs to be
424 // attenuated by the 'x' mix coefficient from above.
425 State->Late.Gain = Effect->Reverb.Gain * Effect->Reverb.LateReverbGain * mixCoeff;
427 /* To compensate for changes in modal density and decay time of the late
428 * reverb signal, the input is attenuated based on the maximal energy of
429 * the outgoing signal. This is calculated as the ratio between a
430 * reference value and the current approximation of energy for the output
431 * signal.
433 * Reverb output matches exponential decay of the form Sum(a^n), where a
434 * is the attenuation coefficient, and n is the sample ranging from 0 to
435 * infinity. The signal energy can thus be approximated using the area
436 * under this curve, calculated as: 1 / (1 - a).
438 * The reference energy is calculated from a signal at the lowest (effect
439 * at 1.0) density with a decay time of one second.
441 * The coefficient is calculated as the average length of the cyclical
442 * delay lines. This produces a better result than calculating the gain
443 * for each line individually (most likely a side effect of diffusion).
445 * The final result is the square root of the ratio bound to a maximum
446 * value of 1 (no amplification).
448 length = (LATE_LINE_LENGTH[0] + LATE_LINE_LENGTH[1] +
449 LATE_LINE_LENGTH[2] + LATE_LINE_LENGTH[3]);
450 g = length * (1.0f + LATE_LINE_MULTIPLIER) * 0.25f;
451 g = pow(10.0f, g * -60.0f / 20.0f);
452 g = 1.0f / (1.0f - (g * g));
453 length *= 1.0f + (Effect->Reverb.Density * LATE_LINE_MULTIPLIER) * 0.25f;
454 length = pow(10.0f, length / Effect->Reverb.DecayTime * -60.0f / 20.0f);
455 length = 1.0f / (1.0f - (length * length));
456 State->Late.DensityGain = __min(aluSqrt(g / length), 1.0f);
458 // Calculate the all-pass feed-back and feed-forward coefficient.
459 State->Late.ApFeedCoeff = 0.6f * pow(Effect->Reverb.Diffusion, 3.0f);
461 // Calculate the mixing matrix coefficient (y / x).
462 g = aluSqrt((1.0f - (mixCoeff * mixCoeff)) / 3.0f);
463 State->Late.MixCoeff = g / mixCoeff;
465 for(index = 0;index < 4;index++)
467 // Calculate the gain (coefficient) for each all-pass line.
468 State->Late.ApCoeff[index] = pow(10.0f, ALLPASS_LINE_LENGTH[index] /
469 Effect->Reverb.DecayTime *
470 -60.0f / 20.0f);
473 // If the HF limit parameter is flagged, calculate an appropriate limit
474 // based on the air absorption parameter.
475 if(Effect->Reverb.DecayHFLimit && Effect->Reverb.AirAbsorptionGainHF < 1.0f)
477 ALfloat limitRatio;
479 // For each of the cyclical delays, find the attenuation due to air
480 // absorption in dB (converting delay time to meters using the speed
481 // of sound). Then reversing the decay equation, solve for HF ratio.
482 // The delay length is cancelled out of the equation, so it can be
483 // calculated once for all lines.
484 limitRatio = 1.0f / (log10(Effect->Reverb.AirAbsorptionGainHF) *
485 SPEEDOFSOUNDMETRESPERSEC *
486 Effect->Reverb.DecayTime / -60.0f * 20.0f);
487 // Need to limit the result to a minimum of 0.1, just like the HF
488 // ratio parameter.
489 limitRatio = __max(limitRatio, 0.1f);
491 // Using the limit calculated above, apply the upper bound to the
492 // HF ratio.
493 hfRatio = __min(hfRatio, limitRatio);
496 // Calculate the low-pass filter frequency.
497 cw = cos(2.0f * M_PI * Effect->Reverb.HFReference / Context->Frequency);
499 for(index = 0;index < 4;index++)
501 // Calculate the length (in seconds) of each cyclical delay line.
502 length = LATE_LINE_LENGTH[index] * (1.0f + (Effect->Reverb.Density *
503 LATE_LINE_MULTIPLIER));
504 // Calculate the delay offset for the cyclical delay lines.
505 State->Late.Offset[index] = (ALuint)(length * Context->Frequency);
507 // Calculate the gain (coefficient) for each cyclical line.
508 State->Late.Coeff[index] = pow(10.0f, length / Effect->Reverb.DecayTime *
509 -60.0f / 20.0f);
511 // Eventually this should boost the high frequencies when the ratio
512 // exceeds 1.
513 coeff = 0.0f;
514 if (hfRatio < 1.0f)
516 // Calculate the decay equation for each low-pass filter.
517 g = pow(10.0f, length / (Effect->Reverb.DecayTime * hfRatio) *
518 -60.0f / 20.0f) / State->Late.Coeff[index];
519 g = __max(g, 0.1f);
520 g *= g;
522 // Calculate the gain (coefficient) for each low-pass filter.
523 if(g < 0.9999f) // 1-epsilon
524 coeff = (1 - g*cw - aluSqrt(2*g*(1-cw) - g*g*(1 - cw*cw))) / (1 - g);
526 // Very low decay times will produce minimal output, so apply an
527 // upper bound to the coefficient.
528 coeff = __min(coeff, 0.98f);
530 State->Late.LpCoeff[index] = coeff;
532 // Attenuate the cyclical line coefficients by the mixing coefficient
533 // (x).
534 State->Late.Coeff[index] *= mixCoeff;
537 // Calculate the 3D-panning gains for the early reflections and late
538 // reverb (for EAX mode).
540 ALfloat earlyPan[3] = { Effect->Reverb.ReflectionsPan[0], Effect->Reverb.ReflectionsPan[1], Effect->Reverb.ReflectionsPan[2] };
541 ALfloat latePan[3] = { Effect->Reverb.LateReverbPan[0], Effect->Reverb.LateReverbPan[1], Effect->Reverb.LateReverbPan[2] };
542 ALfloat *speakerGain, dirGain, ambientGain;
543 ALfloat length;
544 ALint pos;
546 length = earlyPan[0]*earlyPan[0] + earlyPan[1]*earlyPan[1] + earlyPan[2]*earlyPan[2];
547 if(length > 1.0f)
549 length = 1.0f / aluSqrt(length);
550 earlyPan[0] *= length;
551 earlyPan[1] *= length;
552 earlyPan[2] *= length;
554 length = latePan[0]*latePan[0] + latePan[1]*latePan[1] + latePan[2]*latePan[2];
555 if(length > 1.0f)
557 length = 1.0f / aluSqrt(length);
558 latePan[0] *= length;
559 latePan[1] *= length;
560 latePan[2] *= length;
563 // This code applies directional reverb just like the mixer applies
564 // directional sources. It diffuses the sound toward all speakers
565 // as the magnitude of the panning vector drops, which is only an
566 // approximation of the expansion of sound across the speakers from
567 // the panning direction.
568 pos = aluCart2LUTpos(earlyPan[2], earlyPan[0]);
569 speakerGain = &Context->PanningLUT[OUTPUTCHANNELS * pos];
570 dirGain = aluSqrt((earlyPan[0] * earlyPan[0]) + (earlyPan[2] * earlyPan[2]));
571 ambientGain = (1.0 - dirGain);
572 for(index = 0;index < OUTPUTCHANNELS;index++)
573 State->Early.PanGain[index] = dirGain * speakerGain[index] + ambientGain;
575 pos = aluCart2LUTpos(latePan[2], latePan[0]);
576 speakerGain = &Context->PanningLUT[OUTPUTCHANNELS * pos];
577 dirGain = aluSqrt((latePan[0] * latePan[0]) + (latePan[2] * latePan[2]));
578 ambientGain = (1.0 - dirGain);
579 for(index = 0;index < OUTPUTCHANNELS;index++)
580 State->Late.PanGain[index] = dirGain * speakerGain[index] + ambientGain;
584 // This processes the reverb state, given the input samples and an output
585 // buffer.
586 ALvoid VerbProcess(ALeffectState *effect, const ALeffectslot *Slot, ALuint SamplesToDo, const ALfloat *SamplesIn, ALfloat (*SamplesOut)[OUTPUTCHANNELS])
588 ALverbState *State = (ALverbState*)effect;
589 ALuint index;
590 ALfloat early[4], late[4], out[4];
591 ALfloat gain = Slot->Gain;
593 for(index = 0;index < SamplesToDo;index++)
595 // Process reverb for this sample.
596 ReverbInOut(State, SamplesIn[index], early, late);
598 // Mix early reflections and late reverb.
599 out[0] = (early[0] + late[0]) * gain;
600 out[1] = (early[1] + late[1]) * gain;
601 out[2] = (early[2] + late[2]) * gain;
602 out[3] = (early[3] + late[3]) * gain;
604 // Output the results.
605 SamplesOut[index][FRONT_LEFT] += out[0];
606 SamplesOut[index][FRONT_RIGHT] += out[1];
607 SamplesOut[index][FRONT_CENTER] += out[3];
608 SamplesOut[index][SIDE_LEFT] += out[0];
609 SamplesOut[index][SIDE_RIGHT] += out[1];
610 SamplesOut[index][BACK_LEFT] += out[0];
611 SamplesOut[index][BACK_RIGHT] += out[1];
612 SamplesOut[index][BACK_CENTER] += out[2];
616 // This processes the EAX reverb state, given the input samples and an output
617 // buffer.
618 ALvoid EAXVerbProcess(ALeffectState *effect, const ALeffectslot *Slot, ALuint SamplesToDo, const ALfloat *SamplesIn, ALfloat (*SamplesOut)[OUTPUTCHANNELS])
620 ALverbState *State = (ALverbState*)effect;
621 ALuint index;
622 ALfloat early[4], late[4];
623 ALfloat gain = Slot->Gain;
625 for(index = 0;index < SamplesToDo;index++)
627 // Process reverb for this sample.
628 ReverbInOut(State, SamplesIn[index], early, late);
630 // Unfortunately, while the number and configuration of gains for
631 // panning adjust according to OUTPUTCHANNELS, the output from the
632 // reverb engine is not so scalable.
633 SamplesOut[index][FRONT_LEFT] +=
634 (State->Early.PanGain[FRONT_LEFT]*early[0] +
635 State->Late.PanGain[FRONT_LEFT]*late[0]) * gain;
636 SamplesOut[index][FRONT_RIGHT] +=
637 (State->Early.PanGain[FRONT_RIGHT]*early[1] +
638 State->Late.PanGain[FRONT_RIGHT]*late[1]) * gain;
639 SamplesOut[index][FRONT_CENTER] +=
640 (State->Early.PanGain[FRONT_CENTER]*early[3] +
641 State->Late.PanGain[FRONT_CENTER]*late[3]) * gain;
642 SamplesOut[index][SIDE_LEFT] +=
643 (State->Early.PanGain[SIDE_LEFT]*early[0] +
644 State->Late.PanGain[SIDE_LEFT]*late[0]) * gain;
645 SamplesOut[index][SIDE_RIGHT] +=
646 (State->Early.PanGain[SIDE_RIGHT]*early[1] +
647 State->Late.PanGain[SIDE_RIGHT]*late[1]) * gain;
648 SamplesOut[index][BACK_LEFT] +=
649 (State->Early.PanGain[BACK_LEFT]*early[0] +
650 State->Late.PanGain[BACK_LEFT]*late[0]) * gain;
651 SamplesOut[index][BACK_RIGHT] +=
652 (State->Early.PanGain[BACK_RIGHT]*early[1] +
653 State->Late.PanGain[BACK_RIGHT]*late[1]) * gain;
654 SamplesOut[index][BACK_CENTER] +=
655 (State->Early.PanGain[BACK_CENTER]*early[2] +
656 State->Late.PanGain[BACK_CENTER]*late[2]) * gain;
660 // This creates the reverb state. It should be called only when the reverb
661 // effect is loaded into a slot that doesn't already have a reverb effect.
662 ALeffectState *VerbCreate(ALCcontext *Context)
664 ALverbState *State = NULL;
665 ALuint samples, length[13], totalLength, index;
667 State = malloc(sizeof(ALverbState));
668 if(!State)
670 alSetError(AL_OUT_OF_MEMORY);
671 return NULL;
674 State->state.Destroy = VerbDestroy;
675 State->state.Update = VerbUpdate;
676 State->state.Process = VerbProcess;
678 // All line lengths are powers of 2, calculated from their lengths, with
679 // an additional sample in case of rounding errors.
681 // See VerbUpdate() for an explanation of the additional calculation
682 // added to the master line length.
683 samples = (ALuint)
684 ((MASTER_LINE_LENGTH +
685 (LATE_LINE_LENGTH[0] * (1.0f + LATE_LINE_MULTIPLIER) *
686 (DECO_FRACTION * ((DECO_MULTIPLIER * DECO_MULTIPLIER *
687 DECO_MULTIPLIER) - 1.0f)))) *
688 Context->Frequency) + 1;
689 length[0] = NextPowerOf2(samples);
690 totalLength = length[0];
691 for(index = 0;index < 4;index++)
693 samples = (ALuint)(EARLY_LINE_LENGTH[index] * Context->Frequency) + 1;
694 length[1 + index] = NextPowerOf2(samples);
695 totalLength += length[1 + index];
697 for(index = 0;index < 4;index++)
699 samples = (ALuint)(ALLPASS_LINE_LENGTH[index] * Context->Frequency) + 1;
700 length[5 + index] = NextPowerOf2(samples);
701 totalLength += length[5 + index];
703 for(index = 0;index < 4;index++)
705 samples = (ALuint)(LATE_LINE_LENGTH[index] *
706 (1.0f + LATE_LINE_MULTIPLIER) * Context->Frequency) + 1;
707 length[9 + index] = NextPowerOf2(samples);
708 totalLength += length[9 + index];
711 // All lines share a single sample buffer and have their masks and start
712 // addresses calculated once.
713 State->SampleBuffer = malloc(totalLength * sizeof(ALfloat));
714 if(!State->SampleBuffer)
716 free(State);
717 alSetError(AL_OUT_OF_MEMORY);
718 return NULL;
720 for(index = 0; index < totalLength;index++)
721 State->SampleBuffer[index] = 0.0f;
723 State->LpFilter.coeff = 0.0f;
724 State->LpFilter.history[0] = 0.0f;
725 State->LpFilter.history[1] = 0.0f;
726 State->Delay.Mask = length[0] - 1;
727 State->Delay.Line = &State->SampleBuffer[0];
728 totalLength = length[0];
730 State->Tap[0] = 0;
731 State->Tap[1] = 0;
732 State->Tap[2] = 0;
733 State->Tap[3] = 0;
734 State->Tap[4] = 0;
736 State->Early.Gain = 0.0f;
737 for(index = 0;index < 4;index++)
739 State->Early.Coeff[index] = 0.0f;
740 State->Early.Delay[index].Mask = length[1 + index] - 1;
741 State->Early.Delay[index].Line = &State->SampleBuffer[totalLength];
742 totalLength += length[1 + index];
744 // The early delay lines have their read offsets calculated once.
745 State->Early.Offset[index] = (ALuint)(EARLY_LINE_LENGTH[index] *
746 Context->Frequency);
749 State->Late.Gain = 0.0f;
750 State->Late.DensityGain = 0.0f;
751 State->Late.ApFeedCoeff = 0.0f;
752 State->Late.MixCoeff = 0.0f;
754 for(index = 0;index < 4;index++)
756 State->Late.ApCoeff[index] = 0.0f;
757 State->Late.ApDelay[index].Mask = length[5 + index] - 1;
758 State->Late.ApDelay[index].Line = &State->SampleBuffer[totalLength];
759 totalLength += length[5 + index];
761 // The late all-pass lines have their read offsets calculated once.
762 State->Late.ApOffset[index] = (ALuint)(ALLPASS_LINE_LENGTH[index] *
763 Context->Frequency);
766 for(index = 0;index < 4;index++)
768 State->Late.Coeff[index] = 0.0f;
769 State->Late.Delay[index].Mask = length[9 + index] - 1;
770 State->Late.Delay[index].Line = &State->SampleBuffer[totalLength];
771 totalLength += length[9 + index];
773 State->Late.Offset[index] = 0;
775 State->Late.LpCoeff[index] = 0.0f;
776 State->Late.LpSample[index] = 0.0f;
779 // Panning is applied as an independent gain for each output channel.
780 for(index = 0;index < OUTPUTCHANNELS;index++)
782 State->Early.PanGain[index] = 0.0f;
783 State->Late.PanGain[index] = 0.0f;
786 State->Offset = 0;
787 return &State->state;
790 ALeffectState *EAXVerbCreate(ALCcontext *Context)
792 ALeffectState *State = VerbCreate(Context);
793 if(State) State->Process = EAXVerbProcess;
794 return State;