/***************************************************************************
                          videothread.cpp  -  description
                             -------------------
    begin                : Sat Aug 30 2003
    copyright            : (C) 2003 by Martin Merck
    email                : merck@astro.uni-wuerzburg.de
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   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 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 ***************************************************************************/

#include "videothread.h"
#include "amcframegrabber.h"
#include "threadevent.h"
#include <unistd.h>

VideoThread::VideoThread( QObject* p_pReceiver, AMCFrameGrabber* p_pFG )
	: m_pReceiver(p_pReceiver), m_pFG(p_pFG), m_zValid(false), m_zRun(false), m_iCurFrame(0)
{
}

VideoThread::~VideoThread()
{
  if( m_zRun )
    stop();
	wait();
//	m_pFG->waitTillInactive();

	if( m_zValid )
		for( int i=0; i<2; i++)
		{
	  	if ( m_pData != NULL )
				delete[] m_pData[i];
	}
}

/** No descriptions */
void VideoThread::init( int p_iSize )
{
	if( m_zValid )
		return;
	m_iSize = p_iSize;
	for( int i=0; i<2; i++)
	{
		m_pData[i] = new uchar[ p_iSize ];
		if ( m_pData == NULL )
		{
			fprintf(stderr, "new char(%d) failed\n", m_iSize);
			return;
		}
		m_zValid = true;
	}	
}

/** No descriptions */
void VideoThread::run()
{
  qDebug("VideoThread PID: %d - PPID: %d", getpid(), getppid() );
	m_aMutex.lock();
	if( ! m_zValid )
	{
		m_aMutex.unlock();
		return;
	}

	m_zRun = true;
	m_aMutex.unlock();
	while( true )
	{
		m_aMutex.lock();
		if( ! m_zRun )
		{
			m_aMutex.unlock();
			return;
		}	
		uchar* pData = m_pData[m_iCurFrame];
		if ( m_iCurFrame == 0 )
			m_iCurFrame = 1;
		else
			m_iCurFrame = 0;
		m_aMutex.unlock();
		
		m_pFG->grabFrame( pData );
		QThread::postEvent( m_pReceiver, new QCustomEvent( THREAD_FRAME_EVENT ) );
		
	}
		
}

void VideoThread::stop()
{
	m_aMutex.lock();
	m_zRun = false;
	m_aMutex.unlock();
}

void VideoThread::getLastFrame( uchar* p_pData )
{
	m_aMutex.lock();
	memcpy( p_pData, m_pData[m_iCurFrame], m_iSize);
	m_aMutex.unlock();
}
