//	StuckBuffer.cpp - Class which will occasionally trigger a stuck buffer
//					  noise.
//  ----------------------------------------------------------------------------
//	This file is part of 'NiallsAVLib', base code for any kind of audiovisual
//	apps.
//	Copyright (C) 2012  Niall Moody
//	
//	This program is free software: you can redistribute it and/or modify
//	it under the terms of the GNU General Public License as published by
//	the Free Software Foundation, either version 3 of the License, or
//	(at your option) any later version.
//
//	This program 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 General Public License for more details.
//
//	You should have received a copy of the GNU General Public License
//	along with this program.  If not, see <http://www.gnu.org/licenses/>.
//	----------------------------------------------------------------------------

#include "StuckBuffer.h"
#include "Random.h"

//------------------------------------------------------------------------------
StuckBuffer::StuckBuffer():
stuck(false),
stuckSize(22050),
position(0),
fadeIn(0.0f)
{

}

//------------------------------------------------------------------------------
StuckBuffer::~StuckBuffer()
{

}

//------------------------------------------------------------------------------
void StuckBuffer::getAudio(float *output, int numSamples)
{
	int i;

	if(!stuck && (fadeIn >= 1.0f))
	{
		stuck = (Random::getGlobal().getRandomFloat() > 0.995f);
		if(stuck)
		{
			stuckSize = 1024 + Random::getGlobal().getRandomInt(22050-1024);
			unstuckCount = 4 + Random::getGlobal().getRandomInt(16);
		}
	}

	for(i=0;i<numSamples;++i)
	{
		if(!stuck)
			buffer[position] = output[(i*2)];
		else
			buffer[position] += output[(i*2)] * 0.5f;

		output[(i*2)] = buffer[position];
		output[(i*2)+1] = buffer[position];

		++position;
		if(position >= stuckSize)
			position = 0;
		if(fadeIn < 1.0f)
			fadeIn += 0.00001f;
	}

	if(stuck)
	{
		--unstuckCount;
		if(!unstuckCount)
		{
			stuck = false;
			stuckSize = 22050;
		}
	}
}
