/* ***** BEGIN LICENSE BLOCK *****
 * Source last modified: $Id: HXEQEngine.c,v 1.2.2.3 2004/07/09 01:49:47 hubbe Exp $
 * 
 * Portions Copyright (c) 1995-2004 RealNetworks, Inc. All Rights Reserved.
 * 
 * The contents of this file, and the files included with this file,
 * are subject to the current version of the RealNetworks Public
 * Source License (the "RPSL") available at
 * http://www.helixcommunity.org/content/rpsl unless you have licensed
 * the file under the current version of the RealNetworks Community
 * Source License (the "RCSL") available at
 * http://www.helixcommunity.org/content/rcsl, in which case the RCSL
 * will apply. You may also obtain the license terms directly from
 * RealNetworks.  You may not use this file except in compliance with
 * the RPSL or, if you have a valid RCSL with RealNetworks applicable
 * to this file, the RCSL.  Please see the applicable RPSL or RCSL for
 * the rights, obligations and limitations governing use of the
 * contents of the file.
 * 
 * Alternatively, the contents of this file may be used under the
 * terms of the GNU General Public License Version 2 or later (the
 * "GPL") in which case the provisions of the GPL are applicable
 * instead of those above. If you wish to allow use of your version of
 * this file only under the terms of the GPL, and not to allow others
 * to use your version of this file under the terms of either the RPSL
 * or RCSL, indicate your decision by deleting the provisions above
 * and replace them with the notice and other provisions required by
 * the GPL. If you do not delete the provisions above, a recipient may
 * use your version of this file under the terms of any one of the
 * RPSL, the RCSL or the GPL.
 * 
 * This file is part of the Helix DNA Technology. RealNetworks is the
 * developer of the Original Code and owns the copyrights in the
 * portions it created.
 * 
 * This file, and the files included with this file, is distributed
 * and made available on an 'AS IS' basis, WITHOUT WARRANTY OF ANY
 * KIND, EITHER EXPRESS OR IMPLIED, AND REALNETWORKS HEREBY DISCLAIMS
 * ALL SUCH WARRANTIES, INCLUDING WITHOUT LIMITATION, ANY WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, QUIET
 * ENJOYMENT OR NON-INFRINGEMENT.
 * 
 * Technology Compatibility Kit Test Suite(s) Location:
 *    http://www.helixcommunity.org/content/tck
 * 
 * Contributor(s):
 * 
 * ***** END LICENSE BLOCK ***** */

/*
 * DESIGN:
 * Uses separate filter set for each sampling rate.
 * 10-Band with centers at { 31 62 125 250 500 1k 2k 4k 8k 16k }
 * Filter Q = 1.4
 *
 * Each filter is a 2nd order IIR bandpass of the form:
 * y[n] = gain * alpha * (x[n] - x[n-2]) + gamma * y[n-1] + beta * y[n-2];
 *
 * and the final output is:
 * out[n] = x[n] + y1[n] + y2[n] + ... yk[n]
 *
 * PERFORMANCE:
 * Approx 8% of PPro-200 at 44kHz stereo.
 *
 */
#include <stdlib.h>
#include "HXEQEngine.h"

#include <string.h>

//#include "pnheap.h"
#ifdef _DEBUG
#undef PN_THIS_FILE		
//static char PN_THIS_FILE[] = __FILE__;
#endif

//static char pgmrname[] = "1998 Ken Cooke, 1999 Greg Conklin";

/* supported sampling rates */
static int const ratetab[EQ_NRATES] = { 8000, 11025, 16000, 22050, 32000, 44100, 48000 };

/* gain of order 1 IIR low-pass echo filters for reverb */
static float const echoFiltCoeff_tab[EQ_NRATES] = {0.3f, 0.25f, 0.2f, 0.2f, 0.15f, 0.1f, 0.1f};

/* number of active bands for each rate */
static int const nbandtab[EQ_NRATES] = { 
	EQ_NBANDS_8000, EQ_NBANDS_11025, EQ_NBANDS_16000,
	EQ_NBANDS_22050, EQ_NBANDS_32000, EQ_NBANDS_44100,
	EQ_NBANDS_48000
};

/*
 * Set of filter coefficients for each rate.
 * Generate with Matlab scripts.
 */
static float const filtertab[EQ_NRATES][3*EQ_MAXBANDS] = 
/*			alpha					gamma						beta		*/
{{	/* 8000Hz */
	8.710134894088783e-003f, 1.981982598970183e+000f, -9.825797302118224e-001f,
	1.727115128250412e-002f, 1.963089974998454e+000f, -9.654576974349918e-001f,
	3.396593280788152e-002f, 1.922760884501598e+000f, -9.320681343842368e-001f,
	6.577590621415974e-002f, 1.832487552730858e+000f, -8.684481875716803e-001f,
	1.239690282256030e-001f, 1.617815066411626e+000f, -7.520619435487940e-001f,
	2.240723323636952e-001f, 1.085148862569372e+000f, -5.518553352726097e-001f,
	3.864411084133348e-001f, -1.406063057473513e-001f, -2.271177831733304e-001f,
	2.890250750139612e-001f, -1.314230783298363e+000f, -4.219498499720776e-001f,
	0.0f, 0.0f, 0.0f,
	0.0f, 0.0f, 0.0f,
}, {	/* 11025Hz */
	6.335343685943684e-003f, 1.987014148482799e+000f, -9.873293126281128e-001f,
	1.259142257160317e-002f, 1.973564483979041e+000f, -9.748171548567936e-001f,
	2.487362573947438e-002f, 1.945305160724163e+000f, -9.502527485210514e-001f,
	4.856981461880283e-002f, 1.883562934010661e+000f, -9.028603707623942e-001f,
	9.285864973861380e-002f, 1.740868886457108e+000f, -8.142827005227723e-001f,
	1.714210738310449e-001f, 1.391591652958285e+000f, -6.571578523379102e-001f,
	3.017645835264713e-001f, 5.363990129056221e-001f, -3.964708329470574e-001f,
	4.522456271235510e-001f, -9.408631837096566e-001f, -9.550874575289810e-002f,
	0.0f, 0.0f, 0.0f,
	0.0f, 0.0f, 0.0f,
}, {	/* 16000Hz */
	4.374033365920349e-003f, 1.991101994699731e+000f, -9.912519332681594e-001f,
	8.710134894088783e-003f, 1.981982598970183e+000f, -9.825797302118224e-001f,
	1.727115128250412e-002f, 1.963089974998454e+000f, -9.654576974349918e-001f,
	3.396593280788152e-002f, 1.922760884501598e+000f, -9.320681343842368e-001f,
	6.577590621415974e-002f, 1.832487552730858e+000f, -8.684481875716803e-001f,
	1.239690282256030e-001f, 1.617815066411626e+000f, -7.520619435487940e-001f,
	2.240723323636952e-001f, 1.085148862569372e+000f, -5.518553352726097e-001f,
	3.864411084133348e-001f, -1.406063057473513e-001f, -2.271177831733304e-001f,
	2.890250750139612e-001f, -1.314230783298363e+000f, -4.219498499720776e-001f,
	0.0f, 0.0f, 0.0f,
}, {	/* 22050Hz */
	3.177705835768263e-003f, 1.993565546144875e+000f, -9.936445883284634e-001f,
	6.335343685943684e-003f, 1.987014148482799e+000f, -9.873293126281128e-001f,
	1.259142257160317e-002f, 1.973564483979041e+000f, -9.748171548567936e-001f,
	2.487362573947438e-002f, 1.945305160724163e+000f, -9.502527485210514e-001f,
	4.856981461880283e-002f, 1.883562934010661e+000f, -9.028603707623942e-001f,
	9.285864973861380e-002f, 1.740868886457108e+000f, -8.142827005227723e-001f,
	1.714210738310449e-001f, 1.391591652958285e+000f, -6.571578523379102e-001f,
	3.017645835264713e-001f, 5.363990129056221e-001f, -3.964708329470574e-001f,
	4.522456271235510e-001f, -9.408631837096566e-001f, -9.550874575289810e-002f,
	0.0f, 0.0f, 0.0f,
}, {	/* 32000Hz */
	2.191799705892117e-003f, 1.995578833613303e+000f, -9.956164005882160e-001f,
	4.374033365920349e-003f, 1.991101994699731e+000f, -9.912519332681594e-001f,
	8.710134894088783e-003f, 1.981982598970183e+000f, -9.825797302118224e-001f,
	1.727115128250412e-002f, 1.963089974998454e+000f, -9.654576974349918e-001f,
	3.396593280788152e-002f, 1.922760884501598e+000f, -9.320681343842368e-001f,
	6.577590621415974e-002f, 1.832487552730858e+000f, -8.684481875716803e-001f,
	1.239690282256030e-001f, 1.617815066411626e+000f, -7.520619435487940e-001f,
	2.240723323636952e-001f, 1.085148862569372e+000f, -5.518553352726097e-001f,
	3.864411084133348e-001f, -1.406063057473513e-001f, -2.271177831733304e-001f,
	2.890250750139612e-001f, -1.314230783298363e+000f, -4.219498499720776e-001f,
}, {	/* 44100Hz */
	1.591377371402913e-003f, 1.996797453216610e+000f, -9.968172452571942e-001f,
	3.177705835768263e-003f, 1.993565546144875e+000f, -9.936445883284634e-001f,
	6.335343685943684e-003f, 1.987014148482799e+000f, -9.873293126281128e-001f,
	1.259142257160317e-002f, 1.973564483979041e+000f, -9.748171548567936e-001f,
	2.487362573947438e-002f, 1.945305160724163e+000f, -9.502527485210514e-001f,
	4.856981461880283e-002f, 1.883562934010661e+000f, -9.028603707623942e-001f,
	9.285864973861380e-002f, 1.740868886457108e+000f, -8.142827005227723e-001f,
	1.714210738310449e-001f, 1.391591652958285e+000f, -6.571578523379102e-001f,
	3.017645835264713e-001f, 5.363990129056221e-001f, -3.964708329470574e-001f,
	4.522456271235510e-001f, -9.408631837096566e-001f, -9.550874575289810e-002f,
}, {	/* 48000Hz */
	1.462266838385334e-003f, 1.997058757668317e+000f, -9.970754663232294e-001f,
	2.920269686957624e-003f, 1.994092723730942e+000f, -9.941594606260845e-001f,
	5.823582515269456e-003f, 1.988086666872636e+000f, -9.883528349694609e-001f,
	1.158012040231685e-002f, 1.975781286236746e+000f, -9.768397591953663e-001f,
	2.289816913170989e-002f, 1.950018799529792e+000f, -9.542036617365804e-001f,
	4.479454859684075e-002f, 1.894055158922016e+000f, -9.104109028063185e-001f,
	8.591998299109292e-002f, 1.765685036799309e+000f, -8.281600340178141e-001f,
	1.594237125483447e-001f, 1.453270522628865e+000f, -6.811525749033107e-001f,
	2.823330993858340e-001f, 6.828979361551111e-001f, -4.353338012283320e-001f,
	4.818841328568499e-001f, -8.590373446961327e-001f, -3.623173428630035e-002f,
}};

/*
 * Lookup table for pow(10.0, i/(8.0 * 20.0)), -144 <= i <= 144.
 */
static float const powertab[EQ_MAXGAIN-EQ_MINGAIN+1] = {
	0.1258925412f, 0.1277173798f, 0.1295686698f, 0.1314467946f, 
	0.1333521432f, 0.1352851103f, 0.1372460961f, 0.1392355068f, 
	0.1412537545f, 0.1433012570f, 0.1453784386f, 0.1474857293f, 
	0.1496235656f, 0.1517923903f, 0.1539926526f, 0.1562248081f, 
	0.1584893192f, 0.1607866549f, 0.1631172909f, 0.1654817100f, 
	0.1678804018f, 0.1703138632f, 0.1727825981f, 0.1752871178f, 
	0.1778279410f, 0.1804055940f, 0.1830206106f, 0.1856735325f, 
	0.1883649089f, 0.1910952975f, 0.1938652636f, 0.1966753809f, 
	0.1995262315f, 0.2024184057f, 0.2053525026f, 0.2083291299f, 
	0.2113489040f, 0.2144124503f, 0.2175204034f, 0.2206734069f, 
	0.2238721139f, 0.2271171867f, 0.2304092976f, 0.2337491283f, 
	0.2371373706f, 0.2405747261f, 0.2440619068f, 0.2475996349f, 
	0.2511886432f, 0.2548296748f, 0.2585234840f, 0.2622708356f, 
	0.2660725060f, 0.2699292823f, 0.2738419634f, 0.2778113597f, 
	0.2818382931f, 0.2859235978f, 0.2900681199f, 0.2942727176f, 
	0.2985382619f, 0.3028656361f, 0.3072557365f, 0.3117094724f, 
	0.3162277660f, 0.3208115533f, 0.3254617835f, 0.3301794198f, 
	0.3349654392f, 0.3398208329f, 0.3447466066f, 0.3497437804f, 
	0.3548133892f, 0.3599564831f, 0.3651741273f, 0.3704674022f, 
	0.3758374043f, 0.3812852457f, 0.3868120546f, 0.3924189758f, 
	0.3981071706f, 0.4038778168f, 0.4097321098f, 0.4156712620f, 
	0.4216965034f, 0.4278090820f, 0.4340102636f, 0.4403013327f, 
	0.4466835922f, 0.4531583638f, 0.4597269885f, 0.4663908269f, 
	0.4731512590f, 0.4800096849f, 0.4869675252f, 0.4940262208f, 
	0.5011872336f, 0.5084520469f, 0.5158221651f, 0.5232991147f, 
	0.5308844442f, 0.5385797247f, 0.5463865499f, 0.5543065366f, 
	0.5623413252f, 0.5704925797f, 0.5787619883f, 0.5871512638f, 
	0.5956621435f, 0.6042963902f, 0.6130557921f, 0.6219421634f, 
	0.6309573445f, 0.6401032025f, 0.6493816316f, 0.6587945534f, 
	0.6683439176f, 0.6780317017f, 0.6878599123f, 0.6978305849f, 
	0.7079457844f, 0.7182076058f, 0.7286181745f, 0.7391796466f, 
	0.7498942093f, 0.7607640819f, 0.7717915156f, 0.7829787942f, 
	0.7943282347f, 0.8058421878f, 0.8175230379f, 0.8293732045f, 
	0.8413951416f, 0.8535913393f, 0.8659643234f, 0.8785166564f, 
	0.8912509381f, 0.9041698059f, 0.9172759354f, 0.9305720409f, 
	0.9440608763f, 0.9577452351f, 0.9716279516f, 0.9857119009f, 
	1.0000000000f, 1.0144952081f, 1.0292005272f, 1.0441190030f, 
	1.0592537252f, 1.0746078283f, 1.0901844924f, 1.1059869434f, 
	1.1220184543f, 1.1382823453f, 1.1547819847f, 1.1715207898f, 
	1.1885022274f, 1.2057298145f, 1.2232071190f, 1.2409377608f, 
	1.2589254118f, 1.2771737976f, 1.2956866975f, 1.3144679458f, 
	1.3335214322f, 1.3528511028f, 1.3724609610f, 1.3923550682f, 
	1.4125375446f, 1.4330125702f, 1.4537843856f, 1.4748572928f, 
	1.4962356561f, 1.5179239032f, 1.5399265261f, 1.5622480815f, 
	1.5848931925f, 1.6078665491f, 1.6311729092f, 1.6548170999f, 
	1.6788040181f, 1.7031386317f, 1.7278259805f, 1.7528711776f, 
	1.7782794100f, 1.8040559401f, 1.8302061063f, 1.8567353246f, 
	1.8836490895f, 1.9109529750f, 1.9386526360f, 1.9667538093f, 
	1.9952623150f, 2.0241840574f, 2.0535250265f, 2.0832912990f, 
	2.1134890398f, 2.1441245032f, 2.1752040340f, 2.2067340691f, 
	2.2387211386f, 2.2711718673f, 2.3040929761f, 2.3374912832f, 
	2.3713737057f, 2.4057472609f, 2.4406190680f, 2.4759963492f, 
	2.5118864315f, 2.5482967480f, 2.5852348396f, 2.6227083565f, 
	2.6607250598f, 2.6992928232f, 2.7384196343f, 2.7781135966f, 
	2.8183829313f, 2.8592359783f, 2.9006811987f, 2.9427271762f, 
	2.9853826189f, 3.0286563611f, 3.0725573653f, 3.1170947236f, 
	3.1622776602f, 3.2081155328f, 3.2546178350f, 3.3017941977f, 
	3.3496543916f, 3.3982083289f, 3.4474660657f, 3.4974378037f, 
	3.5481338923f, 3.5995648314f, 3.6517412725f, 3.7046740221f, 
	3.7583740429f, 3.8128524566f, 3.8681205463f, 3.9241897585f, 
	3.9810717055f, 4.0387781682f, 4.0973210981f, 4.1567126200f, 
	4.2169650343f, 4.2780908199f, 4.3401026364f, 4.4030133272f, 
	4.4668359215f, 4.5315836376f, 4.5972698853f, 4.6639082688f, 
	4.7315125896f, 4.8000968491f, 4.8696752517f, 4.9402622077f, 
	5.0118723363f, 5.0845204686f, 5.1582216507f, 5.2329911468f, 
	5.3088444423f, 5.3857972471f, 5.4638654988f, 5.5430653661f, 
	5.6234132519f, 5.7049257970f, 5.7876198835f, 5.8715126379f, 
	5.9566214353f, 6.0429639024f, 6.1305579215f, 6.2194216341f, 
	6.3095734448f, 6.4010320247f, 6.4938163158f, 6.5879455344f, 
	6.6834391757f, 6.7803170172f, 6.8785991231f, 6.9783058486f, 
	7.0794578438f, 7.1820760583f, 7.2861817451f, 7.3917964656f, 
	7.4989420933f, 7.6076408193f, 7.7179151559f, 7.8297879419f, 
	7.9432823472f
};

/*
 * table of echo parameters for reverb
 */
static float const feedbackgain_tab[13] = {
	0.000f, 0.040f, 0.060f, 0.070f, 0.075f,
	0.080f, 0.084f, 0.087f, 0.089f, 0.091f,
	0.093f, 0.094f, 0.095f
};

/*
 * table of echo delays for a given room size.
 * each row is a different roomsize. units are millisecs.
 */
static int const delay_tab[13][REVERB_NUM_ECHOS] = {
	{ 60, 63, 71, 83, 92,103,122,136,150,171},
	{ 70, 78, 92,102,114,127,142,157,176,195},
	{ 80, 89,105,117,130,145,161,180,200,223},
	{ 90,100,112,131,146,163,182,202,225,251},
	{100,111,131,146,163,181,202,225,250,279},
	{112,125,147,163,182,203,226,252,281,313},
	{123,139,164,182,203,226,252,281,313,349},
	{123,158,176,197,219,257,287,320,356,397},
	{121,162,199,223,248,277,308,343,404,450},
	{121,162,191,237,271,315,341,413,478,489},
	{121,163,201,243,317,385,421,453,478,489},
	{121,169,217,251,331,415,441,463,478,489},
	{169,237,311,361,415,431,441,463,478,489},
};


/*
 * Fast, rounded float to long.
 */
#ifdef _M_IX86
__inline long
RoundFtoL(float f) {
	long l;
	__asm fld	f
	__asm fistp	l
	return l;
}
#else
#define RoundFtoL(f) ((f) < 0.0 ? (f) - 0.5 : (f) + 0.5 )
#endif

/*
 * Create an EQ instance.
 *
 * Allocates memory.
 * Filter state is cleared.
 * Gains are initialized to flat response.
 * Reverb is reset and turned off.
 *
 * Returns a valid EQ, or NULL on error.
 */
EQPTR
EQInit(int samprate, int nchans)
{
	EQPTR eq;
	int ratecode, i, chan;
	int hist_length;

	/* find rate code */
	ratecode = -1;
	for (i = 0; i < EQ_NRATES; i++) {
		if (ratetab[i] == samprate)
			ratecode = i;
	}
	if (ratecode == -1)
		return NULL;	/* invalid rate */

	/* create EQSTATE struct */
	eq = (EQPTR) malloc(sizeof(EQSTATE));
	if (!eq)
		return NULL;	/* malloc failed */

	/* fill in params */
	eq->ratecode = ratecode;
	eq->nchans = nchans;
	eq->nbands = nbandtab[ratecode];
	eq->coeff = filtertab[ratecode];
    eq->pwrLevelMeasure = 4096*4096.f;
	eq->autopregain = 0;

	eq->itlbuf = (float *) malloc (sizeof(float) * 2 * EQ_MAXSAMPS);
	if (!(eq->itlbuf))
		return NULL;
	
    /* init history to zero */
	for (chan = 0; chan < EQ_MAXCHANS; chan++) {
		eq->ihist[chan][0] = 0.0f;
		eq->ihist[chan][1] = 0.0f;
		eq->mean[chan] = 0.0f;
		for (i = 0; i < 2 * EQ_MAXBANDS; i++)
			eq->ohist[chan][i] = 0.0f;
	}

	/* init gains to flat response */
	eq->pregain = 1.0f;
	for (i = 0; i < EQ_MAXBANDS; i++)
		eq->filtgain[i] = 0.0f;

	/* allocate enough memory for EQ_HIST_DURATION seconds of data */
	hist_length = (int)(samprate * nchans * REVERB_MAX_ECHO_DELAY / 1000) + EQ_MAXSAMPS * nchans + 100;
	eq->eqhist = NULL;

	eq->eqhist = (float *)malloc(sizeof(float) * hist_length);
	if (!(eq->eqhist))
		return NULL;
	else
	{
		for (i = 0; i < hist_length; i++)
			eq->eqhist[i] = 0.0f;
	}
	eq->eqhist_head = eq->eqhist;
	eq->eqhist_end = eq->eqhist + (hist_length) - (EQ_MAXSAMPS * nchans);

	/* reset reverb settings */
	for (i = 0; i < REVERB_NUM_ECHOS; i++)
	{
		eq->echoPtr[i] = eq->eqhist;
		for (chan = 0; chan < EQ_MAXCHANS; chan++) {
			eq->echoFiltState[chan][i] = 0.0f;
		}
	}
	eq->gain = 0.0f;
	eq->reverb = 0;
	eq->roomsize = 0;
	eq->timer = 0L;
	eq->echoFiltCoeff = echoFiltCoeff_tab[ratecode];

#ifdef _EQ_X86_WINDOWS
	// Initialize the limiter
	eq->limState = LimiterInit(samprate, nchans, EQ_FIXED_HEADROOM_BITS);

	init_codecutil();
#endif


	return eq;
}


static void
AddReverb(EQPTR eq, short *inpcm, int nsamps)
{
	// apply reverb
	int		echo;			// the current echo number being processed
	int		chan;			// the current chan being processed
	int		samps;			// samps processed between echo pointer shifts
	float	*fhistPtr;		// working pointer into the eq->eqhist buffer 
	short	*inpcmPtr;		// working pointer to the input pcm data
	int		bufflength;		// length of the eq->eqhist buffer
	float	*loop_echoPtr[REVERB_NUM_ECHOS];
	float	loop_eFiltState[EQ_MAXCHANS][REVERB_NUM_ECHOS];

	register float	fres;	// storage for new reverb'ed samples
	register float	ftmp;
	register float	c = 1.0f - eq->echoFiltCoeff;
	register float	loop_gain;
	register float	*loop_eFiltStatePtr;

	eq->timer += nsamps * 1000 / (ratetab[eq->ratecode] * eq->nchans);

	bufflength = eq->eqhist_end-eq->eqhist;
	eq->eqhist_start = eq->eqhist_head;

	// convert input pcm to floats and fill history
	inpcmPtr = inpcm;
	fhistPtr = eq->eqhist_head;
	while (inpcmPtr < inpcm + nsamps)
	{
		*(eq->eqhist_head) = (float)(*inpcmPtr);
		inpcmPtr++;
		eq->eqhist_head++;
		if (eq->eqhist_head == eq->eqhist_end)
			eq->eqhist_head = eq->eqhist;
	}

	// fill the buffer extension
	if ((eq->eqhist_head <= eq->eqhist + EQ_MAXSAMPS * eq->nchans) || 
		(eq->eqhist_start <= eq->eqhist + EQ_MAXSAMPS * eq->nchans))
	{
		memcpy(eq->eqhist_end,eq->eqhist,EQ_MAXSAMPS * eq->nchans * sizeof(float));
	}

	if (eq->reverb == 0)
		return;

	// add echos to the history
	loop_gain = eq->gain * eq->echoFiltCoeff;
	for (echo = 0; echo < REVERB_NUM_ECHOS; echo++)
	{
		loop_echoPtr[echo] = eq->echoPtr[echo];
		for (chan = 0; chan < eq->nchans; chan++)
		{
			loop_eFiltState[chan][echo] = eq->echoFiltState[chan][echo];
		}
	}

	samps = 1;
	nsamps /= REVERB_NUM_ECHOS;
	echo = 0;
	while (1)
	{
		loop_eFiltStatePtr = &(loop_eFiltState[0][0]);
		for (chan = 0; chan < eq->nchans; chan++)
		{
			fres = (*fhistPtr);

#define PROCESS_ECHO_UP(e) \
			ftmp = (loop_gain*(*(loop_echoPtr[(e)])++)) + c*loop_eFiltStatePtr[(e)]; \
			loop_eFiltStatePtr[(e)] = ftmp; \
			fres += ftmp

#define PROCESS_ECHO_DOWN(e) \
			ftmp = (loop_gain*(*(loop_echoPtr[(e)])++)) + c*loop_eFiltStatePtr[(e)]; \
			loop_eFiltStatePtr[(e)] = ftmp; \
			fres -= ftmp

			PROCESS_ECHO_UP(0);
			PROCESS_ECHO_DOWN(1);
			PROCESS_ECHO_UP(2);
			PROCESS_ECHO_DOWN(3);
			PROCESS_ECHO_UP(4);
			PROCESS_ECHO_DOWN(5);
			PROCESS_ECHO_UP(6);
			PROCESS_ECHO_DOWN(7);
			PROCESS_ECHO_UP(8);
			PROCESS_ECHO_DOWN(9);

			// remove mean from reverb
			eq->mean[chan] = (1.0f - 0.01f) * eq->mean[chan] + 0.01f * fres;
			fres -= eq->mean[chan];

			*fhistPtr++ = fres;
			loop_eFiltStatePtr += REVERB_NUM_ECHOS;
			samps++;
		}

		if (fhistPtr >= eq->eqhist_end)
			fhistPtr -= bufflength;
		if (fhistPtr == eq->eqhist_head)
			break;

#ifdef MOVE_FEEDBACK_DELAYS
		// Move echo pointers a little to prevent resonance effects
		// NOTE: This is currently not compiled in since, as implemented,
		//   it seem to be causing some flanging effects.
		if (samps > nsamps)
		{
			(loop_echoPtr[echo]) += ((((int)(eq->timer) & 1023) < 512) ? (1 - 2 * (echo & 1)) : (2 * (echo & 1) - 1))*(eq->nchans);
			echo++;
			samps = 1;
		}
#endif
	}

	// store the echo locations
	for (echo = 0; echo < REVERB_NUM_ECHOS; echo++)
	{
		if (loop_echoPtr[echo] >= eq->eqhist_end)
			eq->echoPtr[echo] = loop_echoPtr[echo] - bufflength;
		else
			eq->echoPtr[echo] = loop_echoPtr[echo];
		for (chan = 0; chan < eq->nchans; chan++)
		{
			eq->echoFiltState[chan][echo] = loop_eFiltState[chan][echo];
		}
	}

	inpcmPtr = inpcm;
	fhistPtr = eq->eqhist_start;
}


/*
 * Process a single block of samples.
 *
 * Requires nsamps <= EQ_MAXSAMPS * nchans
 * Requires chan = 0 for mono, 0/1 for stereo.
 *
 * Returns the count of clipped outputs.
 */
static void
ProcessBlock(EQPTR eq, int nsamps, int chan)
{
	float *iptr, *optr, *ihptr, *ohptr;
	const float *cptr;
	float *iptrend;
	float alpha, beta, gamma, accum;
	float ibuf1, ibuf2, obuf1, obuf2;
	float ftmp;
	int band, n;

	iptr = eq->iflt;
	optr = eq->oflt;
	cptr = eq->eqhist_start + chan;
	/* if stereo, de-interleave */
	for (n = chan; n < nsamps; n += eq->nchans) {
		ftmp = *cptr;
		*iptr++ = ftmp;
		*optr++ = ftmp;
		cptr += eq->nchans;
		if (cptr >= eq->eqhist_end)
			cptr -= (eq->eqhist_end - eq->eqhist);
	}
	iptrend = iptr;		/* one past last input */

	/* add the filter output from each band */
	cptr = eq->coeff;
	ihptr = eq->ihist[chan];
	ohptr = eq->ohist[chan];
	for (band = 0; band < eq->nbands; band++) {

		/* load band filter coeffs */
		alpha = cptr[0] * eq->filtgain[band];	/* premult filtgain into alpha */
		gamma = cptr[1];
		beta = cptr[2];
		cptr += 3;

		/* fast-path zero-gain case */
		if (eq->filtgain[band] > 0.25f || eq->filtgain[band] < -0.25f)
		{
			/* restore band history */
			ibuf2 = ihptr[0];		/* iptr[-2] */
			ibuf1 = ihptr[1];		/* iptr[-1] */
			obuf2 = ohptr[0];		/* optr[-2] */
			obuf1 = ohptr[1];		/* optr[-1] */

			/* 
			 * The following code is an optimized implementation of:
			 * y[n] = alpha * (x[n] - x[n-2]) + beta * y[n-2] + gamma * y[n-1];
			 * out[n] += y[n];
			 */
			iptr = eq->iflt;
			optr = eq->oflt;
			accum = obuf1;
			/* filter, unrolled by 4 */
			for (; iptr < iptrend-3; ) {
				accum *= gamma;							/* gamma * y[n-1] */
				accum += (iptr[0] - ibuf2) * alpha;		/* alpha * (x[n] - x[n-2]) */
				ibuf2 = iptr[0];						/* flip ibuf */
				accum += obuf2 * beta;					/* beta * y[n-2] */
				optr[0] += accum;						/* out[n] += y[n] */
				obuf2 = accum;							/* flip obuf */

				accum *= gamma;
				accum += (iptr[1] - ibuf1) * alpha;
				ibuf1 = iptr[1];
				accum += obuf1 * beta;
				optr[1] += accum;
				obuf1 = accum;

				accum *= gamma;
				accum += (iptr[2] - ibuf2) * alpha;
				ibuf2 = iptr[2];
				accum += obuf2 * beta;
				optr[2] += accum;
				obuf2 = accum;

				accum *= gamma;
				accum += (iptr[3] - ibuf1) * alpha;
				ibuf1 = iptr[3];
				accum += obuf1 * beta;
				optr[3] += accum;
				obuf1 = accum;

				iptr += 4;
				optr += 4;
			}
			/* filter the remainder */
			for (; iptr < iptrend; ) {
				accum *= gamma;							/* gamma * y[n-1] */
				accum += (*iptr - ibuf2) * alpha;		/* alpha * (x[n] - x[n-2]) */
				ibuf2 = ibuf1;							/* shift ibuf */
				ibuf1 = *iptr++;						/* shift ibuf */
				accum += obuf2 * beta;					/* beta * y[n-2] */
				obuf2 = obuf1;							/* shift obuf */
				obuf1 = accum;							/* shift obuf */
				*optr++ += accum;						/* out[n] += y[n] */
			}

			/* save band output history */
			ohptr[0] = obuf2;
			ohptr[1] = obuf1;
			ohptr += 2;
		}
		else
		{
			/* save band output history */
			ohptr[0] = 0;
			ohptr[1] = 0;
			ohptr += 2;
			ibuf2 = iptrend[-2];		/* iptr[-2] */
			ibuf1 = iptrend[-1];		/* iptr[-1] */
		}
	}

	/* save input history */
	ihptr[0] = ibuf2;
	ihptr[1] = ibuf1;

	/* Re-interleave samples */
	iptr = eq->oflt;
	optr = eq->itlbuf + chan;
	for (n = chan; n < nsamps; n += eq->nchans) {
		*optr = *iptr++;
		optr += eq->nchans;
	}
}


#ifdef _EQ_X86_WINDOWS

#define PWR_NOISE_THRESH  (512.f*512.f)
#define PWR_LOW_THRESH    (4096.f*4096.f)
#define PWR_HIGH_THRESH   (8192.f*8192.f*2.f)

void
ApplyGain(EQPTR eq, int nsamps)
{
	int n, chan, settings_change = 0;
	float *optr;
	float pwr, chan_pwr[EQ_MAXCHANS];
	float prev_pregain, ftmp;

	if (eq->autopregain == 0)
	{
		if (eq->pregain < 0.90 || eq->pregain > 1.1)
		{
			/* Apply fixed pregain */
			optr = eq->itlbuf;
			for (n = 0; n < nsamps; n++)
			{
				ftmp = *optr;
				ftmp *= eq->pregain;
				*optr = ftmp;
				optr ++;
			}
		}
	}
	else
	{
		prev_pregain = eq->pregain;

		/* measure the power in each channel */
		for (chan = 0; chan < eq->nchans; chan++)
		{
			pwr = 0;
			optr = eq->itlbuf + chan;
			for (n = 0; n < nsamps; n += eq->nchans)
			{
				ftmp = *optr;
				ftmp *= prev_pregain;
				ftmp *= ftmp;
				pwr += ftmp;
				optr += eq->nchans;
			}
			chan_pwr[chan] = pwr/(float)(nsamps/eq->nchans);
		}

		/* find the largest power in all channels */
		pwr = 0;
		for (chan = 0; chan < eq->nchans; chan++)
		{
			if (chan_pwr[chan] > pwr)
				pwr = chan_pwr[chan];
		}

		if (pwr > PWR_NOISE_THRESH)
		{
			if (pwr > eq->pwrLevelMeasure)
				eq->pwrLevelMeasure = (1.0f - 0.1f) * eq->pwrLevelMeasure + (0.1f) * pwr;
			else
				eq->pwrLevelMeasure = (1.0f - 0.01f) * eq->pwrLevelMeasure + (0.01f) * pwr;

			/* now adjust desired pregain given the pwr */
			if (eq->pwrLevelMeasure < PWR_LOW_THRESH)
			{
				eq->pregain *= 1.001f;
			}
			else if (eq->pwrLevelMeasure > PWR_HIGH_THRESH)
			{
				eq->pregain *= 0.99f;
			}

			/* bound the pregain to +/-18 dB */
			if (eq->pregain > powertab[EQ_MAXGAIN-EQ_MINGAIN])
				eq->pregain = powertab[EQ_MAXGAIN-EQ_MINGAIN];
			else if (eq->pregain < powertab[0])
				eq->pregain = powertab[0];

			eq->pwrLevelMeasure *= (eq->pregain/prev_pregain);
		}

		/* apply ramping pregain */
		pwr = (eq->pregain - prev_pregain)/(float)(nsamps/eq->nchans);
		
		for (chan = 0; chan < eq->nchans; chan++)
		{
			eq->pregain = prev_pregain;
			optr = eq->itlbuf + chan;
			for (n = 0; n < nsamps; n += eq->nchans)
			{
				ftmp = *optr;
				ftmp *= eq->pregain;
				*optr = ftmp;
				eq->pregain += pwr;
				optr += eq->nchans;
			}
		}

	}
}	

#else // _EQ_X86_WINDOWS

static int 
FillOutputShorts(EQPTR eq, short *outpcm, int nsamps)
{
	float *optr, ftmp;
	int ltmp, n, nclips;
	unsigned int max_samp;

	nclips = 0;
	max_samp = 0;

	/* store output with Auto-Gain adjustments */
	if (eq->autopregain == 1)
	{
		/* store output */
		optr = eq->itlbuf;

		for (n = 0; n < nsamps; n ++) {
			ftmp = *optr++;
			ltmp = RoundFtoL((eq->pregain*ftmp));

			if (ltmp > 32767) {
				eq->pregain *= 32767.f/(float)ltmp;
				ltmp = 32767;
			} else if (ltmp < -32768) {
				eq->pregain *= -32768.f/(float)ltmp;
				ltmp = -32768;
			}
			outpcm[n] = (short)ltmp;

			max_samp |= ((ltmp)^(ltmp>>31));
		}

	    /* only update if we get some audible audio */
	    if (max_samp > 0x0800)
	    {
			/* Update the time averaged maximum measurement */
			if (max_samp > eq->pwrLevelMeasure)
				eq->pwrLevelMeasure = (float)max_samp;
			else
				eq->pwrLevelMeasure = 0.99f * eq->pwrLevelMeasure + 0.01f * (float)max_samp;

			if (eq->pwrLevelMeasure < 8192.f)
			{
				eq->pregain += 0.004f;
			}
	    }

	    /* bound the pregain to +/-18 dB */
	    if (eq->pregain > powertab[EQ_MAXGAIN-EQ_MINGAIN])
			eq->pregain = powertab[EQ_MAXGAIN-EQ_MINGAIN];
	    else if (eq->pregain < powertab[0])
			eq->pregain = powertab[0];
	}
	else
	{
		/* store output */
		optr = eq->itlbuf;

		for (n = 0; n < nsamps; n ++) {
			ftmp = *optr++;
			ltmp = RoundFtoL(eq->pregain*ftmp);

			if (ltmp > 32767) {
				ltmp = 32767;
				nclips++;
			} else if (ltmp < -32768) {
				ltmp = -32768;
				nclips++;
			}
			outpcm[n] = (short)ltmp;
		}
	}

	return nclips;
}


#endif // _EQ_X86_WINDOWS



/*
 * Process a buffer of mono/stereo samples.
 *
 * Requires nsamps to be a multiple of nchans.
 *
 * Returns a count of clipped outputs, intended to drive
 * a clipping indicator.
 */
int
EQProcess(EQPTR eq, short *inpcm, short *outpcm, int nsamps)
{
	int nclips, chan;
	int chunk, maxchunk;
#ifdef _EQ_X86_WINDOWS
	int *fixedbuf;
#endif
	nclips = 0;
	maxchunk = EQ_MAXSAMPS * eq->nchans;	/* double, if stereo */

	/* process in chunks no bigger than maxchunk */
	while (nsamps > 0) {

		/* size of next chunk */
		chunk = (nsamps < maxchunk ? nsamps : maxchunk);

		/* add reverb to input samples -- applies to both channels if stereo */
		AddReverb(eq, inpcm, chunk);

		/* process all channels */
		for (chan = 0; chan < eq->nchans; chan++) {

			/* apply equalizer filtering to samples stored in eq->eqhist. */
			/* The output is written as interleaved 'floats' to eq->inlbuf. */
			ProcessBlock(eq, chunk, chan);
		}

#ifdef _EQ_X86_WINDOWS

		/* perform auto pre-gain control and apply gain */
		/* On x86 the auto pre-gain is based on signal power */
		/* and the subsequent limiter will handle clipping */
		ApplyGain(eq, chunk);

		/* Convert the floating point numbers to 32-bit fixed point */
		fixedbuf = (int *)eq->itlbuf;
		FloatToFixed32(eq->itlbuf, fixedbuf, chunk, EQ_FLT2FIX_SCALE);

		/* Apply limiter */
		LimiterProcess(fixedbuf, chunk, eq->limState);
		LimiterOutput16(fixedbuf, outpcm, chunk, eq->limState);

#else

		/* fill the output pcm data, handle clipping, and auto gain */
		/* (excellent place for a dynamic range compressor) */
		/* On non-x86, (automatic) pre-gain is also handled here */
		nclips += FillOutputShorts(eq, outpcm, chunk);

#endif

		inpcm += chunk;
		outpcm += chunk;
		nsamps -= chunk;
	}

	return nclips;
}

/*
 * Set the EQ gains.
 *
 * dbgain[] is an array of gain settings.
 * units are in 1/8 dB, where 0 = 0 dB.
 * gains above EQ_MAXGAIN are clamped to +18dB.
 * gains below EQ_MINGAIN are clamped to -18dB.
 */
void
EQSetGain(EQPTR eq, int *dbgain)
{
	int i, igain, highgain, chan;

	highgain = 0;

	for (i = 0; i < eq->nbands; i++) {

		igain = dbgain[i];
		
		/* clamp to +/-18dB */
		if (igain > EQ_MAXGAIN)
			igain = EQ_MAXGAIN;
		if (igain < EQ_MINGAIN)
			igain = EQ_MINGAIN;

		/* find the highest positive gain */
		if (igain > highgain)
			highgain = igain;
		/*
		 * Now convert from 1/8 dB to filter gain.
		 * Since bandpass filters are added to a unity-gain passthru,
		 * filter gain g results in response of 20*log10(1 + g) dB.
		 * The inverse is g[i] = 10^(i/20) - 1.
		 *
		 * filtgain = (float)pow(10.0, igain/(8.0 * 20.0)) - 1.0f;
		 */
		
		eq->filtgain[i] = powertab[igain-EQ_MINGAIN] - 1.0f;

	}

	/* init history to zero */
	for (chan = 0; chan < EQ_MAXCHANS; chan++) {
		eq->ihist[chan][0] = 0.0f;
		eq->ihist[chan][1] = 0.0f;
		for (i = 0; i < 2 * EQ_MAXBANDS; i++)
			eq->ohist[chan][i] = 0.0f;
	}
}

/*
 * Set the pre-gain.
 *
 * 'pregain' is the pregain setting.
 * units are in 1/8 dB, where 0 = 0 dB.
 * gains above EQ_MAXGAIN are clamped to +18dB.
 * gains below EQ_MINGAIN are clamped to -18dB.
 */
void
EQSetPreGain(EQPTR eq, int pregain)
{
	int igain;

	igain = pregain;
	
	/* clamp to +/-18dB */
	if (igain > EQ_MAXGAIN)
		igain = EQ_MAXGAIN;
	if (igain < EQ_MINGAIN)
		igain = EQ_MINGAIN;

	/*
	 * Now convert from 1/8 dB to filter gain.
	 * Since bandpass filters are added to a unity-gain passthru,
	 * filter gain g results in response of 20*log10(1 + g) dB.
	 * The inverse is g[i] = 10^(i/20) - 1.
	 *
	 * pregain = (float)pow(10.0, igain/(8.0 * 20.0)) - 1.0f;
	 */
	
	eq->pregain = powertab[igain-EQ_MINGAIN];
}


/*
 * Set the Reverb settings.
 *
 * roomsize:	0-12 sets the size of the room to be simulated.
 *				0: no reverb, 1: very small room, 12: very large room
 * reverb:		0-12 sets the amount of echo.
 *				0: no echo, 1: little echo, 12: tons of echo
 */
void 
EQSetReverb(EQPTR eq, int roomsize, int reverb)
{
	int echo, delay;

	// Assign the reverb settings
	eq->roomsize = roomsize;
	eq->reverb = reverb;

	// setup delays/gains
	eq->gain = feedbackgain_tab[reverb];
	for (echo = 0; echo < REVERB_NUM_ECHOS; echo++)
	{
		delay = (ratetab[eq->ratecode] * delay_tab[roomsize][echo] * (eq->nchans) / 1000) + echo;
		if ((eq->nchans == 2) && (delay & 1))
			delay--;

		eq->echoPtr[echo] = eq->eqhist_head - delay;
		while (eq->echoPtr[echo] < eq->eqhist)
			eq->echoPtr[echo] += eq->eqhist_end - eq->eqhist;
	}
}


/*
 * Get the Reverb settings.
 *
 * roomsize:	0-12 sets the size of the room to be simulated.
 *				0: no reverb, 1: very small room, 12: very large room
 * reverb:		0-12 sets the amount of echo.
 *				0: no echo, 1: little echo, 12: tons of echo
 */
void
EQGetReverb(EQPTR eq, int *roomsize, int *reverb)
{
	// Assign the reverb settings
	*roomsize = eq->roomsize;
	*reverb = eq->reverb;
}
 
/*
 * Enables the automatic pregain control.
 *
 * enable:		0: off, 1: on
 */
void
EQEnableAutoPreGain(EQPTR eq, int enable)
{
    eq->autopregain = enable;
}

/*
 * Get the pre-gain.
 *
 * 'pregain' is a pointer to the pregain setting.
 * units are in 1/8 dB, where 0 = 0 dB.
 * gains above EQ_MAXGAIN are clamped to +18dB.
 * gains below EQ_MINGAIN are clamped to -18dB.
 */
void
EQGetPreGain(EQPTR eq, int *pregain)
{
    int i;

    for (i = 0; i < EQ_MAXGAIN-EQ_MINGAIN+1; i++)
		if (eq->pregain < powertab[i])
			break;

    *pregain = i + EQ_MINGAIN;
}

/*
 * Resets the reverb echo buffers.
 */
void
EQResetReverb(EQPTR eq)
{
	memset(eq->eqhist, 0, (eq->eqhist_end - eq->eqhist + (EQ_MAXSAMPS * eq->nchans)) * sizeof(float));
}

/*
 * Free an EQ instance.
 */
void
EQFree(EQPTR eq)
{
	if (eq) 
	{
		if (eq->eqhist) 
		{
			free(eq->eqhist);
			eq->eqhist = NULL;
		}

		if (eq->itlbuf)
		{
			free(eq->itlbuf);
			eq->itlbuf = NULL;
		}
		
#ifdef _EQ_X86_WINDOWS
		LimiterFree(eq->limState);
#endif

		free(eq);	/* free all memory */
		eq = NULL;
	}
}
