#include "LiveSourceWithx264.h"


LiveSourceWithx264* LiveSourceWithx264::createNew(UsageEnvironment& env, common::ShmQueue *rtspStreamQueue)
{
	return new LiveSourceWithx264(env, rtspStreamQueue);
}

EventTriggerId LiveSourceWithx264::eventTriggerId = 0;

unsigned LiveSourceWithx264::referenceCount = 0;

LiveSourceWithx264::LiveSourceWithx264(UsageEnvironment& env, common::ShmQueue *rtspStreamQueue)
	:FramedSource(env),
	rtspStreamQueue(rtspStreamQueue)
{
	//if(referenceCount == 0)
	//{

	//}
	++referenceCount;
	if(eventTriggerId == 0)
	{
		eventTriggerId = envir().taskScheduler().createEventTrigger(deliverFrame0);
	}

}


LiveSourceWithx264::~LiveSourceWithx264(void)
{
	--referenceCount;
	envir().taskScheduler().deleteEventTrigger(eventTriggerId);
	eventTriggerId = 0;
}


void LiveSourceWithx264::deliverFrame0(void* clientData)
{
	((LiveSourceWithx264*)clientData)->deliverFrame();
}

void LiveSourceWithx264::doGetNextFrame()
{
	gettimeofday(&currentTime,NULL);
	deliverFrame();
}

void LiveSourceWithx264::deliverFrame()
{
	if(!isCurrentlyAwaitingData()) return;

	unsigned char* storage;

	storage = ( unsigned char * )rtspStreamQueue->getBuf( fFrameSize, false );

	if ( fFrameSize > fMaxSize )
	{
		fNumTruncatedBytes = fFrameSize - fMaxSize;
		fFrameSize = fMaxSize;
	}
	//printf("%d\n",fMaxSize );
	fPresentationTime = currentTime;
	memmove(fTo, storage, fFrameSize);

	rtspStreamQueue->releaseBuf();
	FramedSource::afterGetting(this);
}