/*  $Id: fadefilter_generic.cpp,v 1.7 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 "fadefilter_generic.h"

CL_FadeFilter::CL_FadeFilter(float initial_volume)
{
	if(initial_volume < 0.0f)
		initial_volume = 0.0f;
	if(initial_volume > 1.0f)
		initial_volume = 1.0f;

	impl = new CL_FadeFilter_Generic;
	impl->cur_volume = initial_volume;
	impl->new_volume = initial_volume;
	impl->speed = 0;
}

CL_FadeFilter::~CL_FadeFilter()
{
	delete impl;
}

float CL_FadeFilter::get_volume() const
{
	return impl->cur_volume;
}

void CL_FadeFilter::set_volume(float new_volume)
{
	if(new_volume < 0.0f)
		new_volume = 0.0f;
	if(new_volume > 1.0f)
		new_volume = 1.0f;

	impl->cur_volume = new_volume;
	impl->speed = 0.0f;
}

void CL_FadeFilter::fade_to_volume(float new_volume, int duration)
{
	if(new_volume < 0.0f)
		new_volume = 0.0f;
	if(new_volume > 1.0f)
		new_volume = 1.0f;

	impl->new_volume = new_volume;

	float delta_volume = impl->new_volume - impl->cur_volume;
	impl->speed = delta_volume / 22.05f / duration;
}

void CL_FadeFilter::filter(int **sample_data, int num_samples, int channels)
{
	float &cur_volume = impl->cur_volume;
	float &new_volume = impl->new_volume;
	float &speed = impl->speed;

	for (int i=0; i<num_samples; i++)
	{
		for (int j=0; j<channels; j++)
		{
			sample_data[j][i] = (int) (sample_data[j][i] * cur_volume);
		}

		// change volume for every second sample (because data is in stereo).
		cur_volume += speed;
		if (
			(speed > 0 && cur_volume > new_volume) ||
			(speed < 0 && cur_volume < new_volume))
		{
			cur_volume = new_volume;
			speed = 0;
		}
	}
}
