/*********************************************************************************

Copyright(c) 2006 Analog Devices, Inc. All Rights Reserved.

This software is proprietary and confidential.  By using this software you agree
to the terms of the associated Analog Devices License Agreement.

***********************************************************************
			
********* MACROS ************************************************************************/
#define   NTSC_MODE     	// Video frame is of NTSC format
//#define READ_REG_VALUE	// read/print register value enable/disable
#define	  NEC_LCD	
/*********************************************************************

Include files

*********************************************************************/
#include <drivers/adi_dev.h>			// Device manager includes
#include <drivers/decoder/adi_adv7183.h>		// AD7183 device driver includes
#if defined NEC_LCD
#include <drivers/lcd/nec/adi_nl6448BC33_54.h>
#else
#include <drivers/lcd/sharp/adi_lq10d368.h>
#endif
#include <drivers/twi/adi_twi.h>			// TWI device driver includes
//#include <drivers/ppi/adi_ppi.h>			// PPI device driver includes
#include <SDK-ezkitutilities.h>
#include <adi_ssl_Init.h>

#include "stdio.h"
#include "math.h"

/*********************************************************************

Prototypes

*********************************************************************/


/*****************************************************************************

Static data

*****************************************************************************/
#define NTSC	0
#define PAL 	1

// NTSC or PAL Video input
#define ACTIVE_FIELD_DATA_LEN		720	// Active field data length per line for PAL video format

#if defined NTSC_MODE	// NTSC mode
#define ACTIVE_FIELD_LINES	507		// Number of lines per active field frame for NTSC format   
#else // PAL mode
#define ACTIVE_FIELD_LINES	576		// Number of lines per active field frame for PAL format   
#endif

#define ACTIVE_FIELD_FRAME_SIZE	(ACTIVE_FIELD_DATA_LEN * ACTIVE_FIELD_LINES)
#define VIDEOHORZLINES		ACTIVE_FIELD_DATA_LEN/2
#define CROP_HORIZONTAL_LINES	20

#if defined NTSC_MODE	// NTSC mode
#define CROP_VIDEO_LINES	13
#define OFFSET_TO_ODD_FRAME	((ACTIVE_FIELD_LINES+1)/2)
#define IPOFFSET_EVEN	(CROP_VIDEO_LINES*VIDEOHORZLINES)+CROP_HORIZONTAL_LINES// VIDEO buffer offset for even frame
#define IPOFFSET_ODD	IPOFFSET_EVEN + (OFFSET_TO_ODD_FRAME*VIDEOHORZLINES)// VIDEO buffer offset for odd frame
#else
#define CROP_VIDEO_LINES	24
#define OFFSET_TO_ODD_FRAME	288
#define IPOFFSET_EVEN	(CROP_VIDEO_LINES*VIDEOHORZLINES)+CROP_HORIZONTAL_LINES// VIDEO buffer offset for even frame
#define IPOFFSET_ODD	IPOFFSET_EVEN + (OFFSET_TO_ODD_FRAME*VIDEOHORZLINES)// VIDEO buffer offset for odd frame
#endif

// VGA LCD output
#define VGA_WIDTH		640
#define VGA_PADLEFT		0
#define VGA_PADRIGHT		0

#define VGA_HEIGHT		480
#define VGA_PADTOP		33
#define VGA_PADBOTTOM		12

#define VGA_FRAME_WIDTH		(VGA_WIDTH+VGA_PADLEFT+VGA_PADRIGHT) // 640
#define VGA_FRAME_HEIGHT	(VGA_HEIGHT+VGA_PADTOP+VGA_PADBOTTOM) // 525
#define VGA_FRAME_SIZE		(VGA_FRAME_WIDTH*VGA_FRAME_HEIGHT) // 640*525

#define LCDHORZLINES	VGA_FRAME_WIDTH/2
#define OPOFFSET_EVEN	(VGA_PADTOP*LCDHORZLINES)// LCD buffer offset for even frame
#define OPOFFSET_ODD	((VGA_PADTOP+1)*LCDHORZLINES)//LCD buffer offset for odd frame





/*********************************************************************

memory for buffers and data

*********************************************************************/
// Define the DMA buffers for each frame.
// Because of SDRAM performance, each frame must be in a different bank.

section("vd0_sdram") volatile u16 sFrame0[ACTIVE_FIELD_FRAME_SIZE];
section("vd1_sdram") volatile u16 sFrame1[ACTIVE_FIELD_FRAME_SIZE];


section("vd2_sdram") volatile u16 sFrame2[VGA_FRAME_SIZE];

// Storage for YUV to RGB565 conversion
section("L1_data_a") static unsigned long InData[512],OutData[512];

// 2 input buffers used by AD7183
ADI_DEV_2D_BUFFER In1_Buffer2D, In2_Buffer2D;
 
// 2 output buffers used by LCD
ADI_DEV_2D_BUFFER Out1_Buffer2D, Out2_Buffer2D; 
/*********************************************************************

memory for initialization of system services and device manager

*********************************************************************/

/*********************************************************************

handles to device drivers

*********************************************************************/
ADI_DEV_DEVICE_HANDLE AD7183DriverHandle;// handle to the ad7183 driver
ADI_DEV_DEVICE_HANDLE LcdDriverHandle;// handle to the LCD driver

/*********************************************************************

static function prototypes

*********************************************************************/
// exception handlers
static ADI_INT_HANDLER(ExceptionHandler);
static ADI_INT_HANDLER(HWErrorHandler);
static void InitSystemServices(void); // system services initialization
static void CallbackFunction( void *AppHandle, u32 Event,void *pArg);// device driver callback function
static void InitADV7183_Start(void);
static void InitLcd_Start(void);
void convertFrame(u32 num);   
static void convertyuvrgb(unsigned short OutSize, unsigned long *Output, unsigned short InSize, unsigned long *Input);
static void Set7183RangeReg(void);// Set AD7183 Extended Output Control register
static void Read7183StatusReg(void); // Read AD7183 Status register

volatile bool Frame0Flag;
volatile bool Frame1Flag;

/*********************************************************************

	Function:	main
	Description:	Read in ITU656 NTSC or PAL video data into SDRAM input buffer.
			Convert YUV(4:2:2) to RGB565 format and store into SDRAM output buffer.
			Send the output buffer to the VGA LCD.
         
*********************************************************************/

void main(void)
{
	unsigned int i,Result;									// index
	u32	ResponseCount;								// response count
	
	
	// initialize the system services
	InitSystemServices();
	
	// enable LEDs and buttons
    	for (i = EZ_FIRST_LED; i < EZ_NUM_LEDS; i++){
        ezInitLED(i);
    	}
    	
    ezInitButton(EZ_LAST_BUTTON);
	
	// turn off LED's	
	ezTurnOffAllLEDs();

	
	                      
	//reset the processed buffer flag
	Frame0Flag = false;
	Frame1Flag = false;                      

	// initialize the decoder and start the input data flow
	InitADV7183_Start();

	// initialize the LCD and start the output data flow
	InitLcd_Start();
	
	
	// loop forever until the last push button is depressed
    	while (ezIsButtonPushed(EZ_LAST_BUTTON) == FALSE){
    	// convert processed buffer
    		if (Frame0Flag){
    		Frame0Flag = false;
    		convertFrame(0); // convert even field
    		}
    	
    		if (Frame1Flag){
    		Frame1Flag = false;
    		convertFrame(1); // convert odd field
    		}
 	
    	}

	// close the device
	ezErrorCheck(adi_dev_Close(AD7183DriverHandle));

	// close the device
	ezErrorCheck(adi_dev_Close(LcdDriverHandle));
	
	/* terminate the device */
	adi_ssl_Terminate();
	

}




/*********************************************************************

	Function:	CallbackFunction

	Description:	Each type of callback event has it's own unique ID
			so we can use a single callback function for all
			callback events.  The switch statement tells us
			which event has occurred.
			In the example, we'll get a callback when the PPI 
			has completed processing of the input buffer.
			Note that in the device driver model, in order to 
			generate a callback for buffer completion, the 
			CallbackParameter of the buffer must be set to a non-NULL 
			value.
*********************************************************************/

static void CallbackFunction(void *AppHandle,u32  Event,void *pArg)
{
	ADI_DEV_2D_BUFFER *p2DBuffer;	// pointer to the buffer that was processed
		
    	p2DBuffer = (ADI_DEV_2D_BUFFER *)pArg;
	
	switch (Event)
	{
		// CASE (buffer processed)
        	case ADI_DEV_EVENT_BUFFER_PROCESSED:
   	    		
    	    	if(p2DBuffer == &In1_Buffer2D){
    	    	 Frame0Flag = true;
    	    	}
    	    	else if(p2DBuffer == &In2_Buffer2D){
    	    	 Frame1Flag = true;
    	    	}
      	 
           	break;
           
                  // CASE (an error)
		case ADI_DEV_EVENT_DMA_ERROR_INTERRUPT:
			// turn on all LEDs and wait for help
			ezTurnOnAllLEDs();
			while (1) ;
			

	}

	// return
}

/*********************************************************************

	Function:		InitSystemServices

	Description:	Initializes the necessary system services.  

*********************************************************************/

void InitSystemServices(void) {
    
    // initialize the ezKit power,EBIU,DMA....
	adi_ssl_Init();	
		
	// enable and configure async memory
	ezInit(1);
}

/******************************************************************************

	Function: InitADV7183_Start
	
	Description: Open the ADV7183 device, configure the device, 
		     setup 2D output buffer and enable the data flow

******************************************************************************/
static void InitADV7183_Start(void)
{    
	
    	// this example uses the AV-Extender card, so disable the onboard video decoder
	ezDisableVideoDecoder();
	
	// Pseudo TWI will be used to access ADV7183 registers.
	// BF561 Ports (PF0=SCL,PF1=SDA) & Timer(Timer 3) used for Pseudo TWI
	adi_twi_pseudo_port TWIPseudo= {ADI_FLAG_PF0,ADI_FLAG_PF1,ADI_TMR_GP_TIMER_3,(ADI_INT_PERIPHERAL_ID)NULL};
	ADI_DEV_CMD_VALUE_PAIR PseudoTWIConfig[]={
	{ADI_TWI_CMD_SET_PSEUDO,(void *)(&TWIPseudo)},
	{ADI_DEV_CMD_SET_DATAFLOW_METHOD,(void *)ADI_DEV_MODE_SEQ_CHAINED},
	{ADI_DEV_CMD_SET_DATAFLOW,(void *)TRUE},
	{ADI_DEV_CMD_END,NULL}
	};
	
	
	// open the ad7183 driver
	ezErrorCheck(adi_dev_Open(adi_dev_ManagerHandle,		// DevMgr handle
				&ADIADV7183EntryPoint,		// pdd entry point
				0,				// device instance
	            (void *)0x7183,            // client handle (0x7183 will be given to the AD7183 decoder driver)
				&AD7183DriverHandle,			// DevMgr handle for this device
				ADI_DEV_DIRECTION_INBOUND,// data direction for this device
				adi_dma_ManagerHandle,			// handle to DmaMgr for this device
				NULL,				// handle to deferred callback service
				CallbackFunction));		// client's callback function
				
	/********* open AD7183-PPI ****************************************/		
	// open the AD7183-PPI device 0 (see Schematic)
	ezErrorCheck(adi_dev_Control(AD7183DriverHandle, ADI_AD7183_CMD_OPEN_PPI, (void *)0));
			
	// command PPI to work in NTSC or PAL mode
#if defined NTSC_MODE	// NTSC mode
		ezErrorCheck(adi_dev_Control(AD7183DriverHandle, ADI_AD7183_CMD_SET_VIDEO_FORMAT, (void *)NTSC));
#else
		ezErrorCheck(adi_dev_Control(AD7183DriverHandle, ADI_AD7183_CMD_SET_VIDEO_FORMAT, (void *)PAL));
#endif		
				
	/******************* AD7183 Inbound Buffers  ***********************************************/	
	// populate the buffers that we'll use for the PPI input
	In1_Buffer2D.Data = (void*)sFrame0;
	In1_Buffer2D.ElementWidth = 4;
	In1_Buffer2D.XCount = ACTIVE_FIELD_DATA_LEN/2;
	In1_Buffer2D.YCount = ACTIVE_FIELD_LINES;
	In1_Buffer2D.XModify = 4;
	In1_Buffer2D.YModify = 4;
	In1_Buffer2D.CallbackParameter = &In1_Buffer2D;
	In1_Buffer2D.pNext = &In2_Buffer2D;

	
	In2_Buffer2D.Data = (void*)sFrame1;
	In2_Buffer2D.ElementWidth = 4;
	In2_Buffer2D.XCount = ACTIVE_FIELD_DATA_LEN/2;
	In2_Buffer2D.YCount = ACTIVE_FIELD_LINES;
	In2_Buffer2D.XModify = 4;
	In2_Buffer2D.YModify = 4;
	In2_Buffer2D.CallbackParameter = &In2_Buffer2D;
	In2_Buffer2D.pNext = NULL;

	// configure the ad7183 dataflow method
	ezErrorCheck(adi_dev_Control(AD7183DriverHandle, ADI_DEV_CMD_SET_DATAFLOW_METHOD, (void *)ADI_DEV_MODE_CHAINED_LOOPBACK));
	// give the PPI driver the buffer to process
	ezErrorCheck(adi_dev_Read(AD7183DriverHandle, ADI_DEV_2D, (ADI_DEV_BUFFER *)&In1_Buffer2D));

	/********* AD7183 registers access ****************************************/		
	// Send Pseudo TWI Configuration table to AD7183 if register configuratian is needed
	ezErrorCheck(adi_dev_Control(AD7183DriverHandle,ADI_AD7183_CMD_SET_TWI_CONFIG_TABLE,(void*)PseudoTWIConfig)); 

	//set Extended Output Control register to ITU656 for 16<Y<235 and 16<C<240
	Set7183RangeReg();
	
	 // configure the PPI driver for receiving active field only
	ezErrorCheck( adi_dev_Control(AD7183DriverHandle, ADI_AD7183_CMD_SET_ACTIVE_VIDEO, (void*)TRUE));
	
	// start capturing video data
	ezErrorCheck(adi_dev_Control(AD7183DriverHandle, ADI_DEV_CMD_SET_DATAFLOW, (void*)TRUE));

#if defined(READ_REG_VALUE)
	// read AD7183 status register
	Read7183StatusReg();
#endif	

}	


/******************************************************************************

	Function: InitLcd_Start
	
	Description: Open the NEC LCD device, configure the device, 
		     setup 2D output buffer and enable the data flow

******************************************************************************/
static void InitLcd_Start(void)
{	
	// open the nl6448BC3354 driver
	ezErrorCheck(adi_dev_Open(adi_dev_ManagerHandle,		// DevMgr handle
#if defined NEC_LCD
				&ADI_NL6448BC3354_EntryPoint,// pdd entry point for nec lcd driver
#else
				&ADI_LQ10D368_EntryPoint,// pdd entry point for sharp lcd driver
#endif				
				
				0,				// device instance
				NULL,				// client handle callback identifier
				&LcdDriverHandle,			// DevMgr handle for this device
				ADI_DEV_DIRECTION_OUTBOUND,// data direction for this device
				adi_dma_ManagerHandle,			// handle to DmaMgr for this device
				NULL,				// handle to deferred callback service
				CallbackFunction));		// client's callback function
	
	// Select PPI device number and open it for LCD driver.
#if defined NEC_LCD
	ezErrorCheck(adi_dev_Control(LcdDriverHandle, ADI_NL6448BC3354_CMD_OPEN_PPI, (void*)1));
#else
	ezErrorCheck(adi_dev_Control(LcdDriverHandle, ADI_LQ10D368_CMD_OPEN_PPI, (void*)1));
#endif
	// populate LCD outbound buffers
	Out1_Buffer2D.Data = (void*)sFrame2;// address of the data storage
	Out1_Buffer2D.ElementWidth = 4; //4 bytes wide
	Out1_Buffer2D.XCount = (VGA_FRAME_WIDTH/2);
	Out1_Buffer2D.XModify = 4;
	Out1_Buffer2D.YCount = VGA_FRAME_HEIGHT;
	Out1_Buffer2D.YModify = 4;
	Out1_Buffer2D.CallbackParameter = NULL;// no callback
	Out1_Buffer2D.pNext = NULL; // terminate the chain of buffers

	
	// configure the LCD dataflow method
	ezErrorCheck(adi_dev_Control(LcdDriverHandle, ADI_DEV_CMD_SET_DATAFLOW_METHOD, (void *)ADI_DEV_MODE_CHAINED_LOOPBACK));
    	ezErrorCheck(adi_dev_Write(LcdDriverHandle, ADI_DEV_2D, (ADI_DEV_BUFFER *)&Out1_Buffer2D));
	        	 	
	// start outputting LCD video data
	ezErrorCheck ( adi_dev_Control(LcdDriverHandle, ADI_DEV_CMD_SET_DATAFLOW, (void*)TRUE));


}





/******************************************************************************

	Function: convertFrame
	
	Description: When a input buffer is filled by the ADV7183 driver,
		     a function is called to convert each line of the buffer
		     into RGB format.	
******************************************************************************/
void convertFrame(u32 frameNum){
	u32 m;	
	u32 *ipF, *opF;

	if(frameNum == 0){ // process video frame 0
	    
	   ipF =((u32 *)sFrame0)+ IPOFFSET_EVEN; // input point to even section of sFrame0
	   opF=(u32 *)sFrame2+OPOFFSET_EVEN;// output point to even section of sFrame2

	}
	else{// process video frame 1
	   ipF =((u32 *)sFrame1)+ IPOFFSET_ODD; // input point to even section of sFrame0
	   opF=(u32 *)sFrame2+OPOFFSET_ODD;// output point to even section of sFrame2

	}
		
	for(m=0;m<VGA_HEIGHT/2;m++,opF+=LCDHORZLINES*2,ipF+=VIDEOHORZLINES){ //output to every second line.

		convertyuvrgb(LCDHORZLINES,opF,VIDEOHORZLINES,ipF);	
	
	}

}

/******************************************************************************

Exception interrupt handlers

Note: should never get an exception or hardware error...

******************************************************************************/

static ADI_INT_HANDLER(ExceptionHandler)
{
	// turn on all LEDs and wait for help
	ezTurnOnAllLEDs();
	while (1) ;
}


static ADI_INT_HANDLER(HWErrorHandler)
{
	// turn on all LEDs and wait for help
	ezTurnOnAllLEDs();
	while (1) ;
}



/******************************************************************************

	Function: convert_yuv_rgb
	
	Description: This function takes an input buffer, output buffer and
		overlay buffer and combines the input and overlay and writes back to
		the output.

		Cb=*(pYUV+n);
		Y0=*(pYUV+n+1);
		Cr=*(pYUV+n+2);
		Y1=*(pYUV+n+3); 
				
		C = Y - 16
		D = Cb - 128
		E = Cr - 128

		R = clip((298*C + 409*E         ) >> 8)
		G = clip((298*C - 100*D - 208*E ) >> 8)
		B = clip((298*C + 516*D         ) >> 8)



******************************************************************************/

static void convertyuvrgb(
	unsigned short OutSize, unsigned long *Output,
 	unsigned short InSize, unsigned long *Input)
{
 	unsigned short i,j;
 
 	long r,g,b,r1,g1,b1,cb,cr,y0,y1; 
	u8 *yuv;
	
 	for (i=0;i<OutSize;i++) 
  		InData[i]=*Input++;
 
	for (i=0,j=0;i<OutSize;i++,j++)
  	{   

    	
 	    yuv = (u8*)(&InData[j]);
  	    y1 = (*(yuv+3)*298)-16;
  	    cr = *(yuv+2)-128;
   	    y0 = (*(yuv+1)*298)-16;
  	    cb = *yuv-128;
  	    
		r = (409*cr);
  	    g = (100*cb + 208*cr);
  	    b = (516*cb);

		r1=y0+r;
		g1=y0-g;
		b1=y0+b;
		
  	    if(r1>0xFFFF)  r1 = 255; 
  	    else if(r1<0)  r1 = 0;   	    
    	else r1>>=8;
    
    	if(g1>0xFFFF)  g1 = 255; 
    	else if(g1<0)  g1 = 0; 
    	else g1>>=8;
    
    	if(b1>0xFFFF)  b1 = 255; 
    	else if(b1<0)  b1 = 0; 
    	else b1>>=8;
        
    	r=y1+r;
		g=y1-g;
		b=y1+b;
    	
    	if(r>0xFFFF)  r = 255; 
    	else if(r<0)  r = 0; 
    	else r>>=8; 
    
    	if(g>0xFFFF)  g = 255; 
    	else if(g<0)  g = 0; 
    	else g>>=8;
    
    	if(b>0xFFFF)  b = 255; 
    	else if(b<0)  b = 0; 
    	else b>>=8;    		    
  	      	    
    	OutData[j]=
    		((b<<24) & 0xF8000000)|
    		((g<<19) & 0x07E00000)|
    		((r<<13) & 0x001F0000)|
    		((b1<<8) & 0x0000F800)|
    		((g1<<3) & 0x000007E0)|
    		((r1>>3) & 0x0000001F);
	}

 	for (i=0;i<OutSize;i++) *Output++=OutData[i];
}



/**********************************************************************
* Example how to read ADV7183 status registers 
**********************************************************************/
static void Read7183StatusReg(void)	
{
    	u32 Result = 0, i;

    
    ADI_DEV_ACCESS_REGISTER Regs[] = 
	{{ ADV7183_STATUS1_RO, 	0 },		// Register address to access, corresponding register data
         { ADV7183_IDENT_RO, 	0 },
         { ADV7183_STATUS2_RO, 	0 },
         { ADV7183_STATUS3_RO, 	0 },
         { ADI_DEV_REGEND,	0 }};	// Register access delimiter (indicates end of register access)

//To read list of registers in DevRegs
    Result =  adi_dev_Control(AD7183DriverHandle, ADI_DEV_CMD_REGISTER_TABLE_READ, (void *)&Regs);    
    if (Result != 0) printf("CMD_REGISTER_TABLE_READ failed(error:%x)\n",Result);
    else {
    	// print the values	
		printf("AD7183: STATUS1 IDENT STATUS2 STATUS3\n ");
		for (i=0; i<4; i++){
		printf("0x%02X ",Regs[i].Data);
		}
		printf("\n");

    }

}

/**********************************************************************
* Example how to write ADV7183 status registers 
* set field ADV7183_RANGE of register ADV7183_EXTENDED_OUTPUT_CTR to 0
**********************************************************************/
static void Set7183RangeReg(void)	
{
    	u32 Result;

    	ADI_DEV_ACCESS_REGISTER_FIELD RegField	
    	= { ADV7183_EXTENDED_OUTPUT_CTR, ADV7183_RANGE, 0};	// Register address to access, Register field to access, corresponding register field data


// to configure Reg1Field1
	Result = adi_dev_Control(AD7183DriverHandle, ADI_DEV_CMD_REGISTER_FIELD_WRITE, (void *) &RegField);
    if (Result != 0) printf("CMD_REGISTER_FIELD_WRITE failed(error:%x)\n",Result);

}






