/*  $Id: inverse_echofilter_generic.cpp,v 1.8 2003/11/11 10:13:25 grumbel Exp $
**
**  ClanLib Game SDK
**  Copyright (C) 2003  The ClanLib Team
**  For a total list of contributers see the file CREDITS.
**
**  This library is free software; you can redistribute it and/or
**  modify it under the terms of the GNU Lesser General Public
**  License as published by the Free Software Foundation; either
**  version 2.1 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
**  Lesser General Public License for more details.
**
**  You should have received a copy of the GNU Lesser 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
**
*/

#include "Sound/precomp.h"

#ifdef _MSC_VER
#pragma warning (disable:4786)
#endif

#include "inverse_echofilter_generic.h"
#include <memory>
#ifdef BORLAND
#include <memory.h>
#endif

CL_InverseEchoFilter::CL_InverseEchoFilter(int buffer_size)
{
	impl = new CL_InverseEchoFilter_Generic;
	impl->buffer_size = buffer_size;
	impl->pos = 0;

	impl->buffer[0] = new int[buffer_size];
	memset(impl->buffer[0], 0, sizeof(int)*buffer_size);

	impl->buffer[1] = new int[buffer_size];
	memset(impl->buffer[1], 0, sizeof(int)*buffer_size);
}

CL_InverseEchoFilter::~CL_InverseEchoFilter()
{
	delete[] impl->buffer[0];
	delete[] impl->buffer[1];
	delete impl;
}

void CL_InverseEchoFilter::filter(int **sample_data, int num_samples, int channels)
{
	int start_pos = impl->pos;

	for (int c=0; c<2; c++)
	{
		if (c == channels) break;

		int *buffer = impl->buffer[c];
		int &pos = impl->pos;
		int &buffer_size = impl->buffer_size;

		pos = start_pos;

		int delay = buffer_size / 4;
		for (int i=0; i<num_samples; i++)
		{
			buffer[pos] = sample_data[c][i];

			int res = 0;
			for (int j=0; j<4; j++)
			{
				int p = pos+delay*j;
				if (p >= buffer_size) p -= buffer_size;

				res += buffer[p] / (5-j);
			}

			sample_data[c][i] = res;

			pos++;
			if (pos == buffer_size) pos = 0;
		}
	}
}
