// Covox.cpp: implementation of the CCovox class.
//


#include "pch.h"
#include "Config.h"
#include "Covox.h"
#include "resource.h"


/////////////////////////////////////////////////////////////////////////////
// Construction/Destruction


CCovox::CCovox()
{
	if (CreateFIRBuffers(FIR_LENGTH))
	{
		ReInit();
	}
	else
	{
		g_BKMsgBox.Show(IDS_BK_ERROR_NOTENMEMR, MB_OK);
	}
}

CCovox::~CCovox()
    = default;

void CCovox::ReInit()
{
	const double w0 = 2 * 11000.0 / double(g_Config.m_nSoundSampleRate);
	const double w1 = 0.0;
	const int res = fir_linphase(m_nFirLength, w0, w1, FIR_FILTER::LOWPASS,
	                             FIR_WINDOW::BLACKMAN_HARRIS, true, 0.0, m_pH.get());
}

void CCovox::SetData(const uint16_t inVal)
{
	if (m_bEnableSound)
	{
		m_dAccL  = double(LOBYTE(inVal)) * (1.0 / 256.0);
		m_dAccR = m_bStereo ? double(HIBYTE(inVal)) * (1.0 / 256.0) : m_dAccL;
	}
	else
	{
		m_dAccL = m_dAccR = 0.0;
	}
}

void CCovox::SetAZDataL(const int16_t left)
{
	m_dAccL = m_bEnableSound ? double(left) * (1.0 / 65536.0) : 0.0;
}

void CCovox::SetAZDataR(const int16_t right)
{
	m_dAccR = m_bEnableSound ? double(right) * (1.0 / 65536.0) : 0.0;
}

void CCovox::SetAZDataLR(const int16_t left, const int16_t right)
{
	if (m_bEnableSound)
	{
		m_dAccL = double(left) * (1.0 / 65536.0);
		m_dAccR = double(right) * (1.0 / 65536.0);
	}
	else
	{
		m_dAccL = m_dAccR = 0.0;
	}
}

void CCovox::GetSample(sOneSample *pSm)
{
	SAMPLE_INT l = m_dAccL;
	SAMPLE_INT r = m_dAccR;

	if (m_bDCOffset)
	{
		l = DCOffset(l, m_pdDCBufL.get(), m_nDCBufPosL, m_dAvgL);
		r = DCOffset(r, m_pdDCBufR.get(), m_nDCBufPosR, m_dAvgR);
	}

	pSm->s[OSL] = FIRFilter(l, m_pdFBufL.get(), m_nFBufPosL);
	pSm->s[OSR] = FIRFilter(r, m_pdFBufR.get(), m_nFBufPosR);
}
