/*
 *  Based on test routine for XviD using the XviD-API                      
 *  (C) Christoph Lampert, 2002/01/19	              
 */

#include <stdio.h>
#include <malloc.h>
#include <../support/xvidcore/src/xvid.h>
#include <v_lib.h>

#define ARG_FRAMERATE 25
#define ARG_BITRATE 1024

int QUALITY =5;

int XDIM=64;
int YDIM=64;

void *dechandle = NULL;
u8_t decdata[1024 * 1024 * 4];
u32_t datasize;
u8_t data[1024 * 1024];

char *prefix="frame";
vboolean read_data(u32_t num)
{
	vhandle_t infile;
	char fname[256];
	logFormatString(fname,"../xvenc/frame%04u.m4v",num);
	infile=fileOpenRead(fname);
	if(!infile)
		exit(-1);
	datasize = fileSize(infile);
	fileRead(infile,data,datasize);
	return true;
}

#define FRAMERATE_INCR 1001

int dec_init()
{
	int xerr;
	
	XVID_INIT_PARAM xinit;
	XVID_DEC_PARAM xparam;
	memZero(&xinit,sizeof(XVID_INIT_PARAM));
	memZero(&xparam,sizeof(XVID_DEC_PARAM));

	xinit.cpu_flags = 0;
	xvid_init(NULL, 0, &xinit, NULL);
	
	xparam.width = XDIM;
	xparam.height = YDIM;

	xerr = xvid_decore(NULL, XVID_DEC_CREATE, &xparam, NULL);
	dechandle=xparam.handle;
	
	return xerr;
}

u32_t frametime;

int  dec_main(u32_t frame)
{
	int xerr;
	XVID_DEC_FRAME xframe;
	read_data(frame);
	xframe.bitstream = data;
	xframe.length = datasize;
	xframe.image = decdata;
	xframe.stride = XDIM;
	xframe.colorspace = XVID_CSP_RGB32;
	frametime = timeTickCount();
	xerr = xvid_decore(dechandle, XVID_DEC_DECODE, &xframe,NULL);
	frametime = timeTickCount() - frametime;
	return xerr;
}

int  dec_stop()
{
	return xvid_decore(dechandle, XVID_DEC_DESTROY, NULL, NULL);
}

int main()
{
	u32_t frame;
	int status;
	logStartConsoleLog();
	logUpperLevel(LOG_TRACE);
	status = dec_init();
	printf("Decore INIT return %d, handle=%lx\n", status, dechandle);
	for(frame=0;frame<300;frame++)
	{
		char filename[256];
		status = dec_main(frame);
		sprintf(filename,"frame%04d.tga",frame);
		tgaSave(filename,XDIM,YDIM,decdata);
		printf("Frame %u: src %u, %u milliseconds\n",frame,datasize,frametime);
		fflush(stdout);
	}
  	dec_stop();
	return 0;
}
