///////////////////////////////////////////////////////////////////////////////////
// Copyright (C) 2016 Edouard Griffiths, F4EXB                                   //
//                                                                               //
// 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 as 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 V3 for more details.                               //
//                                                                               //
// You should have received a copy of the GNU General Public License             //
// along with this program. If not, see .          //
///////////////////////////////////////////////////////////////////////////////////
#include 
#include 
#include 
#include 
#include 
#include "dsp/samplesourcefifo.h"
#include "filesinkthread.h"
FileSinkThread::FileSinkThread(std::ofstream *samplesStream, SampleSourceFifo* sampleFifo, QObject* parent) :
	QThread(parent),
	m_running(false),
	m_ofstream(samplesStream),
	m_bufsize(0),
	m_samplesChunkSize(0),
	m_sampleFifo(sampleFifo),
	m_samplesCount(0),
    m_samplerate(0),
    m_log2Interpolation(0),
    m_throttlems(FILESINK_THROTTLE_MS),
    m_maxThrottlems(50),
    m_throttleToggle(false),
    m_buf(0)
{
    assert(m_ofstream != 0);
}
FileSinkThread::~FileSinkThread()
{
	if (m_running) {
		stopWork();
	}
    if (m_buf) delete[] m_buf;
}
void FileSinkThread::startWork()
{
	qDebug() << "FileSinkThread::startWork: ";
    if (m_ofstream->is_open())
    {
        qDebug() << "FileSinkThread::startWork: file stream open, starting...";
        m_maxThrottlems = 0;
        m_startWaitMutex.lock();
        m_elapsedTimer.start();
        start();
        while(!m_running)
            m_startWaiter.wait(&m_startWaitMutex, 100);
        m_startWaitMutex.unlock();
    }
    else
    {
        qDebug() << "FileSinkThread::startWork: file stream closed, not starting.";
    }
}
void FileSinkThread::stopWork()
{
	qDebug() << "FileSinkThread::stopWork";
	m_running = false;
	wait();
}
void FileSinkThread::setSamplerate(int samplerate)
{
	if (samplerate != m_samplerate)
	{
	    qDebug() << "FileSinkThread::setSamplerate:"
	            << " new:" << samplerate
	            << " old:" << m_samplerate;
	    bool wasRunning = false;
		if (m_running)
		{
			stopWork();
			wasRunning = true;
		}
		// resize sample FIFO
		if (m_sampleFifo) {
		    m_sampleFifo->resize(samplerate); // 1s buffer
		}
        // resize output buffer
        if (m_buf) delete[] m_buf;
        m_buf = new int16_t[samplerate*(1< 6))
    {
        return;
    }
    if (log2Interpolation != m_log2Interpolation)
    {
        qDebug() << "FileSinkThread::setLog2Interpolation:"
                << " new:" << log2Interpolation
                << " old:" << m_log2Interpolation;
        bool wasRunning = false;
        if (m_running)
        {
            stopWork();
            wasRunning = true;
        }
        // resize output buffer
        if (m_buf) delete[] m_buf;
        m_buf = new int16_t[m_samplerate*(1< m_maxThrottlems)
//        {
//            qDebug("FileSinkThread::tick: m_maxThrottlems: %d", m_maxThrottlems);
//            m_maxThrottlems = m_throttlems;
//        }
        SampleVector::iterator readUntil;
        m_sampleFifo->readAdvance(readUntil, m_samplesChunkSize);
        SampleVector::iterator beginRead = readUntil - m_samplesChunkSize;
        m_samplesCount += m_samplesChunkSize;
        if (m_log2Interpolation == 0)
        {
            m_ofstream->write(reinterpret_cast(&(*beginRead)), m_samplesChunkSize*sizeof(Sample));
        }
        else
        {
            int chunkSize = std::min((int) m_samplesChunkSize, m_samplerate);
            switch (m_log2Interpolation)
            {
            case 1:
                m_interpolators.interpolate2_cen(&beginRead, m_buf, chunkSize*(1<write(reinterpret_cast(m_buf), m_samplesChunkSize*(1<