/*
    modified from an example provided in the mpeg2lib

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

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>*/

#include <stdio.h>
#include <stdlib.h>
#include <inttypes.h>
#include <fcntl.h>

#include "mpeg2.h"
#include "mpeg2convert.h"


FILE *_MPEGload(char *filename)
{
    FILE * mpgfile;

#ifdef _WIN32 /* We need to set stdin/stdout to binary mode. Damn windows. */
  /* Beware the evil ifdef. We avoid these where we can, but this one we
     cannot. Don't add any more, you'll probably go to hell if you do. */
  _setmode( _fileno( stdin ), _O_BINARY );
#endif
	mpgfile = fopen (filename, "rb");
	if (!mpgfile) return NULL;

//mpeg2_accel(MPEG2_ACCEL_X86_MMX);
	return mpgfile;
}

mpeg2dec_t *_MPEGinit()
{
	return mpeg2_init();
}

mpeg2_info_t *_MPEGinfo(mpeg2dec_t *decoder)
{
	return mpeg2_info(decoder);
}

int _MPEGparse(mpeg2dec_t *decoder)
{
	return mpeg2_parse(decoder);
}

int _MPEGdraw(mpeg2dec_t *decoder,mpeg2_info_t *info)
{
    mpeg2_state_t state;
    size_t size;

	state = mpeg2_parse (decoder);
	switch (state) {
	case STATE_BUFFER:
return 3;
	    break;
	case STATE_SEQUENCE:
//	    mpeg2_convert (decoder, mpeg2convert_rgb24, NULL);
//	    break;
	case STATE_SLICE:
	case STATE_END:
	case STATE_INVALID_END:
	    if (info->display_fbuf) return 1;
	    break;
	default:
	    break;
	}
	return 0;
}

int _MPEGdraw2(mpeg2dec_t *decoder,mpeg2_info_t *info,uint8_t *pixmap)
{
    mpeg2_state_t state;
    size_t size;

	state = mpeg2_parse (decoder);
	switch (state) {
	case STATE_BUFFER:
return 3;
	    break;
	case STATE_SEQUENCE:
//	    mpeg2_convert (decoder, mpeg2convert_rgb24, NULL);
//	    break;
	case STATE_SLICE:
	case STATE_END:
	case STATE_INVALID_END:
	    if (info->display_fbuf)
		{
//		YUVdraw(pixmap, 640,480,_MPEGy(info),_MPEGu(info),_MPEGv(info));
		return 1;
		}
	    break;
	default:
	    break;
	}
	return 0;
}

uint8_t *_MPEGy(mpeg2_info_t *info)
{
	return info->display_fbuf->buf[0];
}

uint8_t *_MPEGu(mpeg2_info_t *info)
{
	return info->display_fbuf->buf[2];
}

uint8_t *_MPEGv(mpeg2_info_t *info)
{
	return info->display_fbuf->buf[1];
}

int _MPEGwidth(mpeg2_info_t *info)
{
	return info->sequence->width;
}

int _MPEGheight(mpeg2_info_t *info)
{
	return info->sequence->height;
}

int _MPEGclose(mpeg2dec_t *decoder)
{
	mpeg2_close (decoder);
}