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

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

#define ARG_FRAMERATE 25
#define ARG_BITRATE 1024

int QUALITY =5;

u32_t XDIM=0;
u32_t YDIM=0;

void *enchandle = NULL;
void *data;

char *prefix="frame";

vboolean read_data(u32_t num)
{
	char fname[256];
	if(data)
	{
		memFree(data);
		data=NULL;
	}
	logFormatString(fname,"/home/vladimir/data/frames/frame%04u.tga",num);
/*	logFormatString(fname,"//f/frames/frame%04u.tga",num);*/
	data = tgaLoad(fname,&XDIM,&YDIM);
	if(!data)
		exit(-1);
	return true;
}

#define FRAMERATE_INCR 1001

int enc_init()
{
	int xerr;
	
	XVID_INIT_PARAM xinit;
	XVID_ENC_PARAM xparam;

	xinit.cpu_flags = 0;
	puts("1");
	
	xvid_init(NULL, 0, &xinit, NULL);
	
	puts("2");
	
	read_data(0);

	xparam.width = XDIM;
	xparam.height = YDIM;

	printf("w %u, h %u\n",xparam.width,xparam.height);
	
	if ((ARG_FRAMERATE - (int)ARG_FRAMERATE) == 0)
	{
			xparam.fincr = 1;
			xparam.fbase = (int)ARG_FRAMERATE;
	}
	else
	{
			xparam.fincr = FRAMERATE_INCR;
			xparam.fbase = (int)(FRAMERATE_INCR * ARG_FRAMERATE);
	}

/*
	xparam.rc_bitrate = -1;
	xparam.rc_reaction_delay_factor = -1;
	xparam.rc_averaging_period = -1;
	xparam.rc_buffer = -1;
*/
	
	xparam.min_quantizer = -1;
	xparam.max_quantizer = -1;
	xparam.max_key_interval = (int)ARG_FRAMERATE*10;

	xerr = xvid_encore(NULL, XVID_ENC_CREATE, &xparam, NULL);

	enchandle = xparam.handle;
	
	return xerr;
}

int  enc_main(unsigned char* bitstream, int *streamlength)
{
	int xerr;
	XVID_ENC_FRAME xframe;
	memZero(&xframe,sizeof(XVID_ENC_FRAME));
	xframe.general = XVID_HALFPEL | XVID_ADAPTIVEQUANT;
	xframe.motion = PMV_HALFPELREFINE16;
	xframe.intra = -1;
	xframe.bitstream = bitstream;
	xframe.image = data;
	xframe.colorspace = XVID_CSP_RGB32;
	xerr = xvid_encore(enchandle, XVID_ENC_ENCODE, &xframe,NULL);
	*streamlength = xframe.length;
	return xerr;
}

int  enc_stop()
{
	return xvid_encore(enchandle, XVID_ENC_DESTROY, NULL, NULL);
}

int main()
{
	u32_t frame;
	unsigned char *divx_buffer = NULL;
	int status,m4v_size;
	logStartConsoleLog();
	logUpperLevel(LOG_TRACE);
	divx_buffer = (unsigned char *)memAlloc(1024 * 1024);
	
	puts("HERE");
	
	if(!divx_buffer)
		exit(-1);
	status = enc_init();
	printf("Encore INIT return %d, handle=%lx\n", status, enchandle);
	
	for(frame=0;frame<300;frame++)
	{
		char filename[256];
		vhandle_t out;
  		read_data(frame);
		status = enc_main(divx_buffer,&m4v_size);
		sprintf(filename,"frame%04d.m4v",frame);
		out=fileOpenWrite(filename);
		fileWrite(out,divx_buffer,m4v_size);
		fileClose(out);
		printf("Frame %u: src %u, dst %u,rate %u\n",
			frame,XDIM*YDIM*3,m4v_size,XDIM*YDIM*3 / m4v_size);
		fflush(stdout);
	}
  	enc_stop();
	memFree(divx_buffer);
	if(data)
		memFree(data);
	return 0;
}
