/*
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
 
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
 
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/


#define __SOFT_JPEG__

#include "mbed.h"
#include "rga_func.h"
#include "DisplayBace.h"
#include "rtos.h"
#include "LcdCfg.h"
#include "Touch.h"
#include "rza_io_regrw.h"
#include "USBHostCam.h"
//#include "JPEG_Converter.h"

#include "Images/BinaryImage_RZ_A1H.h"

#ifdef __SOFT_JPEG__
#include "jpeglib.h"
#include <setjmp.h>
#endif

#define VIDEO_CVBS             (0)                 /* Analog  Video Signal */
#define VIDEO_CMOS_CAMERA      (1)                 /* Digital Video Signal */

#define VIDEO_YCBCR422         (0)
#define VIDEO_RGB888           (1)
#define VIDEO_RGB565           (2)

/**** User Selection *********/
#define VIDEO_INPUT_METHOD     (VIDEO_CVBS)        /* Select  VIDEO_CVBS or VIDEO_CMOS_CAMERA                       */
#define VIDEO_INPUT_FORMAT     (VIDEO_RGB565)      /* Select  VIDEO_YCBCR422 or VIDEO_RGB888 or VIDEO_RGB565        */
#define USE_VIDEO_CH           (0)                 /* Select  0 or 1            If selecting VIDEO_CMOS_CAMERA, should be 0.)               */
#define VIDEO_PAL              (1)                 /* Select  0(NTSC) or 1(PAL) If selecting VIDEO_CVBS, this parameter is not referenced.) */
/*****************************/

#if USE_VIDEO_CH == (0)
#define VIDEO_INPUT_CH         (DisplayBase::VIDEO_INPUT_CHANNEL_0)
#define VIDEO_INT_TYPE         (DisplayBase::INT_TYPE_S0_VFIELD)
#else
#define VIDEO_INPUT_CH         (DisplayBase::VIDEO_INPUT_CHANNEL_1)
#define VIDEO_INT_TYPE         (DisplayBase::INT_TYPE_S1_VFIELD)
#endif

/** Video and Grapics (GRAPHICS_LAYER_0) parameter **/
/* NTSC or PAL */
#if VIDEO_PAL == 0
  #define COL_SYS              (DisplayBase::COL_SYS_NTSC_358)
#else
  #define COL_SYS              (DisplayBase::COL_SYS_PAL_443)
#endif

/* Video input and LCD layer 0 output */
#if VIDEO_INPUT_FORMAT == VIDEO_YCBCR422
  #define VIDEO_FORMAT         (DisplayBase::VIDEO_FORMAT_YCBCR422)
  #define GRAPHICS_FORMAT      (DisplayBase::GRAPHICS_FORMAT_YCBCR422)
  #define WR_RD_WRSWA          (DisplayBase::WR_RD_WRSWA_NON)
#elif VIDEO_INPUT_FORMAT == VIDEO_RGB565
  #define VIDEO_FORMAT         (DisplayBase::VIDEO_FORMAT_RGB565)
  #define GRAPHICS_FORMAT      (DisplayBase::GRAPHICS_FORMAT_RGB565)
  #define WR_RD_WRSWA          (DisplayBase::WR_RD_WRSWA_32_16BIT)
#else
  #define VIDEO_FORMAT         (DisplayBase::VIDEO_FORMAT_RGB888)
  #define GRAPHICS_FORMAT      (DisplayBase::GRAPHICS_FORMAT_RGB888)
  #define WR_RD_WRSWA          (DisplayBase::WR_RD_WRSWA_32BIT)
#endif

/* NOSIGNAL bit position */
#define NOSIGNAL			   (11u)
#define MASK(n)				   (1<<(n))

#define MAX_TRY				   3

/* FRAME BUFFER Parameter */
#if ( VIDEO_INPUT_FORMAT == VIDEO_YCBCR422 || VIDEO_INPUT_FORMAT == VIDEO_RGB565 )
  #define FRAME_BUFFER_BYTE_PER_PIXEL         (2u)
#else
  #define FRAME_BUFFER_BYTE_PER_PIXEL         (4u)
#endif
#define FRAME_BUFFER_STRIDE                 (((LCD_PIXEL_WIDTH * FRAME_BUFFER_BYTE_PER_PIXEL) + 31u) & ~31u)
#define FASTR_RENDER							user_video_buffer

#define DRAW_RECTANGLE_CNT_MAX              (4)
#define TOUCH_NUM                           (1u)
#define ROTRNDR_SIZE						((uint8_t*)Board_wide_jpg_File - (uint8_t *)Board_jpg_File)
#define SCRRNDR_SIZE						((uint8_t*)TopScrn_jpg_File - (uint8_t *)Board_wide_jpg_File)

#define VID_X	0
#define VID_Y	0
#define VID_W	LCD_PIXEL_WIDTH-SLIDE_WIDTH
#define VID_H	SLIDE_WIDTH

#define RVID_X	SLIDE_WIDTH
#define RVID_Y	LCD_PIXEL_HEIGHT-SLIDE_WIDTH
#define RVID_W	LCD_PIXEL_WIDTH-SLIDE_WIDTH
#define RVID_H	SLIDE_WIDTH


#define CAM_X	LCD_PIXEL_WIDTH-SLIDE_WIDTH
#define CAM_Y   0
#define CAM_W   SLIDE_WIDTH
#define CAM_H	LCD_PIXEL_HEIGHT

#define RCAM_X	0
#define RCAM_Y  0
#define RCAM_W  SLIDE_WIDTH
#define RCAM_H	LCD_PIXEL_HEIGHT


typedef enum {
    RGA_FUNC_NON,
    RGA_FUNC_DRAW_RECTANGLE,
    RGA_FUNC_DRAW_IMAGE,
    RGA_FUNC_DISSOLVE,
    RGA_FUNC_SCROLL,
    RGA_FUNC_ZOOM,
    RGA_FUNC_ROTATION,
    RGA_FUNC_ACCELERATE,
    RGA_FUNC_ANIME_EASE,
    RGA_FUNC_ANIME_LINEAR,
    RGA_FUNC_ANIME_EASE_IN,
    RGA_FUNC_ANIME_EASE_OUT,
    RGA_FUNC_ANIME_EASE_IN_OUT,
    RGA_FUNC_RETURN,
	RGA_FUNC_AUTO_MANUAL,
	RGA_FUNC_VIDEO,
	RGA_FUNC_USBCAM,
    RGA_FUNC_END
} func_code_t;

DigitalOut  test_point(LED1);
PwmOut      lcd_cntrst(P8_15);
DisplayBase Display;
Touch 		STMPE811;
USBHostCam  Cam(_432x240);
interact_t Interaction_mode;

typedef struct {
        uint32_t x;      /**< The position of the x-coordinate. */
        uint32_t y;      /**< The position of the y-coordinate. */
        bool     touch_down;  /**< IS stylus still down */
} touch_pos_t;

typedef struct {
    uint32_t pic_pos_x;             /* X position of the key picture. */
    uint32_t pic_pos_y;             /* Y position of the key picture. */
    uint32_t pic_width;             /* Width of the key picture. */
    uint32_t pic_height;            /* Height of the key picture. */
    func_code_t func_code;          /* func code of the key picture. */
} key_pic_info_t;

#ifdef __SOFT_JPEG__
struct my_error_mgr {
  struct jpeg_error_mgr pub;	/* "public" fields */

  jmp_buf setjmp_buffer;	/* for return to caller */
};

typedef struct my_error_mgr * my_error_ptr;
#endif

#if defined(__ICCARM__)
#pragma data_alignment=32
static uint8_t user_frame_buffer1[FRAME_BUFFER_STRIDE * LCD_PIXEL_HEIGHT];
static uint8_t user_frame_buffer2[FRAME_BUFFER_STRIDE * LCD_PIXEL_HEIGHT];
static uint8_t  user_video_buffer[FRAME_BUFFER_STRIDE * LCD_PIXEL_HEIGHT];
#pragma data_alignment=4
#else
static uint8_t user_frame_buffer1[FRAME_BUFFER_STRIDE * LCD_PIXEL_HEIGHT]__attribute((aligned(32))); /* 32 bytes aligned */
static uint8_t user_frame_buffer2[FRAME_BUFFER_STRIDE * LCD_PIXEL_HEIGHT]__attribute((aligned(32))); /* 32 bytes aligned */
static uint8_t  user_video_buffer[FRAME_BUFFER_STRIDE * LCD_PIXEL_HEIGHT]__attribute((aligned(32))); /* 32 bytes aligned */
static uint8_t 		  shot_buffer[100                 *             1024]__attribute((aligned(32))); /* 32 bytes aligned */
//static uint8_t 		  shot_buffer[200*1024]__attribute((section("NC_BSS"),aligned(32))); /* 32 bytes aligned */
#endif
static frame_buffer_t frame_buffer_info;
static volatile int32_t vsync_count = 0;
//static volatile int32_t vfield_count_0 = 1;
static volatile bool usb_plug = false;
static volatile bool video_signal = false;
static volatile bool try_cam_connect = false;
static volatile DisplayBase::slide_t slide_screen = DisplayBase::SLIDE_NONE;
static bool graphics_init_end = false;


#if (LCD_VDC5_CH0_PANEL == LCD_CH0_PANEL_VKLCD70RT)
  static const key_pic_info_t top_screen_key_tbl[] = {
    /*   X       Y     Width   Height   Func code                 */
    {    40,    468,    102,    106,    RGA_FUNC_DRAW_RECTANGLE    },  /* RGA Func1 */
    {   180,    468,    102,    106,    RGA_FUNC_DRAW_IMAGE        },  /* RGA Func2 */
    {   322,    468,    102,    106,    RGA_FUNC_DISSOLVE          },  /* RGA Func3 */
    {   462,    468,    102,    106,    RGA_FUNC_SCROLL            },  /* RGA Func4 */
    {   884,    468,    102,    106,    RGA_FUNC_ZOOM              },  /* RGA Func5 */
    {   604,    468,    102,    106,    RGA_FUNC_ROTATION          },  /* RGA Func6 */
    {   744,    468,    102,    106,    RGA_FUNC_ACCELERATE        },  /* RGA Func7 */
	{ VID_X,  VID_Y,  VID_W,  VID_H,	RGA_FUNC_VIDEO             },  /* RGA FuncN */
	{ CAM_X,  CAM_Y,  CAM_W,  CAM_H,	RGA_FUNC_USBCAM			   },
    {     0,      0,      0,      0,    RGA_FUNC_END               }   /* table end */
  };

  static const key_pic_info_t return_key_tbl[] = {
    /*   X       Y     Width   Height   Func code                 */
    {   792,      6,    226,     93,    RGA_FUNC_RETURN            },  /* Return Top Screen */
	{   849,    230,    117,    124,    RGA_FUNC_AUTO_MANUAL       },  /* Interaction_Mode */
    {     0,      0,      0,      0,    RGA_FUNC_END               }   /* table end */
  };

  static const key_pic_info_t animetion_timing_key_tbl[] = {
    /*   X       Y     Width   Height   Func code                 */
    {   792,      6,    226,     93,    RGA_FUNC_RETURN            },  /* Return Top Screen */
    {    21,    501,    173,     66,    RGA_FUNC_ANIME_EASE        },  /* ease */
    {   220,    501,    173,     66,    RGA_FUNC_ANIME_LINEAR      },  /* linear */
    {   422,    501,    173,     66,    RGA_FUNC_ANIME_EASE_IN     },  /* ease-in */
    {   623,    501,    173,     66,    RGA_FUNC_ANIME_EASE_OUT    },  /* ease-out */
    {   823,    501,    173,     66,    RGA_FUNC_ANIME_EASE_IN_OUT },  /* ease-in-out */
    {     0,      0,      0,      0,    RGA_FUNC_END               }   /* table end */
  };
#else
  static const key_pic_info_t top_screen_key_tbl[] = {
    /*   X       Y     Width   Height   Func code                 */
    {    18,    216,     50,     50,    RGA_FUNC_DRAW_RECTANGLE    },  /* RGA Func1 */
    {    84,    216,     50,     50,    RGA_FUNC_DRAW_IMAGE        },  /* RGA Func2 */
    {   150,    216,     50,     50,    RGA_FUNC_DISSOLVE          },  /* RGA Func3 */
    {   216,    216,     50,     50,    RGA_FUNC_SCROLL            },  /* RGA Func4 */
    {   414,    216,     50,     50,    RGA_FUNC_ZOOM              },  /* RGA Func5 */
    {   282,    216,     50,     50,    RGA_FUNC_ROTATION          },  /* RGA Func6 */
    {   348,    216,     50,     50,    RGA_FUNC_ACCELERATE        },  /* RGA Func7 */
	{ VID_X,  VID_Y,  VID_W,  VID_H,	RGA_FUNC_VIDEO             },  /* RGA FuncN */
	{ CAM_X,  CAM_Y,  CAM_W,  CAM_H,	RGA_FUNC_USBCAM			   },
    {     0,      0,      0,      0,    RGA_FUNC_END               }   /* table end */
  };

  static const key_pic_info_t return_key_tbl[] = {
    /*   X       Y     Width   Height   Func code                 */
    {   372,      6,    104,     40,    RGA_FUNC_RETURN            },  /* Return Top Screen */
	{   398,    104,     55,     56,    RGA_FUNC_AUTO_MANUAL       },  /* Interaction_Mode */
    {     0,      0,      0,      0,    RGA_FUNC_END               }   /* table end */
  };

  static const key_pic_info_t animetion_timing_key_tbl[] = {
    /*   X       Y     Width   Height   Func code                 */
    {   372,      6,    104,     40,    RGA_FUNC_RETURN            },  /* Return Top Screen */
    {    10,    227,     81,     30,    RGA_FUNC_ANIME_EASE        },  /* ease */
    {   103,    227,     81,     30,    RGA_FUNC_ANIME_LINEAR      },  /* linear */
    {   198,    227,     81,     30,    RGA_FUNC_ANIME_EASE_IN     },  /* ease-in */
    {   292,    227,     81,     30,    RGA_FUNC_ANIME_EASE_OUT    },  /* ease-out */
    {   386,    227,     81,     30,    RGA_FUNC_ANIME_EASE_IN_OUT },  /* ease-in-out */
    {     0,      0,      0,      0,    RGA_FUNC_END               }   /* table end */
  };
#endif

  static const key_pic_info_t video_screen_key_tbl[] = {
    /*   X       Y     Width   Height   Func code				   */
    {RVID_X, RVID_Y, RVID_W, RVID_H,	RGA_FUNC_RETURN				},  /* Return Top Screen */
    {     0,      0,      0,      0,    RGA_FUNC_END				}   /* table end */
  };

  static const key_pic_info_t cam_screen_key_tbl[] = {
    /*   X       Y     Width   Height   Func code                  */
    {RCAM_X, RCAM_Y, RCAM_W, RCAM_H,	RGA_FUNC_RETURN				},  /* Return Top Screen */
    {     0,      0,      0,      0,    RGA_FUNC_END				}   /* table end */
  };

#ifdef __SOFT_JPEG__
METHODDEF(void)
my_error_exit (j_common_ptr cinfo)
  {
    /* cinfo->err really points to a my_error_mgr struct, so coerce pointer */
    my_error_ptr myerr = (my_error_ptr) cinfo->err;

    /* Always display the message. */
    /* We could postpone this until after returning, if we chose. */
    (*cinfo->err->output_message) (cinfo);

    /* Return control to the setjmp point */
    longjmp(myerr->setjmp_buffer, 1);
  }
#endif


/****** LCD ******/
static void IntCallbackFunc_LoVsync(DisplayBase::int_type_t int_type) {
	bool plug = Cam.plugged();
    /* Interrupt callback function for Vsync interruption */
    if (vsync_count > 0) {
        vsync_count--;
    }

    if(slide_screen != DisplayBase::SLIDE_NONE)
    {
    	Display.Graphics_Read_Change_More(DisplayBase::GRAPHICS_LAYER_2,
    	(void *)frame_buffer_info.buffer_address[frame_buffer_info.draw_buffer_index], FRAME_BUFFER_STRIDE, (DisplayBase::slide_t *)&slide_screen);
    }

    /* Read NOSIGNAL bit */
    video_signal = (RZA_IO_RegRead_16(&DVDEC0.VSYNCSR, NOSIGNAL, MASK(NOSIGNAL)))? false : true;
    /* Read USB ATTCH DTTCH signals */
    if(plug ^ usb_plug)
    {
  		try_cam_connect = plug;
        usb_plug = plug;
    }
}

static void Wait_Vsync(const int32_t wait_count) {
    /* Wait for the specified number of times Vsync occurs */
    vsync_count = wait_count;
    while (vsync_count > 0) {
        /* Do nothing */
    }
}

static void IntCallbackFunc_Vfield_0(DisplayBase::int_type_t int_type) {
    /*DisplayBase::graphics_error_t error;

    // Interrupt callback function
    if (vfield_count_0 == 0) {
        vfield_count_0 = 1;
        error = Display.Video_Stop( DisplayBase::VIDEO_INPUT_CHANNEL_0 );
        if (error != DisplayBase::GRAPHICS_OK) {
            printf("Line %d, error %d\n", __LINE__, error);
            mbed_die();
        }
    } else {
        ;
    }*/
}

static void Init_LCD_Display(void) {
    DisplayBase::graphics_error_t error;
    DisplayBase::lcd_config_t lcd_config;

	#if (LCD_VDC5_CH0_PANEL == LCD_CH0_PANEL_VKLCD70RT)
    	PinName lvds_pin[] = {P5_7, P5_6, P5_5, P5_4, P5_3, P5_2, P5_1, P5_0};
    	Display.Graphics_Lvds_Port_Init(lvds_pin, sizeof(lvds_pin)/sizeof(lvds_pin[0]));
	#else 	 	 	 	  /* D15,  D14,  D13,  D12,  D11,  D10,   D9,   D8,   D7,    D6,    D5,    D4,    D3,    D2,    D1,   D0,   DE,  CLK */
    	PinName lcd_pin[] = {P4_7, P4_6, P4_5, P4_4, P4_3, P4_2, P4_1, P4_0, P3_15, P3_14, P3_13, P3_12, P3_11, P3_10, P3_9, P3_8, P3_1, P3_0};
    	Display.Graphics_Lcd_Port_Init(lcd_pin, sizeof(lcd_pin)/sizeof(lcd_pin[0]));
    #endif


    /* Graphics initialization process */
    lcd_config = LcdCfgTbl;
    error = Display.Graphics_init(&lcd_config);
    if (error != DisplayBase::GRAPHICS_OK) {
        printf("Line %d, error %d\n", __LINE__, error);
        mbed_die();
    }

    /* Interrupt callback function setting (Vsync signal output from scaler 0) */
    error = Display.Graphics_Irq_Handler_Set(DisplayBase::INT_TYPE_S0_LO_VSYNC, 0, IntCallbackFunc_LoVsync);
    if (error != DisplayBase::GRAPHICS_OK) {
        printf("Line %d, error %d\n", __LINE__, error);
        mbed_die();
    }

    graphics_init_end = true;
}

/****** Video ******/
static void Init_Video(void) {
    DisplayBase::graphics_error_t error;

    /* Graphics initialization process */
    if (graphics_init_end == false) {
        /* When not initializing LCD, this processing is needed. */
        error = Display.Graphics_init(NULL);
        if (error != DisplayBase::GRAPHICS_OK) {
            printf("Line %d, error %d\n", __LINE__, error);
            mbed_die();
        }
        graphics_init_end = true;
    }

    error = Display.Graphics_Video_init( DisplayBase::INPUT_SEL_VDEC, NULL);
    if( error != DisplayBase::GRAPHICS_OK ) {
        printf("Line %d, error %d\n", __LINE__, error);
        mbed_die();
    }

    /* Interrupt callback function setting (Field end signal for recording function in scaler 0) */
    error = Display.Graphics_Irq_Handler_Set(VIDEO_INT_TYPE, 0, IntCallbackFunc_Vfield_0);
    if (error != DisplayBase::GRAPHICS_OK) {
        printf("Line %d, error %d\n", __LINE__, error);
        mbed_die();
    }
}

static void Start_Video(DisplayBase::video_input_channel_t ch, uint8_t * p_frame_buffer,
 uint16_t pos_x, uint16_t pos_y, uint16_t width, uint16_t height) {
    DisplayBase::graphics_error_t error;
    //uint8_t * p_buf;

    //p_buf = p_frame_buffer + (FRAME_BUFFER_BYTE_PER_PIXEL * pos_x) + (FRAME_BUFFER_STRIDE * pos_y);

    /* Video capture setting (progressive form fixed) */
    error = Display.Video_Write_Setting(
                ch,
                COL_SYS,
				p_frame_buffer, //p_buf,
                FRAME_BUFFER_STRIDE,
                VIDEO_FORMAT,
                WR_RD_WRSWA,
				height, //(height & ~7u),      /* A multiple of 8 */
				width   //(width  & ~15u)      /* A multiple of 16 */
            );
    if (error != DisplayBase::GRAPHICS_OK) {
        printf("Line %d, error %d\n", __LINE__, error);
        mbed_die();
    }

    /* Video write process start */
    error = Display.Video_Start(ch);
    if (error != DisplayBase::GRAPHICS_OK) {
        printf("Line %d, error %d\n", __LINE__, error);
        mbed_die();
    }

    error = Display.Video_Stop( DisplayBase::VIDEO_INPUT_CHANNEL_0 );
    if (error != DisplayBase::GRAPHICS_OK) {
        printf("Line %d, error %d\n", __LINE__, error);
        mbed_die();
    }
}

static void Start_LCD_Display(uint8_t * p_buf) {
    DisplayBase::rect_t rect;

    rect.vs = 0;
    rect.vw = LCD_PIXEL_HEIGHT;
    rect.hs = 0;
    rect.hw = LCD_PIXEL_WIDTH;
    Display.Graphics_Read_Setting(
        DisplayBase::GRAPHICS_LAYER_0,
        (void *)user_video_buffer,
        FRAME_BUFFER_STRIDE,
        GRAPHICS_FORMAT,
        WR_RD_WRSWA,
        &rect
    );

    Display.Graphics_Start(DisplayBase::GRAPHICS_LAYER_0);

    rect.vs = 0;
    rect.vw = LCD_PIXEL_HEIGHT;
    rect.hs = 0;
    rect.hw = LCD_PIXEL_WIDTH;
    Display.Graphics_Read_Setting(
        DisplayBase::GRAPHICS_LAYER_2,
        (void *)p_buf,
        FRAME_BUFFER_STRIDE,
        GRAPHICS_FORMAT,
        WR_RD_WRSWA,
        &rect
    );

    Display.Graphics_Start(DisplayBase::GRAPHICS_LAYER_2);
}

static void Update_LCD_Display(frame_buffer_t * frmbuf_info) {
    Display.Graphics_Read_Change(DisplayBase::GRAPHICS_LAYER_2,
     (void *)frmbuf_info->buffer_address[frmbuf_info->draw_buffer_index]);
    Wait_Vsync(1);
}

static void Update_VIDEO_Display(frame_buffer_t * frmbuf_info) {
    Display.Graphics_Read_Change(DisplayBase::GRAPHICS_LAYER_0,
     (void *)frmbuf_info->buffer_address[frmbuf_info->draw_buffer_index]);
    Wait_Vsync(1);
}

static void Swap_FrameBuffer(frame_buffer_t * frmbuf_info) {
    if (frmbuf_info->draw_buffer_index == 1) {
        frmbuf_info->draw_buffer_index = 0;
    } else {
        frmbuf_info->draw_buffer_index = 1;
    }
}


/****** Touch ******/
static func_code_t Scan_Key(const key_pic_info_t * key_tbl, const uint32_t pos_x, const uint32_t pos_y) {
    func_code_t ret = RGA_FUNC_NON;

    while (ret == RGA_FUNC_NON) {
        if (key_tbl->func_code == RGA_FUNC_END) {
            break;
        }
        /* Check the range of the X position */
        if ((pos_x >= key_tbl->pic_pos_x) && (pos_x <= (key_tbl->pic_pos_x + key_tbl->pic_width))) {
            /* Check the range of the Y position */
            if ((pos_y >= key_tbl->pic_pos_y) && (pos_y <= (key_tbl->pic_pos_y + key_tbl->pic_height))) {
                /* Decide the func code. */
                ret = key_tbl->func_code;
            }
        }
        key_tbl++;
    }

    return ret;
}

static int GetCoordinates(touch_pos_t * p_touch) {
	touch_pos_t * wk_touch;
	int count = 0;
	int i;

	if (p_touch != NULL)
	{
		wk_touch        = p_touch;
	    wk_touch->x     = 0;
	    wk_touch->y     = 0;
	    wk_touch->touch_down = false;

	    wk_touch->touch_down = STMPE811.Handle_touch((uint8_t*)&count);
	    if(count)
	    {
	    	wk_touch->x = STMPE811.x;
	    	wk_touch->y = STMPE811.y;
	    }
	}

	 return count;
}

/****** Efect ******/
static void Exe_RGA_Func(func_code_t func_name, frame_buffer_t* frmbuf_info) {
    uint8_t touch_num = 0;
    touch_pos_t touch_pos[TOUCH_NUM];

    switch (func_name) {
        case RGA_FUNC_DRAW_RECTANGLE:
            bool key_on = false;
            bool first = false;
            bool second = false;
            int cnt = 0;
            int color_cnt = 0;
            int x_0 = 0;
            int y_0 = 0;
            draw_rectangle_pos_t pos_tbl[DRAW_RECTANGLE_CNT_MAX] = {0};

            pos_tbl[0].style = "#FF0000";  /* red */
            pos_tbl[1].style = "#00FF00";  /* green */
            pos_tbl[2].style = "#0000FF";  /* blue */
            pos_tbl[3].style = "#000000";  /* black */

            while (1) {
                /* Get coordinates */
                touch_num = GetCoordinates(touch_pos);
                if (touch_num != 0)
                {
                    if (Scan_Key(return_key_tbl, touch_pos[0].x, touch_pos[0].y) == RGA_FUNC_RETURN) {
                        break;
                    }
                    if(touch_pos[0].touch_down)  {
                    	if(!key_on)	{
                    		pos_tbl[cnt].x = x_0 = touch_pos[0].x;
                    		pos_tbl[cnt].y = y_0 = touch_pos[0].y;
                    		pos_tbl[cnt].w = 0;
							pos_tbl[cnt].h = 0;
							if(cnt == 0) {
								for (color_cnt = 1; color_cnt < DRAW_RECTANGLE_CNT_MAX; color_cnt++) {
									pos_tbl[color_cnt].x = 0;
							        pos_tbl[color_cnt].y = 0;
							        pos_tbl[color_cnt].w = 0;
							        pos_tbl[color_cnt].h = 0;
							    }
							}
                    		key_on = true;
                    	}
                    	else {
                    		if(touch_pos[0].x >= x_0) {
                    			pos_tbl[cnt].x = x_0;
                    			pos_tbl[cnt].w = touch_pos[0].x - pos_tbl[cnt].x;
                    		}
                    		else {
                    			pos_tbl[cnt].x = touch_pos[0].x;
                    			pos_tbl[cnt].w = x_0 - touch_pos[0].x;
                    		}

                    		if(touch_pos[0].y >= y_0) {
                    			pos_tbl[cnt].y = y_0;
                    			pos_tbl[cnt].h = touch_pos[0].y - pos_tbl[cnt].y;
                    		}
                    		else {
                    			pos_tbl[cnt].y = touch_pos[0].y;
								pos_tbl[cnt].h = y_0 - touch_pos[0].y;
                    		}
                    	}

                    }
                    else {
                    	if(key_on) {
                    		if(touch_pos[0].x >= x_0) {
                    			pos_tbl[cnt].x = x_0;
                    			pos_tbl[cnt].w = touch_pos[0].x - pos_tbl[cnt].x;
                    		}
                    		else {
                    			pos_tbl[cnt].x = touch_pos[0].x;
                    			pos_tbl[cnt].w = x_0 - touch_pos[0].x;
                    		}

                    		if(touch_pos[0].y >= y_0) {
                    			pos_tbl[cnt].y = y_0;
                    			pos_tbl[cnt].h = touch_pos[0].y - pos_tbl[cnt].y;
                    		}
                    		else {
                    			pos_tbl[cnt].y = touch_pos[0].y;
                    			pos_tbl[cnt].h = y_0 - touch_pos[0].y;
                    		}

                    		cnt++;
                    		if (cnt == DRAW_RECTANGLE_CNT_MAX)
                    			cnt = 0;
                    		key_on = false;
                    	}
                    	else
                    	{

                    	}
                    }
                }
                /* Draw screen */
                Swap_FrameBuffer(frmbuf_info);
                RGA_Func_DrawRectangle(frmbuf_info, pos_tbl, DRAW_RECTANGLE_CNT_MAX);
                Update_LCD_Display(frmbuf_info);
            }
            break;
        case RGA_FUNC_DRAW_IMAGE:
            int center_pos_x = 320;
            int center_pos_y = 110;
            while (1) {
                /* Get coordinates */
                touch_num = GetCoordinates(touch_pos);
                if (touch_num != 0) {
                    if (Scan_Key(return_key_tbl, touch_pos[0].x, touch_pos[0].y) == RGA_FUNC_RETURN) {
                        break;
                    }
                    center_pos_x = touch_pos[0].x;
                    center_pos_y = touch_pos[0].y;
                }
                /* Draw screen */
                Swap_FrameBuffer(frmbuf_info);
                RGA_Func_DrawImage(frmbuf_info, center_pos_x, center_pos_y);
                Update_LCD_Display(frmbuf_info);
            }
            break;
        case RGA_FUNC_DISSOLVE:
            float32_t work_alpha = 0.0f;
            uint16_t xa = LCD_PIXEL_WIDTH;

            RGA_Func_Dissolve(frmbuf_info, 0.0f, Interaction_mode);
            Swap_FrameBuffer(frmbuf_info);
            RGA_Func_Dissolve(frmbuf_info, 0.0f, Interaction_mode);
            Update_LCD_Display(frmbuf_info);
            memcpy(FASTR_RENDER, (uint8_t*)Board_jpg_File, ROTRNDR_SIZE);
            while (1) {
                /* Get coordinates */
                touch_num = GetCoordinates(touch_pos);
                if (touch_num != 0) {
                	func_code_t func_code;

                	func_code = Scan_Key(return_key_tbl, touch_pos[0].x, touch_pos[0].y);
                    if (func_code == RGA_FUNC_RETURN) {
                        break;
                    }

                    if(!touch_pos[0].touch_down && (func_code == RGA_FUNC_AUTO_MANUAL))
                    	Interaction_mode = (Interaction_mode == AUTO_INTERACT)? MANUAL_INTERACT : AUTO_INTERACT;
                    else
                    	work_alpha = (float32_t)touch_pos[0].x / (float32_t)(LCD_PIXEL_WIDTH);
                }
                if(Interaction_mode == AUTO_INTERACT)
                {
                	xa= (xa >= LCD_PIXEL_WIDTH)? 0: (xa+1);
                	work_alpha = (float32_t)xa / (float32_t)(LCD_PIXEL_WIDTH);
                }
                /* Draw screen */
                Swap_FrameBuffer(frmbuf_info);
                RGA_Func_Diss(frmbuf_info, work_alpha, Interaction_mode, (graphics_image_t*)FASTR_RENDER);
                Update_LCD_Display(frmbuf_info);
            }
            break;
        case RGA_FUNC_SCROLL:
            int work_width_pos = 0;
            uint16_t xs = LCD_PIXEL_WIDTH;

            RGA_Func_Scroll(frmbuf_info, 0, Interaction_mode);
            Swap_FrameBuffer(frmbuf_info);
            RGA_Func_Scroll(frmbuf_info, 0, Interaction_mode);
            Update_LCD_Display(frmbuf_info);
            memcpy(FASTR_RENDER, (uint8_t*)Board_wide_jpg_File, SCRRNDR_SIZE);
            while (1) {
                /* Get coordinates */
                touch_num = GetCoordinates(touch_pos);
                if (touch_num != 0) {
                	func_code_t func_code;

                	func_code = Scan_Key(return_key_tbl, touch_pos[0].x, touch_pos[0].y);
                    if (func_code == RGA_FUNC_RETURN) {
                        break;
                    }

                    if(!touch_pos[0].touch_down && (func_code == RGA_FUNC_AUTO_MANUAL))
                    	Interaction_mode = (Interaction_mode == AUTO_INTERACT)? MANUAL_INTERACT : AUTO_INTERACT;
                    else
                    	work_width_pos = SCROLL_MAX_NUM * ((float32_t)touch_pos[0].x / (float32_t)(LCD_PIXEL_WIDTH));
                }
                if(Interaction_mode == AUTO_INTERACT)
                {
                	xs= (xs >= LCD_PIXEL_WIDTH)? 0: (xs+1);
                	work_width_pos = SCROLL_MAX_NUM * ((float32_t)xs / (float32_t)(LCD_PIXEL_WIDTH));
                }
                /* Draw screen */
                Swap_FrameBuffer(frmbuf_info);
                RGA_Func_Scr(frmbuf_info, work_width_pos, Interaction_mode, (graphics_image_t*)FASTR_RENDER);
                Update_LCD_Display(frmbuf_info);
            }
            break;
        case RGA_FUNC_ZOOM:
            int work_height_pos = ZOOM_MAX_NUM;
            uint16_t xz = LCD_PIXEL_WIDTH;

            RGA_Func_Zoom(frmbuf_info,  0, Interaction_mode);
            Swap_FrameBuffer(frmbuf_info);
            RGA_Func_Zoom(frmbuf_info,  0, Interaction_mode);
            Update_LCD_Display(frmbuf_info);
            memcpy(FASTR_RENDER, (uint8_t*)Board_jpg_File, ROTRNDR_SIZE);
            while (1) {
                /* Get coordinates */
                touch_num = GetCoordinates(touch_pos);
                if (touch_num != 0) {
                	func_code_t func_code;

                	func_code = Scan_Key(return_key_tbl, touch_pos[0].x, touch_pos[0].y);
                    if (func_code == RGA_FUNC_RETURN) {
                        break;
                    }

                    if(!touch_pos[0].touch_down && (func_code == RGA_FUNC_AUTO_MANUAL))
                    	Interaction_mode = (Interaction_mode == AUTO_INTERACT)? MANUAL_INTERACT : AUTO_INTERACT;
                    else
                    	work_height_pos = ZOOM_MAX_NUM * ((float32_t)touch_pos[0].x / (float32_t)(LCD_PIXEL_WIDTH));
                }
                if(Interaction_mode == AUTO_INTERACT)
                {
                	xz= (xz >= LCD_PIXEL_WIDTH)? 0: (xz+1);
                	work_height_pos = ZOOM_MAX_NUM * ((float32_t)xz / (float32_t)(LCD_PIXEL_WIDTH));
				}
                /* Draw screen */
                Swap_FrameBuffer(frmbuf_info);
                RGA_Func_Zo(frmbuf_info,  work_height_pos, Interaction_mode, (graphics_image_t*)FASTR_RENDER);
                Update_LCD_Display(frmbuf_info);
            }
            break;
        case RGA_FUNC_ROTATION:
            graphics_matrix_float_t work_angle = 0;
            uint16_t xr = LCD_PIXEL_WIDTH;

            RGA_Func_Rotation(frmbuf_info, 0, Interaction_mode);
            Swap_FrameBuffer(frmbuf_info);
            RGA_Func_Rotation(frmbuf_info, 0, Interaction_mode);
            Update_LCD_Display(frmbuf_info);
            memcpy(FASTR_RENDER, (uint8_t*)Board_jpg_File, ROTRNDR_SIZE);
            while (1) {
                /* Get coordinates */
                touch_num = GetCoordinates(touch_pos);
                if (touch_num != 0) {
                	func_code_t func_code;

                	func_code = Scan_Key(return_key_tbl, touch_pos[0].x, touch_pos[0].y);
                    if (func_code == RGA_FUNC_RETURN) {
                        break;
                    }

                    if(!touch_pos[0].touch_down && (func_code == RGA_FUNC_AUTO_MANUAL))
                    	Interaction_mode = (Interaction_mode == AUTO_INTERACT)? MANUAL_INTERACT : AUTO_INTERACT;
                    else
                    	work_angle = ROTATION_MAX_NUM * ((float32_t)touch_pos[0].x / (float32_t)(LCD_PIXEL_WIDTH));
                }
                if(Interaction_mode == AUTO_INTERACT)
                {
                	xr= (xr >= LCD_PIXEL_WIDTH)? 0: (xr+1);
                	work_angle = ROTATION_MAX_NUM * ((float32_t)xr / (float32_t)(LCD_PIXEL_WIDTH));
                }
                /* Draw screen */
                Swap_FrameBuffer(frmbuf_info);
                RGA_Func_Rotor(frmbuf_info, work_angle, Interaction_mode, (graphics_image_t*)FASTR_RENDER);
                Update_LCD_Display(frmbuf_info);
            }
            break;
        case RGA_FUNC_ACCELERATE:
            int acce_frame_num = 0;
            int animation_timing = 0;
            float32_t work_relative_pos;

            RGA_Func_Accelerate(frmbuf_info, 0, 0);
            Swap_FrameBuffer(frmbuf_info);
            RGA_Func_Accelerate(frmbuf_info, 0, 0);
            Update_LCD_Display(frmbuf_info);
            memcpy(FASTR_RENDER, (uint8_t*)Board_jpg_File, ROTRNDR_SIZE);
            while (1) {
                /* Get coordinates */
                touch_num = GetCoordinates(touch_pos);
                if (touch_num != 0) {
                    func_code_t func_code;

                    func_code = Scan_Key(animetion_timing_key_tbl, touch_pos[0].x, touch_pos[0].y);
                    if (func_code == RGA_FUNC_RETURN) {
                        break;
                    }
                    switch (func_code) {
                        case RGA_FUNC_ANIME_EASE:
                            animation_timing = 0;
                            acce_frame_num = 0;
                            break;
                        case RGA_FUNC_ANIME_LINEAR:
                            animation_timing = 1;
                            acce_frame_num = 0;
                            break;
                        case RGA_FUNC_ANIME_EASE_IN:
                            animation_timing = 2;
                            acce_frame_num = 0;
                            break;
                        case RGA_FUNC_ANIME_EASE_OUT:
                            animation_timing = 3;
                            acce_frame_num = 0;
                            break;
                        case RGA_FUNC_ANIME_EASE_IN_OUT:
                            animation_timing = 4;
                            acce_frame_num = 0;
                            break;
                        default:
                            /* Do Nothing */
                            break;
                    }
                }
                work_relative_pos = acce_frame_num / (float32_t)ACCELERATE_MAX_NUM;
                acce_frame_num++;
                if (acce_frame_num > ACCELERATE_MAX_NUM) {
                    acce_frame_num = 0;
                }
                /* Draw screen */
                Swap_FrameBuffer(frmbuf_info);
                RGA_Func_Axel(frmbuf_info, animation_timing, work_relative_pos, (graphics_image_t*)FASTR_RENDER);
                Update_LCD_Display(frmbuf_info);
            }
            break;

        case RGA_FUNC_VIDEO:
        	static bool old_signal;

        	if(video_signal)
        	{	/* Video write process start */
        		if (Display.Video_Start(DisplayBase::VIDEO_INPUT_CHANNEL_0) != DisplayBase::GRAPHICS_OK) {
        			printf("Line %d, error %d\n", __LINE__, error);
        			mbed_die();
        		}
        	}
        	else
        	{
        		frmbuf_info->buffer_address[frmbuf_info->draw_buffer_index] = user_video_buffer;
        		RGA_Func_DrawFullScreen(frmbuf_info, TstScrn_jpg_File);
        		frmbuf_info->buffer_address[frmbuf_info->draw_buffer_index] = (frmbuf_info->draw_buffer_index)? user_frame_buffer2 : user_frame_buffer1;
        	}

        	old_signal = video_signal;
        	slide_screen = DisplayBase::SLIDE_OUT_BOTTOM;
        	while(slide_screen !=DisplayBase::SLIDE_NONE);
        	frmbuf_info->buffer_address[frmbuf_info->draw_buffer_index] = user_video_buffer;

            while (1) {
                /* Get coordinates */
                touch_num = GetCoordinates(touch_pos);
                if (touch_num != 0) {
                    if (Scan_Key(video_screen_key_tbl, touch_pos[0].x, touch_pos[0].y) == RGA_FUNC_RETURN) {
                    	if(video_signal)
                    	{
                    		if (Display.Video_Stop(DisplayBase::VIDEO_INPUT_CHANNEL_0) != DisplayBase::GRAPHICS_OK) {
                    			printf("Line %d, error %d\n", __LINE__, error);
                    			mbed_die();
                    		}
                    	}
                    	frmbuf_info->buffer_address[frmbuf_info->draw_buffer_index] = (frmbuf_info->draw_buffer_index)? user_frame_buffer2 : user_frame_buffer1;
                    	slide_screen = DisplayBase::SLIDE_IN_BOTTOM;
                        break;
                    }
                }

                if(video_signal ^ old_signal)
                {
                	if(video_signal)
                	{
                		if (Display.Video_Start(DisplayBase::VIDEO_INPUT_CHANNEL_0) != DisplayBase::GRAPHICS_OK) {
                		     printf("Line %d, error %d\n", __LINE__, error);
                		     mbed_die();
                		}
                	}
                	else
                	{
                		if (Display.Video_Stop(DisplayBase::VIDEO_INPUT_CHANNEL_0) != DisplayBase::GRAPHICS_OK) {
                			printf("Line %d, error %d\n", __LINE__, error);
                		    mbed_die();
                		}
                		Wait_Vsync(3);
                		RGA_Func_DrawFullScreen(frmbuf_info, TstScrn_jpg_File);
                	}
                	old_signal = video_signal;
                }
            }
            break;

        case RGA_FUNC_USBCAM:
        	static int swaped_idx;
        	static bool old_usbplug;
        	static int try_recognize;
        	int shot_size;

        	try_recognize = 0;
        	swaped_idx = frmbuf_info->draw_buffer_index;
        	frmbuf_info->buffer_address[(swaped_idx)? 0 : 1] = user_video_buffer;
        	frmbuf_info->buffer_address[swaped_idx] = (swaped_idx)? user_frame_buffer1 : user_frame_buffer2;

        	RGA_Func_DrawFullScreen(frmbuf_info, CamScrn_jpg_File);
        	if(!Cam.connected())
        		RGA_Func_DrawPNG(frmbuf_info, NoDevice_png_ARGB4444, NO_DEV_X, NO_DEV_Y);
        	Swap_FrameBuffer(frmbuf_info);
        	RGA_Func_DrawFullScreen(frmbuf_info, CamScrn_jpg_File);
        	if(!Cam.connected())
        	    RGA_Func_DrawPNG(frmbuf_info, NoDevice_png_ARGB4444, NO_DEV_X, NO_DEV_Y);
        	Swap_FrameBuffer(frmbuf_info);

        	frmbuf_info->buffer_address[swaped_idx] = (swaped_idx)? user_frame_buffer2 : user_frame_buffer1;
        	old_usbplug = usb_plug;
        	slide_screen = DisplayBase::SLIDE_OUT_LEFT;
        	while(slide_screen !=DisplayBase::SLIDE_NONE);
        	frmbuf_info->buffer_address[swaped_idx] = (swaped_idx)? user_frame_buffer1 : user_frame_buffer2;

        	if(Cam.connected())
        	{
        		RGA_Func_DrawFullScreen(frmbuf_info, NULL);
        		Swap_FrameBuffer(frmbuf_info);
        		RGA_Func_DrawFullScreen(frmbuf_info, NULL);
        	}


#ifdef __SOFT_JPEG__
            // decompression with libJPEG
            //1:	Allocate and initialize a JPEG decompression object
            //2:	Specify the source of the compressed data (eg, a file)
            //3:	Call jpeg_read_header() to obtain image info
            //4:	Set parameters for decompression
            //5:	jpeg_start_decompress(...);
            //6:	while (scan lines remain to be read)
            //			jpeg_read_scanlines(...);
            //7:	jpeg_finish_decompress(...);
            //8:	Release the JPEG decompression object

            struct jpeg_decompress_struct cinfo;
            struct my_error_mgr jerr;
            JSAMPARRAY buffer;	/* Output row buffer */
            int row_stride;		/* physical row width in output buffer */
            //...
            cinfo.err = jpeg_std_error(&jerr.pub);  /* We set up the normal JPEG error routines  */
            jerr.pub.error_exit = my_error_exit;	/* then override error_exit. */

            /* Establish the setjmp return context for my_error_exit to use. */
              if (setjmp(jerr.setjmp_buffer)) {
                /* If we get here, the JPEG code has signaled an error.
                 * We need to clean up the JPEG object, close the input file, and return.
                 */
                jpeg_destroy_decompress(&cinfo);
              }

            //1:
            jpeg_create_decompress(&cinfo);
#endif

            while (1) {
                /* Get coordinates */
                touch_num = GetCoordinates(touch_pos);
                if (touch_num != 0) {
                   if (Scan_Key(cam_screen_key_tbl, touch_pos[0].x, touch_pos[0].y) == RGA_FUNC_RETURN) {
                	   frmbuf_info->buffer_address[frmbuf_info->draw_buffer_index] = user_video_buffer;
                	   Update_VIDEO_Display(frmbuf_info);
                	   frmbuf_info->buffer_address[0] = user_frame_buffer1;
                	   frmbuf_info->buffer_address[1] = user_frame_buffer2;
                	   slide_screen = DisplayBase::SLIDE_IN_LEFT;
                       break;
                   }
                }

                if(Cam.connected())
                {
                	shot_size = Cam.readJPEG(shot_buffer, sizeof(shot_buffer));
                	//printf("JPEG size: %d\r\n", shot_size);
                	//test_point = !test_point;

                	Swap_FrameBuffer(frmbuf_info);

#ifdef __SOFT_JPEG__
                	//2:
                	jpeg_mem_src(&cinfo, shot_buffer ,shot_size);

					//3:
                	jpeg_read_header(&cinfo, TRUE);
                	//4:
                	// Default decompression parameters
                	//5:
                	jpeg_start_decompress(&cinfo);

                	//6:
                	row_stride = cinfo.output_width * cinfo.output_components;
                	buffer = (*cinfo.mem->alloc_sarray)	((j_common_ptr) &cinfo, JPOOL_IMAGE, row_stride, 1);
                	while (cinfo.output_scanline < cinfo.output_height) {
                		jpeg_read_scanlines(&cinfo, buffer, 1);

                		for(int i=0; i<cinfo.output_width; i++)
                		{
                			uint16_t _565;

                			_565  = (uint16_t)(0xF8 & buffer[0][(i*3)+2])>>3;
                			_565 |= (uint16_t)(0xFC & buffer[0][(i*3)+1])<<3;
                			_565 |= (uint16_t)(0xF8 & buffer[0][i*3])<<8;

                			((uint16_t*)(frmbuf_info->buffer_address[frmbuf_info->draw_buffer_index]))[((cinfo.output_scanline-1)*LCD_PIXEL_WIDTH)+i] = _565;
                		}
                    }
                	//7:
                	jpeg_finish_decompress(&cinfo);

                	RGA_Func_DrawCamScreen(NULL);
#else
                	RGA_Func_DrawCamScreen(shot_buffer);
#endif

                	Update_VIDEO_Display(frmbuf_info);

                	Cam.poll();
                }

                if(usb_plug ^ old_usbplug)
                {
                	if(usb_plug)
                    {
                		//Swap_FrameBuffer(frmbuf_info);
                		//RGA_Func_DrawFullScreen(frmbuf_info, CamScrn_jpg_File);
                		//Update_VIDEO_Display(frmbuf_info);
                    }
                    else
                    {
                    	Swap_FrameBuffer(frmbuf_info);
                    	RGA_Func_DrawFullScreen(frmbuf_info, CamScrn_jpg_File);
                    	RGA_Func_DrawPNG(frmbuf_info, NoDevice_png_ARGB4444, NO_DEV_X, NO_DEV_Y);
                    	Update_VIDEO_Display(frmbuf_info);
                    }
                    old_usbplug = usb_plug;
                }

                if(try_cam_connect)
                {
                	if(!Cam.connected())
                	{
                		Cam.connect();
                		Thread::wait(500);
                		if(try_recognize == 0)
                		{
                			Swap_FrameBuffer(frmbuf_info);
                			RGA_Func_DrawFullScreen(frmbuf_info, CamScrn_jpg_File);
                			Update_VIDEO_Display(frmbuf_info);
                		}

                		try_recognize++;
                		if(try_recognize > MAX_TRY)
                		{
                			try_cam_connect = false;
                			Swap_FrameBuffer(frmbuf_info);
                			RGA_Func_DrawFullScreen(frmbuf_info, CamScrn_jpg_File);
                			RGA_Func_DrawPNG(frmbuf_info, NoDevice_png_ARGB4444, NO_DEV_X, NO_DEV_Y);
                			Update_VIDEO_Display(frmbuf_info);
                		}
                	}
                	else
                	{
                		try_cam_connect = false;
                		RGA_Func_DrawFullScreen(frmbuf_info, NULL);
                		Swap_FrameBuffer(frmbuf_info);
                		RGA_Func_DrawFullScreen(frmbuf_info, NULL);
                		Swap_FrameBuffer(frmbuf_info);
                	}
                }
                else
                	try_recognize = 0;
            }

#ifdef __SOFT_JPEG__
            //8:
            jpeg_destroy_decompress(&cinfo);
#endif
            break;

        default :
            /* Do nothing */
            break;
    }
}


//void test(int x)
//{
//	test_point=x;
//}

int main(void) {
    func_code_t func_code;
    uint8_t touch_num = 0;
    touch_pos_t touch_pos[TOUCH_NUM];

    /* Initialization of LCD */
    Init_LCD_Display();    /* When using LCD, please call before than Init_Video(). */

    /* Initialization of Video */
    Init_Video();

    /* Start of Video ch0 */
    Start_Video(
    	DisplayBase::VIDEO_INPUT_CHANNEL_0,   /* Video input channe */
        user_video_buffer,                    /* Output buffer */
        0,                                    /* The x coordinate of the upper-left corner */
        0,                                    /* The y coordinate of the upper-left corner */
        LCD_PIXEL_WIDTH,                	  /* width  (A multiple of 16) */
        LCD_PIXEL_HEIGHT                      /* height (A multiple of 8) */
    );

    memset(user_frame_buffer1, 0, sizeof(user_frame_buffer1));
    memset(user_frame_buffer2, 0, sizeof(user_frame_buffer2));
    frame_buffer_info.buffer_address[0] = user_frame_buffer1;
    frame_buffer_info.buffer_address[1] = user_frame_buffer2;
    frame_buffer_info.buffer_count      = 2;
    frame_buffer_info.show_buffer_index = 0;
    frame_buffer_info.draw_buffer_index = 0;
    frame_buffer_info.width             = LCD_PIXEL_WIDTH;
    frame_buffer_info.byte_per_pixel    = FRAME_BUFFER_BYTE_PER_PIXEL;
    frame_buffer_info.stride            = LCD_PIXEL_WIDTH * FRAME_BUFFER_BYTE_PER_PIXEL;
    frame_buffer_info.height            = LCD_PIXEL_HEIGHT;
    frame_buffer_info.pixel_format      = PIXEL_FORMAT_RGB565;

    /* Display Top Screen */
    Set_RGAObject(&frame_buffer_info);
    RGA_Func_DrawFullScreen(&frame_buffer_info, TopScrn_jpg_File);

    Swap_FrameBuffer(&frame_buffer_info);
    RGA_Func_DrawFullScreen(&frame_buffer_info, TopScrn_jpg_File);
    Swap_FrameBuffer(&frame_buffer_info);

    /* Start of LCD */
    Start_LCD_Display(frame_buffer_info.buffer_address[0]);

    /* Backlight on */
    Thread::wait(200);
    lcd_cntrst.period_us(100);
    lcd_cntrst.write(((float)LCD_CH0_INITIAL_DC)/100.0f); //

    /* Reset touch IC */
    STMPE811.Init();

    Interaction_mode = MANUAL_INTERACT;

    while (1) {
        /* Get Coordinates */
        touch_num = GetCoordinates(touch_pos);
        if (touch_num != 0) {
            func_code = Scan_Key(top_screen_key_tbl, touch_pos[0].x, touch_pos[0].y);
            if (func_code != RGA_FUNC_NON) {
                /* Wait key off */
                while (1) {
                    touch_num = GetCoordinates(touch_pos);
                    if (touch_num == 0) {
                        break;
                    }
                    Thread::wait(20);
                }

                /* Execute RGA functions */
                Exe_RGA_Func(func_code, &frame_buffer_info);

                /* Return Top Screen */
                touch_num = 0;
                touch_num = (RGA_Func_CheckPorts(&frame_buffer_info, false, false))? 1 : 0;
                touch_num = (RGA_Func_CheckPorts(&frame_buffer_info, video_signal, usb_plug))? 1 : 0;
                if(touch_num == 0)
                {
                	Swap_FrameBuffer(&frame_buffer_info);
                	RGA_Func_DrawFullScreen(&frame_buffer_info, TopScrn_jpg_File);
                }
                Update_LCD_Display(&frame_buffer_info);
            }
        }
        else
        	if(RGA_Func_CheckPorts(&frame_buffer_info, video_signal, usb_plug))
        		Update_LCD_Display(&frame_buffer_info);
        Thread::wait(20);
    }
}


