summaryrefslogtreecommitdiffstats
path: root/make/stub_includes/egl
Commit message (Collapse)AuthorAgeFilesLines
* deployment resturcturing: combine nativewindow/jogl/newt ; newt: 'driver' ↵Sven Gothel2011-08-051-1/+1
| | | | | | | | | | | | | | | | | | | | | separation ; android cleanup remaining all-in-one jnlp's / jars: jogl-all-awt.jnlp -> jogl.all.jar jogl-all-noawt.jnlp -> jogl.all-noawt.jar jogl-all-mobile.jnlp -> jogl.all-mobile.jar native for all above: jogl-all-natives-linux-amd64.jar jogl.all-android.apk jogl.all-android.jar more may follow for each supported platfrom ++++ - newt: proper 'driver' separation - all drivers reside now in jogamp.newt.driver.* - remove intptr.cfg / use gluegen's
* Minor gluegen 'loader file' changeSven Gothel2010-11-062-2/+6
|
* Minor patch to headers for gluegen ; GLES2 extensionsSven Gothel2010-11-061-1/+1
| | | | | | - ifndef GLAPI - GLES2/gl2ext.h add a few basic extensions - gl-64bit-types.h: use khronos 64bit types
* EGL: Fix gluegen usage, use khronos 64bit typedefsSven Gothel2010-11-062-7/+20
|
* Move khronos common header to khrSven Gothel2010-11-062-1033/+0
|
* Remove NVidia licensed KD and OMX files.Sven Gothel2010-11-042-102/+0
| | | | In case we still need these extensions, add them manually.
* Adding patches for gluegen interoperability and adding some extensions:Sven Gothel2010-11-043-9/+51
| | | | | | - eglplatform.h: if platform not recognized, use 'void pointer' for EGLNativeDisplayType, EGLNativeWindowType and EGLNativePixmapType - egl.h: adding ifndef core extension for gluegen and eglGetProcAddress - eglext.h: adding EGL_NV_texture_rectangle, EGL_NV_system_time, EGL_NV_omx_il_sink, EGL_RMSURFACE_NV
* Replaced with khronos versions: egl 1.4 2009-10-21, eglext 8 2010-11-03, ↵Sven Gothel2010-11-043-251/+261
| | | | eglplatform 2010-08-25
* Adding Win MSC patchSven Gothel2010-11-041-0/+5
|
* Replaced with khronos 1.0.3 versionSven Gothel2010-11-042-82/+13
|
* Fix file modesSven Gothel2010-07-079-0/+0
|
* Fix: Locking/Threading; Common IntIntHashMap and Buffers; Fix: ↵Sven Gothel2010-06-101-0/+0
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | glMap*Buffer*; GLX/WGL/CgGL: All runtime dynamic; Misc .. TODO: Compile and test on MacOSX .. Fix: ===== Multithreading/Locking: See jogl/doc/Implementation/MultiThreading.txt - Locking layer is not platform agnostic, ie GLContextImpl, GLDrawableImpl, .. and NEWT: Window/Display - No more use of JAWT global lock necessary, removed. - No need for X11 Display lock, on the contrary, this made the NV driver hang. - Use common window/surface lock - All NativeWindow surfaceLock's are recursive now glMapBuffer: If size is 0, don't do cont with the native call. glMapBufferRange: Fix capacity. glNamedBufferDataEXT: Track the size. glMapNamedBufferEXT: Manual impl. - use the tracked size glXGetVisualFromFBConfig, glXChooseFBConfig, glXChooseVisual: Instead of ignoring and implement a renamed version (*Copied), we just use ManualImplementation for the proper copy-result code. DesktopGLDynamicLookupHelper: Initialize _hasGLBinding* attributes in the determing loadGLJNILibrary() method, which is called by super(). Otherwise static init will overwrite them after the super() call. X11GLXDrawableFactory: Don't release anything at shutdown (removed sharedContext.destroy()), since this caused a freeze/SEGV sometimes. Fixed NEWT's reparentWindow() functionality incl NewtCanvasAWT usage. - Native: if not visible, don't focus, etc - NewtCanvasAWT: Use the container size to start with - Run the command on the EDT Using GlueGen's new DynamicLibraryBundle utility: - X11, Windows and MacOSX OpenGL adapted to DynamicLibraryBundleInfo. - X11GLXDynamicLookupHelper -> X11GLXDynamicLibraryBundleInfo - Remove all path from lib names. - GL order: libGL.so.1, libGL.so, GL - shallLinkGlobal: true -> to server some 'old' DRI systems -> http://dri.sourceforge.net/doc/DRIuserguide.html - shallLookupGlobal: false - Try both : glXGetProcAddressARB and glXGetProcAddress - Using bootstrap: GLX.glXGetProcAddress(long glxGetProcAddressHandle, String glFuncName) Found the issue with LIBGL_DRIVERS_PATH, ie if not set no valid GL instance can be found (ie ATI fglrx/DRI). This may happen if using a differen user than the desktop user for whom the env var is set within some /etc/X11/Xsession.d/ script. Enhancements: ============= GLBufferSizeTracker: Use IntIntHashMap and add DirectState size tracking. GLBufferStateTracker: Use IntIntHashMap. GLStateTracker: Use IntIntHashMap. GLDynamicLookupHelper: More generic (global loading/lookup and GetProcAddress function name list), remove redundant code. FIXME: MacOSXCGLDynamicLookupHelper: - Not tested - Not using NSImage lookup anymore as recommended by OSX API Doc, so dlsym is used always (to be tested) WindowsWGLDynamicLookupHelper: - Not tested GLX/WGL/CgGL is all runtime-dynamic as now, ie loaded and looked-up at runtime, no compile time dependencies to GL anymore, nor a need to specify CgGL. Split up WGL in GDI and WGL, to allow proper dynamic runtime linkage of OpenGL32 while using static binding to GDI32 NEWT events generated by native code are enqueued and not send directly. This should ease locking mechanisms .. if any are necessary. NEWT: More platform specific code moved to *Impl method, simplifying the generic code of the superclass and impl protocol. Cleanup: ========= Replace all InternalBufferUtil's with com.jogamp.common.nio.Buffers Removed all InternalBufferUtil's from repository Removed GLContextImpl notion of 'optimized' surface locking, where the surface gets unlocked during makeCurrent/release. This just makes no sense and would impact multithreading in a horrible way.
* Adaptions toSven Gothel2010-03-301-7/+1
| | | | | http://www.jogamp.org/bugzilla/show_bug.cgi?id=392 7220416bcef3140883d3966d921442feae3107c4
* Update GlueGen to 7dc9c5601d5689dcbc003ca51cfe826942ea3e6b (latest)Sven Gothel2009-08-052-28/+37
| | | | | | | | | | | | | | | | | | | | | | | | | | - Fixes for OpenGL 3.2 - More strict define/function checking - Better documentation in source code: extension relation - GL extension marker exclusion is done by GlueGen now - Adapted gluegen cfg files Added OpenGL 3.2 extensions for GL3 Revalidation of all OpenGL 2.0/3.0/3.1 and 3.2 extensions GL2GL3 based on OpenGL 2.0/3.0 headers EGL shares common egl-common.cfg file Removed experimental java system property 'jogl.GLContext.3_2', try a 3.2 context in case of GL3. X11GLXContext: - Always try to make a created context current, to verify it's usability. This is different than under WGL. - Temporary removed usage: GLX.GLX_CONTEXT_PROFILE_MASK_ARB NV driver bug.
* Add Custom NativeWindow Type 'BroadcomEGL' ↵sg2158892009-07-271-5/+0
| | | | (-Dnativewindow.ws.name=BroadcomEGL): 1st Draft of supporting broadcom's proprietary EGL mapping
* mips changesMorris Meyer2009-07-271-0/+5
|
* Corrected non-C syntax. Worked around ancient compiler/OS onKenneth Russel2009-06-171-1/+6
| | | | | | | Solaris/SPARC nightly build machines. git-svn-id: file:///usr/local/projects/SUN/JOGL/git-svn/svn-server-sync/jogl/trunk@1978 232f8b59-042b-4e1e-8c03-345bb8c30851
* Changed typedef for EGLTimeKHR to use already-defined uint64_t insteadKenneth Russel2009-06-161-1/+1
| | | | | | | of unsigned long long which is not supported in some compilers (e.g. MSVC 6) git-svn-id: file:///usr/local/projects/SUN/JOGL/git-svn/svn-server-sync/jogl/trunk@1963 232f8b59-042b-4e1e-8c03-345bb8c30851
* Copied JOGL_2_SANDBOX r1957 on to trunk; JOGL_2_SANDBOX branch is now closedKenneth Russel2009-06-159-0/+1925
git-svn-id: file:///usr/local/projects/SUN/JOGL/git-svn/svn-server-sync/jogl/trunk@1959 232f8b59-042b-4e1e-8c03-345bb8c30851
id='n729' href='#n729'>729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348
/**
 * Reverb for the OpenAL cross platform audio library
 * Copyright (C) 2008-2009 by Christopher Fitzgerald.
 * This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Library General Public
 *  License as published by the Free Software Foundation; either
 *  version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 *  License along with this library; if not, write to the
 *  Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 *  Boston, MA  02111-1307, USA.
 * Or go to http://www.gnu.org/copyleft/lgpl.html
 */

#include "config.h"

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

#include "AL/al.h"
#include "AL/alc.h"
#include "alMain.h"
#include "alAuxEffectSlot.h"
#include "alEffect.h"
#include "alError.h"
#include "alu.h"

typedef struct DelayLine
{
    // The delay lines use sample lengths that are powers of 2 to allow the
    // use of bit-masking instead of a modulus for wrapping.
    ALuint   Mask;
    ALfloat *Line;
} DelayLine;

typedef struct ALverbState {
    // Must be first in all effects!
    ALeffectState state;

    // All delay lines are allocated as a single buffer to reduce memory
    // fragmentation and management code.
    ALfloat  *SampleBuffer;
    ALuint    TotalSamples;
    // Master effect low-pass filter (2 chained 1-pole filters).
    FILTER    LpFilter;
    ALfloat   LpHistory[2];
    struct {
        // Modulator delay line.
        DelayLine Delay;
        // The vibrato time is tracked with an index over a modulus-wrapped
        // range (in samples).
        ALuint    Index;
        ALuint    Range;
        // The depth of frequency change (also in samples) and its filter.
        ALfloat   Depth;
        ALfloat   Coeff;
        ALfloat   Filter;
    } Mod;
    // Initial effect delay.
    DelayLine Delay;
    // The tap points for the initial delay.  First tap goes to early
    // reflections, the last to late reverb.
    ALuint    DelayTap[2];
    struct {
        // Output gain for early reflections.
        ALfloat   Gain;
        // Early reflections are done with 4 delay lines.
        ALfloat   Coeff[4];
        DelayLine Delay[4];
        ALuint    Offset[4];
        // The gain for each output channel based on 3D panning (only for the
        // EAX path).
        ALfloat   PanGain[MAXCHANNELS];
    } Early;
    // Decorrelator delay line.
    DelayLine Decorrelator;
    // There are actually 4 decorrelator taps, but the first occurs at the
    // initial sample.
    ALuint    DecoTap[3];
    struct {
        // Output gain for late reverb.
        ALfloat   Gain;
        // Attenuation to compensate for the modal density and decay rate of
        // the late lines.
        ALfloat   DensityGain;
        // The feed-back and feed-forward all-pass coefficient.
        ALfloat   ApFeedCoeff;
        // Mixing matrix coefficient.
        ALfloat   MixCoeff;
        // Late reverb has 4 parallel all-pass filters.
        ALfloat   ApCoeff[4];
        DelayLine ApDelay[4];
        ALuint    ApOffset[4];
        // In addition to 4 cyclical delay lines.
        ALfloat   Coeff[4];
        DelayLine Delay[4];
        ALuint    Offset[4];
        // The cyclical delay lines are 1-pole low-pass filtered.
        ALfloat   LpCoeff[4];
        ALfloat   LpSample[4];
        // The gain for each output channel based on 3D panning (only for the
        // EAX path).
        ALfloat   PanGain[MAXCHANNELS];
    } Late;
    struct {
        // Attenuation to compensate for the modal density and decay rate of
        // the echo line.
        ALfloat   DensityGain;
        // Echo delay and all-pass lines.
        DelayLine Delay;
        DelayLine ApDelay;
        ALfloat   Coeff;
        ALfloat   ApFeedCoeff;
        ALfloat   ApCoeff;
        ALuint    Offset;
        ALuint    ApOffset;
        // The echo line is 1-pole low-pass filtered.
        ALfloat   LpCoeff;
        ALfloat   LpSample;
        // Echo mixing coefficients.
        ALfloat   MixCoeff[2];
    } Echo;
    // The current read offset for all delay lines.
    ALuint Offset;

    // The gain for each output channel (non-EAX path only; aliased from
    // Late.PanGain)
    ALfloat *Gain;
} ALverbState;

/* This coefficient is used to define the maximum frequency range controlled
 * by the modulation depth.  The current value of 0.1 will allow it to swing
 * from 0.9x to 1.1x.  This value must be below 1.  At 1 it will cause the
 * sampler to stall on the downswing, and above 1 it will cause it to sample
 * backwards.
 */
static const ALfloat MODULATION_DEPTH_COEFF = 0.1f;

/* A filter is used to avoid the terrible distortion caused by changing
 * modulation time and/or depth.  To be consistent across different sample
 * rates, the coefficient must be raised to a constant divided by the sample
 * rate:  coeff^(constant / rate).
 */
static const ALfloat MODULATION_FILTER_COEFF = 0.048f;
static const ALfloat MODULATION_FILTER_CONST = 100000.0f;

// When diffusion is above 0, an all-pass filter is used to take the edge off
// the echo effect.  It uses the following line length (in seconds).
static const ALfloat ECHO_ALLPASS_LENGTH = 0.0133f;

// Input into the late reverb is decorrelated between four channels.  Their
// timings are dependent on a fraction and multiplier.  See the
// UpdateDecorrelator() routine for the calculations involved.
static const ALfloat DECO_FRACTION = 0.15f;
static const ALfloat DECO_MULTIPLIER = 2.0f;

// All delay line lengths are specified in seconds.

// The lengths of the early delay lines.
static const ALfloat EARLY_LINE_LENGTH[4] =
{
    0.0015f, 0.0045f, 0.0135f, 0.0405f
};

// The lengths of the late all-pass delay lines.
static const ALfloat ALLPASS_LINE_LENGTH[4] =
{
    0.0151f, 0.0167f, 0.0183f, 0.0200f,
};

// The lengths of the late cyclical delay lines.
static const ALfloat LATE_LINE_LENGTH[4] =
{
    0.0211f, 0.0311f, 0.0461f, 0.0680f
};

// The late cyclical delay lines have a variable length dependent on the
// effect's density parameter (inverted for some reason) and this multiplier.
static const ALfloat LATE_LINE_MULTIPLIER = 4.0f;

// Calculate the length of a delay line and store its mask and offset.
static ALuint CalcLineLength(ALfloat length, ALintptrEXT offset, ALuint frequency, DelayLine *Delay)
{
    ALuint samples;

    // All line lengths are powers of 2, calculated from their lengths, with
    // an additional sample in case of rounding errors.
    samples = NextPowerOf2((ALuint)(length * frequency) + 1);
    // All lines share a single sample buffer.
    Delay->Mask = samples - 1;
    Delay->Line = (ALfloat*)offset;
    // Return the sample count for accumulation.
    return samples;
}

// Given the allocated sample buffer, this function updates each delay line
// offset.
static __inline ALvoid RealizeLineOffset(ALfloat * sampleBuffer, DelayLine *Delay)
{
    Delay->Line = &sampleBuffer[(ALintptrEXT)Delay->Line];
}

/* Calculates the delay line metrics and allocates the shared sample buffer
 * for all lines given a flag indicating whether or not to allocate the EAX-
 * related delays (eaxFlag) and the sample rate (frequency).  If an
 * allocation failure occurs, it returns AL_FALSE.
 */
static ALboolean AllocLines(ALboolean eaxFlag, ALuint frequency, ALverbState *State)
{
    ALuint totalSamples, index;
    ALfloat length;
    ALfloat *newBuffer = NULL;

    // All delay line lengths are calculated to accomodate the full range of
    // lengths given their respective paramters.
    totalSamples = 0;
    if(eaxFlag)
    {
        /* The modulator's line length is calculated from the maximum
         * modulation time and depth coefficient, and halfed for the low-to-
         * high frequency swing.  An additional sample is added to keep it
         * stable when there is no modulation.
         */
        length = (AL_EAXREVERB_MAX_MODULATION_TIME * MODULATION_DEPTH_COEFF /
                  2.0f) + (1.0f / frequency);
        totalSamples += CalcLineLength(length, totalSamples, frequency,
                                       &State->Mod.Delay);
    }

    // The initial delay is the sum of the reflections and late reverb
    // delays.
    if(eaxFlag)
        length = AL_EAXREVERB_MAX_REFLECTIONS_DELAY +
                 AL_EAXREVERB_MAX_LATE_REVERB_DELAY;
    else
        length = AL_REVERB_MAX_REFLECTIONS_DELAY +
                 AL_REVERB_MAX_LATE_REVERB_DELAY;
    totalSamples += CalcLineLength(length, totalSamples, frequency,
                                   &State->Delay);

    // The early reflection lines.
    for(index = 0;index < 4;index++)
        totalSamples += CalcLineLength(EARLY_LINE_LENGTH[index], totalSamples,
                                       frequency, &State->Early.Delay[index]);

    // The decorrelator line is calculated from the lowest reverb density (a
    // parameter value of 1).
    length = (DECO_FRACTION * DECO_MULTIPLIER * DECO_MULTIPLIER) *
             LATE_LINE_LENGTH[0] * (1.0f + LATE_LINE_MULTIPLIER);
    totalSamples += CalcLineLength(length, totalSamples, frequency,
                                   &State->Decorrelator);

    // The late all-pass lines.
    for(index = 0;index < 4;index++)
        totalSamples += CalcLineLength(ALLPASS_LINE_LENGTH[index], totalSamples,
                                       frequency, &State->Late.ApDelay[index]);

    // The late delay lines are calculated from the lowest reverb density.
    for(index = 0;index < 4;index++)
    {
        length = LATE_LINE_LENGTH[index] * (1.0f + LATE_LINE_MULTIPLIER);
        totalSamples += CalcLineLength(length, totalSamples, frequency,
                                       &State->Late.Delay[index]);
    }

    if(eaxFlag)
    {
        // The echo all-pass and delay lines.
        totalSamples += CalcLineLength(ECHO_ALLPASS_LENGTH, totalSamples,
                                       frequency, &State->Echo.ApDelay);
        totalSamples += CalcLineLength(AL_EAXREVERB_MAX_ECHO_TIME, totalSamples,
                                       frequency, &State->Echo.Delay);
    }

    if(totalSamples != State->TotalSamples)
    {
        newBuffer = realloc(State->SampleBuffer, sizeof(ALfloat) * totalSamples);
        if(newBuffer == NULL)
            return AL_FALSE;
        State->SampleBuffer = newBuffer;
        State->TotalSamples = totalSamples;
    }

    // Update all delays to reflect the new sample buffer.
    RealizeLineOffset(State->SampleBuffer, &State->Delay);
    RealizeLineOffset(State->SampleBuffer, &State->Decorrelator);
    for(index = 0;index < 4;index++)
    {
        RealizeLineOffset(State->SampleBuffer, &State->Early.Delay[index]);
        RealizeLineOffset(State->SampleBuffer, &State->Late.ApDelay[index]);
        RealizeLineOffset(State->SampleBuffer, &State->Late.Delay[index]);
    }
    if(eaxFlag)
    {
        RealizeLineOffset(State->SampleBuffer, &State->Mod.Delay);
        RealizeLineOffset(State->SampleBuffer, &State->Echo.ApDelay);
        RealizeLineOffset(State->SampleBuffer, &State->Echo.Delay);
    }

    // Clear the sample buffer.
    for(index = 0;index < State->TotalSamples;index++)
        State->SampleBuffer[index] = 0.0f;

    return AL_TRUE;
}

// Calculate a decay coefficient given the length of each cycle and the time
// until the decay reaches -60 dB.
static __inline ALfloat CalcDecayCoeff(ALfloat length, ALfloat decayTime)
{
    return aluPow(10.0f, length / decayTime * -60.0f / 20.0f);
}

// Calculate a decay length from a coefficient and the time until the decay
// reaches -60 dB.
static __inline ALfloat CalcDecayLength(ALfloat coeff, ALfloat decayTime)
{
    return log10(coeff) / -60.0 * 20.0f * decayTime;
}

// Calculate the high frequency parameter for the I3DL2 coefficient
// calculation.
static __inline ALfloat CalcI3DL2HFreq(ALfloat hfRef, ALuint frequency)
{
    return cos(2.0f * M_PI * hfRef / frequency);
}

// Calculate an attenuation to be applied to the input of any echo models to
// compensate for modal density and decay time.
static __inline ALfloat CalcDensityGain(ALfloat a)
{
    /* The energy of a signal can be obtained by finding the area under the
     * squared signal.  This takes the form of Sum(x_n^2), where x is the
     * amplitude for the sample n.
     *
     * Decaying feedback matches exponential decay of the form Sum(a^n),
     * where a is the attenuation coefficient, and n is the sample.  The area
     * under this decay curve can be calculated as:  1 / (1 - a).
     *
     * Modifying the above equation to find the squared area under the curve
     * (for energy) yields:  1 / (1 - a^2).  Input attenuation can then be
     * calculated by inverting the square root of this approximation,
     * yielding:  1 / sqrt(1 / (1 - a^2)), simplified to: sqrt(1 - a^2).
     */
    return aluSqrt(1.0f - (a * a));
}

// Calculate the mixing matrix coefficients given a diffusion factor.
static __inline ALvoid CalcMatrixCoeffs(ALfloat diffusion, ALfloat *x, ALfloat *y)
{
    ALfloat n, t;

    // The matrix is of order 4, so n is sqrt (4 - 1).
    n = aluSqrt(3.0f);
    t = diffusion * atan(n);

    // Calculate the first mixing matrix coefficient.
    *x = cos(t);
    // Calculate the second mixing matrix coefficient.
    *y = sin(t) / n;
}

// Calculate the limited HF ratio for use with the late reverb low-pass
// filters.
static ALfloat CalcLimitedHfRatio(ALfloat hfRatio, ALfloat airAbsorptionGainHF, ALfloat decayTime)
{
    ALfloat limitRatio;

    /* Find the attenuation due to air absorption in dB (converting delay
     * time to meters using the speed of sound).  Then reversing the decay
     * equation, solve for HF ratio.  The delay length is cancelled out of
     * the equation, so it can be calculated once for all lines.
     */
    limitRatio = 1.0f / (CalcDecayLength(airAbsorptionGainHF, decayTime) *
                         SPEEDOFSOUNDMETRESPERSEC);
    // Need to limit the result to a minimum of 0.1, just like the HF ratio
    // parameter.
    limitRatio = __max(limitRatio, 0.1f);

    // Using the limit calculated above, apply the upper bound to the HF
    // ratio.
    return __min(hfRatio, limitRatio);
}

// Calculate the coefficient for a HF (and eventually LF) decay damping
// filter.
static __inline ALfloat CalcDampingCoeff(ALfloat hfRatio, ALfloat length, ALfloat decayTime, ALfloat decayCoeff, ALfloat cw)
{
    ALfloat coeff, g;

    // Eventually this should boost the high frequencies when the ratio
    // exceeds 1.
    coeff = 0.0f;
    if (hfRatio < 1.0f)
    {
        // Calculate the low-pass coefficient by dividing the HF decay
        // coefficient by the full decay coefficient.
        g = CalcDecayCoeff(length, decayTime * hfRatio) / decayCoeff;

        // Damping is done with a 1-pole filter, so g needs to be squared.
        g *= g;
        coeff = lpCoeffCalc(g, cw);

        // Very low decay times will produce minimal output, so apply an
        // upper bound to the coefficient.
        coeff = __min(coeff, 0.98f);
    }
    return coeff;
}

// Update the EAX modulation index, range, and depth.  Keep in mind that this
// kind of vibrato is additive and not multiplicative as one may expect.  The
// downswing will sound stronger than the upswing.
static ALvoid UpdateModulator(ALfloat modTime, ALfloat modDepth, ALuint frequency, ALverbState *State)
{
    ALfloat length;

    /* Modulation is calculated in two parts.
     *
     * The modulation time effects the sinus applied to the change in
     * frequency.  An index out of the current time range (both in samples)
     * is incremented each sample.  The range is bound to a reasonable
     * minimum (1 sample) and when the timing changes, the index is rescaled
     * to the new range (to keep the sinus consistent).
     */
    length = modTime * frequency;
    if (length >= 1.0f) {
       State->Mod.Index = (ALuint)(State->Mod.Index * length /
                                   State->Mod.Range);
       State->Mod.Range = (ALuint)length;
    } else {
       State->Mod.Index = 0;
       State->Mod.Range = 1;
    }

    /* The modulation depth effects the amount of frequency change over the
     * range of the sinus.  It needs to be scaled by the modulation time so
     * that a given depth produces a consistent change in frequency over all
     * ranges of time.  Since the depth is applied to a sinus value, it needs
     * to be halfed once for the sinus range and again for the sinus swing
     * in time (half of it is spent decreasing the frequency, half is spent
     * increasing it).
     */
    State->Mod.Depth = modDepth * MODULATION_DEPTH_COEFF * modTime / 2.0f /
                       2.0f * frequency;
}

// Update the offsets for the initial effect delay line.
static ALvoid UpdateDelayLine(ALfloat earlyDelay, ALfloat lateDelay, ALuint frequency, ALverbState *State)
{
    // Calculate the initial delay taps.
    State->DelayTap[0] = (ALuint)(earlyDelay * frequency);
    State->DelayTap[1] = (ALuint)((earlyDelay + lateDelay) * frequency);
}

// Update the early reflections gain and line coefficients.
static ALvoid UpdateEarlyLines(ALfloat reverbGain, ALfloat earlyGain, ALfloat lateDelay, ALverbState *State)
{
    ALuint index;

    // Calculate the early reflections gain (from the master effect gain, and
    // reflections gain parameters) with a constant attenuation of 0.5.
    State->Early.Gain = 0.5f * reverbGain * earlyGain;

    // Calculate the gain (coefficient) for each early delay line using the
    // late delay time.  This expands the early reflections to the start of
    // the late reverb.
    for(index = 0;index < 4;index++)
        State->Early.Coeff[index] = CalcDecayCoeff(EARLY_LINE_LENGTH[index],
                                                   lateDelay);
}

// Update the offsets for the decorrelator line.
static ALvoid UpdateDecorrelator(ALfloat density, ALuint frequency, ALverbState *State)
{
    ALuint index;
    ALfloat length;

    /* The late reverb inputs are decorrelated to smooth the reverb tail and
     * reduce harsh echos.  The first tap occurs immediately, while the
     * remaining taps are delayed by multiples of a fraction of the smallest
     * cyclical delay time.
     *
     * offset[index] = (FRACTION (MULTIPLIER^index)) smallest_delay
     */
    for(index = 0;index < 3;index++)
    {
        length = (DECO_FRACTION * aluPow(DECO_MULTIPLIER, (ALfloat)index)) *
                 LATE_LINE_LENGTH[0] * (1.0f + (density * LATE_LINE_MULTIPLIER));
        State->DecoTap[index] = (ALuint)(length * frequency);
    }
}

// Update the late reverb gains, line lengths, and line coefficients.
static ALvoid UpdateLateLines(ALfloat reverbGain, ALfloat lateGain, ALfloat xMix, ALfloat density, ALfloat decayTime, ALfloat diffusion, ALfloat hfRatio, ALfloat cw, ALuint frequency, ALverbState *State)
{
    ALfloat length;
    ALuint index;

    /* Calculate the late reverb gain (from the master effect gain, and late
     * reverb gain parameters).  Since the output is tapped prior to the
     * application of the next delay line coefficients, this gain needs to be
     * attenuated by the 'x' mixing matrix coefficient as well.
     */
    State->Late.Gain = reverbGain * lateGain * xMix;

    /* To compensate for changes in modal density and decay time of the late
     * reverb signal, the input is attenuated based on the maximal energy of
     * the outgoing signal.  This approximation is used to keep the apparent
     * energy of the signal equal for all ranges of density and decay time.
     *
     * The average length of the cyclcical delay lines is used to calculate
     * the attenuation coefficient.
     */
    length = (LATE_LINE_LENGTH[0] + LATE_LINE_LENGTH[1] +
              LATE_LINE_LENGTH[2] + LATE_LINE_LENGTH[3]) / 4.0f;
    length *= 1.0f + (density * LATE_LINE_MULTIPLIER);
    State->Late.DensityGain = CalcDensityGain(CalcDecayCoeff(length,
                                                             decayTime));

    // Calculate the all-pass feed-back and feed-forward coefficient.
    State->Late.ApFeedCoeff = 0.5f * aluPow(diffusion, 2.0f);

    for(index = 0;index < 4;index++)
    {
        // Calculate the gain (coefficient) for each all-pass line.
        State->Late.ApCoeff[index] = CalcDecayCoeff(ALLPASS_LINE_LENGTH[index],
                                                    decayTime);

        // Calculate the length (in seconds) of each cyclical delay line.
        length = LATE_LINE_LENGTH[index] * (1.0f + (density *
                                                    LATE_LINE_MULTIPLIER));

        // Calculate the delay offset for each cyclical delay line.
        State->Late.Offset[index] = (ALuint)(length * frequency);

        // Calculate the gain (coefficient) for each cyclical line.
        State->Late.Coeff[index] = CalcDecayCoeff(length, decayTime);

        // Calculate the damping coefficient for each low-pass filter.
        State->Late.LpCoeff[index] =
            CalcDampingCoeff(hfRatio, length, decayTime,
                             State->Late.Coeff[index], cw);

        // Attenuate the cyclical line coefficients by the mixing coefficient
        // (x).
        State->Late.Coeff[index] *= xMix;
    }
}

// Update the echo gain, line offset, line coefficients, and mixing
// coefficients.
static ALvoid UpdateEchoLine(ALfloat reverbGain, ALfloat lateGain, ALfloat echoTime, ALfloat decayTime, ALfloat diffusion, ALfloat echoDepth, ALfloat hfRatio, ALfloat cw, ALuint frequency, ALverbState *State)
{
    // Update the offset and coefficient for the echo delay line.
    State->Echo.Offset = (ALuint)(echoTime * frequency);

    // Calculate the decay coefficient for the echo line.
    State->Echo.Coeff = CalcDecayCoeff(echoTime, decayTime);

    // Calculate the energy-based attenuation coefficient for the echo delay
    // line.
    State->Echo.DensityGain = CalcDensityGain(State->Echo.Coeff);

    // Calculate the echo all-pass feed coefficient.
    State->Echo.ApFeedCoeff = 0.5f * aluPow(diffusion, 2.0f);

    // Calculate the echo all-pass attenuation coefficient.
    State->Echo.ApCoeff = CalcDecayCoeff(ECHO_ALLPASS_LENGTH, decayTime);

    // Calculate the damping coefficient for each low-pass filter.
    State->Echo.LpCoeff = CalcDampingCoeff(hfRatio, echoTime, decayTime,
                                           State->Echo.Coeff, cw);

    /* Calculate the echo mixing coefficients.  The first is applied to the
     * echo itself.  The second is used to attenuate the late reverb when
     * echo depth is high and diffusion is low, so the echo is slightly
     * stronger than the decorrelated echos in the reverb tail.
     */
    State->Echo.MixCoeff[0] = reverbGain * lateGain * echoDepth;
    State->Echo.MixCoeff[1] = 1.0f - (echoDepth * 0.5f * (1.0f - diffusion));
}

// Update the early and late 3D panning gains.
static ALvoid Update3DPanning(const ALCdevice *Device, const ALfloat *ReflectionsPan, const ALfloat *LateReverbPan, ALverbState *State)
{
    ALfloat earlyPan[3] = { ReflectionsPan[0], ReflectionsPan[1],
                            ReflectionsPan[2] };
    ALfloat latePan[3] = { LateReverbPan[0], LateReverbPan[1],
                           LateReverbPan[2] };
    const ALfloat *speakerGain;
    ALfloat dirGain;
    ALfloat length;
    ALuint index;
    ALint pos;

    // Calculate the 3D-panning gains for the early reflections and late
    // reverb.
    length = earlyPan[0]*earlyPan[0] + earlyPan[1]*earlyPan[1] + earlyPan[2]*earlyPan[2];
    if(length > 1.0f)
    {
        length = 1.0f / aluSqrt(length);
        earlyPan[0] *= length;
        earlyPan[1] *= length;
        earlyPan[2] *= length;
    }
    length = latePan[0]*latePan[0] + latePan[1]*latePan[1] + latePan[2]*latePan[2];
    if(length > 1.0f)
    {
        length = 1.0f / aluSqrt(length);
        latePan[0] *= length;
        latePan[1] *= length;
        latePan[2] *= length;
    }

    /* This code applies directional reverb just like the mixer applies
     * directional sources.  It diffuses the sound toward all speakers as the
     * magnitude of the panning vector drops, which is only a rough
     * approximation of the expansion of sound across the speakers from the
     * panning direction.
     */
    pos = aluCart2LUTpos(earlyPan[2], earlyPan[0]);
    speakerGain = &Device->PanningLUT[MAXCHANNELS * pos];
    dirGain = aluSqrt((earlyPan[0] * earlyPan[0]) + (earlyPan[2] * earlyPan[2]));

    for(index = 0;index < MAXCHANNELS;index++)
        State->Early.PanGain[index] = 0.0f;
    for(index = 0;index < Device->NumChan;index++)
    {
        Channel chan = Device->Speaker2Chan[index];
        State->Early.PanGain[chan] = 1.0 + (speakerGain[chan]-1.0)*dirGain;
    }


    pos = aluCart2LUTpos(latePan[2], latePan[0]);
    speakerGain = &Device->PanningLUT[MAXCHANNELS * pos];
    dirGain = aluSqrt((latePan[0] * latePan[0]) + (latePan[2] * latePan[2]));

    for(index = 0;index < MAXCHANNELS;index++)
         State->Late.PanGain[index] = 0.0f;
    for(index = 0;index < Device->NumChan;index++)
    {
        Channel chan = Device->Speaker2Chan[index];
        State->Late.PanGain[chan] = 1.0 + (speakerGain[chan]-1.0)*dirGain;
    }
}

// Basic delay line input/output routines.
static __inline ALfloat DelayLineOut(DelayLine *Delay, ALuint offset)
{
    return Delay->Line[offset&Delay->Mask];
}

static __inline ALvoid DelayLineIn(DelayLine *Delay, ALuint offset, ALfloat in)
{
    Delay->Line[offset&Delay->Mask] = in;
}

// Attenuated delay line output routine.
static __inline ALfloat AttenuatedDelayLineOut(DelayLine *Delay, ALuint offset, ALfloat coeff)
{
    return coeff * Delay->Line[offset&Delay->Mask];
}

// Basic attenuated all-pass input/output routine.
static __inline ALfloat AllpassInOut(DelayLine *Delay, ALuint outOffset, ALuint inOffset, ALfloat in, ALfloat feedCoeff, ALfloat coeff)
{
    ALfloat out, feed;

    out = DelayLineOut(Delay, outOffset);
    feed = feedCoeff * in;
    DelayLineIn(Delay, inOffset, (feedCoeff * (out - feed)) + in);

    // The time-based attenuation is only applied to the delay output to
    // keep it from affecting the feed-back path (which is already controlled
    // by the all-pass feed coefficient).
    return (coeff * out) - feed;
}

// Given an input sample, this function produces modulation for the late
// reverb.
static __inline ALfloat EAXModulation(ALverbState *State, ALfloat in)
{
    ALfloat sinus, frac;
    ALuint offset;
    ALfloat out0, out1;

    // Calculate the sinus rythm (dependent on modulation time and the
    // sampling rate).  The center of the sinus is moved to reduce the delay
    // of the effect when the time or depth are low.
    sinus = 1.0f - cos(2.0f * M_PI * State->Mod.Index / State->Mod.Range);

    // The depth determines the range over which to read the input samples
    // from, so it must be filtered to reduce the distortion caused by even
    // small parameter changes.
    State->Mod.Filter = lerp(State->Mod.Filter, State->Mod.Depth,
                             State->Mod.Coeff);

    // Calculate the read offset and fraction between it and the next sample.
    frac   = (1.0f + (State->Mod.Filter * sinus));
    offset = (ALuint)frac;
    frac  -= offset;

    // Get the two samples crossed by the offset, and feed the delay line
    // with the next input sample.
    out0 = DelayLineOut(&State->Mod.Delay, State->Offset - offset);
    out1 = DelayLineOut(&State->Mod.Delay, State->Offset - offset - 1);
    DelayLineIn(&State->Mod.Delay, State->Offset, in);

    // Step the modulation index forward, keeping it bound to its range.
    State->Mod.Index = (State->Mod.Index + 1) % State->Mod.Range;

    // The output is obtained by linearly interpolating the two samples that
    // were acquired above.
    return lerp(out0, out1, frac);
}

// Delay line output routine for early reflections.
static __inline ALfloat EarlyDelayLineOut(ALverbState *State, ALuint index)
{
    return AttenuatedDelayLineOut(&State->Early.Delay[index],
                                  State->Offset - State->Early.Offset[index],
                                  State->Early.Coeff[index]);
}

// Given an input sample, this function produces four-channel output for the
// early reflections.
static __inline ALvoid EarlyReflection(ALverbState *State, ALfloat in, ALfloat *out)
{
    ALfloat d[4], v, f[4];

    // Obtain the decayed results of each early delay line.
    d[0] = EarlyDelayLineOut(State, 0);
    d[1] = EarlyDelayLineOut(State, 1);
    d[2] = EarlyDelayLineOut(State, 2);
    d[3] = EarlyDelayLineOut(State, 3);

    /* The following uses a lossless scattering junction from waveguide
     * theory.  It actually amounts to a householder mixing matrix, which
     * will produce a maximally diffuse response, and means this can probably
     * be considered a simple feed-back delay network (FDN).
     *          N
     *         ---
     *         \
     * v = 2/N /   d_i
     *         ---
     *         i=1
     */
    v = (d[0] + d[1] + d[2] + d[3]) * 0.5f;
    // The junction is loaded with the input here.
    v += in;

    // Calculate the feed values for the delay lines.
    f[0] = v - d[0];
    f[1] = v - d[1];
    f[2] = v - d[2];
    f[3] = v - d[3];

    // Re-feed the delay lines.
    DelayLineIn(&State->Early.Delay[0], State->Offset, f[0]);
    DelayLineIn(&State->Early.Delay[1], State->Offset, f[1]);
    DelayLineIn(&State->Early.Delay[2], State->Offset, f[2]);
    DelayLineIn(&State->Early.Delay[3], State->Offset, f[3]);

    // Output the results of the junction for all four channels.
    out[0] = State->Early.Gain * f[0];
    out[1] = State->Early.Gain * f[1];
    out[2] = State->Early.Gain * f[2];
    out[3] = State->Early.Gain * f[3];
}

// All-pass input/output routine for late reverb.
static __inline ALfloat LateAllPassInOut(ALverbState *State, ALuint index, ALfloat in)
{
    return AllpassInOut(&State->Late.ApDelay[index],
                        State->Offset - State->Late.ApOffset[index],
                        State->Offset, in, State->Late.ApFeedCoeff,
                        State->Late.ApCoeff[index]);
}

// Delay line output routine for late reverb.
static __inline ALfloat LateDelayLineOut(ALverbState *State, ALuint index)
{
    return AttenuatedDelayLineOut(&State->Late.Delay[index],
                                  State->Offset - State->Late.Offset[index],
                                  State->Late.Coeff[index]);
}

// Low-pass filter input/output routine for late reverb.
static __inline ALfloat LateLowPassInOut(ALverbState *State, ALuint index, ALfloat in)
{
    in = lerp(in, State->Late.LpSample[index], State->Late.LpCoeff[index]);
    State->Late.LpSample[index] = in;
    return in;
}

// Given four decorrelated input samples, this function produces four-channel
// output for the late reverb.
static __inline ALvoid LateReverb(ALverbState *State, ALfloat *in, ALfloat *out)
{
    ALfloat d[4], f[4];

    // Obtain the decayed results of the cyclical delay lines, and add the
    // corresponding input channels.  Then pass the results through the
    // low-pass filters.

    // This is where the feed-back cycles from line 0 to 1 to 3 to 2 and back
    // to 0.
    d[0] = LateLowPassInOut(State, 2, in[2] + LateDelayLineOut(State, 2));
    d[1] = LateLowPassInOut(State, 0, in[0] + LateDelayLineOut(State, 0));
    d[2] = LateLowPassInOut(State, 3, in[3] + LateDelayLineOut(State, 3));
    d[3] = LateLowPassInOut(State, 1, in[1] + LateDelayLineOut(State, 1));

    // To help increase diffusion, run each line through an all-pass filter.
    // When there is no diffusion, the shortest all-pass filter will feed the
    // shortest delay line.
    d[0] = LateAllPassInOut(State, 0, d[0]);
    d[1] = LateAllPassInOut(State, 1, d[1]);
    d[2] = LateAllPassInOut(State, 2, d[2]);
    d[3] = LateAllPassInOut(State, 3, d[3]);

    /* Late reverb is done with a modified feed-back delay network (FDN)
     * topology.  Four input lines are each fed through their own all-pass
     * filter and then into the mixing matrix.  The four outputs of the
     * mixing matrix are then cycled back to the inputs.  Each output feeds
     * a different input to form a circlular feed cycle.
     *
     * The mixing matrix used is a 4D skew-symmetric rotation matrix derived
     * using a single unitary rotational parameter:
     *
     *  [  d,  a,  b,  c ]          1 = a^2 + b^2 + c^2 + d^2
     *  [ -a,  d,  c, -b ]
     *  [ -b, -c,  d,  a ]
     *  [ -c,  b, -a,  d ]
     *
     * The rotation is constructed from the effect's diffusion parameter,
     * yielding:  1 = x^2 + 3 y^2; where a, b, and c are the coefficient y
     * with differing signs, and d is the coefficient x.  The matrix is thus:
     *
     *  [  x,  y, -y,  y ]          n = sqrt(matrix_order - 1)
     *  [ -y,  x,  y,  y ]          t = diffusion_parameter * atan(n)
     *  [  y, -y,  x,  y ]          x = cos(t)
     *  [ -y, -y, -y,  x ]          y = sin(t) / n
     *
     * To reduce the number of multiplies, the x coefficient is applied with
     * the cyclical delay line coefficients.  Thus only the y coefficient is
     * applied when mixing, and is modified to be:  y / x.
     */
    f[0] = d[0] + (State->Late.MixCoeff * (         d[1] + -d[2] + d[3]));
    f[1] = d[1] + (State->Late.MixCoeff * (-d[0]         +  d[2] + d[3]));
    f[2] = d[2] + (State->Late.MixCoeff * ( d[0] + -d[1]         + d[3]));
    f[3] = d[3] + (State->Late.MixCoeff * (-d[0] + -d[1] + -d[2]       ));

    // Output the results of the matrix for all four channels, attenuated by
    // the late reverb gain (which is attenuated by the 'x' mix coefficient).
    out[0] = State->Late.Gain * f[0];
    out[1] = State->Late.Gain * f[1];
    out[2] = State->Late.Gain * f[2];
    out[3] = State->Late.Gain * f[3];

    // Re-feed the cyclical delay lines.
    DelayLineIn(&State->Late.Delay[0], State->Offset, f[0]);
    DelayLineIn(&State->Late.Delay[1], State->Offset, f[1]);
    DelayLineIn(&State->Late.Delay[2], State->Offset, f[2]);
    DelayLineIn(&State->Late.Delay[3], State->Offset, f[3]);
}

// Given an input sample, this function mixes echo into the four-channel late
// reverb.
static __inline ALvoid EAXEcho(ALverbState *State, ALfloat in, ALfloat *late)
{
    ALfloat out, feed;

    // Get the latest attenuated echo sample for output.
    feed = AttenuatedDelayLineOut(&State->Echo.Delay,
                                  State->Offset - State->Echo.Offset,
                                  State->Echo.Coeff);

    // Mix the output into the late reverb channels.
    out = State->Echo.MixCoeff[0] * feed;
    late[0] = (State->Echo.MixCoeff[1] * late[0]) + out;
    late[1] = (State->Echo.MixCoeff[1] * late[1]) + out;
    late[2] = (State->Echo.MixCoeff[1] * late[2]) + out;
    late[3] = (State->Echo.MixCoeff[1] * late[3]) + out;

    // Mix the energy-attenuated input with the output and pass it through
    // the echo low-pass filter.
    feed += State->Echo.DensityGain * in;
    feed = lerp(feed, State->Echo.LpSample, State->Echo.LpCoeff);
    State->Echo.LpSample = feed;

    // Then the echo all-pass filter.
    feed = AllpassInOut(&State->Echo.ApDelay,
                        State->Offset - State->Echo.ApOffset,
                        State->Offset, feed, State->Echo.ApFeedCoeff,
                        State->Echo.ApCoeff);

    // Feed the delay with the mixed and filtered sample.
    DelayLineIn(&State->Echo.Delay, State->Offset, feed);
}

// Perform the non-EAX reverb pass on a given input sample, resulting in
// four-channel output.
static __inline ALvoid VerbPass(ALverbState *State, ALfloat in, ALfloat *early, ALfloat *late)
{
    ALfloat feed, taps[4];

    // Low-pass filter the incoming sample.
    in = lpFilter2P(&State->LpFilter, 0, in);

    // Feed the initial delay line.
    DelayLineIn(&State->Delay, State->Offset, in);

    // Calculate the early reflection from the first delay tap.
    in = DelayLineOut(&State->Delay, State->Offset - State->DelayTap[0]);
    EarlyReflection(State, in, early);

    // Feed the decorrelator from the energy-attenuated output of the second
    // delay tap.
    in = DelayLineOut(&State->Delay, State->Offset - State->DelayTap[1]);
    feed = in * State->Late.DensityGain;
    DelayLineIn(&State->Decorrelator, State->Offset, feed);

    // Calculate the late reverb from the decorrelator taps.
    taps[0] = feed;
    taps[1] = DelayLineOut(&State->Decorrelator, State->Offset - State->DecoTap[0]);
    taps[2] = DelayLineOut(&State->Decorrelator, State->Offset - State->DecoTap[1]);
    taps[3] = DelayLineOut(&State->Decorrelator, State->Offset - State->DecoTap[2]);
    LateReverb(State, taps, late);

    // Step all delays forward one sample.
    State->Offset++;
}

// Perform the EAX reverb pass on a given input sample, resulting in four-
// channel output.
static __inline ALvoid EAXVerbPass(ALverbState *State, ALfloat in, ALfloat *early, ALfloat *late)
{
    ALfloat feed, taps[4];

    // Low-pass filter the incoming sample.
    in = lpFilter2P(&State->LpFilter, 0, in);

    // Perform any modulation on the input.
    in = EAXModulation(State, in);

    // Feed the initial delay line.
    DelayLineIn(&State->Delay, State->Offset, in);

    // Calculate the early reflection from the first delay tap.
    in = DelayLineOut(&State->Delay, State->Offset - State->DelayTap[0]);
    EarlyReflection(State, in, early);

    // Feed the decorrelator from the energy-attenuated output of the second
    // delay tap.
    in = DelayLineOut(&State->Delay, State->Offset - State->DelayTap[1]);
    feed = in * State->Late.DensityGain;
    DelayLineIn(&State->Decorrelator, State->Offset, feed);

    // Calculate the late reverb from the decorrelator taps.
    taps[0] = feed;
    taps[1] = DelayLineOut(&State->Decorrelator, State->Offset - State->DecoTap[0]);
    taps[2] = DelayLineOut(&State->Decorrelator, State->Offset - State->DecoTap[1]);
    taps[3] = DelayLineOut(&State->Decorrelator, State->Offset - State->DecoTap[2]);
    LateReverb(State, taps, late);

    // Calculate and mix in any echo.
    EAXEcho(State, in, late);

    // Step all delays forward one sample.
    State->Offset++;
}

// This destroys the reverb state.  It should be called only when the effect
// slot has a different (or no) effect loaded over the reverb effect.
static ALvoid VerbDestroy(ALeffectState *effect)
{
    ALverbState *State = (ALverbState*)effect;
    if(State)
    {
        free(State->SampleBuffer);
        State->SampleBuffer = NULL;
        free(State);
    }
}

// This updates the device-dependant reverb state.  This is called on
// initialization and any time the device parameters (eg. playback frequency,
// or format) have been changed.
static ALboolean VerbDeviceUpdate(ALeffectState *effect, ALCdevice *Device)
{
    ALverbState *State = (ALverbState*)effect;
    ALuint frequency = Device->Frequency;
    ALuint index;

    // Allocate the delay lines.
    if(!AllocLines(AL_FALSE, frequency, State))
        return AL_FALSE;

    // The early reflection and late all-pass filter line lengths are static,
    // so their offsets only need to be calculated once.
    for(index = 0;index < 4;index++)
    {
        State->Early.Offset[index] = (ALuint)(EARLY_LINE_LENGTH[index] *
                                              frequency);
        State->Late.ApOffset[index] = (ALuint)(ALLPASS_LINE_LENGTH[index] *
                                               frequency);
    }

    for(index = 0;index < MAXCHANNELS;index++)
         State->Gain[index] = 0.0f;
    for(index = 0;index < Device->NumChan;index++)
    {
        Channel chan = Device->Speaker2Chan[index];
        State->Gain[chan] = 1.0f;
    }

    return AL_TRUE;
}

// This updates the device-dependant EAX reverb state.  This is called on
// initialization and any time the device parameters (eg. playback frequency,
// format) have been changed.
static ALboolean EAXVerbDeviceUpdate(ALeffectState *effect, ALCdevice *Device)
{
    ALverbState *State = (ALverbState*)effect;
    ALuint frequency = Device->Frequency, index;

    // Allocate the delay lines.
    if(!AllocLines(AL_TRUE, frequency, State))
        return AL_FALSE;

    // Calculate the modulation filter coefficient.  Notice that the exponent
    // is calculated given the current sample rate.  This ensures that the
    // resulting filter response over time is consistent across all sample
    // rates.
    State->Mod.Coeff = aluPow(MODULATION_FILTER_COEFF,
                              MODULATION_FILTER_CONST / frequency);

    // The early reflection and late all-pass filter line lengths are static,
    // so their offsets only need to be calculated once.
    for(index = 0;index < 4;index++)
    {
        State->Early.Offset[index] = (ALuint)(EARLY_LINE_LENGTH[index] *
                                              frequency);
        State->Late.ApOffset[index] = (ALuint)(ALLPASS_LINE_LENGTH[index] *
                                               frequency);
    }

    // The echo all-pass filter line length is static, so its offset only
    // needs to be calculated once.
    State->Echo.ApOffset = (ALuint)(ECHO_ALLPASS_LENGTH * frequency);

    return AL_TRUE;
}

// This updates the reverb state.  This is called any time the reverb effect
// is loaded into a slot.
static ALvoid VerbUpdate(ALeffectState *effect, ALCcontext *Context, const ALeffect *Effect)
{
    ALverbState *State = (ALverbState*)effect;
    ALuint frequency = Context->Device->Frequency;
    ALfloat cw, x, y, hfRatio;

    // Calculate the master low-pass filter (from the master effect HF gain).
    cw = CalcI3DL2HFreq(Effect->Reverb.HFReference, frequency);
    // This is done with 2 chained 1-pole filters, so no need to square g.
    State->LpFilter.coeff = lpCoeffCalc(Effect->Reverb.GainHF, cw);

    // Update the initial effect delay.
    UpdateDelayLine(Effect->Reverb.ReflectionsDelay,
                    Effect->Reverb.LateReverbDelay, frequency, State);

    // Update the early lines.
    UpdateEarlyLines(Effect->Reverb.Gain, Effect->Reverb.ReflectionsGain,
                     Effect->Reverb.LateReverbDelay, State);

    // Update the decorrelator.
    UpdateDecorrelator(Effect->Reverb.Density, frequency, State);

    // Get the mixing matrix coefficients (x and y).
    CalcMatrixCoeffs(Effect->Reverb.Diffusion, &x, &y);
    // Then divide x into y to simplify the matrix calculation.
    State->Late.MixCoeff = y / x;

    // If the HF limit parameter is flagged, calculate an appropriate limit
    // based on the air absorption parameter.
    hfRatio = Effect->Reverb.DecayHFRatio;
    if(Effect->Reverb.DecayHFLimit && Effect->Reverb.AirAbsorptionGainHF < 1.0f)
        hfRatio = CalcLimitedHfRatio(hfRatio, Effect->Reverb.AirAbsorptionGainHF,
                                     Effect->Reverb.DecayTime);

    // Update the late lines.
    UpdateLateLines(Effect->Reverb.Gain, Effect->Reverb.LateReverbGain,
                    x, Effect->Reverb.Density, Effect->Reverb.DecayTime,
                    Effect->Reverb.Diffusion, hfRatio, cw, frequency, State);
}

// This updates the EAX reverb state.  This is called any time the EAX reverb
// effect is loaded into a slot.
static ALvoid EAXVerbUpdate(ALeffectState *effect, ALCcontext *Context, const ALeffect *Effect)
{
    ALverbState *State = (ALverbState*)effect;
    ALuint frequency = Context->Device->Frequency;
    ALfloat cw, x, y, hfRatio;

    // Calculate the master low-pass filter (from the master effect HF gain).
    cw = CalcI3DL2HFreq(Effect->Reverb.HFReference, frequency);
    // This is done with 2 chained 1-pole filters, so no need to square g.
    State->LpFilter.coeff = lpCoeffCalc(Effect->Reverb.GainHF, cw);

    // Update the modulator line.
    UpdateModulator(Effect->Reverb.ModulationTime,
                    Effect->Reverb.ModulationDepth, frequency, State);

    // Update the initial effect delay.
    UpdateDelayLine(Effect->Reverb.ReflectionsDelay,
                    Effect->Reverb.LateReverbDelay, frequency, State);

    // Update the early lines.
    UpdateEarlyLines(Effect->Reverb.Gain, Effect->Reverb.ReflectionsGain,
                     Effect->Reverb.LateReverbDelay, State);

    // Update the decorrelator.
    UpdateDecorrelator(Effect->Reverb.Density, frequency, State);

    // Get the mixing matrix coefficients (x and y).
    CalcMatrixCoeffs(Effect->Reverb.Diffusion, &x, &y);
    // Then divide x into y to simplify the matrix calculation.
    State->Late.MixCoeff = y / x;

    // If the HF limit parameter is flagged, calculate an appropriate limit
    // based on the air absorption parameter.
    hfRatio = Effect->Reverb.DecayHFRatio;
    if(Effect->Reverb.DecayHFLimit && Effect->Reverb.AirAbsorptionGainHF < 1.0f)
        hfRatio = CalcLimitedHfRatio(hfRatio, Effect->Reverb.AirAbsorptionGainHF,
                                     Effect->Reverb.DecayTime);

    // Update the late lines.
    UpdateLateLines(Effect->Reverb.Gain, Effect->Reverb.LateReverbGain,
                    x, Effect->Reverb.Density, Effect->Reverb.DecayTime,
                    Effect->Reverb.Diffusion, hfRatio, cw, frequency, State);

    // Update the echo line.
    UpdateEchoLine(Effect->Reverb.Gain, Effect->Reverb.LateReverbGain,
                   Effect->Reverb.EchoTime, Effect->Reverb.DecayTime,
                   Effect->Reverb.Diffusion, Effect->Reverb.EchoDepth,
                   hfRatio, cw, frequency, State);

    // Update early and late 3D panning.
    Update3DPanning(Context->Device, Effect->Reverb.ReflectionsPan,
                    Effect->Reverb.LateReverbPan, State);
}

// This processes the reverb state, given the input samples and an output
// buffer.
static ALvoid VerbProcess(ALeffectState *effect, const ALeffectslot *Slot, ALuint SamplesToDo, const ALfloat *SamplesIn, ALfloat (*SamplesOut)[MAXCHANNELS])
{
    ALverbState *State = (ALverbState*)effect;
    ALuint index;
    ALfloat early[4], late[4], out[4];
    ALfloat gain = Slot->Gain;
    const ALfloat *panGain = State->Gain;

    for(index = 0;index < SamplesToDo;index++)
    {
        // Process reverb for this sample.
        VerbPass(State, SamplesIn[index], early, late);

        // Mix early reflections and late reverb.
        out[0] = (early[0] + late[0]) * gain;
        out[1] = (early[1] + late[1]) * gain;
        out[2] = (early[2] + late[2]) * gain;
        out[3] = (early[3] + late[3]) * gain;

        // Output the results.
        SamplesOut[index][FRONT_LEFT]   += panGain[FRONT_LEFT]   * out[0];
        SamplesOut[index][FRONT_RIGHT]  += panGain[FRONT_RIGHT]  * out[1];
        SamplesOut[index][FRONT_CENTER] += panGain[FRONT_CENTER] * out[3];
        SamplesOut[index][SIDE_LEFT]    += panGain[SIDE_LEFT]    * out[0];
        SamplesOut[index][SIDE_RIGHT]   += panGain[SIDE_RIGHT]   * out[1];
        SamplesOut[index][BACK_LEFT]    += panGain[BACK_LEFT]    * out[0];
        SamplesOut[index][BACK_RIGHT]   += panGain[BACK_RIGHT]   * out[1];
        SamplesOut[index][BACK_CENTER]  += panGain[BACK_CENTER]  * out[2];
    }
}

// This processes the EAX reverb state, given the input samples and an output
// buffer.
static ALvoid EAXVerbProcess(ALeffectState *effect, const ALeffectslot *Slot, ALuint SamplesToDo, const ALfloat *SamplesIn, ALfloat (*SamplesOut)[MAXCHANNELS])
{
    ALverbState *State = (ALverbState*)effect;
    ALuint index;
    ALfloat early[4], late[4];
    ALfloat gain = Slot->Gain;

    for(index = 0;index < SamplesToDo;index++)
    {
        // Process reverb for this sample.
        EAXVerbPass(State, SamplesIn[index], early, late);

        // Unfortunately, while the number and configuration of gains for
        // panning adjust according to MAXCHANNELS, the output from the
        // reverb engine is not so scalable.
        SamplesOut[index][FRONT_LEFT] +=
           (State->Early.PanGain[FRONT_LEFT]*early[0] +
            State->Late.PanGain[FRONT_LEFT]*late[0]) * gain;
        SamplesOut[index][FRONT_RIGHT] +=
           (State->Early.PanGain[FRONT_RIGHT]*early[1] +
            State->Late.PanGain[FRONT_RIGHT]*late[1]) * gain;
        SamplesOut[index][FRONT_CENTER] +=
           (State->Early.PanGain[FRONT_CENTER]*early[3] +
            State->Late.PanGain[FRONT_CENTER]*late[3]) * gain;
        SamplesOut[index][SIDE_LEFT] +=
           (State->Early.PanGain[SIDE_LEFT]*early[0] +
            State->Late.PanGain[SIDE_LEFT]*late[0]) * gain;
        SamplesOut[index][SIDE_RIGHT] +=
           (State->Early.PanGain[SIDE_RIGHT]*early[1] +
            State->Late.PanGain[SIDE_RIGHT]*late[1]) * gain;
        SamplesOut[index][BACK_LEFT] +=
           (State->Early.PanGain[BACK_LEFT]*early[0] +
            State->Late.PanGain[BACK_LEFT]*late[0]) * gain;
        SamplesOut[index][BACK_RIGHT] +=
           (State->Early.PanGain[BACK_RIGHT]*early[1] +
            State->Late.PanGain[BACK_RIGHT]*late[1]) * gain;
        SamplesOut[index][BACK_CENTER] +=
           (State->Early.PanGain[BACK_CENTER]*early[2] +
            State->Late.PanGain[BACK_CENTER]*late[2]) * gain;
    }
}

// This creates the reverb state.  It should be called only when the reverb
// effect is loaded into a slot that doesn't already have a reverb effect.
ALeffectState *VerbCreate(void)
{
    ALverbState *State = NULL;
    ALuint index;

    State = malloc(sizeof(ALverbState));
    if(!State)
        return NULL;

    State->state.Destroy = VerbDestroy;
    State->state.DeviceUpdate = VerbDeviceUpdate;
    State->state.Update = VerbUpdate;
    State->state.Process = VerbProcess;

    State->TotalSamples = 0;
    State->SampleBuffer = NULL;

    State->LpFilter.coeff = 0.0f;
    State->LpFilter.history[0] = 0.0f;
    State->LpFilter.history[1] = 0.0f;

    State->Mod.Delay.Mask = 0;
    State->Mod.Delay.Line = NULL;
    State->Mod.Index = 0;
    State->Mod.Range = 1;
    State->Mod.Depth = 0.0f;
    State->Mod.Coeff = 0.0f;
    State->Mod.Filter = 0.0f;

    State->Delay.Mask = 0;
    State->Delay.Line = NULL;
    State->DelayTap[0] = 0;
    State->DelayTap[1] = 0;

    State->Early.Gain = 0.0f;
    for(index = 0;index < 4;index++)
    {
        State->Early.Coeff[index] = 0.0f;
        State->Early.Delay[index].Mask = 0;
        State->Early.Delay[index].Line = NULL;
        State->Early.Offset[index] = 0;
    }

    State->Decorrelator.Mask = 0;
    State->Decorrelator.Line = NULL;
    State->DecoTap[0] = 0;
    State->DecoTap[1] = 0;
    State->DecoTap[2] = 0;

    State->Late.Gain = 0.0f;
    State->Late.DensityGain = 0.0f;
    State->Late.ApFeedCoeff = 0.0f;
    State->Late.MixCoeff = 0.0f;
    for(index = 0;index < 4;index++)
    {
        State->Late.ApCoeff[index] = 0.0f;
        State->Late.ApDelay[index].Mask = 0;
        State->Late.ApDelay[index].Line = NULL;
        State->Late.ApOffset[index] = 0;

        State->Late.Coeff[index] = 0.0f;
        State->Late.Delay[index].Mask = 0;
        State->Late.Delay[index].Line = NULL;
        State->Late.Offset[index] = 0;

        State->Late.LpCoeff[index] = 0.0f;
        State->Late.LpSample[index] = 0.0f;
    }

    for(index = 0;index < MAXCHANNELS;index++)
    {
        State->Early.PanGain[index] = 0.0f;
        State->Late.PanGain[index] = 0.0f;