// msmpeg.cpp : Defines the entry point for the DLL application.
//

#include "stdafx.h"
#include "msmpeg.h"
#include "avcodec.h"
#include "../yuv2rgb.h"

BOOL APIENTRY DllMain( HANDLE hModule, 
                       DWORD  ul_reason_for_call, 
                       LPVOID lpReserved
					 )
{
    switch (ul_reason_for_call)
	{
		case DLL_PROCESS_ATTACH:
		case DLL_THREAD_ATTACH:
		case DLL_THREAD_DETACH:
		case DLL_PROCESS_DETACH:
			break;
    }
    return TRUE;
}

AVCodec *codec;
AVCodecContext codec_context, *c = &codec_context;
int frame, got_picture, len;
FILE *f;
AVPicture picture;


/**
 *
**/

extern unsigned char *decore_stream;
extern int decore_length;

static int decore_init(int hor_size, int ver_size, unsigned long color_depth, int output_format);
static int decore_release();
//int DecodeFrame(unsigned char *stream, int length, unsigned char *bmp, int render_flag);

/***/

static int flag_firstpicture = 1;

/***/

MSMPEG_API int DecodeInit(unsigned long handle, unsigned long dec_opt,
	void *param1, void *param2)
{
	switch (dec_opt)
	{
		case DEC_OPT_INIT:
		{
			DEC_PARAM *dec_param = (DEC_PARAM *) param1;
 			int x_size = dec_param->x_dim;
 			int y_size = dec_param->y_dim;
			unsigned long color_depth = dec_param->color_depth;
			int output_format = dec_param->output_format;

			divxinit(x_size,y_size);

			return DEC_OK;
		}
		break; 
		case DEC_OPT_RELEASE:
		{
			divxdeinit();
			return DEC_OK;
		}
		break;
		default:
		{

			return DEC_OK;
		}
		break;
	}
}

/***/

/***/

MSMPEG_API int DecodeFrame(unsigned char *stream, int length, unsigned char *bmp, int render_flag)
{
    avcodec_decode_video(c, &picture, &got_picture, 
                               stream, 48000,bmp,render_flag,0);
	return 1;
}



void divxinit(int x, int y)
{

	register_all();
    /* find the mpeg1 video decoder */
    codec = avcodec_find_decoder(CODEC_ID_MSMPEG4);
    if (!codec) {
//        fprintf(stderr, "codec not found\n");
        exit(1);
    }

    /* put default values */
    memset(c, 0, sizeof(*c));
	c->width=x;
	c->height=y;
    /* open it */
    if (avcodec_open(c, codec) < 0) {
//        fprintf(stderr, "could not open codec\n");
//        exit(1);
    }
    
}


void divxdeinit()
{
    avcodec_close(c);
}


// This is the constructor of a class that has been exported.
// see msmpeg.h for the class definition
CMsmpeg::CMsmpeg()
{ 
	return; 
}

