#include "Transmitter.h"


Transmitter::Transmitter(void)
	: Thread("Transmitter")
	, m_symbolizer(this)
	, m_formatter(&m_symbolizer)
	, m_symbolMapper()
	, m_bufferSize(0)
	, m_samplerate(192000)
	, m_symbolrate(48000)
	, m_numBitPerSymbol(2)
	, m_carrierFreq(48000)
	, m_txBuf(0, 2)
	, m_symCount(0)
	, m_pCoeffRCF(0)
	, m_upsampleFactor(1)
{
	SymMapInit(&m_symbolMapper, m_numBitPerSymbol, MAP_MODE_QAM);
	m_duc.init(m_carrierFreq/m_samplerate, 0);

	paramChanged();

	bufferResize(2048);
}

Transmitter::~Transmitter(void)
{
	stopThread(1000);

	if (m_pCoeffRCF)
		delete m_pCoeffRCF;

	m_pCoeffRCF = nullptr;

	SymMapFree(&m_symbolMapper);
}

void Transmitter::paramChanged()
{
	uint32_t n_mf;

	const ScopedLock sl (m_lock);

	m_symbolizer.setNumBitsPerSymbol(m_numBitPerSymbol);
	SymMapReinit(&m_symbolMapper, m_numBitPerSymbol, MAP_MODE_QAM);

	m_upsampleFactor = (uint32_t)(m_samplerate/m_symbolrate + 0.5);
	n_mf = (uint32_t)(TRANSMITTER_RCF_OVERSAMPLING*m_upsampleFactor) + 1;

	if (m_pCoeffRCF)
		delete m_pCoeffRCF;

	m_pCoeffRCF = new radio_float_t[n_mf];
	m_kRcf = CalcFirSRRC(m_pCoeffRCF, (radio_float_t)m_samplerate, (radio_float_t)2.0/m_symbolrate, TRANSMITTER_RCF_ROLLOFF, n_mf);

	m_firUp.init(m_upsampleFactor, m_pCoeffRCF, n_mf);
	m_duc.init(m_carrierFreq/m_samplerate, 0);
}

void Transmitter::bufferResize(uint32_t size)
{
	stopThread(10000);

	m_bufferSize = size;

	m_txBuf.resize(size, 8);
	m_bufferRF.resize(size);
	m_bufferSym.resize(size);
	m_bufferSymRcf.resize(size);
	
	m_symCount = 0;
	startThread(0);

}
