include "fastmemcpy.h"
#include "../cpudetect.h"
#include "../postproc/swscale.h"
#include "../postproc/rgb2rgb.h"
#include "../libmpcodecs/vf_scale.h"
#include "mp_msg.h"

// mga_vid drawing functions
static void set_window( void );		/* forward declaration to kill warnings */
#ifdef VO_XMGA
static void mDrawColorKey( void );	/* forward declaration to kill warnings */
#ifdef HAVE_XINERAMA
extern int xinerama_screen;
#endif
#endif

static int mga_next_frame=0;

static mga_vid_config_t mga_vid_config;
static uint8_t *vid_data, *frames[4];
static int f = -1;

static uint32_t               drwX,drwY,drwWidth,drwHeight;
#ifdef VO_XMGA
static uint32_t               drwBorderWidth,drwDepth;
#endif
static uint32_t               drwcX,drwcY,dwidth,dheight;

static void draw_alpha(int x0,int y0, int w,int h, unsigned char* src, unsigned char *srca, int stride){
    uint32_t bespitch = (mga_vid_config.src_width + 31) & ~31;
    x0+=mga_vid_config.src_width*(vo_panscan_x>>1)/(vo_dwidth+vo_panscan_x);
    switch(mga_vid_config.format){
    case MGA_VID_FORMAT_YV12:
    case MGA_VID_FORMAT_IYUV:
    case MGA_VID_FORMAT_I420:
        vo_draw_alpha_yv12(w,h,src,srca,stride,vid_data+bespitch*y0+x0,bespitch);
        break;
    case MGA_VID_FORMAT_YUY2:
        vo_draw_alpha_yuy2(w,h,src,srca,stride,vid_data+2*(bespitch*y0+x0),2*bespitch);
        break;
    case MGA_VID_FORMAT_UYVY:
        vo_draw_alpha_yuy2(w,h,src,srca,stride,vid_data+2*(bespitch*y0+x0)+1,2*bespitch);
        break;
    }
}

static void draw_osd(void)
{
//    vo_draw_text(mga_vid_config.src_width,mga_vid_config.src_height,draw_alpha);
    vo_draw_text(mga_vid_config.src_width-mga_vid_config.src_width*vo_panscan_x/(vo_dwidth+vo_panscan_x),mga_vid_config.src_height,draw_alpha);
}


//static void
//write_slice_g200(uint8_t *y,uint8_t *cr, uint8_t *cb,uint32_t slice_num)

static void
draw_slice_g200(uint8_t *image[], int stride[], int width,int height,int x,int y)
{
	uint8_t *dest;
	uint32_t bespitch = (mga_vid_config.src_width + 31) & ~31;

	dest = vid_data + bespitch*y + x;
	mem2agpcpy_pic(dest, image[0], width, height, bespitch, stride[0]);

        width/=2;height/=2;x/=2;y/=2;

	dest = vid_data + bespitch*mga_vid_config.src_height + bespitch*y + 2*x;

	interleaveBytes(image[1],image[2],dest,
		width, height,
		stride[1], stride[2], bespitch);
}

static void
draw_slice_g400(uint8_t *image[], int stride[], int w,int h,int x,int y)
{
    uint8_t *dest;
    uint8_t *dest2;
    uint32_t bespitch,bespitch2;

    bespitch = (mga_vid_config.src_width + 31) & ~31;
    bespitch2 = bespitch/2;

    dest = vid_data + bespitch * y + x;
    mem2agpcpy_pic(dest, image[0], w, h, bespitch, stride[0]);
    
    w/=2;h/=2;x/=2;y/=2;

    dest = vid_data + bespitch*mga_vid_config.src_height + bespitch2 * y + x;
    dest2= dest + bespitch2*mga_vid_config.src_height / 2; 

  if(mga_vid_config.format==MGA_VID_FORMAT_YV12){
    // mga_vid's YV12 assumes Y,U,V order (insteda of Y,V,U) :(
    mem2agpcpy_pic(dest, image[1], w, h, bespitch2, stride[1]);
    mem2agpcpy_pic(dest2,image[2], w, h, bespitch2, stride[2]);
  } else {
    mem2agpcpy_pic(dest, image[2], w, h, bespitch2, stride[2]);
    mem2agpcpy_pic(dest2,image[1], w, h, bespitch2, stride[1]);
  }

}

static uint32_t
draw_slice(uint8_t *src[], int stride[], int w,int h,int x,int y)
{

#if 0
	printf("vo: %p/%d %p/%d %p/%d  %dx%d/%d;%d  \n",
	    src[0],stride[0],
	    src[1],stride[1],
	    src[2],stride[2],
	    w,h,x,y);
#endif

	if (mga_vid_config.card_type == MGA_G200)
            draw_slice_g200(src,stride,w,h,x,y);
	else
            draw_slice_g400(src,stride,w,h,x,y);
	return 0;
}

static void
vo_mga_flip_page(void)
{

//    printf("-- flip to %d --\n",mga_next_frame);

#if 1
	ioctl(f,MGA_VID_FSEL,&mga_next_frame);
	mga_next_frame=(mga_next_frame+1)%mga_vid_config.num_frames;
	vid_data=frames[mga_next_frame];
#endif

}

static uint32_t
draw_frame(uint8_t *src[])
{
    printf("!!! mga::draw_frame() called !!!\n");
    return 0;
}

static uint32_t get_image(mp_image_t *mpi){
    uint32_t bespitch = (mga_vid_config.src_width + 31) & ~31;
    uint32_t bespitch2 = bespitch/2;
//    printf("mga: get_image() called\n");
    if(mpi->type==MP_IMGTYPE_STATIC && mga_vid_config.num_frames>1) return VO_FALSE; // it is not static
    if(mpi->flags&MP_IMGFLAG_READABLE) return VO_FALSE; // slow video ram
    if(mga_vid_config.card_type == MGA_G200 && mpi->flags&MP_IMGFLAG_PLANAR) return VO_FALSE;
//    printf("width=%d vs. bespitch=%d, flags=0x%X  \n",mpi->width,bespitch,mpi->flags);
    if((mpi->width==bespitch) ||
       (mpi->flags&(MP_IMGFLAG_ACCEPT_STRIDE|MP_IMGFLAG_ACCEPT_WIDTH))){
       // we're lucky or codec accepts stride => ok, let's go!
       if(mpi->flags&MP_IMGFLAG_PLANAR){
	   mpi->planes[0]=vid_data;
	   if(mpi->flags&MP_IMGFLAG_SWAPPED){
	       mpi->planes[1]=vid_data + bespitch*mga_vid_config.src_height;
	       mpi->planes[2]=mpi->planes[1] + bespitch2*mga_vid_config.src_height/2;
	   } else {
	       mpi->planes[2]=vid_data + bespitch*mga_vid_config.src_height;
	       mpi->planes[1]=mpi->planes[2] + bespitch2*mga_vid_config.src_height/2;
	   }
	   mpi->width=mpi->stride[0]=bespitch;
	   mpi->stride[1]=mpi->stride[2]=bespitch2;
       } else {
           mpi->planes[0]=vid_data;
	   mpi->width=bespitch;
	   mpi->stride[0]=mpi->width*(mpi->bpp/8);
       }
       mpi->flags|=MP_IMGFLAG_DIRECT;
//	printf("mga: get_image() SUCCESS -> Direct Rendering ENABLED\n");
       return VO_TRUE;
    }
    return VO_FALSE;
}

static uint32_t
draw_image(mp_image_t *mpi){
    uint32_t bespitch = (mga_vid_config.src_width + 31) & ~31;

    // if -dr or -slices then do nothing:
    if(mpi->flags&(MP_IMGFLAG_DIRECT|MP_IMGFLAG_DRAW_CALLBACK)) return VO_TRUE;

    if(mpi->flags&MP_IMGFLAG_PLANAR){
	// copy planar:
        draw_slice(mpi->planes,mpi->stride,mpi->w,mpi->h,mpi->x,mpi->y);
    } else {
	// copy packed:
	mem2agpcpy_pic(vid_data, mpi->planes[0],	// dst,src
		    mpi->w*(mpi->bpp/8), mpi->h,	// w,h
		    bespitch*2, mpi->stride[0]);	// dstride,sstride
    }
    return VO_TRUE;
}

static uint32_t
query_format(uint32_t format)
{
    switch(format){
    case IMGFMT_YV12:
    case IMGFMT_I420:
    case IMGFMT_IYUV:
    case IMGFMT_YUY2:
    case IMGFMT_UYVY:
        return 3 | VFCAP_OSD|VFCAP_HWSCALE_UP|VFCAP_HWSCALE_DOWN|VFCAP_ACCEPT_STRIDE;
    }
    return 0;
}

static void mga_fullscreen()
{
	uint32_t w,h;
	if ( !vo_fs ) {
		vo_fs=VO_TRUE;
		w=vo_screenwidth; h=vo_screenheight;
		aspect(&w,&h,A_ZOOM);
	} else {
		vo_fs=VO_FALSE;
		w=vo_dwidth; h=vo_dheight;
		aspect(&w,&h,A_NOZOOM);
	}
	mga_vid_config.dest_width = w;
	mga_vid_config.dest_height= h;
	mga_vid_config.x_org=(vo_screenwidth-w)/2;
	mga_vid_config.y_org=(vo_screenheight-h)/2;
	if ( ioctl( f,MGA_VID_CONFIG,&mga_vid_config ) )
		printf( "Error in mga_vid_config ioctl (wrong mga_vid.o version?)" );
}

static uint32_t control(uint32_t request, void *data, ...)
{
  switch (request) {
  case VOCTRL_QUERY_FORMAT:
    return query_format(*((uint32_t*)data));
  case VOCTRL_GET_IMAGE:
    return get_image(data);
  case VOCTRL_DRAW_IMAGE:
    return draw_image(data);
  case VOCTRL_SET_EQUALIZER:
    {
     va_list ap;
     short value;
     uint32_t luma,prev;

     if ( strcmp( data,"brightness" ) && strcmp( data,"contrast" ) ) return VO_FALSE;

     if (ioctl(f,MGA_VID_GET_LUMA,&prev)) {
	perror("Error in mga_vid_config ioctl()");
        printf("Could not get luma values from the kernel module!\n");
	return VO_FALSE;
     }

//     printf("GET: 0x%4X 0x%4X  \n",(prev>>16),(prev&0xffff));

     va_start(ap, data);
     value = va_arg(ap, int);
     va_end(ap);
     
//     printf("value: %d -> ",value);
     value=((value+100)*255)/200-128; // maps -100=>-128 and +100=>127
//     printf("%d  \n",value);

     if(!strcmp(data,"contrast"))
         luma = (prev&0xFFFF0000)|(value&0xFFFF);
     else
         luma = (prev&0xFFFF)|(value<<16);
     
     if (ioctl(f,MGA_VID_SET_LUMA,luma)) {
	perror("Error in mga_vid_config ioctl()");
        printf("Could not set luma values in the kernel module!\n");
	return VO_FALSE;
     }

     return VO_TRUE;
    }

  case VOCTRL_GET_EQUALIZER:
    {
     va_list ap;
     int * value;
     short val;
     uint32_t luma;
     
     if ( strcmp( data,"brightness" ) && strcmp( data,"contrast" ) ) return VO_FALSE;

     if (ioctl(f,MGA_VID_GET_LUMA,&luma)) {
	perror("Error in mga_vid_config ioctl()");
        printf("Could not get luma values from the kernel module!\n");
	return VO_FALSE;
     }
     
     if ( !strcmp( data,"contrast" ) )
	 val=(luma & 0xFFFF);
     else
	 val=(luma >> 16);
	 
     va_start(ap, data);
     value = va_arg(ap, int*);
     va_end(ap);

     *value = (val*200)/255;

     return VO_TRUE;
    }
														       
#ifndef VO_XMGA
  case VOCTRL_FULLSCREEN:
    if (vo_screenwidth && vo_screenheight)
	mga_fullscreen();
    else
	printf("Screen width/height unknown!\n");
    return VO_TRUE;
  case VOCTRL
